xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision a6f32f4015eaf52be6539f1a91d5de4990d37d6f)
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 static SDValue widenVectorToPartType(SelectionDAG &DAG,
618                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
619   if (!PartVT.isVector())
620     return SDValue();
621 
622   EVT ValueVT = Val.getValueType();
623   unsigned PartNumElts = PartVT.getVectorNumElements();
624   unsigned ValueNumElts = ValueVT.getVectorNumElements();
625   if (PartNumElts > ValueNumElts &&
626       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
627     EVT ElementVT = PartVT.getVectorElementType();
628     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
629     // undef elements.
630     SmallVector<SDValue, 16> Ops;
631     DAG.ExtractVectorElements(Val, Ops);
632     SDValue EltUndef = DAG.getUNDEF(ElementVT);
633     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
634       Ops.push_back(EltUndef);
635 
636     // FIXME: Use CONCAT for 2x -> 4x.
637     return DAG.getBuildVector(PartVT, DL, Ops);
638   }
639 
640   return SDValue();
641 }
642 
643 /// getCopyToPartsVector - Create a series of nodes that contain the specified
644 /// value split into legal parts.
645 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
646                                  SDValue Val, SDValue *Parts, unsigned NumParts,
647                                  MVT PartVT, const Value *V,
648                                  Optional<CallingConv::ID> CallConv) {
649   EVT ValueVT = Val.getValueType();
650   assert(ValueVT.isVector() && "Not a vector");
651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
652   const bool IsABIRegCopy = CallConv.hasValue();
653 
654   if (NumParts == 1) {
655     EVT PartEVT = PartVT;
656     if (PartEVT == ValueVT) {
657       // Nothing to do.
658     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
659       // Bitconvert vector->vector case.
660       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
661     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
662       Val = Widened;
663     } else if (PartVT.isVector() &&
664                PartEVT.getVectorElementType().bitsGE(
665                  ValueVT.getVectorElementType()) &&
666                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
667 
668       // Promoted vector extract
669       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
670     } else {
671       if (ValueVT.getVectorNumElements() == 1) {
672         Val = DAG.getNode(
673             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
674             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
675       } else {
676         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
677                "lossy conversion of vector to scalar type");
678         EVT IntermediateType =
679             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
680         Val = DAG.getBitcast(IntermediateType, Val);
681         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
682       }
683     }
684 
685     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
686     Parts[0] = Val;
687     return;
688   }
689 
690   // Handle a multi-element vector.
691   EVT IntermediateVT;
692   MVT RegisterVT;
693   unsigned NumIntermediates;
694   unsigned NumRegs;
695   if (IsABIRegCopy) {
696     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
697         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
698         NumIntermediates, RegisterVT);
699   } else {
700     NumRegs =
701         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
702                                    NumIntermediates, RegisterVT);
703   }
704   unsigned NumElements = ValueVT.getVectorNumElements();
705 
706   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
707   NumParts = NumRegs; // Silence a compiler warning.
708   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
709 
710   // Convert the vector to the appropiate type if necessary.
711   unsigned DestVectorNoElts =
712       NumIntermediates *
713       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
714   EVT BuiltVectorTy = EVT::getVectorVT(
715       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
716   if (Val.getValueType() != BuiltVectorTy)
717     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
718 
719   // Split the vector into intermediate operands.
720   SmallVector<SDValue, 8> Ops(NumIntermediates);
721   for (unsigned i = 0; i != NumIntermediates; ++i) {
722     if (IntermediateVT.isVector())
723       Ops[i] =
724           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
725                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
726                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
727     else
728       Ops[i] = DAG.getNode(
729           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
730           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
731   }
732 
733   // Split the intermediate operands into legal parts.
734   if (NumParts == NumIntermediates) {
735     // If the register was not expanded, promote or copy the value,
736     // as appropriate.
737     for (unsigned i = 0; i != NumParts; ++i)
738       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
739   } else if (NumParts > 0) {
740     // If the intermediate type was expanded, split each the value into
741     // legal parts.
742     assert(NumIntermediates != 0 && "division by zero");
743     assert(NumParts % NumIntermediates == 0 &&
744            "Must expand into a divisible number of parts!");
745     unsigned Factor = NumParts / NumIntermediates;
746     for (unsigned i = 0; i != NumIntermediates; ++i)
747       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
748                      CallConv);
749   }
750 }
751 
752 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
753                            EVT valuevt, Optional<CallingConv::ID> CC)
754     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
755       RegCount(1, regs.size()), CallConv(CC) {}
756 
757 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
758                            const DataLayout &DL, unsigned Reg, Type *Ty,
759                            Optional<CallingConv::ID> CC) {
760   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
761 
762   CallConv = CC;
763 
764   for (EVT ValueVT : ValueVTs) {
765     unsigned NumRegs =
766         isABIMangled()
767             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
768             : TLI.getNumRegisters(Context, ValueVT);
769     MVT RegisterVT =
770         isABIMangled()
771             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
772             : TLI.getRegisterType(Context, ValueVT);
773     for (unsigned i = 0; i != NumRegs; ++i)
774       Regs.push_back(Reg + i);
775     RegVTs.push_back(RegisterVT);
776     RegCount.push_back(NumRegs);
777     Reg += NumRegs;
778   }
779 }
780 
781 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
782                                       FunctionLoweringInfo &FuncInfo,
783                                       const SDLoc &dl, SDValue &Chain,
784                                       SDValue *Flag, const Value *V) const {
785   // A Value with type {} or [0 x %t] needs no registers.
786   if (ValueVTs.empty())
787     return SDValue();
788 
789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
790 
791   // Assemble the legal parts into the final values.
792   SmallVector<SDValue, 4> Values(ValueVTs.size());
793   SmallVector<SDValue, 8> Parts;
794   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
795     // Copy the legal parts from the registers.
796     EVT ValueVT = ValueVTs[Value];
797     unsigned NumRegs = RegCount[Value];
798     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
799                                           *DAG.getContext(),
800                                           CallConv.getValue(), RegVTs[Value])
801                                     : RegVTs[Value];
802 
803     Parts.resize(NumRegs);
804     for (unsigned i = 0; i != NumRegs; ++i) {
805       SDValue P;
806       if (!Flag) {
807         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
808       } else {
809         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
810         *Flag = P.getValue(2);
811       }
812 
813       Chain = P.getValue(1);
814       Parts[i] = P;
815 
816       // If the source register was virtual and if we know something about it,
817       // add an assert node.
818       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
819           !RegisterVT.isInteger() || RegisterVT.isVector())
820         continue;
821 
822       const FunctionLoweringInfo::LiveOutInfo *LOI =
823         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
824       if (!LOI)
825         continue;
826 
827       unsigned RegSize = RegisterVT.getSizeInBits();
828       unsigned NumSignBits = LOI->NumSignBits;
829       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
830 
831       if (NumZeroBits == RegSize) {
832         // The current value is a zero.
833         // Explicitly express that as it would be easier for
834         // optimizations to kick in.
835         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
836         continue;
837       }
838 
839       // FIXME: We capture more information than the dag can represent.  For
840       // now, just use the tightest assertzext/assertsext possible.
841       bool isSExt;
842       EVT FromVT(MVT::Other);
843       if (NumZeroBits) {
844         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
845         isSExt = false;
846       } else if (NumSignBits > 1) {
847         FromVT =
848             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
849         isSExt = true;
850       } else {
851         continue;
852       }
853       // Add an assertion node.
854       assert(FromVT != MVT::Other);
855       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
856                              RegisterVT, P, DAG.getValueType(FromVT));
857     }
858 
859     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
860                                      RegisterVT, ValueVT, V, CallConv);
861     Part += NumRegs;
862     Parts.clear();
863   }
864 
865   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
866 }
867 
868 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
869                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
870                                  const Value *V,
871                                  ISD::NodeType PreferredExtendType) const {
872   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
873   ISD::NodeType ExtendKind = PreferredExtendType;
874 
875   // Get the list of the values's legal parts.
876   unsigned NumRegs = Regs.size();
877   SmallVector<SDValue, 8> Parts(NumRegs);
878   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
879     unsigned NumParts = RegCount[Value];
880 
881     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
882                                           *DAG.getContext(),
883                                           CallConv.getValue(), RegVTs[Value])
884                                     : RegVTs[Value];
885 
886     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
887       ExtendKind = ISD::ZERO_EXTEND;
888 
889     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
890                    NumParts, RegisterVT, V, CallConv, ExtendKind);
891     Part += NumParts;
892   }
893 
894   // Copy the parts into the registers.
895   SmallVector<SDValue, 8> Chains(NumRegs);
896   for (unsigned i = 0; i != NumRegs; ++i) {
897     SDValue Part;
898     if (!Flag) {
899       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
900     } else {
901       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
902       *Flag = Part.getValue(1);
903     }
904 
905     Chains[i] = Part.getValue(0);
906   }
907 
908   if (NumRegs == 1 || Flag)
909     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
910     // flagged to it. That is the CopyToReg nodes and the user are considered
911     // a single scheduling unit. If we create a TokenFactor and return it as
912     // chain, then the TokenFactor is both a predecessor (operand) of the
913     // user as well as a successor (the TF operands are flagged to the user).
914     // c1, f1 = CopyToReg
915     // c2, f2 = CopyToReg
916     // c3     = TokenFactor c1, c2
917     // ...
918     //        = op c3, ..., f2
919     Chain = Chains[NumRegs-1];
920   else
921     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
922 }
923 
924 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
925                                         unsigned MatchingIdx, const SDLoc &dl,
926                                         SelectionDAG &DAG,
927                                         std::vector<SDValue> &Ops) const {
928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
929 
930   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
931   if (HasMatching)
932     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
933   else if (!Regs.empty() &&
934            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
935     // Put the register class of the virtual registers in the flag word.  That
936     // way, later passes can recompute register class constraints for inline
937     // assembly as well as normal instructions.
938     // Don't do this for tied operands that can use the regclass information
939     // from the def.
940     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
941     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
942     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
943   }
944 
945   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
946   Ops.push_back(Res);
947 
948   if (Code == InlineAsm::Kind_Clobber) {
949     // Clobbers should always have a 1:1 mapping with registers, and may
950     // reference registers that have illegal (e.g. vector) types. Hence, we
951     // shouldn't try to apply any sort of splitting logic to them.
952     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
953            "No 1:1 mapping from clobbers to regs?");
954     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
955     (void)SP;
956     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
957       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
958       assert(
959           (Regs[I] != SP ||
960            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
961           "If we clobbered the stack pointer, MFI should know about it.");
962     }
963     return;
964   }
965 
966   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
967     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
968     MVT RegisterVT = RegVTs[Value];
969     for (unsigned i = 0; i != NumRegs; ++i) {
970       assert(Reg < Regs.size() && "Mismatch in # registers expected");
971       unsigned TheReg = Regs[Reg++];
972       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
973     }
974   }
975 }
976 
977 SmallVector<std::pair<unsigned, unsigned>, 4>
978 RegsForValue::getRegsAndSizes() const {
979   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
980   unsigned I = 0;
981   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
982     unsigned RegCount = std::get<0>(CountAndVT);
983     MVT RegisterVT = std::get<1>(CountAndVT);
984     unsigned RegisterSize = RegisterVT.getSizeInBits();
985     for (unsigned E = I + RegCount; I != E; ++I)
986       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
987   }
988   return OutVec;
989 }
990 
991 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
992                                const TargetLibraryInfo *li) {
993   AA = aa;
994   GFI = gfi;
995   LibInfo = li;
996   DL = &DAG.getDataLayout();
997   Context = DAG.getContext();
998   LPadToCallSiteMap.clear();
999 }
1000 
1001 void SelectionDAGBuilder::clear() {
1002   NodeMap.clear();
1003   UnusedArgNodeMap.clear();
1004   PendingLoads.clear();
1005   PendingExports.clear();
1006   CurInst = nullptr;
1007   HasTailCall = false;
1008   SDNodeOrder = LowestSDNodeOrder;
1009   StatepointLowering.clear();
1010 }
1011 
1012 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1013   DanglingDebugInfoMap.clear();
1014 }
1015 
1016 SDValue SelectionDAGBuilder::getRoot() {
1017   if (PendingLoads.empty())
1018     return DAG.getRoot();
1019 
1020   if (PendingLoads.size() == 1) {
1021     SDValue Root = PendingLoads[0];
1022     DAG.setRoot(Root);
1023     PendingLoads.clear();
1024     return Root;
1025   }
1026 
1027   // Otherwise, we have to make a token factor node.
1028   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1029                              PendingLoads);
1030   PendingLoads.clear();
1031   DAG.setRoot(Root);
1032   return Root;
1033 }
1034 
1035 SDValue SelectionDAGBuilder::getControlRoot() {
1036   SDValue Root = DAG.getRoot();
1037 
1038   if (PendingExports.empty())
1039     return Root;
1040 
1041   // Turn all of the CopyToReg chains into one factored node.
1042   if (Root.getOpcode() != ISD::EntryToken) {
1043     unsigned i = 0, e = PendingExports.size();
1044     for (; i != e; ++i) {
1045       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1046       if (PendingExports[i].getNode()->getOperand(0) == Root)
1047         break;  // Don't add the root if we already indirectly depend on it.
1048     }
1049 
1050     if (i == e)
1051       PendingExports.push_back(Root);
1052   }
1053 
1054   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1055                      PendingExports);
1056   PendingExports.clear();
1057   DAG.setRoot(Root);
1058   return Root;
1059 }
1060 
1061 void SelectionDAGBuilder::visit(const Instruction &I) {
1062   // Set up outgoing PHI node register values before emitting the terminator.
1063   if (I.isTerminator()) {
1064     HandlePHINodesInSuccessorBlocks(I.getParent());
1065   }
1066 
1067   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1068   if (!isa<DbgInfoIntrinsic>(I))
1069     ++SDNodeOrder;
1070 
1071   CurInst = &I;
1072 
1073   visit(I.getOpcode(), I);
1074 
1075   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1076     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1077     // maps to this instruction.
1078     // TODO: We could handle all flags (nsw, etc) here.
1079     // TODO: If an IR instruction maps to >1 node, only the final node will have
1080     //       flags set.
1081     if (SDNode *Node = getNodeForIRValue(&I)) {
1082       SDNodeFlags IncomingFlags;
1083       IncomingFlags.copyFMF(*FPMO);
1084       if (!Node->getFlags().isDefined())
1085         Node->setFlags(IncomingFlags);
1086       else
1087         Node->intersectFlagsWith(IncomingFlags);
1088     }
1089   }
1090 
1091   if (!I.isTerminator() && !HasTailCall &&
1092       !isStatepoint(&I)) // statepoints handle their exports internally
1093     CopyToExportRegsIfNeeded(&I);
1094 
1095   CurInst = nullptr;
1096 }
1097 
1098 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1099   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1100 }
1101 
1102 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1103   // Note: this doesn't use InstVisitor, because it has to work with
1104   // ConstantExpr's in addition to instructions.
1105   switch (Opcode) {
1106   default: llvm_unreachable("Unknown instruction type encountered!");
1107     // Build the switch statement using the Instruction.def file.
1108 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1109     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1110 #include "llvm/IR/Instruction.def"
1111   }
1112 }
1113 
1114 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1115                                                 const DIExpression *Expr) {
1116   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1117     const DbgValueInst *DI = DDI.getDI();
1118     DIVariable *DanglingVariable = DI->getVariable();
1119     DIExpression *DanglingExpr = DI->getExpression();
1120     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1121       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1122       return true;
1123     }
1124     return false;
1125   };
1126 
1127   for (auto &DDIMI : DanglingDebugInfoMap) {
1128     DanglingDebugInfoVector &DDIV = DDIMI.second;
1129     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1130   }
1131 }
1132 
1133 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1134 // generate the debug data structures now that we've seen its definition.
1135 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1136                                                    SDValue Val) {
1137   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1138   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1139     return;
1140 
1141   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1142   for (auto &DDI : DDIV) {
1143     const DbgValueInst *DI = DDI.getDI();
1144     assert(DI && "Ill-formed DanglingDebugInfo");
1145     DebugLoc dl = DDI.getdl();
1146     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1147     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1148     DILocalVariable *Variable = DI->getVariable();
1149     DIExpression *Expr = DI->getExpression();
1150     assert(Variable->isValidLocationForIntrinsic(dl) &&
1151            "Expected inlined-at fields to agree");
1152     SDDbgValue *SDV;
1153     if (Val.getNode()) {
1154       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1155         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1156                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1157         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1158         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1159         // inserted after the definition of Val when emitting the instructions
1160         // after ISel. An alternative could be to teach
1161         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1162         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1163                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1164                    << ValSDNodeOrder << "\n");
1165         SDV = getDbgValue(Val, Variable, Expr, dl,
1166                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1167         DAG.AddDbgValue(SDV, Val.getNode(), false);
1168       } else
1169         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1170                           << "in EmitFuncArgumentDbgValue\n");
1171     } else
1172       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1173   }
1174   DDIV.clear();
1175 }
1176 
1177 /// getCopyFromRegs - If there was virtual register allocated for the value V
1178 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1179 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1180   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1181   SDValue Result;
1182 
1183   if (It != FuncInfo.ValueMap.end()) {
1184     unsigned InReg = It->second;
1185 
1186     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1187                      DAG.getDataLayout(), InReg, Ty,
1188                      None); // This is not an ABI copy.
1189     SDValue Chain = DAG.getEntryNode();
1190     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1191                                  V);
1192     resolveDanglingDebugInfo(V, Result);
1193   }
1194 
1195   return Result;
1196 }
1197 
1198 /// getValue - Return an SDValue for the given Value.
1199 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1200   // If we already have an SDValue for this value, use it. It's important
1201   // to do this first, so that we don't create a CopyFromReg if we already
1202   // have a regular SDValue.
1203   SDValue &N = NodeMap[V];
1204   if (N.getNode()) return N;
1205 
1206   // If there's a virtual register allocated and initialized for this
1207   // value, use it.
1208   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1209     return copyFromReg;
1210 
1211   // Otherwise create a new SDValue and remember it.
1212   SDValue Val = getValueImpl(V);
1213   NodeMap[V] = Val;
1214   resolveDanglingDebugInfo(V, Val);
1215   return Val;
1216 }
1217 
1218 // Return true if SDValue exists for the given Value
1219 bool SelectionDAGBuilder::findValue(const Value *V) const {
1220   return (NodeMap.find(V) != NodeMap.end()) ||
1221     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1222 }
1223 
1224 /// getNonRegisterValue - Return an SDValue for the given Value, but
1225 /// don't look in FuncInfo.ValueMap for a virtual register.
1226 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1227   // If we already have an SDValue for this value, use it.
1228   SDValue &N = NodeMap[V];
1229   if (N.getNode()) {
1230     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1231       // Remove the debug location from the node as the node is about to be used
1232       // in a location which may differ from the original debug location.  This
1233       // is relevant to Constant and ConstantFP nodes because they can appear
1234       // as constant expressions inside PHI nodes.
1235       N->setDebugLoc(DebugLoc());
1236     }
1237     return N;
1238   }
1239 
1240   // Otherwise create a new SDValue and remember it.
1241   SDValue Val = getValueImpl(V);
1242   NodeMap[V] = Val;
1243   resolveDanglingDebugInfo(V, Val);
1244   return Val;
1245 }
1246 
1247 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1248 /// Create an SDValue for the given value.
1249 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1251 
1252   if (const Constant *C = dyn_cast<Constant>(V)) {
1253     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1254 
1255     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1256       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1257 
1258     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1259       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1260 
1261     if (isa<ConstantPointerNull>(C)) {
1262       unsigned AS = V->getType()->getPointerAddressSpace();
1263       return DAG.getConstant(0, getCurSDLoc(),
1264                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1265     }
1266 
1267     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1268       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1269 
1270     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1271       return DAG.getUNDEF(VT);
1272 
1273     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1274       visit(CE->getOpcode(), *CE);
1275       SDValue N1 = NodeMap[V];
1276       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1277       return N1;
1278     }
1279 
1280     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1281       SmallVector<SDValue, 4> Constants;
1282       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1283            OI != OE; ++OI) {
1284         SDNode *Val = getValue(*OI).getNode();
1285         // If the operand is an empty aggregate, there are no values.
1286         if (!Val) continue;
1287         // Add each leaf value from the operand to the Constants list
1288         // to form a flattened list of all the values.
1289         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1290           Constants.push_back(SDValue(Val, i));
1291       }
1292 
1293       return DAG.getMergeValues(Constants, getCurSDLoc());
1294     }
1295 
1296     if (const ConstantDataSequential *CDS =
1297           dyn_cast<ConstantDataSequential>(C)) {
1298       SmallVector<SDValue, 4> Ops;
1299       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1300         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1301         // Add each leaf value from the operand to the Constants list
1302         // to form a flattened list of all the values.
1303         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1304           Ops.push_back(SDValue(Val, i));
1305       }
1306 
1307       if (isa<ArrayType>(CDS->getType()))
1308         return DAG.getMergeValues(Ops, getCurSDLoc());
1309       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1310     }
1311 
1312     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1313       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1314              "Unknown struct or array constant!");
1315 
1316       SmallVector<EVT, 4> ValueVTs;
1317       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1318       unsigned NumElts = ValueVTs.size();
1319       if (NumElts == 0)
1320         return SDValue(); // empty struct
1321       SmallVector<SDValue, 4> Constants(NumElts);
1322       for (unsigned i = 0; i != NumElts; ++i) {
1323         EVT EltVT = ValueVTs[i];
1324         if (isa<UndefValue>(C))
1325           Constants[i] = DAG.getUNDEF(EltVT);
1326         else if (EltVT.isFloatingPoint())
1327           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1328         else
1329           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1330       }
1331 
1332       return DAG.getMergeValues(Constants, getCurSDLoc());
1333     }
1334 
1335     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1336       return DAG.getBlockAddress(BA, VT);
1337 
1338     VectorType *VecTy = cast<VectorType>(V->getType());
1339     unsigned NumElements = VecTy->getNumElements();
1340 
1341     // Now that we know the number and type of the elements, get that number of
1342     // elements into the Ops array based on what kind of constant it is.
1343     SmallVector<SDValue, 16> Ops;
1344     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1345       for (unsigned i = 0; i != NumElements; ++i)
1346         Ops.push_back(getValue(CV->getOperand(i)));
1347     } else {
1348       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1349       EVT EltVT =
1350           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1351 
1352       SDValue Op;
1353       if (EltVT.isFloatingPoint())
1354         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1355       else
1356         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1357       Ops.assign(NumElements, Op);
1358     }
1359 
1360     // Create a BUILD_VECTOR node.
1361     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1362   }
1363 
1364   // If this is a static alloca, generate it as the frameindex instead of
1365   // computation.
1366   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1367     DenseMap<const AllocaInst*, int>::iterator SI =
1368       FuncInfo.StaticAllocaMap.find(AI);
1369     if (SI != FuncInfo.StaticAllocaMap.end())
1370       return DAG.getFrameIndex(SI->second,
1371                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1372   }
1373 
1374   // If this is an instruction which fast-isel has deferred, select it now.
1375   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1376     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1377 
1378     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1379                      Inst->getType(), getABIRegCopyCC(V));
1380     SDValue Chain = DAG.getEntryNode();
1381     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1382   }
1383 
1384   llvm_unreachable("Can't get register for value!");
1385 }
1386 
1387 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1388   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1389   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1390   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1391   bool IsSEH = isAsynchronousEHPersonality(Pers);
1392   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1393   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1394   if (!IsSEH)
1395     CatchPadMBB->setIsEHScopeEntry();
1396   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1397   if (IsMSVCCXX || IsCoreCLR)
1398     CatchPadMBB->setIsEHFuncletEntry();
1399   // Wasm does not need catchpads anymore
1400   if (!IsWasmCXX)
1401     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1402                             getControlRoot()));
1403 }
1404 
1405 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1406   // Update machine-CFG edge.
1407   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1408   FuncInfo.MBB->addSuccessor(TargetMBB);
1409 
1410   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1411   bool IsSEH = isAsynchronousEHPersonality(Pers);
1412   if (IsSEH) {
1413     // If this is not a fall-through branch or optimizations are switched off,
1414     // emit the branch.
1415     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1416         TM.getOptLevel() == CodeGenOpt::None)
1417       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1418                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1419     return;
1420   }
1421 
1422   // Figure out the funclet membership for the catchret's successor.
1423   // This will be used by the FuncletLayout pass to determine how to order the
1424   // BB's.
1425   // A 'catchret' returns to the outer scope's color.
1426   Value *ParentPad = I.getCatchSwitchParentPad();
1427   const BasicBlock *SuccessorColor;
1428   if (isa<ConstantTokenNone>(ParentPad))
1429     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1430   else
1431     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1432   assert(SuccessorColor && "No parent funclet for catchret!");
1433   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1434   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1435 
1436   // Create the terminator node.
1437   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1438                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1439                             DAG.getBasicBlock(SuccessorColorMBB));
1440   DAG.setRoot(Ret);
1441 }
1442 
1443 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1444   // Don't emit any special code for the cleanuppad instruction. It just marks
1445   // the start of an EH scope/funclet.
1446   FuncInfo.MBB->setIsEHScopeEntry();
1447   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1448   if (Pers != EHPersonality::Wasm_CXX) {
1449     FuncInfo.MBB->setIsEHFuncletEntry();
1450     FuncInfo.MBB->setIsCleanupFuncletEntry();
1451   }
1452 }
1453 
1454 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1455 /// many places it could ultimately go. In the IR, we have a single unwind
1456 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1457 /// This function skips over imaginary basic blocks that hold catchswitch
1458 /// instructions, and finds all the "real" machine
1459 /// basic block destinations. As those destinations may not be successors of
1460 /// EHPadBB, here we also calculate the edge probability to those destinations.
1461 /// The passed-in Prob is the edge probability to EHPadBB.
1462 static void findUnwindDestinations(
1463     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1464     BranchProbability Prob,
1465     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1466         &UnwindDests) {
1467   EHPersonality Personality =
1468     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1469   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1470   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1471   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1472   bool IsSEH = isAsynchronousEHPersonality(Personality);
1473 
1474   while (EHPadBB) {
1475     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1476     BasicBlock *NewEHPadBB = nullptr;
1477     if (isa<LandingPadInst>(Pad)) {
1478       // Stop on landingpads. They are not funclets.
1479       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1480       break;
1481     } else if (isa<CleanupPadInst>(Pad)) {
1482       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1483       // personalities.
1484       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1485       UnwindDests.back().first->setIsEHScopeEntry();
1486       if (!IsWasmCXX)
1487         UnwindDests.back().first->setIsEHFuncletEntry();
1488       break;
1489     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1490       // Add the catchpad handlers to the possible destinations.
1491       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1492         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1493         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1494         if (IsMSVCCXX || IsCoreCLR)
1495           UnwindDests.back().first->setIsEHFuncletEntry();
1496         if (!IsSEH)
1497           UnwindDests.back().first->setIsEHScopeEntry();
1498       }
1499       NewEHPadBB = CatchSwitch->getUnwindDest();
1500     } else {
1501       continue;
1502     }
1503 
1504     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1505     if (BPI && NewEHPadBB)
1506       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1507     EHPadBB = NewEHPadBB;
1508   }
1509 }
1510 
1511 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1512   // Update successor info.
1513   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1514   auto UnwindDest = I.getUnwindDest();
1515   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1516   BranchProbability UnwindDestProb =
1517       (BPI && UnwindDest)
1518           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1519           : BranchProbability::getZero();
1520   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1521   for (auto &UnwindDest : UnwindDests) {
1522     UnwindDest.first->setIsEHPad();
1523     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1524   }
1525   FuncInfo.MBB->normalizeSuccProbs();
1526 
1527   // Create the terminator node.
1528   SDValue Ret =
1529       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1530   DAG.setRoot(Ret);
1531 }
1532 
1533 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1534   report_fatal_error("visitCatchSwitch not yet implemented!");
1535 }
1536 
1537 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1539   auto &DL = DAG.getDataLayout();
1540   SDValue Chain = getControlRoot();
1541   SmallVector<ISD::OutputArg, 8> Outs;
1542   SmallVector<SDValue, 8> OutVals;
1543 
1544   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1545   // lower
1546   //
1547   //   %val = call <ty> @llvm.experimental.deoptimize()
1548   //   ret <ty> %val
1549   //
1550   // differently.
1551   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1552     LowerDeoptimizingReturn();
1553     return;
1554   }
1555 
1556   if (!FuncInfo.CanLowerReturn) {
1557     unsigned DemoteReg = FuncInfo.DemoteRegister;
1558     const Function *F = I.getParent()->getParent();
1559 
1560     // Emit a store of the return value through the virtual register.
1561     // Leave Outs empty so that LowerReturn won't try to load return
1562     // registers the usual way.
1563     SmallVector<EVT, 1> PtrValueVTs;
1564     ComputeValueVTs(TLI, DL,
1565                     F->getReturnType()->getPointerTo(
1566                         DAG.getDataLayout().getAllocaAddrSpace()),
1567                     PtrValueVTs);
1568 
1569     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1570                                         DemoteReg, PtrValueVTs[0]);
1571     SDValue RetOp = getValue(I.getOperand(0));
1572 
1573     SmallVector<EVT, 4> ValueVTs;
1574     SmallVector<uint64_t, 4> Offsets;
1575     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1576     unsigned NumValues = ValueVTs.size();
1577 
1578     SmallVector<SDValue, 4> Chains(NumValues);
1579     for (unsigned i = 0; i != NumValues; ++i) {
1580       // An aggregate return value cannot wrap around the address space, so
1581       // offsets to its parts don't wrap either.
1582       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1583       Chains[i] = DAG.getStore(
1584           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1585           // FIXME: better loc info would be nice.
1586           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1587     }
1588 
1589     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1590                         MVT::Other, Chains);
1591   } else if (I.getNumOperands() != 0) {
1592     SmallVector<EVT, 4> ValueVTs;
1593     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1594     unsigned NumValues = ValueVTs.size();
1595     if (NumValues) {
1596       SDValue RetOp = getValue(I.getOperand(0));
1597 
1598       const Function *F = I.getParent()->getParent();
1599 
1600       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1601       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1602                                           Attribute::SExt))
1603         ExtendKind = ISD::SIGN_EXTEND;
1604       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1605                                                Attribute::ZExt))
1606         ExtendKind = ISD::ZERO_EXTEND;
1607 
1608       LLVMContext &Context = F->getContext();
1609       bool RetInReg = F->getAttributes().hasAttribute(
1610           AttributeList::ReturnIndex, Attribute::InReg);
1611 
1612       for (unsigned j = 0; j != NumValues; ++j) {
1613         EVT VT = ValueVTs[j];
1614 
1615         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1616           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1617 
1618         CallingConv::ID CC = F->getCallingConv();
1619 
1620         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1621         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1622         SmallVector<SDValue, 4> Parts(NumParts);
1623         getCopyToParts(DAG, getCurSDLoc(),
1624                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1625                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1626 
1627         // 'inreg' on function refers to return value
1628         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1629         if (RetInReg)
1630           Flags.setInReg();
1631 
1632         // Propagate extension type if any
1633         if (ExtendKind == ISD::SIGN_EXTEND)
1634           Flags.setSExt();
1635         else if (ExtendKind == ISD::ZERO_EXTEND)
1636           Flags.setZExt();
1637 
1638         for (unsigned i = 0; i < NumParts; ++i) {
1639           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1640                                         VT, /*isfixed=*/true, 0, 0));
1641           OutVals.push_back(Parts[i]);
1642         }
1643       }
1644     }
1645   }
1646 
1647   // Push in swifterror virtual register as the last element of Outs. This makes
1648   // sure swifterror virtual register will be returned in the swifterror
1649   // physical register.
1650   const Function *F = I.getParent()->getParent();
1651   if (TLI.supportSwiftError() &&
1652       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1653     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1654     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1655     Flags.setSwiftError();
1656     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1657                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1658                                   true /*isfixed*/, 1 /*origidx*/,
1659                                   0 /*partOffs*/));
1660     // Create SDNode for the swifterror virtual register.
1661     OutVals.push_back(
1662         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1663                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1664                         EVT(TLI.getPointerTy(DL))));
1665   }
1666 
1667   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1668   CallingConv::ID CallConv =
1669     DAG.getMachineFunction().getFunction().getCallingConv();
1670   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1671       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1672 
1673   // Verify that the target's LowerReturn behaved as expected.
1674   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1675          "LowerReturn didn't return a valid chain!");
1676 
1677   // Update the DAG with the new chain value resulting from return lowering.
1678   DAG.setRoot(Chain);
1679 }
1680 
1681 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1682 /// created for it, emit nodes to copy the value into the virtual
1683 /// registers.
1684 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1685   // Skip empty types
1686   if (V->getType()->isEmptyTy())
1687     return;
1688 
1689   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1690   if (VMI != FuncInfo.ValueMap.end()) {
1691     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1692     CopyValueToVirtualRegister(V, VMI->second);
1693   }
1694 }
1695 
1696 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1697 /// the current basic block, add it to ValueMap now so that we'll get a
1698 /// CopyTo/FromReg.
1699 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1700   // No need to export constants.
1701   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1702 
1703   // Already exported?
1704   if (FuncInfo.isExportedInst(V)) return;
1705 
1706   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1707   CopyValueToVirtualRegister(V, Reg);
1708 }
1709 
1710 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1711                                                      const BasicBlock *FromBB) {
1712   // The operands of the setcc have to be in this block.  We don't know
1713   // how to export them from some other block.
1714   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1715     // Can export from current BB.
1716     if (VI->getParent() == FromBB)
1717       return true;
1718 
1719     // Is already exported, noop.
1720     return FuncInfo.isExportedInst(V);
1721   }
1722 
1723   // If this is an argument, we can export it if the BB is the entry block or
1724   // if it is already exported.
1725   if (isa<Argument>(V)) {
1726     if (FromBB == &FromBB->getParent()->getEntryBlock())
1727       return true;
1728 
1729     // Otherwise, can only export this if it is already exported.
1730     return FuncInfo.isExportedInst(V);
1731   }
1732 
1733   // Otherwise, constants can always be exported.
1734   return true;
1735 }
1736 
1737 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1738 BranchProbability
1739 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1740                                         const MachineBasicBlock *Dst) const {
1741   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1742   const BasicBlock *SrcBB = Src->getBasicBlock();
1743   const BasicBlock *DstBB = Dst->getBasicBlock();
1744   if (!BPI) {
1745     // If BPI is not available, set the default probability as 1 / N, where N is
1746     // the number of successors.
1747     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1748     return BranchProbability(1, SuccSize);
1749   }
1750   return BPI->getEdgeProbability(SrcBB, DstBB);
1751 }
1752 
1753 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1754                                                MachineBasicBlock *Dst,
1755                                                BranchProbability Prob) {
1756   if (!FuncInfo.BPI)
1757     Src->addSuccessorWithoutProb(Dst);
1758   else {
1759     if (Prob.isUnknown())
1760       Prob = getEdgeProbability(Src, Dst);
1761     Src->addSuccessor(Dst, Prob);
1762   }
1763 }
1764 
1765 static bool InBlock(const Value *V, const BasicBlock *BB) {
1766   if (const Instruction *I = dyn_cast<Instruction>(V))
1767     return I->getParent() == BB;
1768   return true;
1769 }
1770 
1771 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1772 /// This function emits a branch and is used at the leaves of an OR or an
1773 /// AND operator tree.
1774 void
1775 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1776                                                   MachineBasicBlock *TBB,
1777                                                   MachineBasicBlock *FBB,
1778                                                   MachineBasicBlock *CurBB,
1779                                                   MachineBasicBlock *SwitchBB,
1780                                                   BranchProbability TProb,
1781                                                   BranchProbability FProb,
1782                                                   bool InvertCond) {
1783   const BasicBlock *BB = CurBB->getBasicBlock();
1784 
1785   // If the leaf of the tree is a comparison, merge the condition into
1786   // the caseblock.
1787   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1788     // The operands of the cmp have to be in this block.  We don't know
1789     // how to export them from some other block.  If this is the first block
1790     // of the sequence, no exporting is needed.
1791     if (CurBB == SwitchBB ||
1792         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1793          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1794       ISD::CondCode Condition;
1795       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1796         ICmpInst::Predicate Pred =
1797             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1798         Condition = getICmpCondCode(Pred);
1799       } else {
1800         const FCmpInst *FC = cast<FCmpInst>(Cond);
1801         FCmpInst::Predicate Pred =
1802             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1803         Condition = getFCmpCondCode(Pred);
1804         if (TM.Options.NoNaNsFPMath)
1805           Condition = getFCmpCodeWithoutNaN(Condition);
1806       }
1807 
1808       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1809                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1810       SwitchCases.push_back(CB);
1811       return;
1812     }
1813   }
1814 
1815   // Create a CaseBlock record representing this branch.
1816   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1817   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1818                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1819   SwitchCases.push_back(CB);
1820 }
1821 
1822 /// FindMergedConditions - If Cond is an expression like
1823 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1824                                                MachineBasicBlock *TBB,
1825                                                MachineBasicBlock *FBB,
1826                                                MachineBasicBlock *CurBB,
1827                                                MachineBasicBlock *SwitchBB,
1828                                                Instruction::BinaryOps Opc,
1829                                                BranchProbability TProb,
1830                                                BranchProbability FProb,
1831                                                bool InvertCond) {
1832   // Skip over not part of the tree and remember to invert op and operands at
1833   // next level.
1834   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1835     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1836     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1837       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1838                            !InvertCond);
1839       return;
1840     }
1841   }
1842 
1843   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1844   // Compute the effective opcode for Cond, taking into account whether it needs
1845   // to be inverted, e.g.
1846   //   and (not (or A, B)), C
1847   // gets lowered as
1848   //   and (and (not A, not B), C)
1849   unsigned BOpc = 0;
1850   if (BOp) {
1851     BOpc = BOp->getOpcode();
1852     if (InvertCond) {
1853       if (BOpc == Instruction::And)
1854         BOpc = Instruction::Or;
1855       else if (BOpc == Instruction::Or)
1856         BOpc = Instruction::And;
1857     }
1858   }
1859 
1860   // If this node is not part of the or/and tree, emit it as a branch.
1861   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1862       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1863       BOp->getParent() != CurBB->getBasicBlock() ||
1864       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1865       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1866     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1867                                  TProb, FProb, InvertCond);
1868     return;
1869   }
1870 
1871   //  Create TmpBB after CurBB.
1872   MachineFunction::iterator BBI(CurBB);
1873   MachineFunction &MF = DAG.getMachineFunction();
1874   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1875   CurBB->getParent()->insert(++BBI, TmpBB);
1876 
1877   if (Opc == Instruction::Or) {
1878     // Codegen X | Y as:
1879     // BB1:
1880     //   jmp_if_X TBB
1881     //   jmp TmpBB
1882     // TmpBB:
1883     //   jmp_if_Y TBB
1884     //   jmp FBB
1885     //
1886 
1887     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1888     // The requirement is that
1889     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1890     //     = TrueProb for original BB.
1891     // Assuming the original probabilities are A and B, one choice is to set
1892     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1893     // A/(1+B) and 2B/(1+B). This choice assumes that
1894     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1895     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1896     // TmpBB, but the math is more complicated.
1897 
1898     auto NewTrueProb = TProb / 2;
1899     auto NewFalseProb = TProb / 2 + FProb;
1900     // Emit the LHS condition.
1901     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1902                          NewTrueProb, NewFalseProb, InvertCond);
1903 
1904     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1905     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1906     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1907     // Emit the RHS condition into TmpBB.
1908     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1909                          Probs[0], Probs[1], InvertCond);
1910   } else {
1911     assert(Opc == Instruction::And && "Unknown merge op!");
1912     // Codegen X & Y as:
1913     // BB1:
1914     //   jmp_if_X TmpBB
1915     //   jmp FBB
1916     // TmpBB:
1917     //   jmp_if_Y TBB
1918     //   jmp FBB
1919     //
1920     //  This requires creation of TmpBB after CurBB.
1921 
1922     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1923     // The requirement is that
1924     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1925     //     = FalseProb for original BB.
1926     // Assuming the original probabilities are A and B, one choice is to set
1927     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1928     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1929     // TrueProb for BB1 * FalseProb for TmpBB.
1930 
1931     auto NewTrueProb = TProb + FProb / 2;
1932     auto NewFalseProb = FProb / 2;
1933     // Emit the LHS condition.
1934     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1935                          NewTrueProb, NewFalseProb, InvertCond);
1936 
1937     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1938     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1939     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1940     // Emit the RHS condition into TmpBB.
1941     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1942                          Probs[0], Probs[1], InvertCond);
1943   }
1944 }
1945 
1946 /// If the set of cases should be emitted as a series of branches, return true.
1947 /// If we should emit this as a bunch of and/or'd together conditions, return
1948 /// false.
1949 bool
1950 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1951   if (Cases.size() != 2) return true;
1952 
1953   // If this is two comparisons of the same values or'd or and'd together, they
1954   // will get folded into a single comparison, so don't emit two blocks.
1955   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1956        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1957       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1958        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1959     return false;
1960   }
1961 
1962   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1963   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1964   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1965       Cases[0].CC == Cases[1].CC &&
1966       isa<Constant>(Cases[0].CmpRHS) &&
1967       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1968     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1969       return false;
1970     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1971       return false;
1972   }
1973 
1974   return true;
1975 }
1976 
1977 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1978   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1979 
1980   // Update machine-CFG edges.
1981   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1982 
1983   if (I.isUnconditional()) {
1984     // Update machine-CFG edges.
1985     BrMBB->addSuccessor(Succ0MBB);
1986 
1987     // If this is not a fall-through branch or optimizations are switched off,
1988     // emit the branch.
1989     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1990       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1991                               MVT::Other, getControlRoot(),
1992                               DAG.getBasicBlock(Succ0MBB)));
1993 
1994     return;
1995   }
1996 
1997   // If this condition is one of the special cases we handle, do special stuff
1998   // now.
1999   const Value *CondVal = I.getCondition();
2000   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2001 
2002   // If this is a series of conditions that are or'd or and'd together, emit
2003   // this as a sequence of branches instead of setcc's with and/or operations.
2004   // As long as jumps are not expensive, this should improve performance.
2005   // For example, instead of something like:
2006   //     cmp A, B
2007   //     C = seteq
2008   //     cmp D, E
2009   //     F = setle
2010   //     or C, F
2011   //     jnz foo
2012   // Emit:
2013   //     cmp A, B
2014   //     je foo
2015   //     cmp D, E
2016   //     jle foo
2017   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2018     Instruction::BinaryOps Opcode = BOp->getOpcode();
2019     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2020         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2021         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2022       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2023                            Opcode,
2024                            getEdgeProbability(BrMBB, Succ0MBB),
2025                            getEdgeProbability(BrMBB, Succ1MBB),
2026                            /*InvertCond=*/false);
2027       // If the compares in later blocks need to use values not currently
2028       // exported from this block, export them now.  This block should always
2029       // be the first entry.
2030       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2031 
2032       // Allow some cases to be rejected.
2033       if (ShouldEmitAsBranches(SwitchCases)) {
2034         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2035           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2036           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2037         }
2038 
2039         // Emit the branch for this block.
2040         visitSwitchCase(SwitchCases[0], BrMBB);
2041         SwitchCases.erase(SwitchCases.begin());
2042         return;
2043       }
2044 
2045       // Okay, we decided not to do this, remove any inserted MBB's and clear
2046       // SwitchCases.
2047       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2048         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2049 
2050       SwitchCases.clear();
2051     }
2052   }
2053 
2054   // Create a CaseBlock record representing this branch.
2055   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2056                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2057 
2058   // Use visitSwitchCase to actually insert the fast branch sequence for this
2059   // cond branch.
2060   visitSwitchCase(CB, BrMBB);
2061 }
2062 
2063 /// visitSwitchCase - Emits the necessary code to represent a single node in
2064 /// the binary search tree resulting from lowering a switch instruction.
2065 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2066                                           MachineBasicBlock *SwitchBB) {
2067   SDValue Cond;
2068   SDValue CondLHS = getValue(CB.CmpLHS);
2069   SDLoc dl = CB.DL;
2070 
2071   // Build the setcc now.
2072   if (!CB.CmpMHS) {
2073     // Fold "(X == true)" to X and "(X == false)" to !X to
2074     // handle common cases produced by branch lowering.
2075     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2076         CB.CC == ISD::SETEQ)
2077       Cond = CondLHS;
2078     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2079              CB.CC == ISD::SETEQ) {
2080       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2081       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2082     } else
2083       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2084   } else {
2085     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2086 
2087     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2088     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2089 
2090     SDValue CmpOp = getValue(CB.CmpMHS);
2091     EVT VT = CmpOp.getValueType();
2092 
2093     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2094       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2095                           ISD::SETLE);
2096     } else {
2097       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2098                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2099       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2100                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2101     }
2102   }
2103 
2104   // Update successor info
2105   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2106   // TrueBB and FalseBB are always different unless the incoming IR is
2107   // degenerate. This only happens when running llc on weird IR.
2108   if (CB.TrueBB != CB.FalseBB)
2109     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2110   SwitchBB->normalizeSuccProbs();
2111 
2112   // If the lhs block is the next block, invert the condition so that we can
2113   // fall through to the lhs instead of the rhs block.
2114   if (CB.TrueBB == NextBlock(SwitchBB)) {
2115     std::swap(CB.TrueBB, CB.FalseBB);
2116     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2117     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2118   }
2119 
2120   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2121                                MVT::Other, getControlRoot(), Cond,
2122                                DAG.getBasicBlock(CB.TrueBB));
2123 
2124   // Insert the false branch. Do this even if it's a fall through branch,
2125   // this makes it easier to do DAG optimizations which require inverting
2126   // the branch condition.
2127   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2128                        DAG.getBasicBlock(CB.FalseBB));
2129 
2130   DAG.setRoot(BrCond);
2131 }
2132 
2133 /// visitJumpTable - Emit JumpTable node in the current MBB
2134 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2135   // Emit the code for the jump table
2136   assert(JT.Reg != -1U && "Should lower JT Header first!");
2137   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2138   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2139                                      JT.Reg, PTy);
2140   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2141   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2142                                     MVT::Other, Index.getValue(1),
2143                                     Table, Index);
2144   DAG.setRoot(BrJumpTable);
2145 }
2146 
2147 /// visitJumpTableHeader - This function emits necessary code to produce index
2148 /// in the JumpTable from switch case.
2149 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2150                                                JumpTableHeader &JTH,
2151                                                MachineBasicBlock *SwitchBB) {
2152   SDLoc dl = getCurSDLoc();
2153 
2154   // Subtract the lowest switch case value from the value being switched on and
2155   // conditional branch to default mbb if the result is greater than the
2156   // difference between smallest and largest cases.
2157   SDValue SwitchOp = getValue(JTH.SValue);
2158   EVT VT = SwitchOp.getValueType();
2159   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2160                             DAG.getConstant(JTH.First, dl, VT));
2161 
2162   // The SDNode we just created, which holds the value being switched on minus
2163   // the smallest case value, needs to be copied to a virtual register so it
2164   // can be used as an index into the jump table in a subsequent basic block.
2165   // This value may be smaller or larger than the target's pointer type, and
2166   // therefore require extension or truncating.
2167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2168   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2169 
2170   unsigned JumpTableReg =
2171       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2172   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2173                                     JumpTableReg, SwitchOp);
2174   JT.Reg = JumpTableReg;
2175 
2176   // Emit the range check for the jump table, and branch to the default block
2177   // for the switch statement if the value being switched on exceeds the largest
2178   // case in the switch.
2179   SDValue CMP = DAG.getSetCC(
2180       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2181                                  Sub.getValueType()),
2182       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2183 
2184   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2185                                MVT::Other, CopyTo, CMP,
2186                                DAG.getBasicBlock(JT.Default));
2187 
2188   // Avoid emitting unnecessary branches to the next block.
2189   if (JT.MBB != NextBlock(SwitchBB))
2190     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2191                          DAG.getBasicBlock(JT.MBB));
2192 
2193   DAG.setRoot(BrCond);
2194 }
2195 
2196 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2197 /// variable if there exists one.
2198 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2199                                  SDValue &Chain) {
2200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2201   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2202   MachineFunction &MF = DAG.getMachineFunction();
2203   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2204   MachineSDNode *Node =
2205       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2206   if (Global) {
2207     MachinePointerInfo MPInfo(Global);
2208     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2209                  MachineMemOperand::MODereferenceable;
2210     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2211         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2212     DAG.setNodeMemRefs(Node, {MemRef});
2213   }
2214   return SDValue(Node, 0);
2215 }
2216 
2217 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2218 /// tail spliced into a stack protector check success bb.
2219 ///
2220 /// For a high level explanation of how this fits into the stack protector
2221 /// generation see the comment on the declaration of class
2222 /// StackProtectorDescriptor.
2223 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2224                                                   MachineBasicBlock *ParentBB) {
2225 
2226   // First create the loads to the guard/stack slot for the comparison.
2227   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2228   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2229 
2230   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2231   int FI = MFI.getStackProtectorIndex();
2232 
2233   SDValue Guard;
2234   SDLoc dl = getCurSDLoc();
2235   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2236   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2237   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2238 
2239   // Generate code to load the content of the guard slot.
2240   SDValue GuardVal = DAG.getLoad(
2241       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2242       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2243       MachineMemOperand::MOVolatile);
2244 
2245   if (TLI.useStackGuardXorFP())
2246     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2247 
2248   // Retrieve guard check function, nullptr if instrumentation is inlined.
2249   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2250     // The target provides a guard check function to validate the guard value.
2251     // Generate a call to that function with the content of the guard slot as
2252     // argument.
2253     auto *Fn = cast<Function>(GuardCheck);
2254     FunctionType *FnTy = Fn->getFunctionType();
2255     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2256 
2257     TargetLowering::ArgListTy Args;
2258     TargetLowering::ArgListEntry Entry;
2259     Entry.Node = GuardVal;
2260     Entry.Ty = FnTy->getParamType(0);
2261     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2262       Entry.IsInReg = true;
2263     Args.push_back(Entry);
2264 
2265     TargetLowering::CallLoweringInfo CLI(DAG);
2266     CLI.setDebugLoc(getCurSDLoc())
2267       .setChain(DAG.getEntryNode())
2268       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2269                  getValue(GuardCheck), std::move(Args));
2270 
2271     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2272     DAG.setRoot(Result.second);
2273     return;
2274   }
2275 
2276   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2277   // Otherwise, emit a volatile load to retrieve the stack guard value.
2278   SDValue Chain = DAG.getEntryNode();
2279   if (TLI.useLoadStackGuardNode()) {
2280     Guard = getLoadStackGuard(DAG, dl, Chain);
2281   } else {
2282     const Value *IRGuard = TLI.getSDagStackGuard(M);
2283     SDValue GuardPtr = getValue(IRGuard);
2284 
2285     Guard =
2286         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2287                     Align, MachineMemOperand::MOVolatile);
2288   }
2289 
2290   // Perform the comparison via a subtract/getsetcc.
2291   EVT VT = Guard.getValueType();
2292   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2293 
2294   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2295                                                         *DAG.getContext(),
2296                                                         Sub.getValueType()),
2297                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2298 
2299   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2300   // branch to failure MBB.
2301   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2302                                MVT::Other, GuardVal.getOperand(0),
2303                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2304   // Otherwise branch to success MBB.
2305   SDValue Br = DAG.getNode(ISD::BR, dl,
2306                            MVT::Other, BrCond,
2307                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2308 
2309   DAG.setRoot(Br);
2310 }
2311 
2312 /// Codegen the failure basic block for a stack protector check.
2313 ///
2314 /// A failure stack protector machine basic block consists simply of a call to
2315 /// __stack_chk_fail().
2316 ///
2317 /// For a high level explanation of how this fits into the stack protector
2318 /// generation see the comment on the declaration of class
2319 /// StackProtectorDescriptor.
2320 void
2321 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2323   SDValue Chain =
2324       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2325                       None, false, getCurSDLoc(), false, false).second;
2326   DAG.setRoot(Chain);
2327 }
2328 
2329 /// visitBitTestHeader - This function emits necessary code to produce value
2330 /// suitable for "bit tests"
2331 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2332                                              MachineBasicBlock *SwitchBB) {
2333   SDLoc dl = getCurSDLoc();
2334 
2335   // Subtract the minimum value
2336   SDValue SwitchOp = getValue(B.SValue);
2337   EVT VT = SwitchOp.getValueType();
2338   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2339                             DAG.getConstant(B.First, dl, VT));
2340 
2341   // Check range
2342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2343   SDValue RangeCmp = DAG.getSetCC(
2344       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2345                                  Sub.getValueType()),
2346       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2347 
2348   // Determine the type of the test operands.
2349   bool UsePtrType = false;
2350   if (!TLI.isTypeLegal(VT))
2351     UsePtrType = true;
2352   else {
2353     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2354       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2355         // Switch table case range are encoded into series of masks.
2356         // Just use pointer type, it's guaranteed to fit.
2357         UsePtrType = true;
2358         break;
2359       }
2360   }
2361   if (UsePtrType) {
2362     VT = TLI.getPointerTy(DAG.getDataLayout());
2363     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2364   }
2365 
2366   B.RegVT = VT.getSimpleVT();
2367   B.Reg = FuncInfo.CreateReg(B.RegVT);
2368   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2369 
2370   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2371 
2372   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2373   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2374   SwitchBB->normalizeSuccProbs();
2375 
2376   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2377                                 MVT::Other, CopyTo, RangeCmp,
2378                                 DAG.getBasicBlock(B.Default));
2379 
2380   // Avoid emitting unnecessary branches to the next block.
2381   if (MBB != NextBlock(SwitchBB))
2382     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2383                           DAG.getBasicBlock(MBB));
2384 
2385   DAG.setRoot(BrRange);
2386 }
2387 
2388 /// visitBitTestCase - this function produces one "bit test"
2389 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2390                                            MachineBasicBlock* NextMBB,
2391                                            BranchProbability BranchProbToNext,
2392                                            unsigned Reg,
2393                                            BitTestCase &B,
2394                                            MachineBasicBlock *SwitchBB) {
2395   SDLoc dl = getCurSDLoc();
2396   MVT VT = BB.RegVT;
2397   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2398   SDValue Cmp;
2399   unsigned PopCount = countPopulation(B.Mask);
2400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2401   if (PopCount == 1) {
2402     // Testing for a single bit; just compare the shift count with what it
2403     // would need to be to shift a 1 bit in that position.
2404     Cmp = DAG.getSetCC(
2405         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2406         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2407         ISD::SETEQ);
2408   } else if (PopCount == BB.Range) {
2409     // There is only one zero bit in the range, test for it directly.
2410     Cmp = DAG.getSetCC(
2411         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2412         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2413         ISD::SETNE);
2414   } else {
2415     // Make desired shift
2416     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2417                                     DAG.getConstant(1, dl, VT), ShiftOp);
2418 
2419     // Emit bit tests and jumps
2420     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2421                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2422     Cmp = DAG.getSetCC(
2423         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2424         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2425   }
2426 
2427   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2428   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2429   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2430   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2431   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2432   // one as they are relative probabilities (and thus work more like weights),
2433   // and hence we need to normalize them to let the sum of them become one.
2434   SwitchBB->normalizeSuccProbs();
2435 
2436   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2437                               MVT::Other, getControlRoot(),
2438                               Cmp, DAG.getBasicBlock(B.TargetBB));
2439 
2440   // Avoid emitting unnecessary branches to the next block.
2441   if (NextMBB != NextBlock(SwitchBB))
2442     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2443                         DAG.getBasicBlock(NextMBB));
2444 
2445   DAG.setRoot(BrAnd);
2446 }
2447 
2448 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2449   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2450 
2451   // Retrieve successors. Look through artificial IR level blocks like
2452   // catchswitch for successors.
2453   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2454   const BasicBlock *EHPadBB = I.getSuccessor(1);
2455 
2456   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2457   // have to do anything here to lower funclet bundles.
2458   assert(!I.hasOperandBundlesOtherThan(
2459              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2460          "Cannot lower invokes with arbitrary operand bundles yet!");
2461 
2462   const Value *Callee(I.getCalledValue());
2463   const Function *Fn = dyn_cast<Function>(Callee);
2464   if (isa<InlineAsm>(Callee))
2465     visitInlineAsm(&I);
2466   else if (Fn && Fn->isIntrinsic()) {
2467     switch (Fn->getIntrinsicID()) {
2468     default:
2469       llvm_unreachable("Cannot invoke this intrinsic");
2470     case Intrinsic::donothing:
2471       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2472       break;
2473     case Intrinsic::experimental_patchpoint_void:
2474     case Intrinsic::experimental_patchpoint_i64:
2475       visitPatchpoint(&I, EHPadBB);
2476       break;
2477     case Intrinsic::experimental_gc_statepoint:
2478       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2479       break;
2480     }
2481   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2482     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2483     // Eventually we will support lowering the @llvm.experimental.deoptimize
2484     // intrinsic, and right now there are no plans to support other intrinsics
2485     // with deopt state.
2486     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2487   } else {
2488     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2489   }
2490 
2491   // If the value of the invoke is used outside of its defining block, make it
2492   // available as a virtual register.
2493   // We already took care of the exported value for the statepoint instruction
2494   // during call to the LowerStatepoint.
2495   if (!isStatepoint(I)) {
2496     CopyToExportRegsIfNeeded(&I);
2497   }
2498 
2499   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2500   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2501   BranchProbability EHPadBBProb =
2502       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2503           : BranchProbability::getZero();
2504   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2505 
2506   // Update successor info.
2507   addSuccessorWithProb(InvokeMBB, Return);
2508   for (auto &UnwindDest : UnwindDests) {
2509     UnwindDest.first->setIsEHPad();
2510     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2511   }
2512   InvokeMBB->normalizeSuccProbs();
2513 
2514   // Drop into normal successor.
2515   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2516                           MVT::Other, getControlRoot(),
2517                           DAG.getBasicBlock(Return)));
2518 }
2519 
2520 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2521   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2522 }
2523 
2524 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2525   assert(FuncInfo.MBB->isEHPad() &&
2526          "Call to landingpad not in landing pad!");
2527 
2528   MachineBasicBlock *MBB = FuncInfo.MBB;
2529   addLandingPadInfo(LP, *MBB);
2530 
2531   // If there aren't registers to copy the values into (e.g., during SjLj
2532   // exceptions), then don't bother to create these DAG nodes.
2533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2534   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2535   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2536       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2537     return;
2538 
2539   // If landingpad's return type is token type, we don't create DAG nodes
2540   // for its exception pointer and selector value. The extraction of exception
2541   // pointer or selector value from token type landingpads is not currently
2542   // supported.
2543   if (LP.getType()->isTokenTy())
2544     return;
2545 
2546   SmallVector<EVT, 2> ValueVTs;
2547   SDLoc dl = getCurSDLoc();
2548   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2549   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2550 
2551   // Get the two live-in registers as SDValues. The physregs have already been
2552   // copied into virtual registers.
2553   SDValue Ops[2];
2554   if (FuncInfo.ExceptionPointerVirtReg) {
2555     Ops[0] = DAG.getZExtOrTrunc(
2556         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2557                            FuncInfo.ExceptionPointerVirtReg,
2558                            TLI.getPointerTy(DAG.getDataLayout())),
2559         dl, ValueVTs[0]);
2560   } else {
2561     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2562   }
2563   Ops[1] = DAG.getZExtOrTrunc(
2564       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2565                          FuncInfo.ExceptionSelectorVirtReg,
2566                          TLI.getPointerTy(DAG.getDataLayout())),
2567       dl, ValueVTs[1]);
2568 
2569   // Merge into one.
2570   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2571                             DAG.getVTList(ValueVTs), Ops);
2572   setValue(&LP, Res);
2573 }
2574 
2575 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2576 #ifndef NDEBUG
2577   for (const CaseCluster &CC : Clusters)
2578     assert(CC.Low == CC.High && "Input clusters must be single-case");
2579 #endif
2580 
2581   llvm::sort(Clusters.begin(), Clusters.end(),
2582              [](const CaseCluster &a, const CaseCluster &b) {
2583     return a.Low->getValue().slt(b.Low->getValue());
2584   });
2585 
2586   // Merge adjacent clusters with the same destination.
2587   const unsigned N = Clusters.size();
2588   unsigned DstIndex = 0;
2589   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2590     CaseCluster &CC = Clusters[SrcIndex];
2591     const ConstantInt *CaseVal = CC.Low;
2592     MachineBasicBlock *Succ = CC.MBB;
2593 
2594     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2595         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2596       // If this case has the same successor and is a neighbour, merge it into
2597       // the previous cluster.
2598       Clusters[DstIndex - 1].High = CaseVal;
2599       Clusters[DstIndex - 1].Prob += CC.Prob;
2600     } else {
2601       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2602                    sizeof(Clusters[SrcIndex]));
2603     }
2604   }
2605   Clusters.resize(DstIndex);
2606 }
2607 
2608 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2609                                            MachineBasicBlock *Last) {
2610   // Update JTCases.
2611   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2612     if (JTCases[i].first.HeaderBB == First)
2613       JTCases[i].first.HeaderBB = Last;
2614 
2615   // Update BitTestCases.
2616   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2617     if (BitTestCases[i].Parent == First)
2618       BitTestCases[i].Parent = Last;
2619 }
2620 
2621 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2622   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2623 
2624   // Update machine-CFG edges with unique successors.
2625   SmallSet<BasicBlock*, 32> Done;
2626   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2627     BasicBlock *BB = I.getSuccessor(i);
2628     bool Inserted = Done.insert(BB).second;
2629     if (!Inserted)
2630         continue;
2631 
2632     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2633     addSuccessorWithProb(IndirectBrMBB, Succ);
2634   }
2635   IndirectBrMBB->normalizeSuccProbs();
2636 
2637   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2638                           MVT::Other, getControlRoot(),
2639                           getValue(I.getAddress())));
2640 }
2641 
2642 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2643   if (!DAG.getTarget().Options.TrapUnreachable)
2644     return;
2645 
2646   // We may be able to ignore unreachable behind a noreturn call.
2647   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2648     const BasicBlock &BB = *I.getParent();
2649     if (&I != &BB.front()) {
2650       BasicBlock::const_iterator PredI =
2651         std::prev(BasicBlock::const_iterator(&I));
2652       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2653         if (Call->doesNotReturn())
2654           return;
2655       }
2656     }
2657   }
2658 
2659   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2660 }
2661 
2662 void SelectionDAGBuilder::visitFSub(const User &I) {
2663   // -0.0 - X --> fneg
2664   Type *Ty = I.getType();
2665   if (isa<Constant>(I.getOperand(0)) &&
2666       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2667     SDValue Op2 = getValue(I.getOperand(1));
2668     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2669                              Op2.getValueType(), Op2));
2670     return;
2671   }
2672 
2673   visitBinary(I, ISD::FSUB);
2674 }
2675 
2676 /// Checks if the given instruction performs a vector reduction, in which case
2677 /// we have the freedom to alter the elements in the result as long as the
2678 /// reduction of them stays unchanged.
2679 static bool isVectorReductionOp(const User *I) {
2680   const Instruction *Inst = dyn_cast<Instruction>(I);
2681   if (!Inst || !Inst->getType()->isVectorTy())
2682     return false;
2683 
2684   auto OpCode = Inst->getOpcode();
2685   switch (OpCode) {
2686   case Instruction::Add:
2687   case Instruction::Mul:
2688   case Instruction::And:
2689   case Instruction::Or:
2690   case Instruction::Xor:
2691     break;
2692   case Instruction::FAdd:
2693   case Instruction::FMul:
2694     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2695       if (FPOp->getFastMathFlags().isFast())
2696         break;
2697     LLVM_FALLTHROUGH;
2698   default:
2699     return false;
2700   }
2701 
2702   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2703   // Ensure the reduction size is a power of 2.
2704   if (!isPowerOf2_32(ElemNum))
2705     return false;
2706 
2707   unsigned ElemNumToReduce = ElemNum;
2708 
2709   // Do DFS search on the def-use chain from the given instruction. We only
2710   // allow four kinds of operations during the search until we reach the
2711   // instruction that extracts the first element from the vector:
2712   //
2713   //   1. The reduction operation of the same opcode as the given instruction.
2714   //
2715   //   2. PHI node.
2716   //
2717   //   3. ShuffleVector instruction together with a reduction operation that
2718   //      does a partial reduction.
2719   //
2720   //   4. ExtractElement that extracts the first element from the vector, and we
2721   //      stop searching the def-use chain here.
2722   //
2723   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2724   // from 1-3 to the stack to continue the DFS. The given instruction is not
2725   // a reduction operation if we meet any other instructions other than those
2726   // listed above.
2727 
2728   SmallVector<const User *, 16> UsersToVisit{Inst};
2729   SmallPtrSet<const User *, 16> Visited;
2730   bool ReduxExtracted = false;
2731 
2732   while (!UsersToVisit.empty()) {
2733     auto User = UsersToVisit.back();
2734     UsersToVisit.pop_back();
2735     if (!Visited.insert(User).second)
2736       continue;
2737 
2738     for (const auto &U : User->users()) {
2739       auto Inst = dyn_cast<Instruction>(U);
2740       if (!Inst)
2741         return false;
2742 
2743       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2744         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2745           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2746             return false;
2747         UsersToVisit.push_back(U);
2748       } else if (const ShuffleVectorInst *ShufInst =
2749                      dyn_cast<ShuffleVectorInst>(U)) {
2750         // Detect the following pattern: A ShuffleVector instruction together
2751         // with a reduction that do partial reduction on the first and second
2752         // ElemNumToReduce / 2 elements, and store the result in
2753         // ElemNumToReduce / 2 elements in another vector.
2754 
2755         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2756         if (ResultElements < ElemNum)
2757           return false;
2758 
2759         if (ElemNumToReduce == 1)
2760           return false;
2761         if (!isa<UndefValue>(U->getOperand(1)))
2762           return false;
2763         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2764           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2765             return false;
2766         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2767           if (ShufInst->getMaskValue(i) != -1)
2768             return false;
2769 
2770         // There is only one user of this ShuffleVector instruction, which
2771         // must be a reduction operation.
2772         if (!U->hasOneUse())
2773           return false;
2774 
2775         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2776         if (!U2 || U2->getOpcode() != OpCode)
2777           return false;
2778 
2779         // Check operands of the reduction operation.
2780         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2781             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2782           UsersToVisit.push_back(U2);
2783           ElemNumToReduce /= 2;
2784         } else
2785           return false;
2786       } else if (isa<ExtractElementInst>(U)) {
2787         // At this moment we should have reduced all elements in the vector.
2788         if (ElemNumToReduce != 1)
2789           return false;
2790 
2791         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2792         if (!Val || !Val->isZero())
2793           return false;
2794 
2795         ReduxExtracted = true;
2796       } else
2797         return false;
2798     }
2799   }
2800   return ReduxExtracted;
2801 }
2802 
2803 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2804   SDNodeFlags Flags;
2805   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2806     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2807     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2808   }
2809   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2810     Flags.setExact(ExactOp->isExact());
2811   }
2812   if (isVectorReductionOp(&I)) {
2813     Flags.setVectorReduction(true);
2814     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2815   }
2816 
2817   SDValue Op1 = getValue(I.getOperand(0));
2818   SDValue Op2 = getValue(I.getOperand(1));
2819   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2820                                      Op1, Op2, Flags);
2821   setValue(&I, BinNodeValue);
2822 }
2823 
2824 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2825   SDValue Op1 = getValue(I.getOperand(0));
2826   SDValue Op2 = getValue(I.getOperand(1));
2827 
2828   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2829       Op2.getValueType(), DAG.getDataLayout());
2830 
2831   // Coerce the shift amount to the right type if we can.
2832   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2833     unsigned ShiftSize = ShiftTy.getSizeInBits();
2834     unsigned Op2Size = Op2.getValueSizeInBits();
2835     SDLoc DL = getCurSDLoc();
2836 
2837     // If the operand is smaller than the shift count type, promote it.
2838     if (ShiftSize > Op2Size)
2839       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2840 
2841     // If the operand is larger than the shift count type but the shift
2842     // count type has enough bits to represent any shift value, truncate
2843     // it now. This is a common case and it exposes the truncate to
2844     // optimization early.
2845     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2846       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2847     // Otherwise we'll need to temporarily settle for some other convenient
2848     // type.  Type legalization will make adjustments once the shiftee is split.
2849     else
2850       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2851   }
2852 
2853   bool nuw = false;
2854   bool nsw = false;
2855   bool exact = false;
2856 
2857   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2858 
2859     if (const OverflowingBinaryOperator *OFBinOp =
2860             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2861       nuw = OFBinOp->hasNoUnsignedWrap();
2862       nsw = OFBinOp->hasNoSignedWrap();
2863     }
2864     if (const PossiblyExactOperator *ExactOp =
2865             dyn_cast<const PossiblyExactOperator>(&I))
2866       exact = ExactOp->isExact();
2867   }
2868   SDNodeFlags Flags;
2869   Flags.setExact(exact);
2870   Flags.setNoSignedWrap(nsw);
2871   Flags.setNoUnsignedWrap(nuw);
2872   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2873                             Flags);
2874   setValue(&I, Res);
2875 }
2876 
2877 void SelectionDAGBuilder::visitSDiv(const User &I) {
2878   SDValue Op1 = getValue(I.getOperand(0));
2879   SDValue Op2 = getValue(I.getOperand(1));
2880 
2881   SDNodeFlags Flags;
2882   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2883                  cast<PossiblyExactOperator>(&I)->isExact());
2884   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2885                            Op2, Flags));
2886 }
2887 
2888 void SelectionDAGBuilder::visitICmp(const User &I) {
2889   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2890   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2891     predicate = IC->getPredicate();
2892   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2893     predicate = ICmpInst::Predicate(IC->getPredicate());
2894   SDValue Op1 = getValue(I.getOperand(0));
2895   SDValue Op2 = getValue(I.getOperand(1));
2896   ISD::CondCode Opcode = getICmpCondCode(predicate);
2897 
2898   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2899                                                         I.getType());
2900   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2901 }
2902 
2903 void SelectionDAGBuilder::visitFCmp(const User &I) {
2904   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2905   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2906     predicate = FC->getPredicate();
2907   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2908     predicate = FCmpInst::Predicate(FC->getPredicate());
2909   SDValue Op1 = getValue(I.getOperand(0));
2910   SDValue Op2 = getValue(I.getOperand(1));
2911 
2912   ISD::CondCode Condition = getFCmpCondCode(predicate);
2913   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2914   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2915     Condition = getFCmpCodeWithoutNaN(Condition);
2916 
2917   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2918                                                         I.getType());
2919   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2920 }
2921 
2922 // Check if the condition of the select has one use or two users that are both
2923 // selects with the same condition.
2924 static bool hasOnlySelectUsers(const Value *Cond) {
2925   return llvm::all_of(Cond->users(), [](const Value *V) {
2926     return isa<SelectInst>(V);
2927   });
2928 }
2929 
2930 void SelectionDAGBuilder::visitSelect(const User &I) {
2931   SmallVector<EVT, 4> ValueVTs;
2932   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2933                   ValueVTs);
2934   unsigned NumValues = ValueVTs.size();
2935   if (NumValues == 0) return;
2936 
2937   SmallVector<SDValue, 4> Values(NumValues);
2938   SDValue Cond     = getValue(I.getOperand(0));
2939   SDValue LHSVal   = getValue(I.getOperand(1));
2940   SDValue RHSVal   = getValue(I.getOperand(2));
2941   auto BaseOps = {Cond};
2942   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2943     ISD::VSELECT : ISD::SELECT;
2944 
2945   // Min/max matching is only viable if all output VTs are the same.
2946   if (is_splat(ValueVTs)) {
2947     EVT VT = ValueVTs[0];
2948     LLVMContext &Ctx = *DAG.getContext();
2949     auto &TLI = DAG.getTargetLoweringInfo();
2950 
2951     // We care about the legality of the operation after it has been type
2952     // legalized.
2953     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2954            VT != TLI.getTypeToTransformTo(Ctx, VT))
2955       VT = TLI.getTypeToTransformTo(Ctx, VT);
2956 
2957     // If the vselect is legal, assume we want to leave this as a vector setcc +
2958     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2959     // min/max is legal on the scalar type.
2960     bool UseScalarMinMax = VT.isVector() &&
2961       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2962 
2963     Value *LHS, *RHS;
2964     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2965     ISD::NodeType Opc = ISD::DELETED_NODE;
2966     switch (SPR.Flavor) {
2967     case SPF_UMAX:    Opc = ISD::UMAX; break;
2968     case SPF_UMIN:    Opc = ISD::UMIN; break;
2969     case SPF_SMAX:    Opc = ISD::SMAX; break;
2970     case SPF_SMIN:    Opc = ISD::SMIN; break;
2971     case SPF_FMINNUM:
2972       switch (SPR.NaNBehavior) {
2973       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2974       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2975       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2976       case SPNB_RETURNS_ANY: {
2977         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2978           Opc = ISD::FMINNUM;
2979         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2980           Opc = ISD::FMINNAN;
2981         else if (UseScalarMinMax)
2982           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2983             ISD::FMINNUM : ISD::FMINNAN;
2984         break;
2985       }
2986       }
2987       break;
2988     case SPF_FMAXNUM:
2989       switch (SPR.NaNBehavior) {
2990       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2991       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2992       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2993       case SPNB_RETURNS_ANY:
2994 
2995         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2996           Opc = ISD::FMAXNUM;
2997         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2998           Opc = ISD::FMAXNAN;
2999         else if (UseScalarMinMax)
3000           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3001             ISD::FMAXNUM : ISD::FMAXNAN;
3002         break;
3003       }
3004       break;
3005     default: break;
3006     }
3007 
3008     if (Opc != ISD::DELETED_NODE &&
3009         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3010          (UseScalarMinMax &&
3011           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3012         // If the underlying comparison instruction is used by any other
3013         // instruction, the consumed instructions won't be destroyed, so it is
3014         // not profitable to convert to a min/max.
3015         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3016       OpCode = Opc;
3017       LHSVal = getValue(LHS);
3018       RHSVal = getValue(RHS);
3019       BaseOps = {};
3020     }
3021   }
3022 
3023   for (unsigned i = 0; i != NumValues; ++i) {
3024     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3025     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3026     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3027     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3028                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3029                             Ops);
3030   }
3031 
3032   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3033                            DAG.getVTList(ValueVTs), Values));
3034 }
3035 
3036 void SelectionDAGBuilder::visitTrunc(const User &I) {
3037   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3038   SDValue N = getValue(I.getOperand(0));
3039   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3040                                                         I.getType());
3041   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3042 }
3043 
3044 void SelectionDAGBuilder::visitZExt(const User &I) {
3045   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3046   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3047   SDValue N = getValue(I.getOperand(0));
3048   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3049                                                         I.getType());
3050   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3051 }
3052 
3053 void SelectionDAGBuilder::visitSExt(const User &I) {
3054   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3055   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3056   SDValue N = getValue(I.getOperand(0));
3057   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3058                                                         I.getType());
3059   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3060 }
3061 
3062 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3063   // FPTrunc is never a no-op cast, no need to check
3064   SDValue N = getValue(I.getOperand(0));
3065   SDLoc dl = getCurSDLoc();
3066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3067   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3068   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3069                            DAG.getTargetConstant(
3070                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3071 }
3072 
3073 void SelectionDAGBuilder::visitFPExt(const User &I) {
3074   // FPExt is never a no-op cast, no need to check
3075   SDValue N = getValue(I.getOperand(0));
3076   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3077                                                         I.getType());
3078   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3079 }
3080 
3081 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3082   // FPToUI is never a no-op cast, no need to check
3083   SDValue N = getValue(I.getOperand(0));
3084   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3085                                                         I.getType());
3086   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3087 }
3088 
3089 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3090   // FPToSI is never a no-op cast, no need to check
3091   SDValue N = getValue(I.getOperand(0));
3092   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3093                                                         I.getType());
3094   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3095 }
3096 
3097 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3098   // UIToFP is never a no-op cast, no need to check
3099   SDValue N = getValue(I.getOperand(0));
3100   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3101                                                         I.getType());
3102   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3103 }
3104 
3105 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3106   // SIToFP is never a no-op cast, no need to check
3107   SDValue N = getValue(I.getOperand(0));
3108   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3109                                                         I.getType());
3110   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3111 }
3112 
3113 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3114   // What to do depends on the size of the integer and the size of the pointer.
3115   // We can either truncate, zero extend, or no-op, accordingly.
3116   SDValue N = getValue(I.getOperand(0));
3117   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3118                                                         I.getType());
3119   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3120 }
3121 
3122 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3123   // What to do depends on the size of the integer and the size of the pointer.
3124   // We can either truncate, zero extend, or no-op, accordingly.
3125   SDValue N = getValue(I.getOperand(0));
3126   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3127                                                         I.getType());
3128   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3129 }
3130 
3131 void SelectionDAGBuilder::visitBitCast(const User &I) {
3132   SDValue N = getValue(I.getOperand(0));
3133   SDLoc dl = getCurSDLoc();
3134   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3135                                                         I.getType());
3136 
3137   // BitCast assures us that source and destination are the same size so this is
3138   // either a BITCAST or a no-op.
3139   if (DestVT != N.getValueType())
3140     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3141                              DestVT, N)); // convert types.
3142   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3143   // might fold any kind of constant expression to an integer constant and that
3144   // is not what we are looking for. Only recognize a bitcast of a genuine
3145   // constant integer as an opaque constant.
3146   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3147     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3148                                  /*isOpaque*/true));
3149   else
3150     setValue(&I, N);            // noop cast.
3151 }
3152 
3153 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3155   const Value *SV = I.getOperand(0);
3156   SDValue N = getValue(SV);
3157   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3158 
3159   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3160   unsigned DestAS = I.getType()->getPointerAddressSpace();
3161 
3162   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3163     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3164 
3165   setValue(&I, N);
3166 }
3167 
3168 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3170   SDValue InVec = getValue(I.getOperand(0));
3171   SDValue InVal = getValue(I.getOperand(1));
3172   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3173                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3174   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3175                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3176                            InVec, InVal, InIdx));
3177 }
3178 
3179 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3181   SDValue InVec = getValue(I.getOperand(0));
3182   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3183                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3184   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3185                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3186                            InVec, InIdx));
3187 }
3188 
3189 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3190   SDValue Src1 = getValue(I.getOperand(0));
3191   SDValue Src2 = getValue(I.getOperand(1));
3192   SDLoc DL = getCurSDLoc();
3193 
3194   SmallVector<int, 8> Mask;
3195   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3196   unsigned MaskNumElts = Mask.size();
3197 
3198   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3199   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3200   EVT SrcVT = Src1.getValueType();
3201   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3202 
3203   if (SrcNumElts == MaskNumElts) {
3204     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3205     return;
3206   }
3207 
3208   // Normalize the shuffle vector since mask and vector length don't match.
3209   if (SrcNumElts < MaskNumElts) {
3210     // Mask is longer than the source vectors. We can use concatenate vector to
3211     // make the mask and vectors lengths match.
3212 
3213     if (MaskNumElts % SrcNumElts == 0) {
3214       // Mask length is a multiple of the source vector length.
3215       // Check if the shuffle is some kind of concatenation of the input
3216       // vectors.
3217       unsigned NumConcat = MaskNumElts / SrcNumElts;
3218       bool IsConcat = true;
3219       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3220       for (unsigned i = 0; i != MaskNumElts; ++i) {
3221         int Idx = Mask[i];
3222         if (Idx < 0)
3223           continue;
3224         // Ensure the indices in each SrcVT sized piece are sequential and that
3225         // the same source is used for the whole piece.
3226         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3227             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3228              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3229           IsConcat = false;
3230           break;
3231         }
3232         // Remember which source this index came from.
3233         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3234       }
3235 
3236       // The shuffle is concatenating multiple vectors together. Just emit
3237       // a CONCAT_VECTORS operation.
3238       if (IsConcat) {
3239         SmallVector<SDValue, 8> ConcatOps;
3240         for (auto Src : ConcatSrcs) {
3241           if (Src < 0)
3242             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3243           else if (Src == 0)
3244             ConcatOps.push_back(Src1);
3245           else
3246             ConcatOps.push_back(Src2);
3247         }
3248         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3249         return;
3250       }
3251     }
3252 
3253     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3254     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3255     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3256                                     PaddedMaskNumElts);
3257 
3258     // Pad both vectors with undefs to make them the same length as the mask.
3259     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3260 
3261     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3262     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3263     MOps1[0] = Src1;
3264     MOps2[0] = Src2;
3265 
3266     Src1 = Src1.isUndef()
3267                ? DAG.getUNDEF(PaddedVT)
3268                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3269     Src2 = Src2.isUndef()
3270                ? DAG.getUNDEF(PaddedVT)
3271                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3272 
3273     // Readjust mask for new input vector length.
3274     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3275     for (unsigned i = 0; i != MaskNumElts; ++i) {
3276       int Idx = Mask[i];
3277       if (Idx >= (int)SrcNumElts)
3278         Idx -= SrcNumElts - PaddedMaskNumElts;
3279       MappedOps[i] = Idx;
3280     }
3281 
3282     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3283 
3284     // If the concatenated vector was padded, extract a subvector with the
3285     // correct number of elements.
3286     if (MaskNumElts != PaddedMaskNumElts)
3287       Result = DAG.getNode(
3288           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3289           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3290 
3291     setValue(&I, Result);
3292     return;
3293   }
3294 
3295   if (SrcNumElts > MaskNumElts) {
3296     // Analyze the access pattern of the vector to see if we can extract
3297     // two subvectors and do the shuffle.
3298     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3299     bool CanExtract = true;
3300     for (int Idx : Mask) {
3301       unsigned Input = 0;
3302       if (Idx < 0)
3303         continue;
3304 
3305       if (Idx >= (int)SrcNumElts) {
3306         Input = 1;
3307         Idx -= SrcNumElts;
3308       }
3309 
3310       // If all the indices come from the same MaskNumElts sized portion of
3311       // the sources we can use extract. Also make sure the extract wouldn't
3312       // extract past the end of the source.
3313       int NewStartIdx = alignDown(Idx, MaskNumElts);
3314       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3315           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3316         CanExtract = false;
3317       // Make sure we always update StartIdx as we use it to track if all
3318       // elements are undef.
3319       StartIdx[Input] = NewStartIdx;
3320     }
3321 
3322     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3323       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3324       return;
3325     }
3326     if (CanExtract) {
3327       // Extract appropriate subvector and generate a vector shuffle
3328       for (unsigned Input = 0; Input < 2; ++Input) {
3329         SDValue &Src = Input == 0 ? Src1 : Src2;
3330         if (StartIdx[Input] < 0)
3331           Src = DAG.getUNDEF(VT);
3332         else {
3333           Src = DAG.getNode(
3334               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3335               DAG.getConstant(StartIdx[Input], DL,
3336                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3337         }
3338       }
3339 
3340       // Calculate new mask.
3341       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3342       for (int &Idx : MappedOps) {
3343         if (Idx >= (int)SrcNumElts)
3344           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3345         else if (Idx >= 0)
3346           Idx -= StartIdx[0];
3347       }
3348 
3349       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3350       return;
3351     }
3352   }
3353 
3354   // We can't use either concat vectors or extract subvectors so fall back to
3355   // replacing the shuffle with extract and build vector.
3356   // to insert and build vector.
3357   EVT EltVT = VT.getVectorElementType();
3358   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3359   SmallVector<SDValue,8> Ops;
3360   for (int Idx : Mask) {
3361     SDValue Res;
3362 
3363     if (Idx < 0) {
3364       Res = DAG.getUNDEF(EltVT);
3365     } else {
3366       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3367       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3368 
3369       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3370                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3371     }
3372 
3373     Ops.push_back(Res);
3374   }
3375 
3376   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3377 }
3378 
3379 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3380   ArrayRef<unsigned> Indices;
3381   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3382     Indices = IV->getIndices();
3383   else
3384     Indices = cast<ConstantExpr>(&I)->getIndices();
3385 
3386   const Value *Op0 = I.getOperand(0);
3387   const Value *Op1 = I.getOperand(1);
3388   Type *AggTy = I.getType();
3389   Type *ValTy = Op1->getType();
3390   bool IntoUndef = isa<UndefValue>(Op0);
3391   bool FromUndef = isa<UndefValue>(Op1);
3392 
3393   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3394 
3395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3396   SmallVector<EVT, 4> AggValueVTs;
3397   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3398   SmallVector<EVT, 4> ValValueVTs;
3399   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3400 
3401   unsigned NumAggValues = AggValueVTs.size();
3402   unsigned NumValValues = ValValueVTs.size();
3403   SmallVector<SDValue, 4> Values(NumAggValues);
3404 
3405   // Ignore an insertvalue that produces an empty object
3406   if (!NumAggValues) {
3407     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3408     return;
3409   }
3410 
3411   SDValue Agg = getValue(Op0);
3412   unsigned i = 0;
3413   // Copy the beginning value(s) from the original aggregate.
3414   for (; i != LinearIndex; ++i)
3415     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3416                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3417   // Copy values from the inserted value(s).
3418   if (NumValValues) {
3419     SDValue Val = getValue(Op1);
3420     for (; i != LinearIndex + NumValValues; ++i)
3421       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3422                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3423   }
3424   // Copy remaining value(s) from the original aggregate.
3425   for (; i != NumAggValues; ++i)
3426     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3427                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3428 
3429   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3430                            DAG.getVTList(AggValueVTs), Values));
3431 }
3432 
3433 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3434   ArrayRef<unsigned> Indices;
3435   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3436     Indices = EV->getIndices();
3437   else
3438     Indices = cast<ConstantExpr>(&I)->getIndices();
3439 
3440   const Value *Op0 = I.getOperand(0);
3441   Type *AggTy = Op0->getType();
3442   Type *ValTy = I.getType();
3443   bool OutOfUndef = isa<UndefValue>(Op0);
3444 
3445   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3446 
3447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3448   SmallVector<EVT, 4> ValValueVTs;
3449   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3450 
3451   unsigned NumValValues = ValValueVTs.size();
3452 
3453   // Ignore a extractvalue that produces an empty object
3454   if (!NumValValues) {
3455     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3456     return;
3457   }
3458 
3459   SmallVector<SDValue, 4> Values(NumValValues);
3460 
3461   SDValue Agg = getValue(Op0);
3462   // Copy out the selected value(s).
3463   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3464     Values[i - LinearIndex] =
3465       OutOfUndef ?
3466         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3467         SDValue(Agg.getNode(), Agg.getResNo() + i);
3468 
3469   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3470                            DAG.getVTList(ValValueVTs), Values));
3471 }
3472 
3473 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3474   Value *Op0 = I.getOperand(0);
3475   // Note that the pointer operand may be a vector of pointers. Take the scalar
3476   // element which holds a pointer.
3477   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3478   SDValue N = getValue(Op0);
3479   SDLoc dl = getCurSDLoc();
3480 
3481   // Normalize Vector GEP - all scalar operands should be converted to the
3482   // splat vector.
3483   unsigned VectorWidth = I.getType()->isVectorTy() ?
3484     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3485 
3486   if (VectorWidth && !N.getValueType().isVector()) {
3487     LLVMContext &Context = *DAG.getContext();
3488     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3489     N = DAG.getSplatBuildVector(VT, dl, N);
3490   }
3491 
3492   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3493        GTI != E; ++GTI) {
3494     const Value *Idx = GTI.getOperand();
3495     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3496       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3497       if (Field) {
3498         // N = N + Offset
3499         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3500 
3501         // In an inbounds GEP with an offset that is nonnegative even when
3502         // interpreted as signed, assume there is no unsigned overflow.
3503         SDNodeFlags Flags;
3504         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3505           Flags.setNoUnsignedWrap(true);
3506 
3507         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3508                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3509       }
3510     } else {
3511       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3512       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3513       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3514 
3515       // If this is a scalar constant or a splat vector of constants,
3516       // handle it quickly.
3517       const auto *CI = dyn_cast<ConstantInt>(Idx);
3518       if (!CI && isa<ConstantDataVector>(Idx) &&
3519           cast<ConstantDataVector>(Idx)->getSplatValue())
3520         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3521 
3522       if (CI) {
3523         if (CI->isZero())
3524           continue;
3525         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3526         LLVMContext &Context = *DAG.getContext();
3527         SDValue OffsVal = VectorWidth ?
3528           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3529           DAG.getConstant(Offs, dl, IdxTy);
3530 
3531         // In an inbouds GEP with an offset that is nonnegative even when
3532         // interpreted as signed, assume there is no unsigned overflow.
3533         SDNodeFlags Flags;
3534         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3535           Flags.setNoUnsignedWrap(true);
3536 
3537         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3538         continue;
3539       }
3540 
3541       // N = N + Idx * ElementSize;
3542       SDValue IdxN = getValue(Idx);
3543 
3544       if (!IdxN.getValueType().isVector() && VectorWidth) {
3545         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3546         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3547       }
3548 
3549       // If the index is smaller or larger than intptr_t, truncate or extend
3550       // it.
3551       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3552 
3553       // If this is a multiply by a power of two, turn it into a shl
3554       // immediately.  This is a very common case.
3555       if (ElementSize != 1) {
3556         if (ElementSize.isPowerOf2()) {
3557           unsigned Amt = ElementSize.logBase2();
3558           IdxN = DAG.getNode(ISD::SHL, dl,
3559                              N.getValueType(), IdxN,
3560                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3561         } else {
3562           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3563           IdxN = DAG.getNode(ISD::MUL, dl,
3564                              N.getValueType(), IdxN, Scale);
3565         }
3566       }
3567 
3568       N = DAG.getNode(ISD::ADD, dl,
3569                       N.getValueType(), N, IdxN);
3570     }
3571   }
3572 
3573   setValue(&I, N);
3574 }
3575 
3576 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3577   // If this is a fixed sized alloca in the entry block of the function,
3578   // allocate it statically on the stack.
3579   if (FuncInfo.StaticAllocaMap.count(&I))
3580     return;   // getValue will auto-populate this.
3581 
3582   SDLoc dl = getCurSDLoc();
3583   Type *Ty = I.getAllocatedType();
3584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3585   auto &DL = DAG.getDataLayout();
3586   uint64_t TySize = DL.getTypeAllocSize(Ty);
3587   unsigned Align =
3588       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3589 
3590   SDValue AllocSize = getValue(I.getArraySize());
3591 
3592   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3593   if (AllocSize.getValueType() != IntPtr)
3594     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3595 
3596   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3597                           AllocSize,
3598                           DAG.getConstant(TySize, dl, IntPtr));
3599 
3600   // Handle alignment.  If the requested alignment is less than or equal to
3601   // the stack alignment, ignore it.  If the size is greater than or equal to
3602   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3603   unsigned StackAlign =
3604       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3605   if (Align <= StackAlign)
3606     Align = 0;
3607 
3608   // Round the size of the allocation up to the stack alignment size
3609   // by add SA-1 to the size. This doesn't overflow because we're computing
3610   // an address inside an alloca.
3611   SDNodeFlags Flags;
3612   Flags.setNoUnsignedWrap(true);
3613   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3614                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3615 
3616   // Mask out the low bits for alignment purposes.
3617   AllocSize =
3618       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3619                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3620 
3621   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3622   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3623   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3624   setValue(&I, DSA);
3625   DAG.setRoot(DSA.getValue(1));
3626 
3627   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3628 }
3629 
3630 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3631   if (I.isAtomic())
3632     return visitAtomicLoad(I);
3633 
3634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3635   const Value *SV = I.getOperand(0);
3636   if (TLI.supportSwiftError()) {
3637     // Swifterror values can come from either a function parameter with
3638     // swifterror attribute or an alloca with swifterror attribute.
3639     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3640       if (Arg->hasSwiftErrorAttr())
3641         return visitLoadFromSwiftError(I);
3642     }
3643 
3644     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3645       if (Alloca->isSwiftError())
3646         return visitLoadFromSwiftError(I);
3647     }
3648   }
3649 
3650   SDValue Ptr = getValue(SV);
3651 
3652   Type *Ty = I.getType();
3653 
3654   bool isVolatile = I.isVolatile();
3655   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3656   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3657   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3658   unsigned Alignment = I.getAlignment();
3659 
3660   AAMDNodes AAInfo;
3661   I.getAAMetadata(AAInfo);
3662   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3663 
3664   SmallVector<EVT, 4> ValueVTs;
3665   SmallVector<uint64_t, 4> Offsets;
3666   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3667   unsigned NumValues = ValueVTs.size();
3668   if (NumValues == 0)
3669     return;
3670 
3671   SDValue Root;
3672   bool ConstantMemory = false;
3673   if (isVolatile || NumValues > MaxParallelChains)
3674     // Serialize volatile loads with other side effects.
3675     Root = getRoot();
3676   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3677                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3678     // Do not serialize (non-volatile) loads of constant memory with anything.
3679     Root = DAG.getEntryNode();
3680     ConstantMemory = true;
3681   } else {
3682     // Do not serialize non-volatile loads against each other.
3683     Root = DAG.getRoot();
3684   }
3685 
3686   SDLoc dl = getCurSDLoc();
3687 
3688   if (isVolatile)
3689     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3690 
3691   // An aggregate load cannot wrap around the address space, so offsets to its
3692   // parts don't wrap either.
3693   SDNodeFlags Flags;
3694   Flags.setNoUnsignedWrap(true);
3695 
3696   SmallVector<SDValue, 4> Values(NumValues);
3697   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3698   EVT PtrVT = Ptr.getValueType();
3699   unsigned ChainI = 0;
3700   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3701     // Serializing loads here may result in excessive register pressure, and
3702     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3703     // could recover a bit by hoisting nodes upward in the chain by recognizing
3704     // they are side-effect free or do not alias. The optimizer should really
3705     // avoid this case by converting large object/array copies to llvm.memcpy
3706     // (MaxParallelChains should always remain as failsafe).
3707     if (ChainI == MaxParallelChains) {
3708       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3709       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3710                                   makeArrayRef(Chains.data(), ChainI));
3711       Root = Chain;
3712       ChainI = 0;
3713     }
3714     SDValue A = DAG.getNode(ISD::ADD, dl,
3715                             PtrVT, Ptr,
3716                             DAG.getConstant(Offsets[i], dl, PtrVT),
3717                             Flags);
3718     auto MMOFlags = MachineMemOperand::MONone;
3719     if (isVolatile)
3720       MMOFlags |= MachineMemOperand::MOVolatile;
3721     if (isNonTemporal)
3722       MMOFlags |= MachineMemOperand::MONonTemporal;
3723     if (isInvariant)
3724       MMOFlags |= MachineMemOperand::MOInvariant;
3725     if (isDereferenceable)
3726       MMOFlags |= MachineMemOperand::MODereferenceable;
3727     MMOFlags |= TLI.getMMOFlags(I);
3728 
3729     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3730                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3731                             MMOFlags, AAInfo, Ranges);
3732 
3733     Values[i] = L;
3734     Chains[ChainI] = L.getValue(1);
3735   }
3736 
3737   if (!ConstantMemory) {
3738     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3739                                 makeArrayRef(Chains.data(), ChainI));
3740     if (isVolatile)
3741       DAG.setRoot(Chain);
3742     else
3743       PendingLoads.push_back(Chain);
3744   }
3745 
3746   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3747                            DAG.getVTList(ValueVTs), Values));
3748 }
3749 
3750 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3751   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3752          "call visitStoreToSwiftError when backend supports swifterror");
3753 
3754   SmallVector<EVT, 4> ValueVTs;
3755   SmallVector<uint64_t, 4> Offsets;
3756   const Value *SrcV = I.getOperand(0);
3757   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3758                   SrcV->getType(), ValueVTs, &Offsets);
3759   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3760          "expect a single EVT for swifterror");
3761 
3762   SDValue Src = getValue(SrcV);
3763   // Create a virtual register, then update the virtual register.
3764   unsigned VReg; bool CreatedVReg;
3765   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3766   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3767   // Chain can be getRoot or getControlRoot.
3768   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3769                                       SDValue(Src.getNode(), Src.getResNo()));
3770   DAG.setRoot(CopyNode);
3771   if (CreatedVReg)
3772     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3773 }
3774 
3775 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3776   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3777          "call visitLoadFromSwiftError when backend supports swifterror");
3778 
3779   assert(!I.isVolatile() &&
3780          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3781          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3782          "Support volatile, non temporal, invariant for load_from_swift_error");
3783 
3784   const Value *SV = I.getOperand(0);
3785   Type *Ty = I.getType();
3786   AAMDNodes AAInfo;
3787   I.getAAMetadata(AAInfo);
3788   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3789              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3790          "load_from_swift_error should not be constant memory");
3791 
3792   SmallVector<EVT, 4> ValueVTs;
3793   SmallVector<uint64_t, 4> Offsets;
3794   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3795                   ValueVTs, &Offsets);
3796   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3797          "expect a single EVT for swifterror");
3798 
3799   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3800   SDValue L = DAG.getCopyFromReg(
3801       getRoot(), getCurSDLoc(),
3802       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3803       ValueVTs[0]);
3804 
3805   setValue(&I, L);
3806 }
3807 
3808 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3809   if (I.isAtomic())
3810     return visitAtomicStore(I);
3811 
3812   const Value *SrcV = I.getOperand(0);
3813   const Value *PtrV = I.getOperand(1);
3814 
3815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3816   if (TLI.supportSwiftError()) {
3817     // Swifterror values can come from either a function parameter with
3818     // swifterror attribute or an alloca with swifterror attribute.
3819     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3820       if (Arg->hasSwiftErrorAttr())
3821         return visitStoreToSwiftError(I);
3822     }
3823 
3824     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3825       if (Alloca->isSwiftError())
3826         return visitStoreToSwiftError(I);
3827     }
3828   }
3829 
3830   SmallVector<EVT, 4> ValueVTs;
3831   SmallVector<uint64_t, 4> Offsets;
3832   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3833                   SrcV->getType(), ValueVTs, &Offsets);
3834   unsigned NumValues = ValueVTs.size();
3835   if (NumValues == 0)
3836     return;
3837 
3838   // Get the lowered operands. Note that we do this after
3839   // checking if NumResults is zero, because with zero results
3840   // the operands won't have values in the map.
3841   SDValue Src = getValue(SrcV);
3842   SDValue Ptr = getValue(PtrV);
3843 
3844   SDValue Root = getRoot();
3845   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3846   SDLoc dl = getCurSDLoc();
3847   EVT PtrVT = Ptr.getValueType();
3848   unsigned Alignment = I.getAlignment();
3849   AAMDNodes AAInfo;
3850   I.getAAMetadata(AAInfo);
3851 
3852   auto MMOFlags = MachineMemOperand::MONone;
3853   if (I.isVolatile())
3854     MMOFlags |= MachineMemOperand::MOVolatile;
3855   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3856     MMOFlags |= MachineMemOperand::MONonTemporal;
3857   MMOFlags |= TLI.getMMOFlags(I);
3858 
3859   // An aggregate load cannot wrap around the address space, so offsets to its
3860   // parts don't wrap either.
3861   SDNodeFlags Flags;
3862   Flags.setNoUnsignedWrap(true);
3863 
3864   unsigned ChainI = 0;
3865   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3866     // See visitLoad comments.
3867     if (ChainI == MaxParallelChains) {
3868       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3869                                   makeArrayRef(Chains.data(), ChainI));
3870       Root = Chain;
3871       ChainI = 0;
3872     }
3873     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3874                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3875     SDValue St = DAG.getStore(
3876         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3877         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3878     Chains[ChainI] = St;
3879   }
3880 
3881   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3882                                   makeArrayRef(Chains.data(), ChainI));
3883   DAG.setRoot(StoreNode);
3884 }
3885 
3886 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3887                                            bool IsCompressing) {
3888   SDLoc sdl = getCurSDLoc();
3889 
3890   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3891                            unsigned& Alignment) {
3892     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3893     Src0 = I.getArgOperand(0);
3894     Ptr = I.getArgOperand(1);
3895     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3896     Mask = I.getArgOperand(3);
3897   };
3898   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3899                            unsigned& Alignment) {
3900     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3901     Src0 = I.getArgOperand(0);
3902     Ptr = I.getArgOperand(1);
3903     Mask = I.getArgOperand(2);
3904     Alignment = 0;
3905   };
3906 
3907   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3908   unsigned Alignment;
3909   if (IsCompressing)
3910     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3911   else
3912     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3913 
3914   SDValue Ptr = getValue(PtrOperand);
3915   SDValue Src0 = getValue(Src0Operand);
3916   SDValue Mask = getValue(MaskOperand);
3917 
3918   EVT VT = Src0.getValueType();
3919   if (!Alignment)
3920     Alignment = DAG.getEVTAlignment(VT);
3921 
3922   AAMDNodes AAInfo;
3923   I.getAAMetadata(AAInfo);
3924 
3925   MachineMemOperand *MMO =
3926     DAG.getMachineFunction().
3927     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3928                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3929                           Alignment, AAInfo);
3930   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3931                                          MMO, false /* Truncating */,
3932                                          IsCompressing);
3933   DAG.setRoot(StoreNode);
3934   setValue(&I, StoreNode);
3935 }
3936 
3937 // Get a uniform base for the Gather/Scatter intrinsic.
3938 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3939 // We try to represent it as a base pointer + vector of indices.
3940 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3941 // The first operand of the GEP may be a single pointer or a vector of pointers
3942 // Example:
3943 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3944 //  or
3945 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3946 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3947 //
3948 // When the first GEP operand is a single pointer - it is the uniform base we
3949 // are looking for. If first operand of the GEP is a splat vector - we
3950 // extract the splat value and use it as a uniform base.
3951 // In all other cases the function returns 'false'.
3952 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3953                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3954   SelectionDAG& DAG = SDB->DAG;
3955   LLVMContext &Context = *DAG.getContext();
3956 
3957   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3958   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3959   if (!GEP)
3960     return false;
3961 
3962   const Value *GEPPtr = GEP->getPointerOperand();
3963   if (!GEPPtr->getType()->isVectorTy())
3964     Ptr = GEPPtr;
3965   else if (!(Ptr = getSplatValue(GEPPtr)))
3966     return false;
3967 
3968   unsigned FinalIndex = GEP->getNumOperands() - 1;
3969   Value *IndexVal = GEP->getOperand(FinalIndex);
3970 
3971   // Ensure all the other indices are 0.
3972   for (unsigned i = 1; i < FinalIndex; ++i) {
3973     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3974     if (!C || !C->isZero())
3975       return false;
3976   }
3977 
3978   // The operands of the GEP may be defined in another basic block.
3979   // In this case we'll not find nodes for the operands.
3980   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3981     return false;
3982 
3983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3984   const DataLayout &DL = DAG.getDataLayout();
3985   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3986                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3987   Base = SDB->getValue(Ptr);
3988   Index = SDB->getValue(IndexVal);
3989 
3990   if (!Index.getValueType().isVector()) {
3991     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3992     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3993     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3994   }
3995   return true;
3996 }
3997 
3998 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3999   SDLoc sdl = getCurSDLoc();
4000 
4001   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4002   const Value *Ptr = I.getArgOperand(1);
4003   SDValue Src0 = getValue(I.getArgOperand(0));
4004   SDValue Mask = getValue(I.getArgOperand(3));
4005   EVT VT = Src0.getValueType();
4006   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4007   if (!Alignment)
4008     Alignment = DAG.getEVTAlignment(VT);
4009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4010 
4011   AAMDNodes AAInfo;
4012   I.getAAMetadata(AAInfo);
4013 
4014   SDValue Base;
4015   SDValue Index;
4016   SDValue Scale;
4017   const Value *BasePtr = Ptr;
4018   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4019 
4020   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4021   MachineMemOperand *MMO = DAG.getMachineFunction().
4022     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4023                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4024                          Alignment, AAInfo);
4025   if (!UniformBase) {
4026     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4027     Index = getValue(Ptr);
4028     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4029   }
4030   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4031   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4032                                          Ops, MMO);
4033   DAG.setRoot(Scatter);
4034   setValue(&I, Scatter);
4035 }
4036 
4037 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4038   SDLoc sdl = getCurSDLoc();
4039 
4040   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4041                            unsigned& Alignment) {
4042     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4043     Ptr = I.getArgOperand(0);
4044     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4045     Mask = I.getArgOperand(2);
4046     Src0 = I.getArgOperand(3);
4047   };
4048   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4049                            unsigned& Alignment) {
4050     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4051     Ptr = I.getArgOperand(0);
4052     Alignment = 0;
4053     Mask = I.getArgOperand(1);
4054     Src0 = I.getArgOperand(2);
4055   };
4056 
4057   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4058   unsigned Alignment;
4059   if (IsExpanding)
4060     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4061   else
4062     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4063 
4064   SDValue Ptr = getValue(PtrOperand);
4065   SDValue Src0 = getValue(Src0Operand);
4066   SDValue Mask = getValue(MaskOperand);
4067 
4068   EVT VT = Src0.getValueType();
4069   if (!Alignment)
4070     Alignment = DAG.getEVTAlignment(VT);
4071 
4072   AAMDNodes AAInfo;
4073   I.getAAMetadata(AAInfo);
4074   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4075 
4076   // Do not serialize masked loads of constant memory with anything.
4077   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4078       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4079   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4080 
4081   MachineMemOperand *MMO =
4082     DAG.getMachineFunction().
4083     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4084                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4085                           Alignment, AAInfo, Ranges);
4086 
4087   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4088                                    ISD::NON_EXTLOAD, IsExpanding);
4089   if (AddToChain)
4090     PendingLoads.push_back(Load.getValue(1));
4091   setValue(&I, Load);
4092 }
4093 
4094 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4095   SDLoc sdl = getCurSDLoc();
4096 
4097   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4098   const Value *Ptr = I.getArgOperand(0);
4099   SDValue Src0 = getValue(I.getArgOperand(3));
4100   SDValue Mask = getValue(I.getArgOperand(2));
4101 
4102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4103   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4104   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4105   if (!Alignment)
4106     Alignment = DAG.getEVTAlignment(VT);
4107 
4108   AAMDNodes AAInfo;
4109   I.getAAMetadata(AAInfo);
4110   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4111 
4112   SDValue Root = DAG.getRoot();
4113   SDValue Base;
4114   SDValue Index;
4115   SDValue Scale;
4116   const Value *BasePtr = Ptr;
4117   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4118   bool ConstantMemory = false;
4119   if (UniformBase &&
4120       AA && AA->pointsToConstantMemory(MemoryLocation(
4121           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4122           AAInfo))) {
4123     // Do not serialize (non-volatile) loads of constant memory with anything.
4124     Root = DAG.getEntryNode();
4125     ConstantMemory = true;
4126   }
4127 
4128   MachineMemOperand *MMO =
4129     DAG.getMachineFunction().
4130     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4131                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4132                          Alignment, AAInfo, Ranges);
4133 
4134   if (!UniformBase) {
4135     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4136     Index = getValue(Ptr);
4137     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4138   }
4139   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4140   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4141                                        Ops, MMO);
4142 
4143   SDValue OutChain = Gather.getValue(1);
4144   if (!ConstantMemory)
4145     PendingLoads.push_back(OutChain);
4146   setValue(&I, Gather);
4147 }
4148 
4149 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4150   SDLoc dl = getCurSDLoc();
4151   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4152   AtomicOrdering FailureOrder = I.getFailureOrdering();
4153   SyncScope::ID SSID = I.getSyncScopeID();
4154 
4155   SDValue InChain = getRoot();
4156 
4157   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4158   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4159   SDValue L = DAG.getAtomicCmpSwap(
4160       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4161       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4162       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4163       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4164 
4165   SDValue OutChain = L.getValue(2);
4166 
4167   setValue(&I, L);
4168   DAG.setRoot(OutChain);
4169 }
4170 
4171 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4172   SDLoc dl = getCurSDLoc();
4173   ISD::NodeType NT;
4174   switch (I.getOperation()) {
4175   default: llvm_unreachable("Unknown atomicrmw operation");
4176   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4177   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4178   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4179   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4180   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4181   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4182   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4183   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4184   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4185   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4186   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4187   }
4188   AtomicOrdering Order = I.getOrdering();
4189   SyncScope::ID SSID = I.getSyncScopeID();
4190 
4191   SDValue InChain = getRoot();
4192 
4193   SDValue L =
4194     DAG.getAtomic(NT, dl,
4195                   getValue(I.getValOperand()).getSimpleValueType(),
4196                   InChain,
4197                   getValue(I.getPointerOperand()),
4198                   getValue(I.getValOperand()),
4199                   I.getPointerOperand(),
4200                   /* Alignment=*/ 0, Order, SSID);
4201 
4202   SDValue OutChain = L.getValue(1);
4203 
4204   setValue(&I, L);
4205   DAG.setRoot(OutChain);
4206 }
4207 
4208 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4209   SDLoc dl = getCurSDLoc();
4210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4211   SDValue Ops[3];
4212   Ops[0] = getRoot();
4213   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4214                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4215   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4216                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4217   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4218 }
4219 
4220 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4221   SDLoc dl = getCurSDLoc();
4222   AtomicOrdering Order = I.getOrdering();
4223   SyncScope::ID SSID = I.getSyncScopeID();
4224 
4225   SDValue InChain = getRoot();
4226 
4227   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4228   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4229 
4230   if (!TLI.supportsUnalignedAtomics() &&
4231       I.getAlignment() < VT.getStoreSize())
4232     report_fatal_error("Cannot generate unaligned atomic load");
4233 
4234   MachineMemOperand *MMO =
4235       DAG.getMachineFunction().
4236       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4237                            MachineMemOperand::MOVolatile |
4238                            MachineMemOperand::MOLoad,
4239                            VT.getStoreSize(),
4240                            I.getAlignment() ? I.getAlignment() :
4241                                               DAG.getEVTAlignment(VT),
4242                            AAMDNodes(), nullptr, SSID, Order);
4243 
4244   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4245   SDValue L =
4246       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4247                     getValue(I.getPointerOperand()), MMO);
4248 
4249   SDValue OutChain = L.getValue(1);
4250 
4251   setValue(&I, L);
4252   DAG.setRoot(OutChain);
4253 }
4254 
4255 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4256   SDLoc dl = getCurSDLoc();
4257 
4258   AtomicOrdering Order = I.getOrdering();
4259   SyncScope::ID SSID = I.getSyncScopeID();
4260 
4261   SDValue InChain = getRoot();
4262 
4263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4264   EVT VT =
4265       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4266 
4267   if (I.getAlignment() < VT.getStoreSize())
4268     report_fatal_error("Cannot generate unaligned atomic store");
4269 
4270   SDValue OutChain =
4271     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4272                   InChain,
4273                   getValue(I.getPointerOperand()),
4274                   getValue(I.getValueOperand()),
4275                   I.getPointerOperand(), I.getAlignment(),
4276                   Order, SSID);
4277 
4278   DAG.setRoot(OutChain);
4279 }
4280 
4281 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4282 /// node.
4283 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4284                                                unsigned Intrinsic) {
4285   // Ignore the callsite's attributes. A specific call site may be marked with
4286   // readnone, but the lowering code will expect the chain based on the
4287   // definition.
4288   const Function *F = I.getCalledFunction();
4289   bool HasChain = !F->doesNotAccessMemory();
4290   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4291 
4292   // Build the operand list.
4293   SmallVector<SDValue, 8> Ops;
4294   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4295     if (OnlyLoad) {
4296       // We don't need to serialize loads against other loads.
4297       Ops.push_back(DAG.getRoot());
4298     } else {
4299       Ops.push_back(getRoot());
4300     }
4301   }
4302 
4303   // Info is set by getTgtMemInstrinsic
4304   TargetLowering::IntrinsicInfo Info;
4305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4306   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4307                                                DAG.getMachineFunction(),
4308                                                Intrinsic);
4309 
4310   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4311   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4312       Info.opc == ISD::INTRINSIC_W_CHAIN)
4313     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4314                                         TLI.getPointerTy(DAG.getDataLayout())));
4315 
4316   // Add all operands of the call to the operand list.
4317   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4318     SDValue Op = getValue(I.getArgOperand(i));
4319     Ops.push_back(Op);
4320   }
4321 
4322   SmallVector<EVT, 4> ValueVTs;
4323   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4324 
4325   if (HasChain)
4326     ValueVTs.push_back(MVT::Other);
4327 
4328   SDVTList VTs = DAG.getVTList(ValueVTs);
4329 
4330   // Create the node.
4331   SDValue Result;
4332   if (IsTgtIntrinsic) {
4333     // This is target intrinsic that touches memory
4334     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4335       Ops, Info.memVT,
4336       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4337       Info.flags, Info.size);
4338   } else if (!HasChain) {
4339     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4340   } else if (!I.getType()->isVoidTy()) {
4341     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4342   } else {
4343     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4344   }
4345 
4346   if (HasChain) {
4347     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4348     if (OnlyLoad)
4349       PendingLoads.push_back(Chain);
4350     else
4351       DAG.setRoot(Chain);
4352   }
4353 
4354   if (!I.getType()->isVoidTy()) {
4355     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4356       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4357       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4358     } else
4359       Result = lowerRangeToAssertZExt(DAG, I, Result);
4360 
4361     setValue(&I, Result);
4362   }
4363 }
4364 
4365 /// GetSignificand - Get the significand and build it into a floating-point
4366 /// number with exponent of 1:
4367 ///
4368 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4369 ///
4370 /// where Op is the hexadecimal representation of floating point value.
4371 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4372   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4373                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4374   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4375                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4376   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4377 }
4378 
4379 /// GetExponent - Get the exponent:
4380 ///
4381 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4382 ///
4383 /// where Op is the hexadecimal representation of floating point value.
4384 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4385                            const TargetLowering &TLI, const SDLoc &dl) {
4386   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4387                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4388   SDValue t1 = DAG.getNode(
4389       ISD::SRL, dl, MVT::i32, t0,
4390       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4391   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4392                            DAG.getConstant(127, dl, MVT::i32));
4393   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4394 }
4395 
4396 /// getF32Constant - Get 32-bit floating point constant.
4397 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4398                               const SDLoc &dl) {
4399   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4400                            MVT::f32);
4401 }
4402 
4403 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4404                                        SelectionDAG &DAG) {
4405   // TODO: What fast-math-flags should be set on the floating-point nodes?
4406 
4407   //   IntegerPartOfX = ((int32_t)(t0);
4408   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4409 
4410   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4411   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4412   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4413 
4414   //   IntegerPartOfX <<= 23;
4415   IntegerPartOfX = DAG.getNode(
4416       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4417       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4418                                   DAG.getDataLayout())));
4419 
4420   SDValue TwoToFractionalPartOfX;
4421   if (LimitFloatPrecision <= 6) {
4422     // For floating-point precision of 6:
4423     //
4424     //   TwoToFractionalPartOfX =
4425     //     0.997535578f +
4426     //       (0.735607626f + 0.252464424f * x) * x;
4427     //
4428     // error 0.0144103317, which is 6 bits
4429     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4430                              getF32Constant(DAG, 0x3e814304, dl));
4431     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4432                              getF32Constant(DAG, 0x3f3c50c8, dl));
4433     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4434     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4435                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4436   } else if (LimitFloatPrecision <= 12) {
4437     // For floating-point precision of 12:
4438     //
4439     //   TwoToFractionalPartOfX =
4440     //     0.999892986f +
4441     //       (0.696457318f +
4442     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4443     //
4444     // error 0.000107046256, which is 13 to 14 bits
4445     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4446                              getF32Constant(DAG, 0x3da235e3, dl));
4447     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4448                              getF32Constant(DAG, 0x3e65b8f3, dl));
4449     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4450     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4451                              getF32Constant(DAG, 0x3f324b07, dl));
4452     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4453     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4454                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4455   } else { // LimitFloatPrecision <= 18
4456     // For floating-point precision of 18:
4457     //
4458     //   TwoToFractionalPartOfX =
4459     //     0.999999982f +
4460     //       (0.693148872f +
4461     //         (0.240227044f +
4462     //           (0.554906021e-1f +
4463     //             (0.961591928e-2f +
4464     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4465     // error 2.47208000*10^(-7), which is better than 18 bits
4466     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4467                              getF32Constant(DAG, 0x3924b03e, dl));
4468     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4469                              getF32Constant(DAG, 0x3ab24b87, dl));
4470     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4471     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4472                              getF32Constant(DAG, 0x3c1d8c17, dl));
4473     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4474     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4475                              getF32Constant(DAG, 0x3d634a1d, dl));
4476     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4477     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4478                              getF32Constant(DAG, 0x3e75fe14, dl));
4479     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4480     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4481                               getF32Constant(DAG, 0x3f317234, dl));
4482     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4483     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4484                                          getF32Constant(DAG, 0x3f800000, dl));
4485   }
4486 
4487   // Add the exponent into the result in integer domain.
4488   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4489   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4490                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4491 }
4492 
4493 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4494 /// limited-precision mode.
4495 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4496                          const TargetLowering &TLI) {
4497   if (Op.getValueType() == MVT::f32 &&
4498       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4499 
4500     // Put the exponent in the right bit position for later addition to the
4501     // final result:
4502     //
4503     //   #define LOG2OFe 1.4426950f
4504     //   t0 = Op * LOG2OFe
4505 
4506     // TODO: What fast-math-flags should be set here?
4507     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4508                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4509     return getLimitedPrecisionExp2(t0, dl, DAG);
4510   }
4511 
4512   // No special expansion.
4513   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4514 }
4515 
4516 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4517 /// limited-precision mode.
4518 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4519                          const TargetLowering &TLI) {
4520   // TODO: What fast-math-flags should be set on the floating-point nodes?
4521 
4522   if (Op.getValueType() == MVT::f32 &&
4523       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4524     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4525 
4526     // Scale the exponent by log(2) [0.69314718f].
4527     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4528     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4529                                         getF32Constant(DAG, 0x3f317218, dl));
4530 
4531     // Get the significand and build it into a floating-point number with
4532     // exponent of 1.
4533     SDValue X = GetSignificand(DAG, Op1, dl);
4534 
4535     SDValue LogOfMantissa;
4536     if (LimitFloatPrecision <= 6) {
4537       // For floating-point precision of 6:
4538       //
4539       //   LogofMantissa =
4540       //     -1.1609546f +
4541       //       (1.4034025f - 0.23903021f * x) * x;
4542       //
4543       // error 0.0034276066, which is better than 8 bits
4544       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4545                                getF32Constant(DAG, 0xbe74c456, dl));
4546       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4547                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4548       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4549       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4550                                   getF32Constant(DAG, 0x3f949a29, dl));
4551     } else if (LimitFloatPrecision <= 12) {
4552       // For floating-point precision of 12:
4553       //
4554       //   LogOfMantissa =
4555       //     -1.7417939f +
4556       //       (2.8212026f +
4557       //         (-1.4699568f +
4558       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4559       //
4560       // error 0.000061011436, which is 14 bits
4561       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4562                                getF32Constant(DAG, 0xbd67b6d6, dl));
4563       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4564                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4565       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4566       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4567                                getF32Constant(DAG, 0x3fbc278b, dl));
4568       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4569       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4570                                getF32Constant(DAG, 0x40348e95, dl));
4571       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4572       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4573                                   getF32Constant(DAG, 0x3fdef31a, dl));
4574     } else { // LimitFloatPrecision <= 18
4575       // For floating-point precision of 18:
4576       //
4577       //   LogOfMantissa =
4578       //     -2.1072184f +
4579       //       (4.2372794f +
4580       //         (-3.7029485f +
4581       //           (2.2781945f +
4582       //             (-0.87823314f +
4583       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4584       //
4585       // error 0.0000023660568, which is better than 18 bits
4586       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4587                                getF32Constant(DAG, 0xbc91e5ac, dl));
4588       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4589                                getF32Constant(DAG, 0x3e4350aa, dl));
4590       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4591       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4592                                getF32Constant(DAG, 0x3f60d3e3, dl));
4593       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4594       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4595                                getF32Constant(DAG, 0x4011cdf0, dl));
4596       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4597       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4598                                getF32Constant(DAG, 0x406cfd1c, dl));
4599       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4600       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4601                                getF32Constant(DAG, 0x408797cb, dl));
4602       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4603       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4604                                   getF32Constant(DAG, 0x4006dcab, dl));
4605     }
4606 
4607     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4608   }
4609 
4610   // No special expansion.
4611   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4612 }
4613 
4614 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4615 /// limited-precision mode.
4616 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4617                           const TargetLowering &TLI) {
4618   // TODO: What fast-math-flags should be set on the floating-point nodes?
4619 
4620   if (Op.getValueType() == MVT::f32 &&
4621       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4622     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4623 
4624     // Get the exponent.
4625     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4626 
4627     // Get the significand and build it into a floating-point number with
4628     // exponent of 1.
4629     SDValue X = GetSignificand(DAG, Op1, dl);
4630 
4631     // Different possible minimax approximations of significand in
4632     // floating-point for various degrees of accuracy over [1,2].
4633     SDValue Log2ofMantissa;
4634     if (LimitFloatPrecision <= 6) {
4635       // For floating-point precision of 6:
4636       //
4637       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4638       //
4639       // error 0.0049451742, which is more than 7 bits
4640       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4641                                getF32Constant(DAG, 0xbeb08fe0, dl));
4642       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4643                                getF32Constant(DAG, 0x40019463, dl));
4644       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4645       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4646                                    getF32Constant(DAG, 0x3fd6633d, dl));
4647     } else if (LimitFloatPrecision <= 12) {
4648       // For floating-point precision of 12:
4649       //
4650       //   Log2ofMantissa =
4651       //     -2.51285454f +
4652       //       (4.07009056f +
4653       //         (-2.12067489f +
4654       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4655       //
4656       // error 0.0000876136000, which is better than 13 bits
4657       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4658                                getF32Constant(DAG, 0xbda7262e, dl));
4659       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4660                                getF32Constant(DAG, 0x3f25280b, dl));
4661       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4662       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4663                                getF32Constant(DAG, 0x4007b923, dl));
4664       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4665       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4666                                getF32Constant(DAG, 0x40823e2f, dl));
4667       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4668       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4669                                    getF32Constant(DAG, 0x4020d29c, dl));
4670     } else { // LimitFloatPrecision <= 18
4671       // For floating-point precision of 18:
4672       //
4673       //   Log2ofMantissa =
4674       //     -3.0400495f +
4675       //       (6.1129976f +
4676       //         (-5.3420409f +
4677       //           (3.2865683f +
4678       //             (-1.2669343f +
4679       //               (0.27515199f -
4680       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4681       //
4682       // error 0.0000018516, which is better than 18 bits
4683       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4684                                getF32Constant(DAG, 0xbcd2769e, dl));
4685       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4686                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4687       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4688       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4689                                getF32Constant(DAG, 0x3fa22ae7, dl));
4690       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4691       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4692                                getF32Constant(DAG, 0x40525723, dl));
4693       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4694       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4695                                getF32Constant(DAG, 0x40aaf200, dl));
4696       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4697       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4698                                getF32Constant(DAG, 0x40c39dad, dl));
4699       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4700       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4701                                    getF32Constant(DAG, 0x4042902c, dl));
4702     }
4703 
4704     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4705   }
4706 
4707   // No special expansion.
4708   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4709 }
4710 
4711 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4712 /// limited-precision mode.
4713 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4714                            const TargetLowering &TLI) {
4715   // TODO: What fast-math-flags should be set on the floating-point nodes?
4716 
4717   if (Op.getValueType() == MVT::f32 &&
4718       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4719     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4720 
4721     // Scale the exponent by log10(2) [0.30102999f].
4722     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4723     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4724                                         getF32Constant(DAG, 0x3e9a209a, dl));
4725 
4726     // Get the significand and build it into a floating-point number with
4727     // exponent of 1.
4728     SDValue X = GetSignificand(DAG, Op1, dl);
4729 
4730     SDValue Log10ofMantissa;
4731     if (LimitFloatPrecision <= 6) {
4732       // For floating-point precision of 6:
4733       //
4734       //   Log10ofMantissa =
4735       //     -0.50419619f +
4736       //       (0.60948995f - 0.10380950f * x) * x;
4737       //
4738       // error 0.0014886165, which is 6 bits
4739       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4740                                getF32Constant(DAG, 0xbdd49a13, dl));
4741       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4742                                getF32Constant(DAG, 0x3f1c0789, dl));
4743       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4744       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4745                                     getF32Constant(DAG, 0x3f011300, dl));
4746     } else if (LimitFloatPrecision <= 12) {
4747       // For floating-point precision of 12:
4748       //
4749       //   Log10ofMantissa =
4750       //     -0.64831180f +
4751       //       (0.91751397f +
4752       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4753       //
4754       // error 0.00019228036, which is better than 12 bits
4755       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4756                                getF32Constant(DAG, 0x3d431f31, dl));
4757       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4758                                getF32Constant(DAG, 0x3ea21fb2, dl));
4759       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4760       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4761                                getF32Constant(DAG, 0x3f6ae232, dl));
4762       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4763       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4764                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4765     } else { // LimitFloatPrecision <= 18
4766       // For floating-point precision of 18:
4767       //
4768       //   Log10ofMantissa =
4769       //     -0.84299375f +
4770       //       (1.5327582f +
4771       //         (-1.0688956f +
4772       //           (0.49102474f +
4773       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4774       //
4775       // error 0.0000037995730, which is better than 18 bits
4776       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4777                                getF32Constant(DAG, 0x3c5d51ce, dl));
4778       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4779                                getF32Constant(DAG, 0x3e00685a, dl));
4780       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4781       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4782                                getF32Constant(DAG, 0x3efb6798, dl));
4783       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4784       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4785                                getF32Constant(DAG, 0x3f88d192, dl));
4786       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4787       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4788                                getF32Constant(DAG, 0x3fc4316c, dl));
4789       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4790       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4791                                     getF32Constant(DAG, 0x3f57ce70, dl));
4792     }
4793 
4794     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4795   }
4796 
4797   // No special expansion.
4798   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4799 }
4800 
4801 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4802 /// limited-precision mode.
4803 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4804                           const TargetLowering &TLI) {
4805   if (Op.getValueType() == MVT::f32 &&
4806       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4807     return getLimitedPrecisionExp2(Op, dl, DAG);
4808 
4809   // No special expansion.
4810   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4811 }
4812 
4813 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4814 /// limited-precision mode with x == 10.0f.
4815 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4816                          SelectionDAG &DAG, const TargetLowering &TLI) {
4817   bool IsExp10 = false;
4818   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4819       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4820     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4821       APFloat Ten(10.0f);
4822       IsExp10 = LHSC->isExactlyValue(Ten);
4823     }
4824   }
4825 
4826   // TODO: What fast-math-flags should be set on the FMUL node?
4827   if (IsExp10) {
4828     // Put the exponent in the right bit position for later addition to the
4829     // final result:
4830     //
4831     //   #define LOG2OF10 3.3219281f
4832     //   t0 = Op * LOG2OF10;
4833     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4834                              getF32Constant(DAG, 0x40549a78, dl));
4835     return getLimitedPrecisionExp2(t0, dl, DAG);
4836   }
4837 
4838   // No special expansion.
4839   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4840 }
4841 
4842 /// ExpandPowI - Expand a llvm.powi intrinsic.
4843 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4844                           SelectionDAG &DAG) {
4845   // If RHS is a constant, we can expand this out to a multiplication tree,
4846   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4847   // optimizing for size, we only want to do this if the expansion would produce
4848   // a small number of multiplies, otherwise we do the full expansion.
4849   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4850     // Get the exponent as a positive value.
4851     unsigned Val = RHSC->getSExtValue();
4852     if ((int)Val < 0) Val = -Val;
4853 
4854     // powi(x, 0) -> 1.0
4855     if (Val == 0)
4856       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4857 
4858     const Function &F = DAG.getMachineFunction().getFunction();
4859     if (!F.optForSize() ||
4860         // If optimizing for size, don't insert too many multiplies.
4861         // This inserts up to 5 multiplies.
4862         countPopulation(Val) + Log2_32(Val) < 7) {
4863       // We use the simple binary decomposition method to generate the multiply
4864       // sequence.  There are more optimal ways to do this (for example,
4865       // powi(x,15) generates one more multiply than it should), but this has
4866       // the benefit of being both really simple and much better than a libcall.
4867       SDValue Res;  // Logically starts equal to 1.0
4868       SDValue CurSquare = LHS;
4869       // TODO: Intrinsics should have fast-math-flags that propagate to these
4870       // nodes.
4871       while (Val) {
4872         if (Val & 1) {
4873           if (Res.getNode())
4874             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4875           else
4876             Res = CurSquare;  // 1.0*CurSquare.
4877         }
4878 
4879         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4880                                 CurSquare, CurSquare);
4881         Val >>= 1;
4882       }
4883 
4884       // If the original was negative, invert the result, producing 1/(x*x*x).
4885       if (RHSC->getSExtValue() < 0)
4886         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4887                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4888       return Res;
4889     }
4890   }
4891 
4892   // Otherwise, expand to a libcall.
4893   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4894 }
4895 
4896 // getUnderlyingArgReg - Find underlying register used for a truncated or
4897 // bitcasted argument.
4898 static unsigned getUnderlyingArgReg(const SDValue &N) {
4899   switch (N.getOpcode()) {
4900   case ISD::CopyFromReg:
4901     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4902   case ISD::BITCAST:
4903   case ISD::AssertZext:
4904   case ISD::AssertSext:
4905   case ISD::TRUNCATE:
4906     return getUnderlyingArgReg(N.getOperand(0));
4907   default:
4908     return 0;
4909   }
4910 }
4911 
4912 /// If the DbgValueInst is a dbg_value of a function argument, create the
4913 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4914 /// instruction selection, they will be inserted to the entry BB.
4915 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4916     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4917     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4918   const Argument *Arg = dyn_cast<Argument>(V);
4919   if (!Arg)
4920     return false;
4921 
4922   MachineFunction &MF = DAG.getMachineFunction();
4923   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4924 
4925   bool IsIndirect = false;
4926   Optional<MachineOperand> Op;
4927   // Some arguments' frame index is recorded during argument lowering.
4928   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4929   if (FI != std::numeric_limits<int>::max())
4930     Op = MachineOperand::CreateFI(FI);
4931 
4932   if (!Op && N.getNode()) {
4933     unsigned Reg = getUnderlyingArgReg(N);
4934     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4935       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4936       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4937       if (PR)
4938         Reg = PR;
4939     }
4940     if (Reg) {
4941       Op = MachineOperand::CreateReg(Reg, false);
4942       IsIndirect = IsDbgDeclare;
4943     }
4944   }
4945 
4946   if (!Op && N.getNode())
4947     // Check if frame index is available.
4948     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4949       if (FrameIndexSDNode *FINode =
4950           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4951         Op = MachineOperand::CreateFI(FINode->getIndex());
4952 
4953   if (!Op) {
4954     // Check if ValueMap has reg number.
4955     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4956     if (VMI != FuncInfo.ValueMap.end()) {
4957       const auto &TLI = DAG.getTargetLoweringInfo();
4958       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4959                        V->getType(), getABIRegCopyCC(V));
4960       if (RFV.occupiesMultipleRegs()) {
4961         unsigned Offset = 0;
4962         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4963           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4964           auto FragmentExpr = DIExpression::createFragmentExpression(
4965               Expr, Offset, RegAndSize.second);
4966           if (!FragmentExpr)
4967             continue;
4968           FuncInfo.ArgDbgValues.push_back(
4969               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4970                       Op->getReg(), Variable, *FragmentExpr));
4971           Offset += RegAndSize.second;
4972         }
4973         return true;
4974       }
4975       Op = MachineOperand::CreateReg(VMI->second, false);
4976       IsIndirect = IsDbgDeclare;
4977     }
4978   }
4979 
4980   if (!Op)
4981     return false;
4982 
4983   assert(Variable->isValidLocationForIntrinsic(DL) &&
4984          "Expected inlined-at fields to agree");
4985   IsIndirect = (Op->isReg()) ? IsIndirect : true;
4986   FuncInfo.ArgDbgValues.push_back(
4987       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4988               *Op, Variable, Expr));
4989 
4990   return true;
4991 }
4992 
4993 /// Return the appropriate SDDbgValue based on N.
4994 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4995                                              DILocalVariable *Variable,
4996                                              DIExpression *Expr,
4997                                              const DebugLoc &dl,
4998                                              unsigned DbgSDNodeOrder) {
4999   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5000     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5001     // stack slot locations.
5002     //
5003     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5004     // debug values here after optimization:
5005     //
5006     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5007     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5008     //
5009     // Both describe the direct values of their associated variables.
5010     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5011                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5012   }
5013   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5014                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5015 }
5016 
5017 // VisualStudio defines setjmp as _setjmp
5018 #if defined(_MSC_VER) && defined(setjmp) && \
5019                          !defined(setjmp_undefined_for_msvc)
5020 #  pragma push_macro("setjmp")
5021 #  undef setjmp
5022 #  define setjmp_undefined_for_msvc
5023 #endif
5024 
5025 /// Lower the call to the specified intrinsic function. If we want to emit this
5026 /// as a call to a named external function, return the name. Otherwise, lower it
5027 /// and return null.
5028 const char *
5029 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5031   SDLoc sdl = getCurSDLoc();
5032   DebugLoc dl = getCurDebugLoc();
5033   SDValue Res;
5034 
5035   switch (Intrinsic) {
5036   default:
5037     // By default, turn this into a target intrinsic node.
5038     visitTargetIntrinsic(I, Intrinsic);
5039     return nullptr;
5040   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5041   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5042   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5043   case Intrinsic::returnaddress:
5044     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5045                              TLI.getPointerTy(DAG.getDataLayout()),
5046                              getValue(I.getArgOperand(0))));
5047     return nullptr;
5048   case Intrinsic::addressofreturnaddress:
5049     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5050                              TLI.getPointerTy(DAG.getDataLayout())));
5051     return nullptr;
5052   case Intrinsic::frameaddress:
5053     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5054                              TLI.getPointerTy(DAG.getDataLayout()),
5055                              getValue(I.getArgOperand(0))));
5056     return nullptr;
5057   case Intrinsic::read_register: {
5058     Value *Reg = I.getArgOperand(0);
5059     SDValue Chain = getRoot();
5060     SDValue RegName =
5061         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5062     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5063     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5064       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5065     setValue(&I, Res);
5066     DAG.setRoot(Res.getValue(1));
5067     return nullptr;
5068   }
5069   case Intrinsic::write_register: {
5070     Value *Reg = I.getArgOperand(0);
5071     Value *RegValue = I.getArgOperand(1);
5072     SDValue Chain = getRoot();
5073     SDValue RegName =
5074         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5075     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5076                             RegName, getValue(RegValue)));
5077     return nullptr;
5078   }
5079   case Intrinsic::setjmp:
5080     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5081   case Intrinsic::longjmp:
5082     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5083   case Intrinsic::memcpy: {
5084     const auto &MCI = cast<MemCpyInst>(I);
5085     SDValue Op1 = getValue(I.getArgOperand(0));
5086     SDValue Op2 = getValue(I.getArgOperand(1));
5087     SDValue Op3 = getValue(I.getArgOperand(2));
5088     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5089     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5090     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5091     unsigned Align = MinAlign(DstAlign, SrcAlign);
5092     bool isVol = MCI.isVolatile();
5093     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5094     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5095     // node.
5096     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5097                                false, isTC,
5098                                MachinePointerInfo(I.getArgOperand(0)),
5099                                MachinePointerInfo(I.getArgOperand(1)));
5100     updateDAGForMaybeTailCall(MC);
5101     return nullptr;
5102   }
5103   case Intrinsic::memset: {
5104     const auto &MSI = cast<MemSetInst>(I);
5105     SDValue Op1 = getValue(I.getArgOperand(0));
5106     SDValue Op2 = getValue(I.getArgOperand(1));
5107     SDValue Op3 = getValue(I.getArgOperand(2));
5108     // @llvm.memset defines 0 and 1 to both mean no alignment.
5109     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5110     bool isVol = MSI.isVolatile();
5111     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5112     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5113                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5114     updateDAGForMaybeTailCall(MS);
5115     return nullptr;
5116   }
5117   case Intrinsic::memmove: {
5118     const auto &MMI = cast<MemMoveInst>(I);
5119     SDValue Op1 = getValue(I.getArgOperand(0));
5120     SDValue Op2 = getValue(I.getArgOperand(1));
5121     SDValue Op3 = getValue(I.getArgOperand(2));
5122     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5123     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5124     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5125     unsigned Align = MinAlign(DstAlign, SrcAlign);
5126     bool isVol = MMI.isVolatile();
5127     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5128     // FIXME: Support passing different dest/src alignments to the memmove DAG
5129     // node.
5130     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5131                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5132                                 MachinePointerInfo(I.getArgOperand(1)));
5133     updateDAGForMaybeTailCall(MM);
5134     return nullptr;
5135   }
5136   case Intrinsic::memcpy_element_unordered_atomic: {
5137     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5138     SDValue Dst = getValue(MI.getRawDest());
5139     SDValue Src = getValue(MI.getRawSource());
5140     SDValue Length = getValue(MI.getLength());
5141 
5142     unsigned DstAlign = MI.getDestAlignment();
5143     unsigned SrcAlign = MI.getSourceAlignment();
5144     Type *LengthTy = MI.getLength()->getType();
5145     unsigned ElemSz = MI.getElementSizeInBytes();
5146     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5147     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5148                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5149                                      MachinePointerInfo(MI.getRawDest()),
5150                                      MachinePointerInfo(MI.getRawSource()));
5151     updateDAGForMaybeTailCall(MC);
5152     return nullptr;
5153   }
5154   case Intrinsic::memmove_element_unordered_atomic: {
5155     auto &MI = cast<AtomicMemMoveInst>(I);
5156     SDValue Dst = getValue(MI.getRawDest());
5157     SDValue Src = getValue(MI.getRawSource());
5158     SDValue Length = getValue(MI.getLength());
5159 
5160     unsigned DstAlign = MI.getDestAlignment();
5161     unsigned SrcAlign = MI.getSourceAlignment();
5162     Type *LengthTy = MI.getLength()->getType();
5163     unsigned ElemSz = MI.getElementSizeInBytes();
5164     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5165     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5166                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5167                                       MachinePointerInfo(MI.getRawDest()),
5168                                       MachinePointerInfo(MI.getRawSource()));
5169     updateDAGForMaybeTailCall(MC);
5170     return nullptr;
5171   }
5172   case Intrinsic::memset_element_unordered_atomic: {
5173     auto &MI = cast<AtomicMemSetInst>(I);
5174     SDValue Dst = getValue(MI.getRawDest());
5175     SDValue Val = getValue(MI.getValue());
5176     SDValue Length = getValue(MI.getLength());
5177 
5178     unsigned DstAlign = MI.getDestAlignment();
5179     Type *LengthTy = MI.getLength()->getType();
5180     unsigned ElemSz = MI.getElementSizeInBytes();
5181     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5182     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5183                                      LengthTy, ElemSz, isTC,
5184                                      MachinePointerInfo(MI.getRawDest()));
5185     updateDAGForMaybeTailCall(MC);
5186     return nullptr;
5187   }
5188   case Intrinsic::dbg_addr:
5189   case Intrinsic::dbg_declare: {
5190     const auto &DI = cast<DbgVariableIntrinsic>(I);
5191     DILocalVariable *Variable = DI.getVariable();
5192     DIExpression *Expression = DI.getExpression();
5193     dropDanglingDebugInfo(Variable, Expression);
5194     assert(Variable && "Missing variable");
5195 
5196     // Check if address has undef value.
5197     const Value *Address = DI.getVariableLocation();
5198     if (!Address || isa<UndefValue>(Address) ||
5199         (Address->use_empty() && !isa<Argument>(Address))) {
5200       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5201       return nullptr;
5202     }
5203 
5204     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5205 
5206     // Check if this variable can be described by a frame index, typically
5207     // either as a static alloca or a byval parameter.
5208     int FI = std::numeric_limits<int>::max();
5209     if (const auto *AI =
5210             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5211       if (AI->isStaticAlloca()) {
5212         auto I = FuncInfo.StaticAllocaMap.find(AI);
5213         if (I != FuncInfo.StaticAllocaMap.end())
5214           FI = I->second;
5215       }
5216     } else if (const auto *Arg = dyn_cast<Argument>(
5217                    Address->stripInBoundsConstantOffsets())) {
5218       FI = FuncInfo.getArgumentFrameIndex(Arg);
5219     }
5220 
5221     // llvm.dbg.addr is control dependent and always generates indirect
5222     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5223     // the MachineFunction variable table.
5224     if (FI != std::numeric_limits<int>::max()) {
5225       if (Intrinsic == Intrinsic::dbg_addr) {
5226         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5227             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5228         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5229       }
5230       return nullptr;
5231     }
5232 
5233     SDValue &N = NodeMap[Address];
5234     if (!N.getNode() && isa<Argument>(Address))
5235       // Check unused arguments map.
5236       N = UnusedArgNodeMap[Address];
5237     SDDbgValue *SDV;
5238     if (N.getNode()) {
5239       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5240         Address = BCI->getOperand(0);
5241       // Parameters are handled specially.
5242       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5243       if (isParameter && FINode) {
5244         // Byval parameter. We have a frame index at this point.
5245         SDV =
5246             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5247                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5248       } else if (isa<Argument>(Address)) {
5249         // Address is an argument, so try to emit its dbg value using
5250         // virtual register info from the FuncInfo.ValueMap.
5251         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5252         return nullptr;
5253       } else {
5254         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5255                               true, dl, SDNodeOrder);
5256       }
5257       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5258     } else {
5259       // If Address is an argument then try to emit its dbg value using
5260       // virtual register info from the FuncInfo.ValueMap.
5261       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5262                                     N)) {
5263         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5264       }
5265     }
5266     return nullptr;
5267   }
5268   case Intrinsic::dbg_label: {
5269     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5270     DILabel *Label = DI.getLabel();
5271     assert(Label && "Missing label");
5272 
5273     SDDbgLabel *SDV;
5274     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5275     DAG.AddDbgLabel(SDV);
5276     return nullptr;
5277   }
5278   case Intrinsic::dbg_value: {
5279     const DbgValueInst &DI = cast<DbgValueInst>(I);
5280     assert(DI.getVariable() && "Missing variable");
5281 
5282     DILocalVariable *Variable = DI.getVariable();
5283     DIExpression *Expression = DI.getExpression();
5284     dropDanglingDebugInfo(Variable, Expression);
5285     const Value *V = DI.getValue();
5286     if (!V)
5287       return nullptr;
5288 
5289     SDDbgValue *SDV;
5290     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5291       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5292       DAG.AddDbgValue(SDV, nullptr, false);
5293       return nullptr;
5294     }
5295 
5296     // Do not use getValue() in here; we don't want to generate code at
5297     // this point if it hasn't been done yet.
5298     SDValue N = NodeMap[V];
5299     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5300       N = UnusedArgNodeMap[V];
5301     if (N.getNode()) {
5302       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5303         return nullptr;
5304       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5305       DAG.AddDbgValue(SDV, N.getNode(), false);
5306       return nullptr;
5307     }
5308 
5309     // PHI nodes have already been selected, so we should know which VReg that
5310     // is assigns to already.
5311     if (isa<PHINode>(V)) {
5312       auto VMI = FuncInfo.ValueMap.find(V);
5313       if (VMI != FuncInfo.ValueMap.end()) {
5314         unsigned Reg = VMI->second;
5315         // The PHI node may be split up into several MI PHI nodes (in
5316         // FunctionLoweringInfo::set).
5317         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5318                          V->getType(), None);
5319         if (RFV.occupiesMultipleRegs()) {
5320           unsigned Offset = 0;
5321           unsigned BitsToDescribe = 0;
5322           if (auto VarSize = Variable->getSizeInBits())
5323             BitsToDescribe = *VarSize;
5324           if (auto Fragment = Expression->getFragmentInfo())
5325             BitsToDescribe = Fragment->SizeInBits;
5326           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5327             unsigned RegisterSize = RegAndSize.second;
5328             // Bail out if all bits are described already.
5329             if (Offset >= BitsToDescribe)
5330               break;
5331             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5332                 ? BitsToDescribe - Offset
5333                 : RegisterSize;
5334             auto FragmentExpr = DIExpression::createFragmentExpression(
5335                 Expression, Offset, FragmentSize);
5336             if (!FragmentExpr)
5337                 continue;
5338             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5339                                       false, dl, SDNodeOrder);
5340             DAG.AddDbgValue(SDV, nullptr, false);
5341             Offset += RegisterSize;
5342           }
5343         } else {
5344           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5345                                     SDNodeOrder);
5346           DAG.AddDbgValue(SDV, nullptr, false);
5347         }
5348         return nullptr;
5349       }
5350     }
5351 
5352     // TODO: When we get here we will either drop the dbg.value completely, or
5353     // we try to move it forward by letting it dangle for awhile. So we should
5354     // probably add an extra DbgValue to the DAG here, with a reference to
5355     // "noreg", to indicate that we have lost the debug location for the
5356     // variable.
5357 
5358     if (!V->use_empty() ) {
5359       // Do not call getValue(V) yet, as we don't want to generate code.
5360       // Remember it for later.
5361       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5362       return nullptr;
5363     }
5364 
5365     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5366     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5367     return nullptr;
5368   }
5369 
5370   case Intrinsic::eh_typeid_for: {
5371     // Find the type id for the given typeinfo.
5372     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5373     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5374     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5375     setValue(&I, Res);
5376     return nullptr;
5377   }
5378 
5379   case Intrinsic::eh_return_i32:
5380   case Intrinsic::eh_return_i64:
5381     DAG.getMachineFunction().setCallsEHReturn(true);
5382     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5383                             MVT::Other,
5384                             getControlRoot(),
5385                             getValue(I.getArgOperand(0)),
5386                             getValue(I.getArgOperand(1))));
5387     return nullptr;
5388   case Intrinsic::eh_unwind_init:
5389     DAG.getMachineFunction().setCallsUnwindInit(true);
5390     return nullptr;
5391   case Intrinsic::eh_dwarf_cfa:
5392     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5393                              TLI.getPointerTy(DAG.getDataLayout()),
5394                              getValue(I.getArgOperand(0))));
5395     return nullptr;
5396   case Intrinsic::eh_sjlj_callsite: {
5397     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5398     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5399     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5400     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5401 
5402     MMI.setCurrentCallSite(CI->getZExtValue());
5403     return nullptr;
5404   }
5405   case Intrinsic::eh_sjlj_functioncontext: {
5406     // Get and store the index of the function context.
5407     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5408     AllocaInst *FnCtx =
5409       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5410     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5411     MFI.setFunctionContextIndex(FI);
5412     return nullptr;
5413   }
5414   case Intrinsic::eh_sjlj_setjmp: {
5415     SDValue Ops[2];
5416     Ops[0] = getRoot();
5417     Ops[1] = getValue(I.getArgOperand(0));
5418     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5419                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5420     setValue(&I, Op.getValue(0));
5421     DAG.setRoot(Op.getValue(1));
5422     return nullptr;
5423   }
5424   case Intrinsic::eh_sjlj_longjmp:
5425     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5426                             getRoot(), getValue(I.getArgOperand(0))));
5427     return nullptr;
5428   case Intrinsic::eh_sjlj_setup_dispatch:
5429     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5430                             getRoot()));
5431     return nullptr;
5432   case Intrinsic::masked_gather:
5433     visitMaskedGather(I);
5434     return nullptr;
5435   case Intrinsic::masked_load:
5436     visitMaskedLoad(I);
5437     return nullptr;
5438   case Intrinsic::masked_scatter:
5439     visitMaskedScatter(I);
5440     return nullptr;
5441   case Intrinsic::masked_store:
5442     visitMaskedStore(I);
5443     return nullptr;
5444   case Intrinsic::masked_expandload:
5445     visitMaskedLoad(I, true /* IsExpanding */);
5446     return nullptr;
5447   case Intrinsic::masked_compressstore:
5448     visitMaskedStore(I, true /* IsCompressing */);
5449     return nullptr;
5450   case Intrinsic::x86_mmx_pslli_w:
5451   case Intrinsic::x86_mmx_pslli_d:
5452   case Intrinsic::x86_mmx_pslli_q:
5453   case Intrinsic::x86_mmx_psrli_w:
5454   case Intrinsic::x86_mmx_psrli_d:
5455   case Intrinsic::x86_mmx_psrli_q:
5456   case Intrinsic::x86_mmx_psrai_w:
5457   case Intrinsic::x86_mmx_psrai_d: {
5458     SDValue ShAmt = getValue(I.getArgOperand(1));
5459     if (isa<ConstantSDNode>(ShAmt)) {
5460       visitTargetIntrinsic(I, Intrinsic);
5461       return nullptr;
5462     }
5463     unsigned NewIntrinsic = 0;
5464     EVT ShAmtVT = MVT::v2i32;
5465     switch (Intrinsic) {
5466     case Intrinsic::x86_mmx_pslli_w:
5467       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5468       break;
5469     case Intrinsic::x86_mmx_pslli_d:
5470       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5471       break;
5472     case Intrinsic::x86_mmx_pslli_q:
5473       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5474       break;
5475     case Intrinsic::x86_mmx_psrli_w:
5476       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5477       break;
5478     case Intrinsic::x86_mmx_psrli_d:
5479       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5480       break;
5481     case Intrinsic::x86_mmx_psrli_q:
5482       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5483       break;
5484     case Intrinsic::x86_mmx_psrai_w:
5485       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5486       break;
5487     case Intrinsic::x86_mmx_psrai_d:
5488       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5489       break;
5490     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5491     }
5492 
5493     // The vector shift intrinsics with scalars uses 32b shift amounts but
5494     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5495     // to be zero.
5496     // We must do this early because v2i32 is not a legal type.
5497     SDValue ShOps[2];
5498     ShOps[0] = ShAmt;
5499     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5500     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5501     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5502     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5503     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5504                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5505                        getValue(I.getArgOperand(0)), ShAmt);
5506     setValue(&I, Res);
5507     return nullptr;
5508   }
5509   case Intrinsic::powi:
5510     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5511                             getValue(I.getArgOperand(1)), DAG));
5512     return nullptr;
5513   case Intrinsic::log:
5514     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5515     return nullptr;
5516   case Intrinsic::log2:
5517     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5518     return nullptr;
5519   case Intrinsic::log10:
5520     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5521     return nullptr;
5522   case Intrinsic::exp:
5523     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5524     return nullptr;
5525   case Intrinsic::exp2:
5526     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5527     return nullptr;
5528   case Intrinsic::pow:
5529     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5530                            getValue(I.getArgOperand(1)), DAG, TLI));
5531     return nullptr;
5532   case Intrinsic::sqrt:
5533   case Intrinsic::fabs:
5534   case Intrinsic::sin:
5535   case Intrinsic::cos:
5536   case Intrinsic::floor:
5537   case Intrinsic::ceil:
5538   case Intrinsic::trunc:
5539   case Intrinsic::rint:
5540   case Intrinsic::nearbyint:
5541   case Intrinsic::round:
5542   case Intrinsic::canonicalize: {
5543     unsigned Opcode;
5544     switch (Intrinsic) {
5545     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5546     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5547     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5548     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5549     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5550     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5551     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5552     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5553     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5554     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5555     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5556     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5557     }
5558 
5559     setValue(&I, DAG.getNode(Opcode, sdl,
5560                              getValue(I.getArgOperand(0)).getValueType(),
5561                              getValue(I.getArgOperand(0))));
5562     return nullptr;
5563   }
5564   case Intrinsic::minnum: {
5565     auto VT = getValue(I.getArgOperand(0)).getValueType();
5566     unsigned Opc =
5567         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5568             ? ISD::FMINNAN
5569             : ISD::FMINNUM;
5570     setValue(&I, DAG.getNode(Opc, sdl, VT,
5571                              getValue(I.getArgOperand(0)),
5572                              getValue(I.getArgOperand(1))));
5573     return nullptr;
5574   }
5575   case Intrinsic::maxnum: {
5576     auto VT = getValue(I.getArgOperand(0)).getValueType();
5577     unsigned Opc =
5578         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5579             ? ISD::FMAXNAN
5580             : ISD::FMAXNUM;
5581     setValue(&I, DAG.getNode(Opc, sdl, VT,
5582                              getValue(I.getArgOperand(0)),
5583                              getValue(I.getArgOperand(1))));
5584     return nullptr;
5585   }
5586   case Intrinsic::copysign:
5587     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5588                              getValue(I.getArgOperand(0)).getValueType(),
5589                              getValue(I.getArgOperand(0)),
5590                              getValue(I.getArgOperand(1))));
5591     return nullptr;
5592   case Intrinsic::fma:
5593     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5594                              getValue(I.getArgOperand(0)).getValueType(),
5595                              getValue(I.getArgOperand(0)),
5596                              getValue(I.getArgOperand(1)),
5597                              getValue(I.getArgOperand(2))));
5598     return nullptr;
5599   case Intrinsic::experimental_constrained_fadd:
5600   case Intrinsic::experimental_constrained_fsub:
5601   case Intrinsic::experimental_constrained_fmul:
5602   case Intrinsic::experimental_constrained_fdiv:
5603   case Intrinsic::experimental_constrained_frem:
5604   case Intrinsic::experimental_constrained_fma:
5605   case Intrinsic::experimental_constrained_sqrt:
5606   case Intrinsic::experimental_constrained_pow:
5607   case Intrinsic::experimental_constrained_powi:
5608   case Intrinsic::experimental_constrained_sin:
5609   case Intrinsic::experimental_constrained_cos:
5610   case Intrinsic::experimental_constrained_exp:
5611   case Intrinsic::experimental_constrained_exp2:
5612   case Intrinsic::experimental_constrained_log:
5613   case Intrinsic::experimental_constrained_log10:
5614   case Intrinsic::experimental_constrained_log2:
5615   case Intrinsic::experimental_constrained_rint:
5616   case Intrinsic::experimental_constrained_nearbyint:
5617     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5618     return nullptr;
5619   case Intrinsic::fmuladd: {
5620     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5621     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5622         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5623       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5624                                getValue(I.getArgOperand(0)).getValueType(),
5625                                getValue(I.getArgOperand(0)),
5626                                getValue(I.getArgOperand(1)),
5627                                getValue(I.getArgOperand(2))));
5628     } else {
5629       // TODO: Intrinsic calls should have fast-math-flags.
5630       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5631                                 getValue(I.getArgOperand(0)).getValueType(),
5632                                 getValue(I.getArgOperand(0)),
5633                                 getValue(I.getArgOperand(1)));
5634       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5635                                 getValue(I.getArgOperand(0)).getValueType(),
5636                                 Mul,
5637                                 getValue(I.getArgOperand(2)));
5638       setValue(&I, Add);
5639     }
5640     return nullptr;
5641   }
5642   case Intrinsic::convert_to_fp16:
5643     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5644                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5645                                          getValue(I.getArgOperand(0)),
5646                                          DAG.getTargetConstant(0, sdl,
5647                                                                MVT::i32))));
5648     return nullptr;
5649   case Intrinsic::convert_from_fp16:
5650     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5651                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5652                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5653                                          getValue(I.getArgOperand(0)))));
5654     return nullptr;
5655   case Intrinsic::pcmarker: {
5656     SDValue Tmp = getValue(I.getArgOperand(0));
5657     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5658     return nullptr;
5659   }
5660   case Intrinsic::readcyclecounter: {
5661     SDValue Op = getRoot();
5662     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5663                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5664     setValue(&I, Res);
5665     DAG.setRoot(Res.getValue(1));
5666     return nullptr;
5667   }
5668   case Intrinsic::bitreverse:
5669     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5670                              getValue(I.getArgOperand(0)).getValueType(),
5671                              getValue(I.getArgOperand(0))));
5672     return nullptr;
5673   case Intrinsic::bswap:
5674     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5675                              getValue(I.getArgOperand(0)).getValueType(),
5676                              getValue(I.getArgOperand(0))));
5677     return nullptr;
5678   case Intrinsic::cttz: {
5679     SDValue Arg = getValue(I.getArgOperand(0));
5680     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5681     EVT Ty = Arg.getValueType();
5682     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5683                              sdl, Ty, Arg));
5684     return nullptr;
5685   }
5686   case Intrinsic::ctlz: {
5687     SDValue Arg = getValue(I.getArgOperand(0));
5688     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5689     EVT Ty = Arg.getValueType();
5690     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5691                              sdl, Ty, Arg));
5692     return nullptr;
5693   }
5694   case Intrinsic::ctpop: {
5695     SDValue Arg = getValue(I.getArgOperand(0));
5696     EVT Ty = Arg.getValueType();
5697     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5698     return nullptr;
5699   }
5700   case Intrinsic::fshl:
5701   case Intrinsic::fshr: {
5702     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5703     SDValue X = getValue(I.getArgOperand(0));
5704     SDValue Y = getValue(I.getArgOperand(1));
5705     SDValue Z = getValue(I.getArgOperand(2));
5706     EVT VT = X.getValueType();
5707     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5708     SDValue Zero = DAG.getConstant(0, sdl, VT);
5709     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5710 
5711     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5712     // avoid the select that is necessary in the general case to filter out
5713     // the 0-shift possibility that leads to UB.
5714     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5715       // TODO: This should also be done if the operation is custom, but we have
5716       // to make sure targets are handling the modulo shift amount as expected.
5717       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5718       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5719         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5720         return nullptr;
5721       }
5722 
5723       // Some targets only rotate one way. Try the opposite direction.
5724       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5725       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5726         // Negate the shift amount because it is safe to ignore the high bits.
5727         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5728         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5729         return nullptr;
5730       }
5731 
5732       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5733       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5734       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5735       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5736       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5737       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5738       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5739       return nullptr;
5740     }
5741 
5742     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5743     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5744     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5745     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5746     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5747     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5748 
5749     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5750     // and that is undefined. We must compare and select to avoid UB.
5751     EVT CCVT = MVT::i1;
5752     if (VT.isVector())
5753       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5754 
5755     // For fshl, 0-shift returns the 1st arg (X).
5756     // For fshr, 0-shift returns the 2nd arg (Y).
5757     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5758     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5759     return nullptr;
5760   }
5761   case Intrinsic::stacksave: {
5762     SDValue Op = getRoot();
5763     Res = DAG.getNode(
5764         ISD::STACKSAVE, sdl,
5765         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5766     setValue(&I, Res);
5767     DAG.setRoot(Res.getValue(1));
5768     return nullptr;
5769   }
5770   case Intrinsic::stackrestore:
5771     Res = getValue(I.getArgOperand(0));
5772     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5773     return nullptr;
5774   case Intrinsic::get_dynamic_area_offset: {
5775     SDValue Op = getRoot();
5776     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5777     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5778     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5779     // target.
5780     if (PtrTy != ResTy)
5781       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5782                          " intrinsic!");
5783     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5784                       Op);
5785     DAG.setRoot(Op);
5786     setValue(&I, Res);
5787     return nullptr;
5788   }
5789   case Intrinsic::stackguard: {
5790     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5791     MachineFunction &MF = DAG.getMachineFunction();
5792     const Module &M = *MF.getFunction().getParent();
5793     SDValue Chain = getRoot();
5794     if (TLI.useLoadStackGuardNode()) {
5795       Res = getLoadStackGuard(DAG, sdl, Chain);
5796     } else {
5797       const Value *Global = TLI.getSDagStackGuard(M);
5798       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5799       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5800                         MachinePointerInfo(Global, 0), Align,
5801                         MachineMemOperand::MOVolatile);
5802     }
5803     if (TLI.useStackGuardXorFP())
5804       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5805     DAG.setRoot(Chain);
5806     setValue(&I, Res);
5807     return nullptr;
5808   }
5809   case Intrinsic::stackprotector: {
5810     // Emit code into the DAG to store the stack guard onto the stack.
5811     MachineFunction &MF = DAG.getMachineFunction();
5812     MachineFrameInfo &MFI = MF.getFrameInfo();
5813     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5814     SDValue Src, Chain = getRoot();
5815 
5816     if (TLI.useLoadStackGuardNode())
5817       Src = getLoadStackGuard(DAG, sdl, Chain);
5818     else
5819       Src = getValue(I.getArgOperand(0));   // The guard's value.
5820 
5821     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5822 
5823     int FI = FuncInfo.StaticAllocaMap[Slot];
5824     MFI.setStackProtectorIndex(FI);
5825 
5826     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5827 
5828     // Store the stack protector onto the stack.
5829     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5830                                                  DAG.getMachineFunction(), FI),
5831                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5832     setValue(&I, Res);
5833     DAG.setRoot(Res);
5834     return nullptr;
5835   }
5836   case Intrinsic::objectsize: {
5837     // If we don't know by now, we're never going to know.
5838     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5839 
5840     assert(CI && "Non-constant type in __builtin_object_size?");
5841 
5842     SDValue Arg = getValue(I.getCalledValue());
5843     EVT Ty = Arg.getValueType();
5844 
5845     if (CI->isZero())
5846       Res = DAG.getConstant(-1ULL, sdl, Ty);
5847     else
5848       Res = DAG.getConstant(0, sdl, Ty);
5849 
5850     setValue(&I, Res);
5851     return nullptr;
5852   }
5853   case Intrinsic::annotation:
5854   case Intrinsic::ptr_annotation:
5855   case Intrinsic::launder_invariant_group:
5856   case Intrinsic::strip_invariant_group:
5857     // Drop the intrinsic, but forward the value
5858     setValue(&I, getValue(I.getOperand(0)));
5859     return nullptr;
5860   case Intrinsic::assume:
5861   case Intrinsic::var_annotation:
5862   case Intrinsic::sideeffect:
5863     // Discard annotate attributes, assumptions, and artificial side-effects.
5864     return nullptr;
5865 
5866   case Intrinsic::codeview_annotation: {
5867     // Emit a label associated with this metadata.
5868     MachineFunction &MF = DAG.getMachineFunction();
5869     MCSymbol *Label =
5870         MF.getMMI().getContext().createTempSymbol("annotation", true);
5871     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5872     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5873     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5874     DAG.setRoot(Res);
5875     return nullptr;
5876   }
5877 
5878   case Intrinsic::init_trampoline: {
5879     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5880 
5881     SDValue Ops[6];
5882     Ops[0] = getRoot();
5883     Ops[1] = getValue(I.getArgOperand(0));
5884     Ops[2] = getValue(I.getArgOperand(1));
5885     Ops[3] = getValue(I.getArgOperand(2));
5886     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5887     Ops[5] = DAG.getSrcValue(F);
5888 
5889     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5890 
5891     DAG.setRoot(Res);
5892     return nullptr;
5893   }
5894   case Intrinsic::adjust_trampoline:
5895     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5896                              TLI.getPointerTy(DAG.getDataLayout()),
5897                              getValue(I.getArgOperand(0))));
5898     return nullptr;
5899   case Intrinsic::gcroot: {
5900     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5901            "only valid in functions with gc specified, enforced by Verifier");
5902     assert(GFI && "implied by previous");
5903     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5904     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5905 
5906     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5907     GFI->addStackRoot(FI->getIndex(), TypeMap);
5908     return nullptr;
5909   }
5910   case Intrinsic::gcread:
5911   case Intrinsic::gcwrite:
5912     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5913   case Intrinsic::flt_rounds:
5914     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5915     return nullptr;
5916 
5917   case Intrinsic::expect:
5918     // Just replace __builtin_expect(exp, c) with EXP.
5919     setValue(&I, getValue(I.getArgOperand(0)));
5920     return nullptr;
5921 
5922   case Intrinsic::debugtrap:
5923   case Intrinsic::trap: {
5924     StringRef TrapFuncName =
5925         I.getAttributes()
5926             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5927             .getValueAsString();
5928     if (TrapFuncName.empty()) {
5929       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5930         ISD::TRAP : ISD::DEBUGTRAP;
5931       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5932       return nullptr;
5933     }
5934     TargetLowering::ArgListTy Args;
5935 
5936     TargetLowering::CallLoweringInfo CLI(DAG);
5937     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5938         CallingConv::C, I.getType(),
5939         DAG.getExternalSymbol(TrapFuncName.data(),
5940                               TLI.getPointerTy(DAG.getDataLayout())),
5941         std::move(Args));
5942 
5943     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5944     DAG.setRoot(Result.second);
5945     return nullptr;
5946   }
5947 
5948   case Intrinsic::uadd_with_overflow:
5949   case Intrinsic::sadd_with_overflow:
5950   case Intrinsic::usub_with_overflow:
5951   case Intrinsic::ssub_with_overflow:
5952   case Intrinsic::umul_with_overflow:
5953   case Intrinsic::smul_with_overflow: {
5954     ISD::NodeType Op;
5955     switch (Intrinsic) {
5956     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5957     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5958     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5959     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5960     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5961     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5962     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5963     }
5964     SDValue Op1 = getValue(I.getArgOperand(0));
5965     SDValue Op2 = getValue(I.getArgOperand(1));
5966 
5967     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5968     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5969     return nullptr;
5970   }
5971   case Intrinsic::prefetch: {
5972     SDValue Ops[5];
5973     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5974     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5975     Ops[0] = DAG.getRoot();
5976     Ops[1] = getValue(I.getArgOperand(0));
5977     Ops[2] = getValue(I.getArgOperand(1));
5978     Ops[3] = getValue(I.getArgOperand(2));
5979     Ops[4] = getValue(I.getArgOperand(3));
5980     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5981                                              DAG.getVTList(MVT::Other), Ops,
5982                                              EVT::getIntegerVT(*Context, 8),
5983                                              MachinePointerInfo(I.getArgOperand(0)),
5984                                              0, /* align */
5985                                              Flags);
5986 
5987     // Chain the prefetch in parallell with any pending loads, to stay out of
5988     // the way of later optimizations.
5989     PendingLoads.push_back(Result);
5990     Result = getRoot();
5991     DAG.setRoot(Result);
5992     return nullptr;
5993   }
5994   case Intrinsic::lifetime_start:
5995   case Intrinsic::lifetime_end: {
5996     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5997     // Stack coloring is not enabled in O0, discard region information.
5998     if (TM.getOptLevel() == CodeGenOpt::None)
5999       return nullptr;
6000 
6001     SmallVector<Value *, 4> Allocas;
6002     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6003 
6004     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6005            E = Allocas.end(); Object != E; ++Object) {
6006       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6007 
6008       // Could not find an Alloca.
6009       if (!LifetimeObject)
6010         continue;
6011 
6012       // First check that the Alloca is static, otherwise it won't have a
6013       // valid frame index.
6014       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6015       if (SI == FuncInfo.StaticAllocaMap.end())
6016         return nullptr;
6017 
6018       int FI = SI->second;
6019 
6020       SDValue Ops[2];
6021       Ops[0] = getRoot();
6022       Ops[1] =
6023           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6024       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6025 
6026       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6027       DAG.setRoot(Res);
6028     }
6029     return nullptr;
6030   }
6031   case Intrinsic::invariant_start:
6032     // Discard region information.
6033     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6034     return nullptr;
6035   case Intrinsic::invariant_end:
6036     // Discard region information.
6037     return nullptr;
6038   case Intrinsic::clear_cache:
6039     return TLI.getClearCacheBuiltinName();
6040   case Intrinsic::donothing:
6041     // ignore
6042     return nullptr;
6043   case Intrinsic::experimental_stackmap:
6044     visitStackmap(I);
6045     return nullptr;
6046   case Intrinsic::experimental_patchpoint_void:
6047   case Intrinsic::experimental_patchpoint_i64:
6048     visitPatchpoint(&I);
6049     return nullptr;
6050   case Intrinsic::experimental_gc_statepoint:
6051     LowerStatepoint(ImmutableStatepoint(&I));
6052     return nullptr;
6053   case Intrinsic::experimental_gc_result:
6054     visitGCResult(cast<GCResultInst>(I));
6055     return nullptr;
6056   case Intrinsic::experimental_gc_relocate:
6057     visitGCRelocate(cast<GCRelocateInst>(I));
6058     return nullptr;
6059   case Intrinsic::instrprof_increment:
6060     llvm_unreachable("instrprof failed to lower an increment");
6061   case Intrinsic::instrprof_value_profile:
6062     llvm_unreachable("instrprof failed to lower a value profiling call");
6063   case Intrinsic::localescape: {
6064     MachineFunction &MF = DAG.getMachineFunction();
6065     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6066 
6067     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6068     // is the same on all targets.
6069     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6070       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6071       if (isa<ConstantPointerNull>(Arg))
6072         continue; // Skip null pointers. They represent a hole in index space.
6073       AllocaInst *Slot = cast<AllocaInst>(Arg);
6074       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6075              "can only escape static allocas");
6076       int FI = FuncInfo.StaticAllocaMap[Slot];
6077       MCSymbol *FrameAllocSym =
6078           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6079               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6080       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6081               TII->get(TargetOpcode::LOCAL_ESCAPE))
6082           .addSym(FrameAllocSym)
6083           .addFrameIndex(FI);
6084     }
6085 
6086     return nullptr;
6087   }
6088 
6089   case Intrinsic::localrecover: {
6090     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6091     MachineFunction &MF = DAG.getMachineFunction();
6092     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6093 
6094     // Get the symbol that defines the frame offset.
6095     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6096     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6097     unsigned IdxVal =
6098         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6099     MCSymbol *FrameAllocSym =
6100         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6101             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6102 
6103     // Create a MCSymbol for the label to avoid any target lowering
6104     // that would make this PC relative.
6105     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6106     SDValue OffsetVal =
6107         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6108 
6109     // Add the offset to the FP.
6110     Value *FP = I.getArgOperand(1);
6111     SDValue FPVal = getValue(FP);
6112     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6113     setValue(&I, Add);
6114 
6115     return nullptr;
6116   }
6117 
6118   case Intrinsic::eh_exceptionpointer:
6119   case Intrinsic::eh_exceptioncode: {
6120     // Get the exception pointer vreg, copy from it, and resize it to fit.
6121     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6122     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6123     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6124     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6125     SDValue N =
6126         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6127     if (Intrinsic == Intrinsic::eh_exceptioncode)
6128       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6129     setValue(&I, N);
6130     return nullptr;
6131   }
6132   case Intrinsic::xray_customevent: {
6133     // Here we want to make sure that the intrinsic behaves as if it has a
6134     // specific calling convention, and only for x86_64.
6135     // FIXME: Support other platforms later.
6136     const auto &Triple = DAG.getTarget().getTargetTriple();
6137     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6138       return nullptr;
6139 
6140     SDLoc DL = getCurSDLoc();
6141     SmallVector<SDValue, 8> Ops;
6142 
6143     // We want to say that we always want the arguments in registers.
6144     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6145     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6146     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6147     SDValue Chain = getRoot();
6148     Ops.push_back(LogEntryVal);
6149     Ops.push_back(StrSizeVal);
6150     Ops.push_back(Chain);
6151 
6152     // We need to enforce the calling convention for the callsite, so that
6153     // argument ordering is enforced correctly, and that register allocation can
6154     // see that some registers may be assumed clobbered and have to preserve
6155     // them across calls to the intrinsic.
6156     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6157                                            DL, NodeTys, Ops);
6158     SDValue patchableNode = SDValue(MN, 0);
6159     DAG.setRoot(patchableNode);
6160     setValue(&I, patchableNode);
6161     return nullptr;
6162   }
6163   case Intrinsic::xray_typedevent: {
6164     // Here we want to make sure that the intrinsic behaves as if it has a
6165     // specific calling convention, and only for x86_64.
6166     // FIXME: Support other platforms later.
6167     const auto &Triple = DAG.getTarget().getTargetTriple();
6168     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6169       return nullptr;
6170 
6171     SDLoc DL = getCurSDLoc();
6172     SmallVector<SDValue, 8> Ops;
6173 
6174     // We want to say that we always want the arguments in registers.
6175     // It's unclear to me how manipulating the selection DAG here forces callers
6176     // to provide arguments in registers instead of on the stack.
6177     SDValue LogTypeId = getValue(I.getArgOperand(0));
6178     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6179     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6180     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6181     SDValue Chain = getRoot();
6182     Ops.push_back(LogTypeId);
6183     Ops.push_back(LogEntryVal);
6184     Ops.push_back(StrSizeVal);
6185     Ops.push_back(Chain);
6186 
6187     // We need to enforce the calling convention for the callsite, so that
6188     // argument ordering is enforced correctly, and that register allocation can
6189     // see that some registers may be assumed clobbered and have to preserve
6190     // them across calls to the intrinsic.
6191     MachineSDNode *MN = DAG.getMachineNode(
6192         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6193     SDValue patchableNode = SDValue(MN, 0);
6194     DAG.setRoot(patchableNode);
6195     setValue(&I, patchableNode);
6196     return nullptr;
6197   }
6198   case Intrinsic::experimental_deoptimize:
6199     LowerDeoptimizeCall(&I);
6200     return nullptr;
6201 
6202   case Intrinsic::experimental_vector_reduce_fadd:
6203   case Intrinsic::experimental_vector_reduce_fmul:
6204   case Intrinsic::experimental_vector_reduce_add:
6205   case Intrinsic::experimental_vector_reduce_mul:
6206   case Intrinsic::experimental_vector_reduce_and:
6207   case Intrinsic::experimental_vector_reduce_or:
6208   case Intrinsic::experimental_vector_reduce_xor:
6209   case Intrinsic::experimental_vector_reduce_smax:
6210   case Intrinsic::experimental_vector_reduce_smin:
6211   case Intrinsic::experimental_vector_reduce_umax:
6212   case Intrinsic::experimental_vector_reduce_umin:
6213   case Intrinsic::experimental_vector_reduce_fmax:
6214   case Intrinsic::experimental_vector_reduce_fmin:
6215     visitVectorReduce(I, Intrinsic);
6216     return nullptr;
6217 
6218   case Intrinsic::icall_branch_funnel: {
6219     SmallVector<SDValue, 16> Ops;
6220     Ops.push_back(DAG.getRoot());
6221     Ops.push_back(getValue(I.getArgOperand(0)));
6222 
6223     int64_t Offset;
6224     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6225         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6226     if (!Base)
6227       report_fatal_error(
6228           "llvm.icall.branch.funnel operand must be a GlobalValue");
6229     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6230 
6231     struct BranchFunnelTarget {
6232       int64_t Offset;
6233       SDValue Target;
6234     };
6235     SmallVector<BranchFunnelTarget, 8> Targets;
6236 
6237     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6238       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6239           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6240       if (ElemBase != Base)
6241         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6242                            "to the same GlobalValue");
6243 
6244       SDValue Val = getValue(I.getArgOperand(Op + 1));
6245       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6246       if (!GA)
6247         report_fatal_error(
6248             "llvm.icall.branch.funnel operand must be a GlobalValue");
6249       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6250                                      GA->getGlobal(), getCurSDLoc(),
6251                                      Val.getValueType(), GA->getOffset())});
6252     }
6253     llvm::sort(Targets.begin(), Targets.end(),
6254                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6255                  return T1.Offset < T2.Offset;
6256                });
6257 
6258     for (auto &T : Targets) {
6259       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6260       Ops.push_back(T.Target);
6261     }
6262 
6263     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6264                                  getCurSDLoc(), MVT::Other, Ops),
6265               0);
6266     DAG.setRoot(N);
6267     setValue(&I, N);
6268     HasTailCall = true;
6269     return nullptr;
6270   }
6271 
6272   case Intrinsic::wasm_landingpad_index: {
6273     // TODO store landing pad index in a map, which will be used when generating
6274     // LSDA information
6275     return nullptr;
6276   }
6277   }
6278 }
6279 
6280 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6281     const ConstrainedFPIntrinsic &FPI) {
6282   SDLoc sdl = getCurSDLoc();
6283   unsigned Opcode;
6284   switch (FPI.getIntrinsicID()) {
6285   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6286   case Intrinsic::experimental_constrained_fadd:
6287     Opcode = ISD::STRICT_FADD;
6288     break;
6289   case Intrinsic::experimental_constrained_fsub:
6290     Opcode = ISD::STRICT_FSUB;
6291     break;
6292   case Intrinsic::experimental_constrained_fmul:
6293     Opcode = ISD::STRICT_FMUL;
6294     break;
6295   case Intrinsic::experimental_constrained_fdiv:
6296     Opcode = ISD::STRICT_FDIV;
6297     break;
6298   case Intrinsic::experimental_constrained_frem:
6299     Opcode = ISD::STRICT_FREM;
6300     break;
6301   case Intrinsic::experimental_constrained_fma:
6302     Opcode = ISD::STRICT_FMA;
6303     break;
6304   case Intrinsic::experimental_constrained_sqrt:
6305     Opcode = ISD::STRICT_FSQRT;
6306     break;
6307   case Intrinsic::experimental_constrained_pow:
6308     Opcode = ISD::STRICT_FPOW;
6309     break;
6310   case Intrinsic::experimental_constrained_powi:
6311     Opcode = ISD::STRICT_FPOWI;
6312     break;
6313   case Intrinsic::experimental_constrained_sin:
6314     Opcode = ISD::STRICT_FSIN;
6315     break;
6316   case Intrinsic::experimental_constrained_cos:
6317     Opcode = ISD::STRICT_FCOS;
6318     break;
6319   case Intrinsic::experimental_constrained_exp:
6320     Opcode = ISD::STRICT_FEXP;
6321     break;
6322   case Intrinsic::experimental_constrained_exp2:
6323     Opcode = ISD::STRICT_FEXP2;
6324     break;
6325   case Intrinsic::experimental_constrained_log:
6326     Opcode = ISD::STRICT_FLOG;
6327     break;
6328   case Intrinsic::experimental_constrained_log10:
6329     Opcode = ISD::STRICT_FLOG10;
6330     break;
6331   case Intrinsic::experimental_constrained_log2:
6332     Opcode = ISD::STRICT_FLOG2;
6333     break;
6334   case Intrinsic::experimental_constrained_rint:
6335     Opcode = ISD::STRICT_FRINT;
6336     break;
6337   case Intrinsic::experimental_constrained_nearbyint:
6338     Opcode = ISD::STRICT_FNEARBYINT;
6339     break;
6340   }
6341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6342   SDValue Chain = getRoot();
6343   SmallVector<EVT, 4> ValueVTs;
6344   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6345   ValueVTs.push_back(MVT::Other); // Out chain
6346 
6347   SDVTList VTs = DAG.getVTList(ValueVTs);
6348   SDValue Result;
6349   if (FPI.isUnaryOp())
6350     Result = DAG.getNode(Opcode, sdl, VTs,
6351                          { Chain, getValue(FPI.getArgOperand(0)) });
6352   else if (FPI.isTernaryOp())
6353     Result = DAG.getNode(Opcode, sdl, VTs,
6354                          { Chain, getValue(FPI.getArgOperand(0)),
6355                                   getValue(FPI.getArgOperand(1)),
6356                                   getValue(FPI.getArgOperand(2)) });
6357   else
6358     Result = DAG.getNode(Opcode, sdl, VTs,
6359                          { Chain, getValue(FPI.getArgOperand(0)),
6360                            getValue(FPI.getArgOperand(1))  });
6361 
6362   assert(Result.getNode()->getNumValues() == 2);
6363   SDValue OutChain = Result.getValue(1);
6364   DAG.setRoot(OutChain);
6365   SDValue FPResult = Result.getValue(0);
6366   setValue(&FPI, FPResult);
6367 }
6368 
6369 std::pair<SDValue, SDValue>
6370 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6371                                     const BasicBlock *EHPadBB) {
6372   MachineFunction &MF = DAG.getMachineFunction();
6373   MachineModuleInfo &MMI = MF.getMMI();
6374   MCSymbol *BeginLabel = nullptr;
6375 
6376   if (EHPadBB) {
6377     // Insert a label before the invoke call to mark the try range.  This can be
6378     // used to detect deletion of the invoke via the MachineModuleInfo.
6379     BeginLabel = MMI.getContext().createTempSymbol();
6380 
6381     // For SjLj, keep track of which landing pads go with which invokes
6382     // so as to maintain the ordering of pads in the LSDA.
6383     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6384     if (CallSiteIndex) {
6385       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6386       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6387 
6388       // Now that the call site is handled, stop tracking it.
6389       MMI.setCurrentCallSite(0);
6390     }
6391 
6392     // Both PendingLoads and PendingExports must be flushed here;
6393     // this call might not return.
6394     (void)getRoot();
6395     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6396 
6397     CLI.setChain(getRoot());
6398   }
6399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6400   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6401 
6402   assert((CLI.IsTailCall || Result.second.getNode()) &&
6403          "Non-null chain expected with non-tail call!");
6404   assert((Result.second.getNode() || !Result.first.getNode()) &&
6405          "Null value expected with tail call!");
6406 
6407   if (!Result.second.getNode()) {
6408     // As a special case, a null chain means that a tail call has been emitted
6409     // and the DAG root is already updated.
6410     HasTailCall = true;
6411 
6412     // Since there's no actual continuation from this block, nothing can be
6413     // relying on us setting vregs for them.
6414     PendingExports.clear();
6415   } else {
6416     DAG.setRoot(Result.second);
6417   }
6418 
6419   if (EHPadBB) {
6420     // Insert a label at the end of the invoke call to mark the try range.  This
6421     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6422     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6423     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6424 
6425     // Inform MachineModuleInfo of range.
6426     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6427     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6428     // actually use outlined funclets and their LSDA info style.
6429     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6430       assert(CLI.CS);
6431       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6432       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6433                                 BeginLabel, EndLabel);
6434     } else {
6435       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6436     }
6437   }
6438 
6439   return Result;
6440 }
6441 
6442 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6443                                       bool isTailCall,
6444                                       const BasicBlock *EHPadBB) {
6445   auto &DL = DAG.getDataLayout();
6446   FunctionType *FTy = CS.getFunctionType();
6447   Type *RetTy = CS.getType();
6448 
6449   TargetLowering::ArgListTy Args;
6450   Args.reserve(CS.arg_size());
6451 
6452   const Value *SwiftErrorVal = nullptr;
6453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6454 
6455   // We can't tail call inside a function with a swifterror argument. Lowering
6456   // does not support this yet. It would have to move into the swifterror
6457   // register before the call.
6458   auto *Caller = CS.getInstruction()->getParent()->getParent();
6459   if (TLI.supportSwiftError() &&
6460       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6461     isTailCall = false;
6462 
6463   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6464        i != e; ++i) {
6465     TargetLowering::ArgListEntry Entry;
6466     const Value *V = *i;
6467 
6468     // Skip empty types
6469     if (V->getType()->isEmptyTy())
6470       continue;
6471 
6472     SDValue ArgNode = getValue(V);
6473     Entry.Node = ArgNode; Entry.Ty = V->getType();
6474 
6475     Entry.setAttributes(&CS, i - CS.arg_begin());
6476 
6477     // Use swifterror virtual register as input to the call.
6478     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6479       SwiftErrorVal = V;
6480       // We find the virtual register for the actual swifterror argument.
6481       // Instead of using the Value, we use the virtual register instead.
6482       Entry.Node = DAG.getRegister(FuncInfo
6483                                        .getOrCreateSwiftErrorVRegUseAt(
6484                                            CS.getInstruction(), FuncInfo.MBB, V)
6485                                        .first,
6486                                    EVT(TLI.getPointerTy(DL)));
6487     }
6488 
6489     Args.push_back(Entry);
6490 
6491     // If we have an explicit sret argument that is an Instruction, (i.e., it
6492     // might point to function-local memory), we can't meaningfully tail-call.
6493     if (Entry.IsSRet && isa<Instruction>(V))
6494       isTailCall = false;
6495   }
6496 
6497   // Check if target-independent constraints permit a tail call here.
6498   // Target-dependent constraints are checked within TLI->LowerCallTo.
6499   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6500     isTailCall = false;
6501 
6502   // Disable tail calls if there is an swifterror argument. Targets have not
6503   // been updated to support tail calls.
6504   if (TLI.supportSwiftError() && SwiftErrorVal)
6505     isTailCall = false;
6506 
6507   TargetLowering::CallLoweringInfo CLI(DAG);
6508   CLI.setDebugLoc(getCurSDLoc())
6509       .setChain(getRoot())
6510       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6511       .setTailCall(isTailCall)
6512       .setConvergent(CS.isConvergent());
6513   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6514 
6515   if (Result.first.getNode()) {
6516     const Instruction *Inst = CS.getInstruction();
6517     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6518     setValue(Inst, Result.first);
6519   }
6520 
6521   // The last element of CLI.InVals has the SDValue for swifterror return.
6522   // Here we copy it to a virtual register and update SwiftErrorMap for
6523   // book-keeping.
6524   if (SwiftErrorVal && TLI.supportSwiftError()) {
6525     // Get the last element of InVals.
6526     SDValue Src = CLI.InVals.back();
6527     unsigned VReg; bool CreatedVReg;
6528     std::tie(VReg, CreatedVReg) =
6529         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6530     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6531     // We update the virtual register for the actual swifterror argument.
6532     if (CreatedVReg)
6533       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6534     DAG.setRoot(CopyNode);
6535   }
6536 }
6537 
6538 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6539                              SelectionDAGBuilder &Builder) {
6540   // Check to see if this load can be trivially constant folded, e.g. if the
6541   // input is from a string literal.
6542   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6543     // Cast pointer to the type we really want to load.
6544     Type *LoadTy =
6545         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6546     if (LoadVT.isVector())
6547       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6548 
6549     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6550                                          PointerType::getUnqual(LoadTy));
6551 
6552     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6553             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6554       return Builder.getValue(LoadCst);
6555   }
6556 
6557   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6558   // still constant memory, the input chain can be the entry node.
6559   SDValue Root;
6560   bool ConstantMemory = false;
6561 
6562   // Do not serialize (non-volatile) loads of constant memory with anything.
6563   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6564     Root = Builder.DAG.getEntryNode();
6565     ConstantMemory = true;
6566   } else {
6567     // Do not serialize non-volatile loads against each other.
6568     Root = Builder.DAG.getRoot();
6569   }
6570 
6571   SDValue Ptr = Builder.getValue(PtrVal);
6572   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6573                                         Ptr, MachinePointerInfo(PtrVal),
6574                                         /* Alignment = */ 1);
6575 
6576   if (!ConstantMemory)
6577     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6578   return LoadVal;
6579 }
6580 
6581 /// Record the value for an instruction that produces an integer result,
6582 /// converting the type where necessary.
6583 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6584                                                   SDValue Value,
6585                                                   bool IsSigned) {
6586   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6587                                                     I.getType(), true);
6588   if (IsSigned)
6589     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6590   else
6591     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6592   setValue(&I, Value);
6593 }
6594 
6595 /// See if we can lower a memcmp call into an optimized form. If so, return
6596 /// true and lower it. Otherwise return false, and it will be lowered like a
6597 /// normal call.
6598 /// The caller already checked that \p I calls the appropriate LibFunc with a
6599 /// correct prototype.
6600 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6601   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6602   const Value *Size = I.getArgOperand(2);
6603   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6604   if (CSize && CSize->getZExtValue() == 0) {
6605     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6606                                                           I.getType(), true);
6607     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6608     return true;
6609   }
6610 
6611   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6612   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6613       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6614       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6615   if (Res.first.getNode()) {
6616     processIntegerCallValue(I, Res.first, true);
6617     PendingLoads.push_back(Res.second);
6618     return true;
6619   }
6620 
6621   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6622   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6623   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6624     return false;
6625 
6626   // If the target has a fast compare for the given size, it will return a
6627   // preferred load type for that size. Require that the load VT is legal and
6628   // that the target supports unaligned loads of that type. Otherwise, return
6629   // INVALID.
6630   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6631     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6632     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6633     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6634       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6635       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6636       // TODO: Check alignment of src and dest ptrs.
6637       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6638       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6639       if (!TLI.isTypeLegal(LVT) ||
6640           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6641           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6642         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6643     }
6644 
6645     return LVT;
6646   };
6647 
6648   // This turns into unaligned loads. We only do this if the target natively
6649   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6650   // we'll only produce a small number of byte loads.
6651   MVT LoadVT;
6652   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6653   switch (NumBitsToCompare) {
6654   default:
6655     return false;
6656   case 16:
6657     LoadVT = MVT::i16;
6658     break;
6659   case 32:
6660     LoadVT = MVT::i32;
6661     break;
6662   case 64:
6663   case 128:
6664   case 256:
6665     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6666     break;
6667   }
6668 
6669   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6670     return false;
6671 
6672   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6673   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6674 
6675   // Bitcast to a wide integer type if the loads are vectors.
6676   if (LoadVT.isVector()) {
6677     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6678     LoadL = DAG.getBitcast(CmpVT, LoadL);
6679     LoadR = DAG.getBitcast(CmpVT, LoadR);
6680   }
6681 
6682   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6683   processIntegerCallValue(I, Cmp, false);
6684   return true;
6685 }
6686 
6687 /// See if we can lower a memchr call into an optimized form. If so, return
6688 /// true and lower it. Otherwise return false, and it will be lowered like a
6689 /// normal call.
6690 /// The caller already checked that \p I calls the appropriate LibFunc with a
6691 /// correct prototype.
6692 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6693   const Value *Src = I.getArgOperand(0);
6694   const Value *Char = I.getArgOperand(1);
6695   const Value *Length = I.getArgOperand(2);
6696 
6697   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6698   std::pair<SDValue, SDValue> Res =
6699     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6700                                 getValue(Src), getValue(Char), getValue(Length),
6701                                 MachinePointerInfo(Src));
6702   if (Res.first.getNode()) {
6703     setValue(&I, Res.first);
6704     PendingLoads.push_back(Res.second);
6705     return true;
6706   }
6707 
6708   return false;
6709 }
6710 
6711 /// See if we can lower a mempcpy call into an optimized form. If so, return
6712 /// true and lower it. Otherwise return false, and it will be lowered like a
6713 /// normal call.
6714 /// The caller already checked that \p I calls the appropriate LibFunc with a
6715 /// correct prototype.
6716 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6717   SDValue Dst = getValue(I.getArgOperand(0));
6718   SDValue Src = getValue(I.getArgOperand(1));
6719   SDValue Size = getValue(I.getArgOperand(2));
6720 
6721   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6722   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6723   unsigned Align = std::min(DstAlign, SrcAlign);
6724   if (Align == 0) // Alignment of one or both could not be inferred.
6725     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6726 
6727   bool isVol = false;
6728   SDLoc sdl = getCurSDLoc();
6729 
6730   // In the mempcpy context we need to pass in a false value for isTailCall
6731   // because the return pointer needs to be adjusted by the size of
6732   // the copied memory.
6733   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6734                              false, /*isTailCall=*/false,
6735                              MachinePointerInfo(I.getArgOperand(0)),
6736                              MachinePointerInfo(I.getArgOperand(1)));
6737   assert(MC.getNode() != nullptr &&
6738          "** memcpy should not be lowered as TailCall in mempcpy context **");
6739   DAG.setRoot(MC);
6740 
6741   // Check if Size needs to be truncated or extended.
6742   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6743 
6744   // Adjust return pointer to point just past the last dst byte.
6745   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6746                                     Dst, Size);
6747   setValue(&I, DstPlusSize);
6748   return true;
6749 }
6750 
6751 /// See if we can lower a strcpy call into an optimized form.  If so, return
6752 /// true and lower it, otherwise return false and it will be lowered like a
6753 /// normal call.
6754 /// The caller already checked that \p I calls the appropriate LibFunc with a
6755 /// correct prototype.
6756 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6757   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6758 
6759   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6760   std::pair<SDValue, SDValue> Res =
6761     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6762                                 getValue(Arg0), getValue(Arg1),
6763                                 MachinePointerInfo(Arg0),
6764                                 MachinePointerInfo(Arg1), isStpcpy);
6765   if (Res.first.getNode()) {
6766     setValue(&I, Res.first);
6767     DAG.setRoot(Res.second);
6768     return true;
6769   }
6770 
6771   return false;
6772 }
6773 
6774 /// See if we can lower a strcmp call into an optimized form.  If so, return
6775 /// true and lower it, otherwise return false and it will be lowered like a
6776 /// normal call.
6777 /// The caller already checked that \p I calls the appropriate LibFunc with a
6778 /// correct prototype.
6779 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6780   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6781 
6782   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6783   std::pair<SDValue, SDValue> Res =
6784     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6785                                 getValue(Arg0), getValue(Arg1),
6786                                 MachinePointerInfo(Arg0),
6787                                 MachinePointerInfo(Arg1));
6788   if (Res.first.getNode()) {
6789     processIntegerCallValue(I, Res.first, true);
6790     PendingLoads.push_back(Res.second);
6791     return true;
6792   }
6793 
6794   return false;
6795 }
6796 
6797 /// See if we can lower a strlen call into an optimized form.  If so, return
6798 /// true and lower it, otherwise return false and it will be lowered like a
6799 /// normal call.
6800 /// The caller already checked that \p I calls the appropriate LibFunc with a
6801 /// correct prototype.
6802 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6803   const Value *Arg0 = I.getArgOperand(0);
6804 
6805   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6806   std::pair<SDValue, SDValue> Res =
6807     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6808                                 getValue(Arg0), MachinePointerInfo(Arg0));
6809   if (Res.first.getNode()) {
6810     processIntegerCallValue(I, Res.first, false);
6811     PendingLoads.push_back(Res.second);
6812     return true;
6813   }
6814 
6815   return false;
6816 }
6817 
6818 /// See if we can lower a strnlen call into an optimized form.  If so, return
6819 /// true and lower it, otherwise return false and it will be lowered like a
6820 /// normal call.
6821 /// The caller already checked that \p I calls the appropriate LibFunc with a
6822 /// correct prototype.
6823 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6824   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6825 
6826   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6827   std::pair<SDValue, SDValue> Res =
6828     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6829                                  getValue(Arg0), getValue(Arg1),
6830                                  MachinePointerInfo(Arg0));
6831   if (Res.first.getNode()) {
6832     processIntegerCallValue(I, Res.first, false);
6833     PendingLoads.push_back(Res.second);
6834     return true;
6835   }
6836 
6837   return false;
6838 }
6839 
6840 /// See if we can lower a unary floating-point operation into an SDNode with
6841 /// the specified Opcode.  If so, return true and lower it, otherwise return
6842 /// false and it will be lowered like a normal call.
6843 /// The caller already checked that \p I calls the appropriate LibFunc with a
6844 /// correct prototype.
6845 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6846                                               unsigned Opcode) {
6847   // We already checked this call's prototype; verify it doesn't modify errno.
6848   if (!I.onlyReadsMemory())
6849     return false;
6850 
6851   SDValue Tmp = getValue(I.getArgOperand(0));
6852   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6853   return true;
6854 }
6855 
6856 /// See if we can lower a binary floating-point operation into an SDNode with
6857 /// the specified Opcode. If so, return true and lower it. Otherwise return
6858 /// false, and it will be lowered like a normal call.
6859 /// The caller already checked that \p I calls the appropriate LibFunc with a
6860 /// correct prototype.
6861 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6862                                                unsigned Opcode) {
6863   // We already checked this call's prototype; verify it doesn't modify errno.
6864   if (!I.onlyReadsMemory())
6865     return false;
6866 
6867   SDValue Tmp0 = getValue(I.getArgOperand(0));
6868   SDValue Tmp1 = getValue(I.getArgOperand(1));
6869   EVT VT = Tmp0.getValueType();
6870   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6871   return true;
6872 }
6873 
6874 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6875   // Handle inline assembly differently.
6876   if (isa<InlineAsm>(I.getCalledValue())) {
6877     visitInlineAsm(&I);
6878     return;
6879   }
6880 
6881   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6882   computeUsesVAFloatArgument(I, MMI);
6883 
6884   const char *RenameFn = nullptr;
6885   if (Function *F = I.getCalledFunction()) {
6886     if (F->isDeclaration()) {
6887       // Is this an LLVM intrinsic or a target-specific intrinsic?
6888       unsigned IID = F->getIntrinsicID();
6889       if (!IID)
6890         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6891           IID = II->getIntrinsicID(F);
6892 
6893       if (IID) {
6894         RenameFn = visitIntrinsicCall(I, IID);
6895         if (!RenameFn)
6896           return;
6897       }
6898     }
6899 
6900     // Check for well-known libc/libm calls.  If the function is internal, it
6901     // can't be a library call.  Don't do the check if marked as nobuiltin for
6902     // some reason or the call site requires strict floating point semantics.
6903     LibFunc Func;
6904     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6905         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6906         LibInfo->hasOptimizedCodeGen(Func)) {
6907       switch (Func) {
6908       default: break;
6909       case LibFunc_copysign:
6910       case LibFunc_copysignf:
6911       case LibFunc_copysignl:
6912         // We already checked this call's prototype; verify it doesn't modify
6913         // errno.
6914         if (I.onlyReadsMemory()) {
6915           SDValue LHS = getValue(I.getArgOperand(0));
6916           SDValue RHS = getValue(I.getArgOperand(1));
6917           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6918                                    LHS.getValueType(), LHS, RHS));
6919           return;
6920         }
6921         break;
6922       case LibFunc_fabs:
6923       case LibFunc_fabsf:
6924       case LibFunc_fabsl:
6925         if (visitUnaryFloatCall(I, ISD::FABS))
6926           return;
6927         break;
6928       case LibFunc_fmin:
6929       case LibFunc_fminf:
6930       case LibFunc_fminl:
6931         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6932           return;
6933         break;
6934       case LibFunc_fmax:
6935       case LibFunc_fmaxf:
6936       case LibFunc_fmaxl:
6937         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6938           return;
6939         break;
6940       case LibFunc_sin:
6941       case LibFunc_sinf:
6942       case LibFunc_sinl:
6943         if (visitUnaryFloatCall(I, ISD::FSIN))
6944           return;
6945         break;
6946       case LibFunc_cos:
6947       case LibFunc_cosf:
6948       case LibFunc_cosl:
6949         if (visitUnaryFloatCall(I, ISD::FCOS))
6950           return;
6951         break;
6952       case LibFunc_sqrt:
6953       case LibFunc_sqrtf:
6954       case LibFunc_sqrtl:
6955       case LibFunc_sqrt_finite:
6956       case LibFunc_sqrtf_finite:
6957       case LibFunc_sqrtl_finite:
6958         if (visitUnaryFloatCall(I, ISD::FSQRT))
6959           return;
6960         break;
6961       case LibFunc_floor:
6962       case LibFunc_floorf:
6963       case LibFunc_floorl:
6964         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6965           return;
6966         break;
6967       case LibFunc_nearbyint:
6968       case LibFunc_nearbyintf:
6969       case LibFunc_nearbyintl:
6970         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6971           return;
6972         break;
6973       case LibFunc_ceil:
6974       case LibFunc_ceilf:
6975       case LibFunc_ceill:
6976         if (visitUnaryFloatCall(I, ISD::FCEIL))
6977           return;
6978         break;
6979       case LibFunc_rint:
6980       case LibFunc_rintf:
6981       case LibFunc_rintl:
6982         if (visitUnaryFloatCall(I, ISD::FRINT))
6983           return;
6984         break;
6985       case LibFunc_round:
6986       case LibFunc_roundf:
6987       case LibFunc_roundl:
6988         if (visitUnaryFloatCall(I, ISD::FROUND))
6989           return;
6990         break;
6991       case LibFunc_trunc:
6992       case LibFunc_truncf:
6993       case LibFunc_truncl:
6994         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6995           return;
6996         break;
6997       case LibFunc_log2:
6998       case LibFunc_log2f:
6999       case LibFunc_log2l:
7000         if (visitUnaryFloatCall(I, ISD::FLOG2))
7001           return;
7002         break;
7003       case LibFunc_exp2:
7004       case LibFunc_exp2f:
7005       case LibFunc_exp2l:
7006         if (visitUnaryFloatCall(I, ISD::FEXP2))
7007           return;
7008         break;
7009       case LibFunc_memcmp:
7010         if (visitMemCmpCall(I))
7011           return;
7012         break;
7013       case LibFunc_mempcpy:
7014         if (visitMemPCpyCall(I))
7015           return;
7016         break;
7017       case LibFunc_memchr:
7018         if (visitMemChrCall(I))
7019           return;
7020         break;
7021       case LibFunc_strcpy:
7022         if (visitStrCpyCall(I, false))
7023           return;
7024         break;
7025       case LibFunc_stpcpy:
7026         if (visitStrCpyCall(I, true))
7027           return;
7028         break;
7029       case LibFunc_strcmp:
7030         if (visitStrCmpCall(I))
7031           return;
7032         break;
7033       case LibFunc_strlen:
7034         if (visitStrLenCall(I))
7035           return;
7036         break;
7037       case LibFunc_strnlen:
7038         if (visitStrNLenCall(I))
7039           return;
7040         break;
7041       }
7042     }
7043   }
7044 
7045   SDValue Callee;
7046   if (!RenameFn)
7047     Callee = getValue(I.getCalledValue());
7048   else
7049     Callee = DAG.getExternalSymbol(
7050         RenameFn,
7051         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7052 
7053   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7054   // have to do anything here to lower funclet bundles.
7055   assert(!I.hasOperandBundlesOtherThan(
7056              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7057          "Cannot lower calls with arbitrary operand bundles!");
7058 
7059   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7060     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7061   else
7062     // Check if we can potentially perform a tail call. More detailed checking
7063     // is be done within LowerCallTo, after more information about the call is
7064     // known.
7065     LowerCallTo(&I, Callee, I.isTailCall());
7066 }
7067 
7068 namespace {
7069 
7070 /// AsmOperandInfo - This contains information for each constraint that we are
7071 /// lowering.
7072 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7073 public:
7074   /// CallOperand - If this is the result output operand or a clobber
7075   /// this is null, otherwise it is the incoming operand to the CallInst.
7076   /// This gets modified as the asm is processed.
7077   SDValue CallOperand;
7078 
7079   /// AssignedRegs - If this is a register or register class operand, this
7080   /// contains the set of register corresponding to the operand.
7081   RegsForValue AssignedRegs;
7082 
7083   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7084     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7085   }
7086 
7087   /// Whether or not this operand accesses memory
7088   bool hasMemory(const TargetLowering &TLI) const {
7089     // Indirect operand accesses access memory.
7090     if (isIndirect)
7091       return true;
7092 
7093     for (const auto &Code : Codes)
7094       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7095         return true;
7096 
7097     return false;
7098   }
7099 
7100   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7101   /// corresponds to.  If there is no Value* for this operand, it returns
7102   /// MVT::Other.
7103   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7104                            const DataLayout &DL) const {
7105     if (!CallOperandVal) return MVT::Other;
7106 
7107     if (isa<BasicBlock>(CallOperandVal))
7108       return TLI.getPointerTy(DL);
7109 
7110     llvm::Type *OpTy = CallOperandVal->getType();
7111 
7112     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7113     // If this is an indirect operand, the operand is a pointer to the
7114     // accessed type.
7115     if (isIndirect) {
7116       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7117       if (!PtrTy)
7118         report_fatal_error("Indirect operand for inline asm not a pointer!");
7119       OpTy = PtrTy->getElementType();
7120     }
7121 
7122     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7123     if (StructType *STy = dyn_cast<StructType>(OpTy))
7124       if (STy->getNumElements() == 1)
7125         OpTy = STy->getElementType(0);
7126 
7127     // If OpTy is not a single value, it may be a struct/union that we
7128     // can tile with integers.
7129     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7130       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7131       switch (BitSize) {
7132       default: break;
7133       case 1:
7134       case 8:
7135       case 16:
7136       case 32:
7137       case 64:
7138       case 128:
7139         OpTy = IntegerType::get(Context, BitSize);
7140         break;
7141       }
7142     }
7143 
7144     return TLI.getValueType(DL, OpTy, true);
7145   }
7146 };
7147 
7148 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7149 
7150 } // end anonymous namespace
7151 
7152 /// Make sure that the output operand \p OpInfo and its corresponding input
7153 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7154 /// out).
7155 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7156                                SDISelAsmOperandInfo &MatchingOpInfo,
7157                                SelectionDAG &DAG) {
7158   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7159     return;
7160 
7161   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7162   const auto &TLI = DAG.getTargetLoweringInfo();
7163 
7164   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7165       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7166                                        OpInfo.ConstraintVT);
7167   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7168       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7169                                        MatchingOpInfo.ConstraintVT);
7170   if ((OpInfo.ConstraintVT.isInteger() !=
7171        MatchingOpInfo.ConstraintVT.isInteger()) ||
7172       (MatchRC.second != InputRC.second)) {
7173     // FIXME: error out in a more elegant fashion
7174     report_fatal_error("Unsupported asm: input constraint"
7175                        " with a matching output constraint of"
7176                        " incompatible type!");
7177   }
7178   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7179 }
7180 
7181 /// Get a direct memory input to behave well as an indirect operand.
7182 /// This may introduce stores, hence the need for a \p Chain.
7183 /// \return The (possibly updated) chain.
7184 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7185                                         SDISelAsmOperandInfo &OpInfo,
7186                                         SelectionDAG &DAG) {
7187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7188 
7189   // If we don't have an indirect input, put it in the constpool if we can,
7190   // otherwise spill it to a stack slot.
7191   // TODO: This isn't quite right. We need to handle these according to
7192   // the addressing mode that the constraint wants. Also, this may take
7193   // an additional register for the computation and we don't want that
7194   // either.
7195 
7196   // If the operand is a float, integer, or vector constant, spill to a
7197   // constant pool entry to get its address.
7198   const Value *OpVal = OpInfo.CallOperandVal;
7199   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7200       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7201     OpInfo.CallOperand = DAG.getConstantPool(
7202         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7203     return Chain;
7204   }
7205 
7206   // Otherwise, create a stack slot and emit a store to it before the asm.
7207   Type *Ty = OpVal->getType();
7208   auto &DL = DAG.getDataLayout();
7209   uint64_t TySize = DL.getTypeAllocSize(Ty);
7210   unsigned Align = DL.getPrefTypeAlignment(Ty);
7211   MachineFunction &MF = DAG.getMachineFunction();
7212   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7213   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7214   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7215                        MachinePointerInfo::getFixedStack(MF, SSFI));
7216   OpInfo.CallOperand = StackSlot;
7217 
7218   return Chain;
7219 }
7220 
7221 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7222 /// specified operand.  We prefer to assign virtual registers, to allow the
7223 /// register allocator to handle the assignment process.  However, if the asm
7224 /// uses features that we can't model on machineinstrs, we have SDISel do the
7225 /// allocation.  This produces generally horrible, but correct, code.
7226 ///
7227 ///   OpInfo describes the operand
7228 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7229 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7230                                  const SDLoc &DL, SDISelAsmOperandInfo &OpInfo,
7231                                  SDISelAsmOperandInfo &RefOpInfo) {
7232   LLVMContext &Context = *DAG.getContext();
7233 
7234   MachineFunction &MF = DAG.getMachineFunction();
7235   SmallVector<unsigned, 4> Regs;
7236   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7237 
7238   // If this is a constraint for a single physreg, or a constraint for a
7239   // register class, find it.
7240   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7241       TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode,
7242                                        RefOpInfo.ConstraintVT);
7243 
7244   unsigned NumRegs = 1;
7245   if (OpInfo.ConstraintVT != MVT::Other) {
7246     // If this is an FP operand in an integer register (or visa versa), or more
7247     // generally if the operand value disagrees with the register class we plan
7248     // to stick it in, fix the operand type.
7249     //
7250     // If this is an input value, the bitcast to the new type is done now.
7251     // Bitcast for output value is done at the end of visitInlineAsm().
7252     if ((OpInfo.Type == InlineAsm::isOutput ||
7253          OpInfo.Type == InlineAsm::isInput) &&
7254         PhysReg.second &&
7255         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7256       // Try to convert to the first EVT that the reg class contains.  If the
7257       // types are identical size, use a bitcast to convert (e.g. two differing
7258       // vector types).  Note: output bitcast is done at the end of
7259       // visitInlineAsm().
7260       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7261       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7262         // Exclude indirect inputs while they are unsupported because the code
7263         // to perform the load is missing and thus OpInfo.CallOperand still
7264         // refers to the input address rather than the pointed-to value.
7265         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7266           OpInfo.CallOperand =
7267               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7268         OpInfo.ConstraintVT = RegVT;
7269         // If the operand is an FP value and we want it in integer registers,
7270         // use the corresponding integer type. This turns an f64 value into
7271         // i64, which can be passed with two i32 values on a 32-bit machine.
7272       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7273         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7274         if (OpInfo.Type == InlineAsm::isInput)
7275           OpInfo.CallOperand =
7276               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7277         OpInfo.ConstraintVT = RegVT;
7278       }
7279     }
7280 
7281     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7282   }
7283 
7284   // No need to allocate a matching input constraint since the constraint it's
7285   // matching to has already been allocated.
7286   if (OpInfo.isMatchingInputConstraint())
7287     return;
7288 
7289   MVT RegVT;
7290   EVT ValueVT = OpInfo.ConstraintVT;
7291 
7292   // If this is a constraint for a specific physical register, like {r17},
7293   // assign it now.
7294   if (unsigned AssignedReg = PhysReg.first) {
7295     const TargetRegisterClass *RC = PhysReg.second;
7296     if (OpInfo.ConstraintVT == MVT::Other)
7297       ValueVT = *TRI.legalclasstypes_begin(*RC);
7298 
7299     // Get the actual register value type.  This is important, because the user
7300     // may have asked for (e.g.) the AX register in i32 type.  We need to
7301     // remember that AX is actually i16 to get the right extension.
7302     RegVT = *TRI.legalclasstypes_begin(*RC);
7303 
7304     // This is an explicit reference to a physical register.
7305     Regs.push_back(AssignedReg);
7306 
7307     // If this is an expanded reference, add the rest of the regs to Regs.
7308     if (NumRegs != 1) {
7309       TargetRegisterClass::iterator I = RC->begin();
7310       for (; *I != AssignedReg; ++I)
7311         assert(I != RC->end() && "Didn't find reg!");
7312 
7313       // Already added the first reg.
7314       --NumRegs; ++I;
7315       for (; NumRegs; --NumRegs, ++I) {
7316         assert(I != RC->end() && "Ran out of registers to allocate!");
7317         Regs.push_back(*I);
7318       }
7319     }
7320 
7321     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7322     return;
7323   }
7324 
7325   // Otherwise, if this was a reference to an LLVM register class, create vregs
7326   // for this reference.
7327   if (const TargetRegisterClass *RC = PhysReg.second) {
7328     RegVT = *TRI.legalclasstypes_begin(*RC);
7329     if (OpInfo.ConstraintVT == MVT::Other)
7330       ValueVT = RegVT;
7331 
7332     // Create the appropriate number of virtual registers.
7333     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7334     for (; NumRegs; --NumRegs)
7335       Regs.push_back(RegInfo.createVirtualRegister(RC));
7336 
7337     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7338     return;
7339   }
7340 
7341   // Otherwise, we couldn't allocate enough registers for this.
7342 }
7343 
7344 static unsigned
7345 findMatchingInlineAsmOperand(unsigned OperandNo,
7346                              const std::vector<SDValue> &AsmNodeOperands) {
7347   // Scan until we find the definition we already emitted of this operand.
7348   unsigned CurOp = InlineAsm::Op_FirstOperand;
7349   for (; OperandNo; --OperandNo) {
7350     // Advance to the next operand.
7351     unsigned OpFlag =
7352         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7353     assert((InlineAsm::isRegDefKind(OpFlag) ||
7354             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7355             InlineAsm::isMemKind(OpFlag)) &&
7356            "Skipped past definitions?");
7357     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7358   }
7359   return CurOp;
7360 }
7361 
7362 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7363 /// \return true if it has succeeded, false otherwise
7364 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7365                               MVT RegVT, SelectionDAG &DAG) {
7366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7367   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7368   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7369     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7370       Regs.push_back(RegInfo.createVirtualRegister(RC));
7371     else
7372       return false;
7373   }
7374   return true;
7375 }
7376 
7377 namespace {
7378 
7379 class ExtraFlags {
7380   unsigned Flags = 0;
7381 
7382 public:
7383   explicit ExtraFlags(ImmutableCallSite CS) {
7384     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7385     if (IA->hasSideEffects())
7386       Flags |= InlineAsm::Extra_HasSideEffects;
7387     if (IA->isAlignStack())
7388       Flags |= InlineAsm::Extra_IsAlignStack;
7389     if (CS.isConvergent())
7390       Flags |= InlineAsm::Extra_IsConvergent;
7391     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7392   }
7393 
7394   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7395     // Ideally, we would only check against memory constraints.  However, the
7396     // meaning of an Other constraint can be target-specific and we can't easily
7397     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7398     // for Other constraints as well.
7399     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7400         OpInfo.ConstraintType == TargetLowering::C_Other) {
7401       if (OpInfo.Type == InlineAsm::isInput)
7402         Flags |= InlineAsm::Extra_MayLoad;
7403       else if (OpInfo.Type == InlineAsm::isOutput)
7404         Flags |= InlineAsm::Extra_MayStore;
7405       else if (OpInfo.Type == InlineAsm::isClobber)
7406         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7407     }
7408   }
7409 
7410   unsigned get() const { return Flags; }
7411 };
7412 
7413 } // end anonymous namespace
7414 
7415 /// visitInlineAsm - Handle a call to an InlineAsm object.
7416 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7417   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7418 
7419   /// ConstraintOperands - Information about all of the constraints.
7420   SDISelAsmOperandInfoVector ConstraintOperands;
7421 
7422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7423   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7424       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7425 
7426   bool hasMemory = false;
7427 
7428   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7429   ExtraFlags ExtraInfo(CS);
7430 
7431   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7432   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7433   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7434     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7435     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7436 
7437     MVT OpVT = MVT::Other;
7438 
7439     // Compute the value type for each operand.
7440     if (OpInfo.Type == InlineAsm::isInput ||
7441         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7442       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7443 
7444       // Process the call argument. BasicBlocks are labels, currently appearing
7445       // only in asm's.
7446       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7447         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7448       } else {
7449         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7450       }
7451 
7452       OpVT =
7453           OpInfo
7454               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7455               .getSimpleVT();
7456     }
7457 
7458     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7459       // The return value of the call is this value.  As such, there is no
7460       // corresponding argument.
7461       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7462       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7463         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7464                                       STy->getElementType(ResNo));
7465       } else {
7466         assert(ResNo == 0 && "Asm only has one result!");
7467         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7468       }
7469       ++ResNo;
7470     }
7471 
7472     OpInfo.ConstraintVT = OpVT;
7473 
7474     if (!hasMemory)
7475       hasMemory = OpInfo.hasMemory(TLI);
7476 
7477     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7478     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7479     auto TargetConstraint = TargetConstraints[i];
7480 
7481     // Compute the constraint code and ConstraintType to use.
7482     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7483 
7484     ExtraInfo.update(TargetConstraint);
7485   }
7486 
7487   SDValue Chain, Flag;
7488 
7489   // We won't need to flush pending loads if this asm doesn't touch
7490   // memory and is nonvolatile.
7491   if (hasMemory || IA->hasSideEffects())
7492     Chain = getRoot();
7493   else
7494     Chain = DAG.getRoot();
7495 
7496   // Second pass over the constraints: compute which constraint option to use
7497   // and assign registers to constraints that want a specific physreg.
7498   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7499     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7500 
7501     // If this is an output operand with a matching input operand, look up the
7502     // matching input. If their types mismatch, e.g. one is an integer, the
7503     // other is floating point, or their sizes are different, flag it as an
7504     // error.
7505     if (OpInfo.hasMatchingInput()) {
7506       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7507       patchMatchingInput(OpInfo, Input, DAG);
7508     }
7509 
7510     // Compute the constraint code and ConstraintType to use.
7511     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7512 
7513     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7514         OpInfo.Type == InlineAsm::isClobber)
7515       continue;
7516 
7517     // If this is a memory input, and if the operand is not indirect, do what we
7518     // need to provide an address for the memory input.
7519     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7520         !OpInfo.isIndirect) {
7521       assert((OpInfo.isMultipleAlternative ||
7522               (OpInfo.Type == InlineAsm::isInput)) &&
7523              "Can only indirectify direct input operands!");
7524 
7525       // Memory operands really want the address of the value.
7526       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7527 
7528       // There is no longer a Value* corresponding to this operand.
7529       OpInfo.CallOperandVal = nullptr;
7530 
7531       // It is now an indirect operand.
7532       OpInfo.isIndirect = true;
7533     }
7534 
7535     // If this constraint is for a specific register, allocate it before
7536     // anything else.
7537     SDISelAsmOperandInfo &RefOpInfo =
7538         OpInfo.isMatchingInputConstraint()
7539             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7540             : ConstraintOperands[i];
7541     if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
7542       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7543   }
7544 
7545   // Third pass - Loop over all of the operands, assigning virtual or physregs
7546   // to register class operands.
7547   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7548     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7549     SDISelAsmOperandInfo &RefOpInfo =
7550         OpInfo.isMatchingInputConstraint()
7551             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7552             : ConstraintOperands[i];
7553 
7554     // C_Register operands have already been allocated, Other/Memory don't need
7555     // to be.
7556     if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7557       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7558   }
7559 
7560   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7561   std::vector<SDValue> AsmNodeOperands;
7562   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7563   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7564       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7565 
7566   // If we have a !srcloc metadata node associated with it, we want to attach
7567   // this to the ultimately generated inline asm machineinstr.  To do this, we
7568   // pass in the third operand as this (potentially null) inline asm MDNode.
7569   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7570   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7571 
7572   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7573   // bits as operand 3.
7574   AsmNodeOperands.push_back(DAG.getTargetConstant(
7575       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7576 
7577   // Loop over all of the inputs, copying the operand values into the
7578   // appropriate registers and processing the output regs.
7579   RegsForValue RetValRegs;
7580 
7581   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7582   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7583 
7584   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7585     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7586 
7587     switch (OpInfo.Type) {
7588     case InlineAsm::isOutput:
7589       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7590           OpInfo.ConstraintType != TargetLowering::C_Register) {
7591         // Memory output, or 'other' output (e.g. 'X' constraint).
7592         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7593 
7594         unsigned ConstraintID =
7595             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7596         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7597                "Failed to convert memory constraint code to constraint id.");
7598 
7599         // Add information to the INLINEASM node to know about this output.
7600         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7601         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7602         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7603                                                         MVT::i32));
7604         AsmNodeOperands.push_back(OpInfo.CallOperand);
7605         break;
7606       }
7607 
7608       // Otherwise, this is a register or register class output.
7609 
7610       // Copy the output from the appropriate register.  Find a register that
7611       // we can use.
7612       if (OpInfo.AssignedRegs.Regs.empty()) {
7613         emitInlineAsmError(
7614             CS, "couldn't allocate output register for constraint '" +
7615                     Twine(OpInfo.ConstraintCode) + "'");
7616         return;
7617       }
7618 
7619       // If this is an indirect operand, store through the pointer after the
7620       // asm.
7621       if (OpInfo.isIndirect) {
7622         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7623                                                       OpInfo.CallOperandVal));
7624       } else {
7625         // This is the result value of the call.
7626         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7627         // Concatenate this output onto the outputs list.
7628         RetValRegs.append(OpInfo.AssignedRegs);
7629       }
7630 
7631       // Add information to the INLINEASM node to know that this register is
7632       // set.
7633       OpInfo.AssignedRegs
7634           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7635                                     ? InlineAsm::Kind_RegDefEarlyClobber
7636                                     : InlineAsm::Kind_RegDef,
7637                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7638       break;
7639 
7640     case InlineAsm::isInput: {
7641       SDValue InOperandVal = OpInfo.CallOperand;
7642 
7643       if (OpInfo.isMatchingInputConstraint()) {
7644         // If this is required to match an output register we have already set,
7645         // just use its register.
7646         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7647                                                   AsmNodeOperands);
7648         unsigned OpFlag =
7649           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7650         if (InlineAsm::isRegDefKind(OpFlag) ||
7651             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7652           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7653           if (OpInfo.isIndirect) {
7654             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7655             emitInlineAsmError(CS, "inline asm not supported yet:"
7656                                    " don't know how to handle tied "
7657                                    "indirect register inputs");
7658             return;
7659           }
7660 
7661           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7662           SmallVector<unsigned, 4> Regs;
7663 
7664           if (!createVirtualRegs(Regs,
7665                                  InlineAsm::getNumOperandRegisters(OpFlag),
7666                                  RegVT, DAG)) {
7667             emitInlineAsmError(CS, "inline asm error: This value type register "
7668                                    "class is not natively supported!");
7669             return;
7670           }
7671 
7672           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7673 
7674           SDLoc dl = getCurSDLoc();
7675           // Use the produced MatchedRegs object to
7676           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7677                                     CS.getInstruction());
7678           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7679                                            true, OpInfo.getMatchedOperand(), dl,
7680                                            DAG, AsmNodeOperands);
7681           break;
7682         }
7683 
7684         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7685         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7686                "Unexpected number of operands");
7687         // Add information to the INLINEASM node to know about this input.
7688         // See InlineAsm.h isUseOperandTiedToDef.
7689         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7690         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7691                                                     OpInfo.getMatchedOperand());
7692         AsmNodeOperands.push_back(DAG.getTargetConstant(
7693             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7694         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7695         break;
7696       }
7697 
7698       // Treat indirect 'X' constraint as memory.
7699       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7700           OpInfo.isIndirect)
7701         OpInfo.ConstraintType = TargetLowering::C_Memory;
7702 
7703       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7704         std::vector<SDValue> Ops;
7705         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7706                                           Ops, DAG);
7707         if (Ops.empty()) {
7708           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7709                                      Twine(OpInfo.ConstraintCode) + "'");
7710           return;
7711         }
7712 
7713         // Add information to the INLINEASM node to know about this input.
7714         unsigned ResOpType =
7715           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7716         AsmNodeOperands.push_back(DAG.getTargetConstant(
7717             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7718         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7719         break;
7720       }
7721 
7722       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7723         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7724         assert(InOperandVal.getValueType() ==
7725                    TLI.getPointerTy(DAG.getDataLayout()) &&
7726                "Memory operands expect pointer values");
7727 
7728         unsigned ConstraintID =
7729             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7730         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7731                "Failed to convert memory constraint code to constraint id.");
7732 
7733         // Add information to the INLINEASM node to know about this input.
7734         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7735         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7736         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7737                                                         getCurSDLoc(),
7738                                                         MVT::i32));
7739         AsmNodeOperands.push_back(InOperandVal);
7740         break;
7741       }
7742 
7743       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7744               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7745              "Unknown constraint type!");
7746 
7747       // TODO: Support this.
7748       if (OpInfo.isIndirect) {
7749         emitInlineAsmError(
7750             CS, "Don't know how to handle indirect register inputs yet "
7751                 "for constraint '" +
7752                     Twine(OpInfo.ConstraintCode) + "'");
7753         return;
7754       }
7755 
7756       // Copy the input into the appropriate registers.
7757       if (OpInfo.AssignedRegs.Regs.empty()) {
7758         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7759                                    Twine(OpInfo.ConstraintCode) + "'");
7760         return;
7761       }
7762 
7763       SDLoc dl = getCurSDLoc();
7764 
7765       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7766                                         Chain, &Flag, CS.getInstruction());
7767 
7768       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7769                                                dl, DAG, AsmNodeOperands);
7770       break;
7771     }
7772     case InlineAsm::isClobber:
7773       // Add the clobbered value to the operand list, so that the register
7774       // allocator is aware that the physreg got clobbered.
7775       if (!OpInfo.AssignedRegs.Regs.empty())
7776         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7777                                                  false, 0, getCurSDLoc(), DAG,
7778                                                  AsmNodeOperands);
7779       break;
7780     }
7781   }
7782 
7783   // Finish up input operands.  Set the input chain and add the flag last.
7784   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7785   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7786 
7787   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7788                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7789   Flag = Chain.getValue(1);
7790 
7791   // If this asm returns a register value, copy the result from that register
7792   // and set it as the value of the call.
7793   if (!RetValRegs.Regs.empty()) {
7794     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7795                                              Chain, &Flag, CS.getInstruction());
7796 
7797     llvm::Type *CSResultType = CS.getType();
7798     unsigned numRet;
7799     ArrayRef<Type *> ResultTypes;
7800     SmallVector<SDValue, 1> ResultValues(1);
7801     if (CSResultType->isSingleValueType()) {
7802       numRet = 1;
7803       ResultValues[0] = Val;
7804       ResultTypes = makeArrayRef(CSResultType);
7805     } else {
7806       numRet = CSResultType->getNumContainedTypes();
7807       assert(Val->getNumOperands() == numRet &&
7808              "Mismatch in number of output operands in asm result");
7809       ResultTypes = CSResultType->subtypes();
7810       ArrayRef<SDUse> ValueUses = Val->ops();
7811       ResultValues.resize(numRet);
7812       std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(),
7813                      [](const SDUse &u) -> SDValue { return u.get(); });
7814     }
7815     SmallVector<EVT, 1> ResultVTs(numRet);
7816     for (unsigned i = 0; i < numRet; i++) {
7817       EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]);
7818       SDValue Val = ResultValues[i];
7819       assert(ResultTypes[i]->isSized() && "Unexpected unsized type");
7820       // If the type of the inline asm call site return value is different but
7821       // has same size as the type of the asm output bitcast it.  One example
7822       // of this is for vectors with different width / number of elements.
7823       // This can happen for register classes that can contain multiple
7824       // different value types.  The preg or vreg allocated may not have the
7825       // same VT as was expected.
7826       //
7827       // This can also happen for a return value that disagrees with the
7828       // register class it is put in, eg. a double in a general-purpose
7829       // register on a 32-bit machine.
7830       if (ResultVT != Val.getValueType() &&
7831           ResultVT.getSizeInBits() == Val.getValueSizeInBits())
7832         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val);
7833       else if (ResultVT != Val.getValueType() && ResultVT.isInteger() &&
7834                Val.getValueType().isInteger()) {
7835         // If a result value was tied to an input value, the computed result
7836         // may have a wider width than the expected result.  Extract the
7837         // relevant portion.
7838         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val);
7839       }
7840 
7841       assert(ResultVT == Val.getValueType() && "Asm result value mismatch!");
7842       ResultVTs[i] = ResultVT;
7843       ResultValues[i] = Val;
7844     }
7845 
7846     Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7847                       DAG.getVTList(ResultVTs), ResultValues);
7848     setValue(CS.getInstruction(), Val);
7849     // Don't need to use this as a chain in this case.
7850     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7851       return;
7852   }
7853 
7854   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7855 
7856   // Process indirect outputs, first output all of the flagged copies out of
7857   // physregs.
7858   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7859     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7860     const Value *Ptr = IndirectStoresToEmit[i].second;
7861     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7862                                              Chain, &Flag, IA);
7863     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7864   }
7865 
7866   // Emit the non-flagged stores from the physregs.
7867   SmallVector<SDValue, 8> OutChains;
7868   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7869     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7870                                getValue(StoresToEmit[i].second),
7871                                MachinePointerInfo(StoresToEmit[i].second));
7872     OutChains.push_back(Val);
7873   }
7874 
7875   if (!OutChains.empty())
7876     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7877 
7878   DAG.setRoot(Chain);
7879 }
7880 
7881 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7882                                              const Twine &Message) {
7883   LLVMContext &Ctx = *DAG.getContext();
7884   Ctx.emitError(CS.getInstruction(), Message);
7885 
7886   // Make sure we leave the DAG in a valid state
7887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7888   SmallVector<EVT, 1> ValueVTs;
7889   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7890 
7891   if (ValueVTs.empty())
7892     return;
7893 
7894   SmallVector<SDValue, 1> Ops;
7895   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7896     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7897 
7898   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7899 }
7900 
7901 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7902   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7903                           MVT::Other, getRoot(),
7904                           getValue(I.getArgOperand(0)),
7905                           DAG.getSrcValue(I.getArgOperand(0))));
7906 }
7907 
7908 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7910   const DataLayout &DL = DAG.getDataLayout();
7911   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7912                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7913                            DAG.getSrcValue(I.getOperand(0)),
7914                            DL.getABITypeAlignment(I.getType()));
7915   setValue(&I, V);
7916   DAG.setRoot(V.getValue(1));
7917 }
7918 
7919 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7920   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7921                           MVT::Other, getRoot(),
7922                           getValue(I.getArgOperand(0)),
7923                           DAG.getSrcValue(I.getArgOperand(0))));
7924 }
7925 
7926 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7927   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7928                           MVT::Other, getRoot(),
7929                           getValue(I.getArgOperand(0)),
7930                           getValue(I.getArgOperand(1)),
7931                           DAG.getSrcValue(I.getArgOperand(0)),
7932                           DAG.getSrcValue(I.getArgOperand(1))));
7933 }
7934 
7935 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7936                                                     const Instruction &I,
7937                                                     SDValue Op) {
7938   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7939   if (!Range)
7940     return Op;
7941 
7942   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7943   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7944     return Op;
7945 
7946   APInt Lo = CR.getUnsignedMin();
7947   if (!Lo.isMinValue())
7948     return Op;
7949 
7950   APInt Hi = CR.getUnsignedMax();
7951   unsigned Bits = Hi.getActiveBits();
7952 
7953   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7954 
7955   SDLoc SL = getCurSDLoc();
7956 
7957   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7958                              DAG.getValueType(SmallVT));
7959   unsigned NumVals = Op.getNode()->getNumValues();
7960   if (NumVals == 1)
7961     return ZExt;
7962 
7963   SmallVector<SDValue, 4> Ops;
7964 
7965   Ops.push_back(ZExt);
7966   for (unsigned I = 1; I != NumVals; ++I)
7967     Ops.push_back(Op.getValue(I));
7968 
7969   return DAG.getMergeValues(Ops, SL);
7970 }
7971 
7972 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
7973 /// the call being lowered.
7974 ///
7975 /// This is a helper for lowering intrinsics that follow a target calling
7976 /// convention or require stack pointer adjustment. Only a subset of the
7977 /// intrinsic's operands need to participate in the calling convention.
7978 void SelectionDAGBuilder::populateCallLoweringInfo(
7979     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7980     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7981     bool IsPatchPoint) {
7982   TargetLowering::ArgListTy Args;
7983   Args.reserve(NumArgs);
7984 
7985   // Populate the argument list.
7986   // Attributes for args start at offset 1, after the return attribute.
7987   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7988        ArgI != ArgE; ++ArgI) {
7989     const Value *V = CS->getOperand(ArgI);
7990 
7991     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7992 
7993     TargetLowering::ArgListEntry Entry;
7994     Entry.Node = getValue(V);
7995     Entry.Ty = V->getType();
7996     Entry.setAttributes(&CS, ArgI);
7997     Args.push_back(Entry);
7998   }
7999 
8000   CLI.setDebugLoc(getCurSDLoc())
8001       .setChain(getRoot())
8002       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
8003       .setDiscardResult(CS->use_empty())
8004       .setIsPatchPoint(IsPatchPoint);
8005 }
8006 
8007 /// Add a stack map intrinsic call's live variable operands to a stackmap
8008 /// or patchpoint target node's operand list.
8009 ///
8010 /// Constants are converted to TargetConstants purely as an optimization to
8011 /// avoid constant materialization and register allocation.
8012 ///
8013 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8014 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8015 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8016 /// address materialization and register allocation, but may also be required
8017 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8018 /// alloca in the entry block, then the runtime may assume that the alloca's
8019 /// StackMap location can be read immediately after compilation and that the
8020 /// location is valid at any point during execution (this is similar to the
8021 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8022 /// only available in a register, then the runtime would need to trap when
8023 /// execution reaches the StackMap in order to read the alloca's location.
8024 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8025                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8026                                 SelectionDAGBuilder &Builder) {
8027   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8028     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8029     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8030       Ops.push_back(
8031         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8032       Ops.push_back(
8033         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8034     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8035       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8036       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8037           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8038     } else
8039       Ops.push_back(OpVal);
8040   }
8041 }
8042 
8043 /// Lower llvm.experimental.stackmap directly to its target opcode.
8044 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8045   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8046   //                                  [live variables...])
8047 
8048   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8049 
8050   SDValue Chain, InFlag, Callee, NullPtr;
8051   SmallVector<SDValue, 32> Ops;
8052 
8053   SDLoc DL = getCurSDLoc();
8054   Callee = getValue(CI.getCalledValue());
8055   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8056 
8057   // The stackmap intrinsic only records the live variables (the arguemnts
8058   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8059   // intrinsic, this won't be lowered to a function call. This means we don't
8060   // have to worry about calling conventions and target specific lowering code.
8061   // Instead we perform the call lowering right here.
8062   //
8063   // chain, flag = CALLSEQ_START(chain, 0, 0)
8064   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8065   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8066   //
8067   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8068   InFlag = Chain.getValue(1);
8069 
8070   // Add the <id> and <numBytes> constants.
8071   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8072   Ops.push_back(DAG.getTargetConstant(
8073                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8074   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8075   Ops.push_back(DAG.getTargetConstant(
8076                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8077                   MVT::i32));
8078 
8079   // Push live variables for the stack map.
8080   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8081 
8082   // We are not pushing any register mask info here on the operands list,
8083   // because the stackmap doesn't clobber anything.
8084 
8085   // Push the chain and the glue flag.
8086   Ops.push_back(Chain);
8087   Ops.push_back(InFlag);
8088 
8089   // Create the STACKMAP node.
8090   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8091   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8092   Chain = SDValue(SM, 0);
8093   InFlag = Chain.getValue(1);
8094 
8095   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8096 
8097   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8098 
8099   // Set the root to the target-lowered call chain.
8100   DAG.setRoot(Chain);
8101 
8102   // Inform the Frame Information that we have a stackmap in this function.
8103   FuncInfo.MF->getFrameInfo().setHasStackMap();
8104 }
8105 
8106 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8107 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8108                                           const BasicBlock *EHPadBB) {
8109   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8110   //                                                 i32 <numBytes>,
8111   //                                                 i8* <target>,
8112   //                                                 i32 <numArgs>,
8113   //                                                 [Args...],
8114   //                                                 [live variables...])
8115 
8116   CallingConv::ID CC = CS.getCallingConv();
8117   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8118   bool HasDef = !CS->getType()->isVoidTy();
8119   SDLoc dl = getCurSDLoc();
8120   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8121 
8122   // Handle immediate and symbolic callees.
8123   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8124     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8125                                    /*isTarget=*/true);
8126   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8127     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8128                                          SDLoc(SymbolicCallee),
8129                                          SymbolicCallee->getValueType(0));
8130 
8131   // Get the real number of arguments participating in the call <numArgs>
8132   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8133   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8134 
8135   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8136   // Intrinsics include all meta-operands up to but not including CC.
8137   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8138   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8139          "Not enough arguments provided to the patchpoint intrinsic");
8140 
8141   // For AnyRegCC the arguments are lowered later on manually.
8142   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8143   Type *ReturnTy =
8144     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8145 
8146   TargetLowering::CallLoweringInfo CLI(DAG);
8147   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8148                            true);
8149   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8150 
8151   SDNode *CallEnd = Result.second.getNode();
8152   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8153     CallEnd = CallEnd->getOperand(0).getNode();
8154 
8155   /// Get a call instruction from the call sequence chain.
8156   /// Tail calls are not allowed.
8157   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8158          "Expected a callseq node.");
8159   SDNode *Call = CallEnd->getOperand(0).getNode();
8160   bool HasGlue = Call->getGluedNode();
8161 
8162   // Replace the target specific call node with the patchable intrinsic.
8163   SmallVector<SDValue, 8> Ops;
8164 
8165   // Add the <id> and <numBytes> constants.
8166   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8167   Ops.push_back(DAG.getTargetConstant(
8168                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8169   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8170   Ops.push_back(DAG.getTargetConstant(
8171                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8172                   MVT::i32));
8173 
8174   // Add the callee.
8175   Ops.push_back(Callee);
8176 
8177   // Adjust <numArgs> to account for any arguments that have been passed on the
8178   // stack instead.
8179   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8180   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8181   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8182   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8183 
8184   // Add the calling convention
8185   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8186 
8187   // Add the arguments we omitted previously. The register allocator should
8188   // place these in any free register.
8189   if (IsAnyRegCC)
8190     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8191       Ops.push_back(getValue(CS.getArgument(i)));
8192 
8193   // Push the arguments from the call instruction up to the register mask.
8194   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8195   Ops.append(Call->op_begin() + 2, e);
8196 
8197   // Push live variables for the stack map.
8198   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8199 
8200   // Push the register mask info.
8201   if (HasGlue)
8202     Ops.push_back(*(Call->op_end()-2));
8203   else
8204     Ops.push_back(*(Call->op_end()-1));
8205 
8206   // Push the chain (this is originally the first operand of the call, but
8207   // becomes now the last or second to last operand).
8208   Ops.push_back(*(Call->op_begin()));
8209 
8210   // Push the glue flag (last operand).
8211   if (HasGlue)
8212     Ops.push_back(*(Call->op_end()-1));
8213 
8214   SDVTList NodeTys;
8215   if (IsAnyRegCC && HasDef) {
8216     // Create the return types based on the intrinsic definition
8217     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8218     SmallVector<EVT, 3> ValueVTs;
8219     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8220     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8221 
8222     // There is always a chain and a glue type at the end
8223     ValueVTs.push_back(MVT::Other);
8224     ValueVTs.push_back(MVT::Glue);
8225     NodeTys = DAG.getVTList(ValueVTs);
8226   } else
8227     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8228 
8229   // Replace the target specific call node with a PATCHPOINT node.
8230   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8231                                          dl, NodeTys, Ops);
8232 
8233   // Update the NodeMap.
8234   if (HasDef) {
8235     if (IsAnyRegCC)
8236       setValue(CS.getInstruction(), SDValue(MN, 0));
8237     else
8238       setValue(CS.getInstruction(), Result.first);
8239   }
8240 
8241   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8242   // call sequence. Furthermore the location of the chain and glue can change
8243   // when the AnyReg calling convention is used and the intrinsic returns a
8244   // value.
8245   if (IsAnyRegCC && HasDef) {
8246     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8247     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8248     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8249   } else
8250     DAG.ReplaceAllUsesWith(Call, MN);
8251   DAG.DeleteNode(Call);
8252 
8253   // Inform the Frame Information that we have a patchpoint in this function.
8254   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8255 }
8256 
8257 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8258                                             unsigned Intrinsic) {
8259   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8260   SDValue Op1 = getValue(I.getArgOperand(0));
8261   SDValue Op2;
8262   if (I.getNumArgOperands() > 1)
8263     Op2 = getValue(I.getArgOperand(1));
8264   SDLoc dl = getCurSDLoc();
8265   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8266   SDValue Res;
8267   FastMathFlags FMF;
8268   if (isa<FPMathOperator>(I))
8269     FMF = I.getFastMathFlags();
8270 
8271   switch (Intrinsic) {
8272   case Intrinsic::experimental_vector_reduce_fadd:
8273     if (FMF.isFast())
8274       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8275     else
8276       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8277     break;
8278   case Intrinsic::experimental_vector_reduce_fmul:
8279     if (FMF.isFast())
8280       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8281     else
8282       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8283     break;
8284   case Intrinsic::experimental_vector_reduce_add:
8285     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8286     break;
8287   case Intrinsic::experimental_vector_reduce_mul:
8288     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8289     break;
8290   case Intrinsic::experimental_vector_reduce_and:
8291     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8292     break;
8293   case Intrinsic::experimental_vector_reduce_or:
8294     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8295     break;
8296   case Intrinsic::experimental_vector_reduce_xor:
8297     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8298     break;
8299   case Intrinsic::experimental_vector_reduce_smax:
8300     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8301     break;
8302   case Intrinsic::experimental_vector_reduce_smin:
8303     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8304     break;
8305   case Intrinsic::experimental_vector_reduce_umax:
8306     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8307     break;
8308   case Intrinsic::experimental_vector_reduce_umin:
8309     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8310     break;
8311   case Intrinsic::experimental_vector_reduce_fmax:
8312     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8313     break;
8314   case Intrinsic::experimental_vector_reduce_fmin:
8315     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8316     break;
8317   default:
8318     llvm_unreachable("Unhandled vector reduce intrinsic");
8319   }
8320   setValue(&I, Res);
8321 }
8322 
8323 /// Returns an AttributeList representing the attributes applied to the return
8324 /// value of the given call.
8325 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8326   SmallVector<Attribute::AttrKind, 2> Attrs;
8327   if (CLI.RetSExt)
8328     Attrs.push_back(Attribute::SExt);
8329   if (CLI.RetZExt)
8330     Attrs.push_back(Attribute::ZExt);
8331   if (CLI.IsInReg)
8332     Attrs.push_back(Attribute::InReg);
8333 
8334   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8335                             Attrs);
8336 }
8337 
8338 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8339 /// implementation, which just calls LowerCall.
8340 /// FIXME: When all targets are
8341 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8342 std::pair<SDValue, SDValue>
8343 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8344   // Handle the incoming return values from the call.
8345   CLI.Ins.clear();
8346   Type *OrigRetTy = CLI.RetTy;
8347   SmallVector<EVT, 4> RetTys;
8348   SmallVector<uint64_t, 4> Offsets;
8349   auto &DL = CLI.DAG.getDataLayout();
8350   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8351 
8352   if (CLI.IsPostTypeLegalization) {
8353     // If we are lowering a libcall after legalization, split the return type.
8354     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8355     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8356     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8357       EVT RetVT = OldRetTys[i];
8358       uint64_t Offset = OldOffsets[i];
8359       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8360       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8361       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8362       RetTys.append(NumRegs, RegisterVT);
8363       for (unsigned j = 0; j != NumRegs; ++j)
8364         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8365     }
8366   }
8367 
8368   SmallVector<ISD::OutputArg, 4> Outs;
8369   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8370 
8371   bool CanLowerReturn =
8372       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8373                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8374 
8375   SDValue DemoteStackSlot;
8376   int DemoteStackIdx = -100;
8377   if (!CanLowerReturn) {
8378     // FIXME: equivalent assert?
8379     // assert(!CS.hasInAllocaArgument() &&
8380     //        "sret demotion is incompatible with inalloca");
8381     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8382     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8383     MachineFunction &MF = CLI.DAG.getMachineFunction();
8384     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8385     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8386                                               DL.getAllocaAddrSpace());
8387 
8388     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8389     ArgListEntry Entry;
8390     Entry.Node = DemoteStackSlot;
8391     Entry.Ty = StackSlotPtrType;
8392     Entry.IsSExt = false;
8393     Entry.IsZExt = false;
8394     Entry.IsInReg = false;
8395     Entry.IsSRet = true;
8396     Entry.IsNest = false;
8397     Entry.IsByVal = false;
8398     Entry.IsReturned = false;
8399     Entry.IsSwiftSelf = false;
8400     Entry.IsSwiftError = false;
8401     Entry.Alignment = Align;
8402     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8403     CLI.NumFixedArgs += 1;
8404     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8405 
8406     // sret demotion isn't compatible with tail-calls, since the sret argument
8407     // points into the callers stack frame.
8408     CLI.IsTailCall = false;
8409   } else {
8410     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8411       EVT VT = RetTys[I];
8412       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8413                                                      CLI.CallConv, VT);
8414       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8415                                                        CLI.CallConv, VT);
8416       for (unsigned i = 0; i != NumRegs; ++i) {
8417         ISD::InputArg MyFlags;
8418         MyFlags.VT = RegisterVT;
8419         MyFlags.ArgVT = VT;
8420         MyFlags.Used = CLI.IsReturnValueUsed;
8421         if (CLI.RetSExt)
8422           MyFlags.Flags.setSExt();
8423         if (CLI.RetZExt)
8424           MyFlags.Flags.setZExt();
8425         if (CLI.IsInReg)
8426           MyFlags.Flags.setInReg();
8427         CLI.Ins.push_back(MyFlags);
8428       }
8429     }
8430   }
8431 
8432   // We push in swifterror return as the last element of CLI.Ins.
8433   ArgListTy &Args = CLI.getArgs();
8434   if (supportSwiftError()) {
8435     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8436       if (Args[i].IsSwiftError) {
8437         ISD::InputArg MyFlags;
8438         MyFlags.VT = getPointerTy(DL);
8439         MyFlags.ArgVT = EVT(getPointerTy(DL));
8440         MyFlags.Flags.setSwiftError();
8441         CLI.Ins.push_back(MyFlags);
8442       }
8443     }
8444   }
8445 
8446   // Handle all of the outgoing arguments.
8447   CLI.Outs.clear();
8448   CLI.OutVals.clear();
8449   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8450     SmallVector<EVT, 4> ValueVTs;
8451     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8452     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8453     Type *FinalType = Args[i].Ty;
8454     if (Args[i].IsByVal)
8455       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8456     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8457         FinalType, CLI.CallConv, CLI.IsVarArg);
8458     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8459          ++Value) {
8460       EVT VT = ValueVTs[Value];
8461       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8462       SDValue Op = SDValue(Args[i].Node.getNode(),
8463                            Args[i].Node.getResNo() + Value);
8464       ISD::ArgFlagsTy Flags;
8465 
8466       // Certain targets (such as MIPS), may have a different ABI alignment
8467       // for a type depending on the context. Give the target a chance to
8468       // specify the alignment it wants.
8469       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8470 
8471       if (Args[i].IsZExt)
8472         Flags.setZExt();
8473       if (Args[i].IsSExt)
8474         Flags.setSExt();
8475       if (Args[i].IsInReg) {
8476         // If we are using vectorcall calling convention, a structure that is
8477         // passed InReg - is surely an HVA
8478         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8479             isa<StructType>(FinalType)) {
8480           // The first value of a structure is marked
8481           if (0 == Value)
8482             Flags.setHvaStart();
8483           Flags.setHva();
8484         }
8485         // Set InReg Flag
8486         Flags.setInReg();
8487       }
8488       if (Args[i].IsSRet)
8489         Flags.setSRet();
8490       if (Args[i].IsSwiftSelf)
8491         Flags.setSwiftSelf();
8492       if (Args[i].IsSwiftError)
8493         Flags.setSwiftError();
8494       if (Args[i].IsByVal)
8495         Flags.setByVal();
8496       if (Args[i].IsInAlloca) {
8497         Flags.setInAlloca();
8498         // Set the byval flag for CCAssignFn callbacks that don't know about
8499         // inalloca.  This way we can know how many bytes we should've allocated
8500         // and how many bytes a callee cleanup function will pop.  If we port
8501         // inalloca to more targets, we'll have to add custom inalloca handling
8502         // in the various CC lowering callbacks.
8503         Flags.setByVal();
8504       }
8505       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8506         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8507         Type *ElementTy = Ty->getElementType();
8508         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8509         // For ByVal, alignment should come from FE.  BE will guess if this
8510         // info is not there but there are cases it cannot get right.
8511         unsigned FrameAlign;
8512         if (Args[i].Alignment)
8513           FrameAlign = Args[i].Alignment;
8514         else
8515           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8516         Flags.setByValAlign(FrameAlign);
8517       }
8518       if (Args[i].IsNest)
8519         Flags.setNest();
8520       if (NeedsRegBlock)
8521         Flags.setInConsecutiveRegs();
8522       Flags.setOrigAlign(OriginalAlignment);
8523 
8524       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8525                                                  CLI.CallConv, VT);
8526       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8527                                                         CLI.CallConv, VT);
8528       SmallVector<SDValue, 4> Parts(NumParts);
8529       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8530 
8531       if (Args[i].IsSExt)
8532         ExtendKind = ISD::SIGN_EXTEND;
8533       else if (Args[i].IsZExt)
8534         ExtendKind = ISD::ZERO_EXTEND;
8535 
8536       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8537       // for now.
8538       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8539           CanLowerReturn) {
8540         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8541                "unexpected use of 'returned'");
8542         // Before passing 'returned' to the target lowering code, ensure that
8543         // either the register MVT and the actual EVT are the same size or that
8544         // the return value and argument are extended in the same way; in these
8545         // cases it's safe to pass the argument register value unchanged as the
8546         // return register value (although it's at the target's option whether
8547         // to do so)
8548         // TODO: allow code generation to take advantage of partially preserved
8549         // registers rather than clobbering the entire register when the
8550         // parameter extension method is not compatible with the return
8551         // extension method
8552         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8553             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8554              CLI.RetZExt == Args[i].IsZExt))
8555           Flags.setReturned();
8556       }
8557 
8558       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8559                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8560 
8561       for (unsigned j = 0; j != NumParts; ++j) {
8562         // if it isn't first piece, alignment must be 1
8563         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8564                                i < CLI.NumFixedArgs,
8565                                i, j*Parts[j].getValueType().getStoreSize());
8566         if (NumParts > 1 && j == 0)
8567           MyFlags.Flags.setSplit();
8568         else if (j != 0) {
8569           MyFlags.Flags.setOrigAlign(1);
8570           if (j == NumParts - 1)
8571             MyFlags.Flags.setSplitEnd();
8572         }
8573 
8574         CLI.Outs.push_back(MyFlags);
8575         CLI.OutVals.push_back(Parts[j]);
8576       }
8577 
8578       if (NeedsRegBlock && Value == NumValues - 1)
8579         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8580     }
8581   }
8582 
8583   SmallVector<SDValue, 4> InVals;
8584   CLI.Chain = LowerCall(CLI, InVals);
8585 
8586   // Update CLI.InVals to use outside of this function.
8587   CLI.InVals = InVals;
8588 
8589   // Verify that the target's LowerCall behaved as expected.
8590   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8591          "LowerCall didn't return a valid chain!");
8592   assert((!CLI.IsTailCall || InVals.empty()) &&
8593          "LowerCall emitted a return value for a tail call!");
8594   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8595          "LowerCall didn't emit the correct number of values!");
8596 
8597   // For a tail call, the return value is merely live-out and there aren't
8598   // any nodes in the DAG representing it. Return a special value to
8599   // indicate that a tail call has been emitted and no more Instructions
8600   // should be processed in the current block.
8601   if (CLI.IsTailCall) {
8602     CLI.DAG.setRoot(CLI.Chain);
8603     return std::make_pair(SDValue(), SDValue());
8604   }
8605 
8606 #ifndef NDEBUG
8607   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8608     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8609     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8610            "LowerCall emitted a value with the wrong type!");
8611   }
8612 #endif
8613 
8614   SmallVector<SDValue, 4> ReturnValues;
8615   if (!CanLowerReturn) {
8616     // The instruction result is the result of loading from the
8617     // hidden sret parameter.
8618     SmallVector<EVT, 1> PVTs;
8619     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8620 
8621     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8622     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8623     EVT PtrVT = PVTs[0];
8624 
8625     unsigned NumValues = RetTys.size();
8626     ReturnValues.resize(NumValues);
8627     SmallVector<SDValue, 4> Chains(NumValues);
8628 
8629     // An aggregate return value cannot wrap around the address space, so
8630     // offsets to its parts don't wrap either.
8631     SDNodeFlags Flags;
8632     Flags.setNoUnsignedWrap(true);
8633 
8634     for (unsigned i = 0; i < NumValues; ++i) {
8635       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8636                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8637                                                         PtrVT), Flags);
8638       SDValue L = CLI.DAG.getLoad(
8639           RetTys[i], CLI.DL, CLI.Chain, Add,
8640           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8641                                             DemoteStackIdx, Offsets[i]),
8642           /* Alignment = */ 1);
8643       ReturnValues[i] = L;
8644       Chains[i] = L.getValue(1);
8645     }
8646 
8647     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8648   } else {
8649     // Collect the legal value parts into potentially illegal values
8650     // that correspond to the original function's return values.
8651     Optional<ISD::NodeType> AssertOp;
8652     if (CLI.RetSExt)
8653       AssertOp = ISD::AssertSext;
8654     else if (CLI.RetZExt)
8655       AssertOp = ISD::AssertZext;
8656     unsigned CurReg = 0;
8657     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8658       EVT VT = RetTys[I];
8659       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8660                                                      CLI.CallConv, VT);
8661       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8662                                                        CLI.CallConv, VT);
8663 
8664       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8665                                               NumRegs, RegisterVT, VT, nullptr,
8666                                               CLI.CallConv, AssertOp));
8667       CurReg += NumRegs;
8668     }
8669 
8670     // For a function returning void, there is no return value. We can't create
8671     // such a node, so we just return a null return value in that case. In
8672     // that case, nothing will actually look at the value.
8673     if (ReturnValues.empty())
8674       return std::make_pair(SDValue(), CLI.Chain);
8675   }
8676 
8677   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8678                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8679   return std::make_pair(Res, CLI.Chain);
8680 }
8681 
8682 void TargetLowering::LowerOperationWrapper(SDNode *N,
8683                                            SmallVectorImpl<SDValue> &Results,
8684                                            SelectionDAG &DAG) const {
8685   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8686     Results.push_back(Res);
8687 }
8688 
8689 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8690   llvm_unreachable("LowerOperation not implemented for this target!");
8691 }
8692 
8693 void
8694 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8695   SDValue Op = getNonRegisterValue(V);
8696   assert((Op.getOpcode() != ISD::CopyFromReg ||
8697           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8698          "Copy from a reg to the same reg!");
8699   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8700 
8701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8702   // If this is an InlineAsm we have to match the registers required, not the
8703   // notional registers required by the type.
8704 
8705   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8706                    None); // This is not an ABI copy.
8707   SDValue Chain = DAG.getEntryNode();
8708 
8709   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8710                               FuncInfo.PreferredExtendType.end())
8711                                  ? ISD::ANY_EXTEND
8712                                  : FuncInfo.PreferredExtendType[V];
8713   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8714   PendingExports.push_back(Chain);
8715 }
8716 
8717 #include "llvm/CodeGen/SelectionDAGISel.h"
8718 
8719 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8720 /// entry block, return true.  This includes arguments used by switches, since
8721 /// the switch may expand into multiple basic blocks.
8722 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8723   // With FastISel active, we may be splitting blocks, so force creation
8724   // of virtual registers for all non-dead arguments.
8725   if (FastISel)
8726     return A->use_empty();
8727 
8728   const BasicBlock &Entry = A->getParent()->front();
8729   for (const User *U : A->users())
8730     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8731       return false;  // Use not in entry block.
8732 
8733   return true;
8734 }
8735 
8736 using ArgCopyElisionMapTy =
8737     DenseMap<const Argument *,
8738              std::pair<const AllocaInst *, const StoreInst *>>;
8739 
8740 /// Scan the entry block of the function in FuncInfo for arguments that look
8741 /// like copies into a local alloca. Record any copied arguments in
8742 /// ArgCopyElisionCandidates.
8743 static void
8744 findArgumentCopyElisionCandidates(const DataLayout &DL,
8745                                   FunctionLoweringInfo *FuncInfo,
8746                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8747   // Record the state of every static alloca used in the entry block. Argument
8748   // allocas are all used in the entry block, so we need approximately as many
8749   // entries as we have arguments.
8750   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8751   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8752   unsigned NumArgs = FuncInfo->Fn->arg_size();
8753   StaticAllocas.reserve(NumArgs * 2);
8754 
8755   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8756     if (!V)
8757       return nullptr;
8758     V = V->stripPointerCasts();
8759     const auto *AI = dyn_cast<AllocaInst>(V);
8760     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8761       return nullptr;
8762     auto Iter = StaticAllocas.insert({AI, Unknown});
8763     return &Iter.first->second;
8764   };
8765 
8766   // Look for stores of arguments to static allocas. Look through bitcasts and
8767   // GEPs to handle type coercions, as long as the alloca is fully initialized
8768   // by the store. Any non-store use of an alloca escapes it and any subsequent
8769   // unanalyzed store might write it.
8770   // FIXME: Handle structs initialized with multiple stores.
8771   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8772     // Look for stores, and handle non-store uses conservatively.
8773     const auto *SI = dyn_cast<StoreInst>(&I);
8774     if (!SI) {
8775       // We will look through cast uses, so ignore them completely.
8776       if (I.isCast())
8777         continue;
8778       // Ignore debug info intrinsics, they don't escape or store to allocas.
8779       if (isa<DbgInfoIntrinsic>(I))
8780         continue;
8781       // This is an unknown instruction. Assume it escapes or writes to all
8782       // static alloca operands.
8783       for (const Use &U : I.operands()) {
8784         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8785           *Info = StaticAllocaInfo::Clobbered;
8786       }
8787       continue;
8788     }
8789 
8790     // If the stored value is a static alloca, mark it as escaped.
8791     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8792       *Info = StaticAllocaInfo::Clobbered;
8793 
8794     // Check if the destination is a static alloca.
8795     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8796     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8797     if (!Info)
8798       continue;
8799     const AllocaInst *AI = cast<AllocaInst>(Dst);
8800 
8801     // Skip allocas that have been initialized or clobbered.
8802     if (*Info != StaticAllocaInfo::Unknown)
8803       continue;
8804 
8805     // Check if the stored value is an argument, and that this store fully
8806     // initializes the alloca. Don't elide copies from the same argument twice.
8807     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8808     const auto *Arg = dyn_cast<Argument>(Val);
8809     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8810         Arg->getType()->isEmptyTy() ||
8811         DL.getTypeStoreSize(Arg->getType()) !=
8812             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8813         ArgCopyElisionCandidates.count(Arg)) {
8814       *Info = StaticAllocaInfo::Clobbered;
8815       continue;
8816     }
8817 
8818     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8819                       << '\n');
8820 
8821     // Mark this alloca and store for argument copy elision.
8822     *Info = StaticAllocaInfo::Elidable;
8823     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8824 
8825     // Stop scanning if we've seen all arguments. This will happen early in -O0
8826     // builds, which is useful, because -O0 builds have large entry blocks and
8827     // many allocas.
8828     if (ArgCopyElisionCandidates.size() == NumArgs)
8829       break;
8830   }
8831 }
8832 
8833 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8834 /// ArgVal is a load from a suitable fixed stack object.
8835 static void tryToElideArgumentCopy(
8836     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8837     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8838     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8839     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8840     SDValue ArgVal, bool &ArgHasUses) {
8841   // Check if this is a load from a fixed stack object.
8842   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8843   if (!LNode)
8844     return;
8845   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8846   if (!FINode)
8847     return;
8848 
8849   // Check that the fixed stack object is the right size and alignment.
8850   // Look at the alignment that the user wrote on the alloca instead of looking
8851   // at the stack object.
8852   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8853   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8854   const AllocaInst *AI = ArgCopyIter->second.first;
8855   int FixedIndex = FINode->getIndex();
8856   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8857   int OldIndex = AllocaIndex;
8858   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8859   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8860     LLVM_DEBUG(
8861         dbgs() << "  argument copy elision failed due to bad fixed stack "
8862                   "object size\n");
8863     return;
8864   }
8865   unsigned RequiredAlignment = AI->getAlignment();
8866   if (!RequiredAlignment) {
8867     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8868         AI->getAllocatedType());
8869   }
8870   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8871     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8872                          "greater than stack argument alignment ("
8873                       << RequiredAlignment << " vs "
8874                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8875     return;
8876   }
8877 
8878   // Perform the elision. Delete the old stack object and replace its only use
8879   // in the variable info map. Mark the stack object as mutable.
8880   LLVM_DEBUG({
8881     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8882            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8883            << '\n';
8884   });
8885   MFI.RemoveStackObject(OldIndex);
8886   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8887   AllocaIndex = FixedIndex;
8888   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8889   Chains.push_back(ArgVal.getValue(1));
8890 
8891   // Avoid emitting code for the store implementing the copy.
8892   const StoreInst *SI = ArgCopyIter->second.second;
8893   ElidedArgCopyInstrs.insert(SI);
8894 
8895   // Check for uses of the argument again so that we can avoid exporting ArgVal
8896   // if it is't used by anything other than the store.
8897   for (const Value *U : Arg.users()) {
8898     if (U != SI) {
8899       ArgHasUses = true;
8900       break;
8901     }
8902   }
8903 }
8904 
8905 void SelectionDAGISel::LowerArguments(const Function &F) {
8906   SelectionDAG &DAG = SDB->DAG;
8907   SDLoc dl = SDB->getCurSDLoc();
8908   const DataLayout &DL = DAG.getDataLayout();
8909   SmallVector<ISD::InputArg, 16> Ins;
8910 
8911   if (!FuncInfo->CanLowerReturn) {
8912     // Put in an sret pointer parameter before all the other parameters.
8913     SmallVector<EVT, 1> ValueVTs;
8914     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8915                     F.getReturnType()->getPointerTo(
8916                         DAG.getDataLayout().getAllocaAddrSpace()),
8917                     ValueVTs);
8918 
8919     // NOTE: Assuming that a pointer will never break down to more than one VT
8920     // or one register.
8921     ISD::ArgFlagsTy Flags;
8922     Flags.setSRet();
8923     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8924     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8925                          ISD::InputArg::NoArgIndex, 0);
8926     Ins.push_back(RetArg);
8927   }
8928 
8929   // Look for stores of arguments to static allocas. Mark such arguments with a
8930   // flag to ask the target to give us the memory location of that argument if
8931   // available.
8932   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8933   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8934 
8935   // Set up the incoming argument description vector.
8936   for (const Argument &Arg : F.args()) {
8937     unsigned ArgNo = Arg.getArgNo();
8938     SmallVector<EVT, 4> ValueVTs;
8939     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8940     bool isArgValueUsed = !Arg.use_empty();
8941     unsigned PartBase = 0;
8942     Type *FinalType = Arg.getType();
8943     if (Arg.hasAttribute(Attribute::ByVal))
8944       FinalType = cast<PointerType>(FinalType)->getElementType();
8945     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8946         FinalType, F.getCallingConv(), F.isVarArg());
8947     for (unsigned Value = 0, NumValues = ValueVTs.size();
8948          Value != NumValues; ++Value) {
8949       EVT VT = ValueVTs[Value];
8950       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8951       ISD::ArgFlagsTy Flags;
8952 
8953       // Certain targets (such as MIPS), may have a different ABI alignment
8954       // for a type depending on the context. Give the target a chance to
8955       // specify the alignment it wants.
8956       unsigned OriginalAlignment =
8957           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8958 
8959       if (Arg.hasAttribute(Attribute::ZExt))
8960         Flags.setZExt();
8961       if (Arg.hasAttribute(Attribute::SExt))
8962         Flags.setSExt();
8963       if (Arg.hasAttribute(Attribute::InReg)) {
8964         // If we are using vectorcall calling convention, a structure that is
8965         // passed InReg - is surely an HVA
8966         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8967             isa<StructType>(Arg.getType())) {
8968           // The first value of a structure is marked
8969           if (0 == Value)
8970             Flags.setHvaStart();
8971           Flags.setHva();
8972         }
8973         // Set InReg Flag
8974         Flags.setInReg();
8975       }
8976       if (Arg.hasAttribute(Attribute::StructRet))
8977         Flags.setSRet();
8978       if (Arg.hasAttribute(Attribute::SwiftSelf))
8979         Flags.setSwiftSelf();
8980       if (Arg.hasAttribute(Attribute::SwiftError))
8981         Flags.setSwiftError();
8982       if (Arg.hasAttribute(Attribute::ByVal))
8983         Flags.setByVal();
8984       if (Arg.hasAttribute(Attribute::InAlloca)) {
8985         Flags.setInAlloca();
8986         // Set the byval flag for CCAssignFn callbacks that don't know about
8987         // inalloca.  This way we can know how many bytes we should've allocated
8988         // and how many bytes a callee cleanup function will pop.  If we port
8989         // inalloca to more targets, we'll have to add custom inalloca handling
8990         // in the various CC lowering callbacks.
8991         Flags.setByVal();
8992       }
8993       if (F.getCallingConv() == CallingConv::X86_INTR) {
8994         // IA Interrupt passes frame (1st parameter) by value in the stack.
8995         if (ArgNo == 0)
8996           Flags.setByVal();
8997       }
8998       if (Flags.isByVal() || Flags.isInAlloca()) {
8999         PointerType *Ty = cast<PointerType>(Arg.getType());
9000         Type *ElementTy = Ty->getElementType();
9001         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9002         // For ByVal, alignment should be passed from FE.  BE will guess if
9003         // this info is not there but there are cases it cannot get right.
9004         unsigned FrameAlign;
9005         if (Arg.getParamAlignment())
9006           FrameAlign = Arg.getParamAlignment();
9007         else
9008           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9009         Flags.setByValAlign(FrameAlign);
9010       }
9011       if (Arg.hasAttribute(Attribute::Nest))
9012         Flags.setNest();
9013       if (NeedsRegBlock)
9014         Flags.setInConsecutiveRegs();
9015       Flags.setOrigAlign(OriginalAlignment);
9016       if (ArgCopyElisionCandidates.count(&Arg))
9017         Flags.setCopyElisionCandidate();
9018 
9019       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9020           *CurDAG->getContext(), F.getCallingConv(), VT);
9021       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9022           *CurDAG->getContext(), F.getCallingConv(), VT);
9023       for (unsigned i = 0; i != NumRegs; ++i) {
9024         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9025                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9026         if (NumRegs > 1 && i == 0)
9027           MyFlags.Flags.setSplit();
9028         // if it isn't first piece, alignment must be 1
9029         else if (i > 0) {
9030           MyFlags.Flags.setOrigAlign(1);
9031           if (i == NumRegs - 1)
9032             MyFlags.Flags.setSplitEnd();
9033         }
9034         Ins.push_back(MyFlags);
9035       }
9036       if (NeedsRegBlock && Value == NumValues - 1)
9037         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9038       PartBase += VT.getStoreSize();
9039     }
9040   }
9041 
9042   // Call the target to set up the argument values.
9043   SmallVector<SDValue, 8> InVals;
9044   SDValue NewRoot = TLI->LowerFormalArguments(
9045       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9046 
9047   // Verify that the target's LowerFormalArguments behaved as expected.
9048   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9049          "LowerFormalArguments didn't return a valid chain!");
9050   assert(InVals.size() == Ins.size() &&
9051          "LowerFormalArguments didn't emit the correct number of values!");
9052   LLVM_DEBUG({
9053     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9054       assert(InVals[i].getNode() &&
9055              "LowerFormalArguments emitted a null value!");
9056       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9057              "LowerFormalArguments emitted a value with the wrong type!");
9058     }
9059   });
9060 
9061   // Update the DAG with the new chain value resulting from argument lowering.
9062   DAG.setRoot(NewRoot);
9063 
9064   // Set up the argument values.
9065   unsigned i = 0;
9066   if (!FuncInfo->CanLowerReturn) {
9067     // Create a virtual register for the sret pointer, and put in a copy
9068     // from the sret argument into it.
9069     SmallVector<EVT, 1> ValueVTs;
9070     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9071                     F.getReturnType()->getPointerTo(
9072                         DAG.getDataLayout().getAllocaAddrSpace()),
9073                     ValueVTs);
9074     MVT VT = ValueVTs[0].getSimpleVT();
9075     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9076     Optional<ISD::NodeType> AssertOp = None;
9077     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9078                                         nullptr, F.getCallingConv(), AssertOp);
9079 
9080     MachineFunction& MF = SDB->DAG.getMachineFunction();
9081     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9082     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9083     FuncInfo->DemoteRegister = SRetReg;
9084     NewRoot =
9085         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9086     DAG.setRoot(NewRoot);
9087 
9088     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9089     ++i;
9090   }
9091 
9092   SmallVector<SDValue, 4> Chains;
9093   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9094   for (const Argument &Arg : F.args()) {
9095     SmallVector<SDValue, 4> ArgValues;
9096     SmallVector<EVT, 4> ValueVTs;
9097     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9098     unsigned NumValues = ValueVTs.size();
9099     if (NumValues == 0)
9100       continue;
9101 
9102     bool ArgHasUses = !Arg.use_empty();
9103 
9104     // Elide the copying store if the target loaded this argument from a
9105     // suitable fixed stack object.
9106     if (Ins[i].Flags.isCopyElisionCandidate()) {
9107       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9108                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9109                              InVals[i], ArgHasUses);
9110     }
9111 
9112     // If this argument is unused then remember its value. It is used to generate
9113     // debugging information.
9114     bool isSwiftErrorArg =
9115         TLI->supportSwiftError() &&
9116         Arg.hasAttribute(Attribute::SwiftError);
9117     if (!ArgHasUses && !isSwiftErrorArg) {
9118       SDB->setUnusedArgValue(&Arg, InVals[i]);
9119 
9120       // Also remember any frame index for use in FastISel.
9121       if (FrameIndexSDNode *FI =
9122           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9123         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9124     }
9125 
9126     for (unsigned Val = 0; Val != NumValues; ++Val) {
9127       EVT VT = ValueVTs[Val];
9128       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9129                                                       F.getCallingConv(), VT);
9130       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9131           *CurDAG->getContext(), F.getCallingConv(), VT);
9132 
9133       // Even an apparant 'unused' swifterror argument needs to be returned. So
9134       // we do generate a copy for it that can be used on return from the
9135       // function.
9136       if (ArgHasUses || isSwiftErrorArg) {
9137         Optional<ISD::NodeType> AssertOp;
9138         if (Arg.hasAttribute(Attribute::SExt))
9139           AssertOp = ISD::AssertSext;
9140         else if (Arg.hasAttribute(Attribute::ZExt))
9141           AssertOp = ISD::AssertZext;
9142 
9143         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9144                                              PartVT, VT, nullptr,
9145                                              F.getCallingConv(), AssertOp));
9146       }
9147 
9148       i += NumParts;
9149     }
9150 
9151     // We don't need to do anything else for unused arguments.
9152     if (ArgValues.empty())
9153       continue;
9154 
9155     // Note down frame index.
9156     if (FrameIndexSDNode *FI =
9157         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9158       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9159 
9160     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9161                                      SDB->getCurSDLoc());
9162 
9163     SDB->setValue(&Arg, Res);
9164     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9165       // We want to associate the argument with the frame index, among
9166       // involved operands, that correspond to the lowest address. The
9167       // getCopyFromParts function, called earlier, is swapping the order of
9168       // the operands to BUILD_PAIR depending on endianness. The result of
9169       // that swapping is that the least significant bits of the argument will
9170       // be in the first operand of the BUILD_PAIR node, and the most
9171       // significant bits will be in the second operand.
9172       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9173       if (LoadSDNode *LNode =
9174           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9175         if (FrameIndexSDNode *FI =
9176             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9177           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9178     }
9179 
9180     // Update the SwiftErrorVRegDefMap.
9181     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9182       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9183       if (TargetRegisterInfo::isVirtualRegister(Reg))
9184         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9185                                            FuncInfo->SwiftErrorArg, Reg);
9186     }
9187 
9188     // If this argument is live outside of the entry block, insert a copy from
9189     // wherever we got it to the vreg that other BB's will reference it as.
9190     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9191       // If we can, though, try to skip creating an unnecessary vreg.
9192       // FIXME: This isn't very clean... it would be nice to make this more
9193       // general.  It's also subtly incompatible with the hacks FastISel
9194       // uses with vregs.
9195       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9196       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9197         FuncInfo->ValueMap[&Arg] = Reg;
9198         continue;
9199       }
9200     }
9201     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9202       FuncInfo->InitializeRegForValue(&Arg);
9203       SDB->CopyToExportRegsIfNeeded(&Arg);
9204     }
9205   }
9206 
9207   if (!Chains.empty()) {
9208     Chains.push_back(NewRoot);
9209     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9210   }
9211 
9212   DAG.setRoot(NewRoot);
9213 
9214   assert(i == InVals.size() && "Argument register count mismatch!");
9215 
9216   // If any argument copy elisions occurred and we have debug info, update the
9217   // stale frame indices used in the dbg.declare variable info table.
9218   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9219   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9220     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9221       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9222       if (I != ArgCopyElisionFrameIndexMap.end())
9223         VI.Slot = I->second;
9224     }
9225   }
9226 
9227   // Finally, if the target has anything special to do, allow it to do so.
9228   EmitFunctionEntryCode();
9229 }
9230 
9231 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9232 /// ensure constants are generated when needed.  Remember the virtual registers
9233 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9234 /// directly add them, because expansion might result in multiple MBB's for one
9235 /// BB.  As such, the start of the BB might correspond to a different MBB than
9236 /// the end.
9237 void
9238 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9239   const TerminatorInst *TI = LLVMBB->getTerminator();
9240 
9241   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9242 
9243   // Check PHI nodes in successors that expect a value to be available from this
9244   // block.
9245   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9246     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9247     if (!isa<PHINode>(SuccBB->begin())) continue;
9248     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9249 
9250     // If this terminator has multiple identical successors (common for
9251     // switches), only handle each succ once.
9252     if (!SuccsHandled.insert(SuccMBB).second)
9253       continue;
9254 
9255     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9256 
9257     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9258     // nodes and Machine PHI nodes, but the incoming operands have not been
9259     // emitted yet.
9260     for (const PHINode &PN : SuccBB->phis()) {
9261       // Ignore dead phi's.
9262       if (PN.use_empty())
9263         continue;
9264 
9265       // Skip empty types
9266       if (PN.getType()->isEmptyTy())
9267         continue;
9268 
9269       unsigned Reg;
9270       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9271 
9272       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9273         unsigned &RegOut = ConstantsOut[C];
9274         if (RegOut == 0) {
9275           RegOut = FuncInfo.CreateRegs(C->getType());
9276           CopyValueToVirtualRegister(C, RegOut);
9277         }
9278         Reg = RegOut;
9279       } else {
9280         DenseMap<const Value *, unsigned>::iterator I =
9281           FuncInfo.ValueMap.find(PHIOp);
9282         if (I != FuncInfo.ValueMap.end())
9283           Reg = I->second;
9284         else {
9285           assert(isa<AllocaInst>(PHIOp) &&
9286                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9287                  "Didn't codegen value into a register!??");
9288           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9289           CopyValueToVirtualRegister(PHIOp, Reg);
9290         }
9291       }
9292 
9293       // Remember that this register needs to added to the machine PHI node as
9294       // the input for this MBB.
9295       SmallVector<EVT, 4> ValueVTs;
9296       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9297       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9298       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9299         EVT VT = ValueVTs[vti];
9300         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9301         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9302           FuncInfo.PHINodesToUpdate.push_back(
9303               std::make_pair(&*MBBI++, Reg + i));
9304         Reg += NumRegisters;
9305       }
9306     }
9307   }
9308 
9309   ConstantsOut.clear();
9310 }
9311 
9312 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9313 /// is 0.
9314 MachineBasicBlock *
9315 SelectionDAGBuilder::StackProtectorDescriptor::
9316 AddSuccessorMBB(const BasicBlock *BB,
9317                 MachineBasicBlock *ParentMBB,
9318                 bool IsLikely,
9319                 MachineBasicBlock *SuccMBB) {
9320   // If SuccBB has not been created yet, create it.
9321   if (!SuccMBB) {
9322     MachineFunction *MF = ParentMBB->getParent();
9323     MachineFunction::iterator BBI(ParentMBB);
9324     SuccMBB = MF->CreateMachineBasicBlock(BB);
9325     MF->insert(++BBI, SuccMBB);
9326   }
9327   // Add it as a successor of ParentMBB.
9328   ParentMBB->addSuccessor(
9329       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9330   return SuccMBB;
9331 }
9332 
9333 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9334   MachineFunction::iterator I(MBB);
9335   if (++I == FuncInfo.MF->end())
9336     return nullptr;
9337   return &*I;
9338 }
9339 
9340 /// During lowering new call nodes can be created (such as memset, etc.).
9341 /// Those will become new roots of the current DAG, but complications arise
9342 /// when they are tail calls. In such cases, the call lowering will update
9343 /// the root, but the builder still needs to know that a tail call has been
9344 /// lowered in order to avoid generating an additional return.
9345 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9346   // If the node is null, we do have a tail call.
9347   if (MaybeTC.getNode() != nullptr)
9348     DAG.setRoot(MaybeTC);
9349   else
9350     HasTailCall = true;
9351 }
9352 
9353 uint64_t
9354 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9355                                        unsigned First, unsigned Last) const {
9356   assert(Last >= First);
9357   const APInt &LowCase = Clusters[First].Low->getValue();
9358   const APInt &HighCase = Clusters[Last].High->getValue();
9359   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9360 
9361   // FIXME: A range of consecutive cases has 100% density, but only requires one
9362   // comparison to lower. We should discriminate against such consecutive ranges
9363   // in jump tables.
9364 
9365   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9366 }
9367 
9368 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9369     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9370     unsigned Last) const {
9371   assert(Last >= First);
9372   assert(TotalCases[Last] >= TotalCases[First]);
9373   uint64_t NumCases =
9374       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9375   return NumCases;
9376 }
9377 
9378 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9379                                          unsigned First, unsigned Last,
9380                                          const SwitchInst *SI,
9381                                          MachineBasicBlock *DefaultMBB,
9382                                          CaseCluster &JTCluster) {
9383   assert(First <= Last);
9384 
9385   auto Prob = BranchProbability::getZero();
9386   unsigned NumCmps = 0;
9387   std::vector<MachineBasicBlock*> Table;
9388   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9389 
9390   // Initialize probabilities in JTProbs.
9391   for (unsigned I = First; I <= Last; ++I)
9392     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9393 
9394   for (unsigned I = First; I <= Last; ++I) {
9395     assert(Clusters[I].Kind == CC_Range);
9396     Prob += Clusters[I].Prob;
9397     const APInt &Low = Clusters[I].Low->getValue();
9398     const APInt &High = Clusters[I].High->getValue();
9399     NumCmps += (Low == High) ? 1 : 2;
9400     if (I != First) {
9401       // Fill the gap between this and the previous cluster.
9402       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9403       assert(PreviousHigh.slt(Low));
9404       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9405       for (uint64_t J = 0; J < Gap; J++)
9406         Table.push_back(DefaultMBB);
9407     }
9408     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9409     for (uint64_t J = 0; J < ClusterSize; ++J)
9410       Table.push_back(Clusters[I].MBB);
9411     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9412   }
9413 
9414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9415   unsigned NumDests = JTProbs.size();
9416   if (TLI.isSuitableForBitTests(
9417           NumDests, NumCmps, Clusters[First].Low->getValue(),
9418           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9419     // Clusters[First..Last] should be lowered as bit tests instead.
9420     return false;
9421   }
9422 
9423   // Create the MBB that will load from and jump through the table.
9424   // Note: We create it here, but it's not inserted into the function yet.
9425   MachineFunction *CurMF = FuncInfo.MF;
9426   MachineBasicBlock *JumpTableMBB =
9427       CurMF->CreateMachineBasicBlock(SI->getParent());
9428 
9429   // Add successors. Note: use table order for determinism.
9430   SmallPtrSet<MachineBasicBlock *, 8> Done;
9431   for (MachineBasicBlock *Succ : Table) {
9432     if (Done.count(Succ))
9433       continue;
9434     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9435     Done.insert(Succ);
9436   }
9437   JumpTableMBB->normalizeSuccProbs();
9438 
9439   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9440                      ->createJumpTableIndex(Table);
9441 
9442   // Set up the jump table info.
9443   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9444   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9445                       Clusters[Last].High->getValue(), SI->getCondition(),
9446                       nullptr, false);
9447   JTCases.emplace_back(std::move(JTH), std::move(JT));
9448 
9449   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9450                                      JTCases.size() - 1, Prob);
9451   return true;
9452 }
9453 
9454 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9455                                          const SwitchInst *SI,
9456                                          MachineBasicBlock *DefaultMBB) {
9457 #ifndef NDEBUG
9458   // Clusters must be non-empty, sorted, and only contain Range clusters.
9459   assert(!Clusters.empty());
9460   for (CaseCluster &C : Clusters)
9461     assert(C.Kind == CC_Range);
9462   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9463     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9464 #endif
9465 
9466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9467   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9468     return;
9469 
9470   const int64_t N = Clusters.size();
9471   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9472   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9473 
9474   if (N < 2 || N < MinJumpTableEntries)
9475     return;
9476 
9477   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9478   SmallVector<unsigned, 8> TotalCases(N);
9479   for (unsigned i = 0; i < N; ++i) {
9480     const APInt &Hi = Clusters[i].High->getValue();
9481     const APInt &Lo = Clusters[i].Low->getValue();
9482     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9483     if (i != 0)
9484       TotalCases[i] += TotalCases[i - 1];
9485   }
9486 
9487   // Cheap case: the whole range may be suitable for jump table.
9488   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9489   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9490   assert(NumCases < UINT64_MAX / 100);
9491   assert(Range >= NumCases);
9492   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9493     CaseCluster JTCluster;
9494     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9495       Clusters[0] = JTCluster;
9496       Clusters.resize(1);
9497       return;
9498     }
9499   }
9500 
9501   // The algorithm below is not suitable for -O0.
9502   if (TM.getOptLevel() == CodeGenOpt::None)
9503     return;
9504 
9505   // Split Clusters into minimum number of dense partitions. The algorithm uses
9506   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9507   // for the Case Statement'" (1994), but builds the MinPartitions array in
9508   // reverse order to make it easier to reconstruct the partitions in ascending
9509   // order. In the choice between two optimal partitionings, it picks the one
9510   // which yields more jump tables.
9511 
9512   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9513   SmallVector<unsigned, 8> MinPartitions(N);
9514   // LastElement[i] is the last element of the partition starting at i.
9515   SmallVector<unsigned, 8> LastElement(N);
9516   // PartitionsScore[i] is used to break ties when choosing between two
9517   // partitionings resulting in the same number of partitions.
9518   SmallVector<unsigned, 8> PartitionsScore(N);
9519   // For PartitionsScore, a small number of comparisons is considered as good as
9520   // a jump table and a single comparison is considered better than a jump
9521   // table.
9522   enum PartitionScores : unsigned {
9523     NoTable = 0,
9524     Table = 1,
9525     FewCases = 1,
9526     SingleCase = 2
9527   };
9528 
9529   // Base case: There is only one way to partition Clusters[N-1].
9530   MinPartitions[N - 1] = 1;
9531   LastElement[N - 1] = N - 1;
9532   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9533 
9534   // Note: loop indexes are signed to avoid underflow.
9535   for (int64_t i = N - 2; i >= 0; i--) {
9536     // Find optimal partitioning of Clusters[i..N-1].
9537     // Baseline: Put Clusters[i] into a partition on its own.
9538     MinPartitions[i] = MinPartitions[i + 1] + 1;
9539     LastElement[i] = i;
9540     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9541 
9542     // Search for a solution that results in fewer partitions.
9543     for (int64_t j = N - 1; j > i; j--) {
9544       // Try building a partition from Clusters[i..j].
9545       uint64_t Range = getJumpTableRange(Clusters, i, j);
9546       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9547       assert(NumCases < UINT64_MAX / 100);
9548       assert(Range >= NumCases);
9549       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9550         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9551         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9552         int64_t NumEntries = j - i + 1;
9553 
9554         if (NumEntries == 1)
9555           Score += PartitionScores::SingleCase;
9556         else if (NumEntries <= SmallNumberOfEntries)
9557           Score += PartitionScores::FewCases;
9558         else if (NumEntries >= MinJumpTableEntries)
9559           Score += PartitionScores::Table;
9560 
9561         // If this leads to fewer partitions, or to the same number of
9562         // partitions with better score, it is a better partitioning.
9563         if (NumPartitions < MinPartitions[i] ||
9564             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9565           MinPartitions[i] = NumPartitions;
9566           LastElement[i] = j;
9567           PartitionsScore[i] = Score;
9568         }
9569       }
9570     }
9571   }
9572 
9573   // Iterate over the partitions, replacing some with jump tables in-place.
9574   unsigned DstIndex = 0;
9575   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9576     Last = LastElement[First];
9577     assert(Last >= First);
9578     assert(DstIndex <= First);
9579     unsigned NumClusters = Last - First + 1;
9580 
9581     CaseCluster JTCluster;
9582     if (NumClusters >= MinJumpTableEntries &&
9583         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9584       Clusters[DstIndex++] = JTCluster;
9585     } else {
9586       for (unsigned I = First; I <= Last; ++I)
9587         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9588     }
9589   }
9590   Clusters.resize(DstIndex);
9591 }
9592 
9593 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9594                                         unsigned First, unsigned Last,
9595                                         const SwitchInst *SI,
9596                                         CaseCluster &BTCluster) {
9597   assert(First <= Last);
9598   if (First == Last)
9599     return false;
9600 
9601   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9602   unsigned NumCmps = 0;
9603   for (int64_t I = First; I <= Last; ++I) {
9604     assert(Clusters[I].Kind == CC_Range);
9605     Dests.set(Clusters[I].MBB->getNumber());
9606     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9607   }
9608   unsigned NumDests = Dests.count();
9609 
9610   APInt Low = Clusters[First].Low->getValue();
9611   APInt High = Clusters[Last].High->getValue();
9612   assert(Low.slt(High));
9613 
9614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9615   const DataLayout &DL = DAG.getDataLayout();
9616   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9617     return false;
9618 
9619   APInt LowBound;
9620   APInt CmpRange;
9621 
9622   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9623   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9624          "Case range must fit in bit mask!");
9625 
9626   // Check if the clusters cover a contiguous range such that no value in the
9627   // range will jump to the default statement.
9628   bool ContiguousRange = true;
9629   for (int64_t I = First + 1; I <= Last; ++I) {
9630     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9631       ContiguousRange = false;
9632       break;
9633     }
9634   }
9635 
9636   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9637     // Optimize the case where all the case values fit in a word without having
9638     // to subtract minValue. In this case, we can optimize away the subtraction.
9639     LowBound = APInt::getNullValue(Low.getBitWidth());
9640     CmpRange = High;
9641     ContiguousRange = false;
9642   } else {
9643     LowBound = Low;
9644     CmpRange = High - Low;
9645   }
9646 
9647   CaseBitsVector CBV;
9648   auto TotalProb = BranchProbability::getZero();
9649   for (unsigned i = First; i <= Last; ++i) {
9650     // Find the CaseBits for this destination.
9651     unsigned j;
9652     for (j = 0; j < CBV.size(); ++j)
9653       if (CBV[j].BB == Clusters[i].MBB)
9654         break;
9655     if (j == CBV.size())
9656       CBV.push_back(
9657           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9658     CaseBits *CB = &CBV[j];
9659 
9660     // Update Mask, Bits and ExtraProb.
9661     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9662     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9663     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9664     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9665     CB->Bits += Hi - Lo + 1;
9666     CB->ExtraProb += Clusters[i].Prob;
9667     TotalProb += Clusters[i].Prob;
9668   }
9669 
9670   BitTestInfo BTI;
9671   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9672     // Sort by probability first, number of bits second, bit mask third.
9673     if (a.ExtraProb != b.ExtraProb)
9674       return a.ExtraProb > b.ExtraProb;
9675     if (a.Bits != b.Bits)
9676       return a.Bits > b.Bits;
9677     return a.Mask < b.Mask;
9678   });
9679 
9680   for (auto &CB : CBV) {
9681     MachineBasicBlock *BitTestBB =
9682         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9683     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9684   }
9685   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9686                             SI->getCondition(), -1U, MVT::Other, false,
9687                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9688                             TotalProb);
9689 
9690   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9691                                     BitTestCases.size() - 1, TotalProb);
9692   return true;
9693 }
9694 
9695 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9696                                               const SwitchInst *SI) {
9697 // Partition Clusters into as few subsets as possible, where each subset has a
9698 // range that fits in a machine word and has <= 3 unique destinations.
9699 
9700 #ifndef NDEBUG
9701   // Clusters must be sorted and contain Range or JumpTable clusters.
9702   assert(!Clusters.empty());
9703   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9704   for (const CaseCluster &C : Clusters)
9705     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9706   for (unsigned i = 1; i < Clusters.size(); ++i)
9707     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9708 #endif
9709 
9710   // The algorithm below is not suitable for -O0.
9711   if (TM.getOptLevel() == CodeGenOpt::None)
9712     return;
9713 
9714   // If target does not have legal shift left, do not emit bit tests at all.
9715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9716   const DataLayout &DL = DAG.getDataLayout();
9717 
9718   EVT PTy = TLI.getPointerTy(DL);
9719   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9720     return;
9721 
9722   int BitWidth = PTy.getSizeInBits();
9723   const int64_t N = Clusters.size();
9724 
9725   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9726   SmallVector<unsigned, 8> MinPartitions(N);
9727   // LastElement[i] is the last element of the partition starting at i.
9728   SmallVector<unsigned, 8> LastElement(N);
9729 
9730   // FIXME: This might not be the best algorithm for finding bit test clusters.
9731 
9732   // Base case: There is only one way to partition Clusters[N-1].
9733   MinPartitions[N - 1] = 1;
9734   LastElement[N - 1] = N - 1;
9735 
9736   // Note: loop indexes are signed to avoid underflow.
9737   for (int64_t i = N - 2; i >= 0; --i) {
9738     // Find optimal partitioning of Clusters[i..N-1].
9739     // Baseline: Put Clusters[i] into a partition on its own.
9740     MinPartitions[i] = MinPartitions[i + 1] + 1;
9741     LastElement[i] = i;
9742 
9743     // Search for a solution that results in fewer partitions.
9744     // Note: the search is limited by BitWidth, reducing time complexity.
9745     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9746       // Try building a partition from Clusters[i..j].
9747 
9748       // Check the range.
9749       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9750                                Clusters[j].High->getValue(), DL))
9751         continue;
9752 
9753       // Check nbr of destinations and cluster types.
9754       // FIXME: This works, but doesn't seem very efficient.
9755       bool RangesOnly = true;
9756       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9757       for (int64_t k = i; k <= j; k++) {
9758         if (Clusters[k].Kind != CC_Range) {
9759           RangesOnly = false;
9760           break;
9761         }
9762         Dests.set(Clusters[k].MBB->getNumber());
9763       }
9764       if (!RangesOnly || Dests.count() > 3)
9765         break;
9766 
9767       // Check if it's a better partition.
9768       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9769       if (NumPartitions < MinPartitions[i]) {
9770         // Found a better partition.
9771         MinPartitions[i] = NumPartitions;
9772         LastElement[i] = j;
9773       }
9774     }
9775   }
9776 
9777   // Iterate over the partitions, replacing with bit-test clusters in-place.
9778   unsigned DstIndex = 0;
9779   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9780     Last = LastElement[First];
9781     assert(First <= Last);
9782     assert(DstIndex <= First);
9783 
9784     CaseCluster BitTestCluster;
9785     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9786       Clusters[DstIndex++] = BitTestCluster;
9787     } else {
9788       size_t NumClusters = Last - First + 1;
9789       std::memmove(&Clusters[DstIndex], &Clusters[First],
9790                    sizeof(Clusters[0]) * NumClusters);
9791       DstIndex += NumClusters;
9792     }
9793   }
9794   Clusters.resize(DstIndex);
9795 }
9796 
9797 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9798                                         MachineBasicBlock *SwitchMBB,
9799                                         MachineBasicBlock *DefaultMBB) {
9800   MachineFunction *CurMF = FuncInfo.MF;
9801   MachineBasicBlock *NextMBB = nullptr;
9802   MachineFunction::iterator BBI(W.MBB);
9803   if (++BBI != FuncInfo.MF->end())
9804     NextMBB = &*BBI;
9805 
9806   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9807 
9808   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9809 
9810   if (Size == 2 && W.MBB == SwitchMBB) {
9811     // If any two of the cases has the same destination, and if one value
9812     // is the same as the other, but has one bit unset that the other has set,
9813     // use bit manipulation to do two compares at once.  For example:
9814     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9815     // TODO: This could be extended to merge any 2 cases in switches with 3
9816     // cases.
9817     // TODO: Handle cases where W.CaseBB != SwitchBB.
9818     CaseCluster &Small = *W.FirstCluster;
9819     CaseCluster &Big = *W.LastCluster;
9820 
9821     if (Small.Low == Small.High && Big.Low == Big.High &&
9822         Small.MBB == Big.MBB) {
9823       const APInt &SmallValue = Small.Low->getValue();
9824       const APInt &BigValue = Big.Low->getValue();
9825 
9826       // Check that there is only one bit different.
9827       APInt CommonBit = BigValue ^ SmallValue;
9828       if (CommonBit.isPowerOf2()) {
9829         SDValue CondLHS = getValue(Cond);
9830         EVT VT = CondLHS.getValueType();
9831         SDLoc DL = getCurSDLoc();
9832 
9833         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9834                                  DAG.getConstant(CommonBit, DL, VT));
9835         SDValue Cond = DAG.getSetCC(
9836             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9837             ISD::SETEQ);
9838 
9839         // Update successor info.
9840         // Both Small and Big will jump to Small.BB, so we sum up the
9841         // probabilities.
9842         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9843         if (BPI)
9844           addSuccessorWithProb(
9845               SwitchMBB, DefaultMBB,
9846               // The default destination is the first successor in IR.
9847               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9848         else
9849           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9850 
9851         // Insert the true branch.
9852         SDValue BrCond =
9853             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9854                         DAG.getBasicBlock(Small.MBB));
9855         // Insert the false branch.
9856         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9857                              DAG.getBasicBlock(DefaultMBB));
9858 
9859         DAG.setRoot(BrCond);
9860         return;
9861       }
9862     }
9863   }
9864 
9865   if (TM.getOptLevel() != CodeGenOpt::None) {
9866     // Here, we order cases by probability so the most likely case will be
9867     // checked first. However, two clusters can have the same probability in
9868     // which case their relative ordering is non-deterministic. So we use Low
9869     // as a tie-breaker as clusters are guaranteed to never overlap.
9870     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9871                [](const CaseCluster &a, const CaseCluster &b) {
9872       return a.Prob != b.Prob ?
9873              a.Prob > b.Prob :
9874              a.Low->getValue().slt(b.Low->getValue());
9875     });
9876 
9877     // Rearrange the case blocks so that the last one falls through if possible
9878     // without changing the order of probabilities.
9879     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9880       --I;
9881       if (I->Prob > W.LastCluster->Prob)
9882         break;
9883       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9884         std::swap(*I, *W.LastCluster);
9885         break;
9886       }
9887     }
9888   }
9889 
9890   // Compute total probability.
9891   BranchProbability DefaultProb = W.DefaultProb;
9892   BranchProbability UnhandledProbs = DefaultProb;
9893   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9894     UnhandledProbs += I->Prob;
9895 
9896   MachineBasicBlock *CurMBB = W.MBB;
9897   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9898     MachineBasicBlock *Fallthrough;
9899     if (I == W.LastCluster) {
9900       // For the last cluster, fall through to the default destination.
9901       Fallthrough = DefaultMBB;
9902     } else {
9903       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9904       CurMF->insert(BBI, Fallthrough);
9905       // Put Cond in a virtual register to make it available from the new blocks.
9906       ExportFromCurrentBlock(Cond);
9907     }
9908     UnhandledProbs -= I->Prob;
9909 
9910     switch (I->Kind) {
9911       case CC_JumpTable: {
9912         // FIXME: Optimize away range check based on pivot comparisons.
9913         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9914         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9915 
9916         // The jump block hasn't been inserted yet; insert it here.
9917         MachineBasicBlock *JumpMBB = JT->MBB;
9918         CurMF->insert(BBI, JumpMBB);
9919 
9920         auto JumpProb = I->Prob;
9921         auto FallthroughProb = UnhandledProbs;
9922 
9923         // If the default statement is a target of the jump table, we evenly
9924         // distribute the default probability to successors of CurMBB. Also
9925         // update the probability on the edge from JumpMBB to Fallthrough.
9926         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9927                                               SE = JumpMBB->succ_end();
9928              SI != SE; ++SI) {
9929           if (*SI == DefaultMBB) {
9930             JumpProb += DefaultProb / 2;
9931             FallthroughProb -= DefaultProb / 2;
9932             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9933             JumpMBB->normalizeSuccProbs();
9934             break;
9935           }
9936         }
9937 
9938         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9939         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9940         CurMBB->normalizeSuccProbs();
9941 
9942         // The jump table header will be inserted in our current block, do the
9943         // range check, and fall through to our fallthrough block.
9944         JTH->HeaderBB = CurMBB;
9945         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9946 
9947         // If we're in the right place, emit the jump table header right now.
9948         if (CurMBB == SwitchMBB) {
9949           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9950           JTH->Emitted = true;
9951         }
9952         break;
9953       }
9954       case CC_BitTests: {
9955         // FIXME: Optimize away range check based on pivot comparisons.
9956         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9957 
9958         // The bit test blocks haven't been inserted yet; insert them here.
9959         for (BitTestCase &BTC : BTB->Cases)
9960           CurMF->insert(BBI, BTC.ThisBB);
9961 
9962         // Fill in fields of the BitTestBlock.
9963         BTB->Parent = CurMBB;
9964         BTB->Default = Fallthrough;
9965 
9966         BTB->DefaultProb = UnhandledProbs;
9967         // If the cases in bit test don't form a contiguous range, we evenly
9968         // distribute the probability on the edge to Fallthrough to two
9969         // successors of CurMBB.
9970         if (!BTB->ContiguousRange) {
9971           BTB->Prob += DefaultProb / 2;
9972           BTB->DefaultProb -= DefaultProb / 2;
9973         }
9974 
9975         // If we're in the right place, emit the bit test header right now.
9976         if (CurMBB == SwitchMBB) {
9977           visitBitTestHeader(*BTB, SwitchMBB);
9978           BTB->Emitted = true;
9979         }
9980         break;
9981       }
9982       case CC_Range: {
9983         const Value *RHS, *LHS, *MHS;
9984         ISD::CondCode CC;
9985         if (I->Low == I->High) {
9986           // Check Cond == I->Low.
9987           CC = ISD::SETEQ;
9988           LHS = Cond;
9989           RHS=I->Low;
9990           MHS = nullptr;
9991         } else {
9992           // Check I->Low <= Cond <= I->High.
9993           CC = ISD::SETLE;
9994           LHS = I->Low;
9995           MHS = Cond;
9996           RHS = I->High;
9997         }
9998 
9999         // The false probability is the sum of all unhandled cases.
10000         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10001                      getCurSDLoc(), I->Prob, UnhandledProbs);
10002 
10003         if (CurMBB == SwitchMBB)
10004           visitSwitchCase(CB, SwitchMBB);
10005         else
10006           SwitchCases.push_back(CB);
10007 
10008         break;
10009       }
10010     }
10011     CurMBB = Fallthrough;
10012   }
10013 }
10014 
10015 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10016                                               CaseClusterIt First,
10017                                               CaseClusterIt Last) {
10018   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10019     if (X.Prob != CC.Prob)
10020       return X.Prob > CC.Prob;
10021 
10022     // Ties are broken by comparing the case value.
10023     return X.Low->getValue().slt(CC.Low->getValue());
10024   });
10025 }
10026 
10027 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10028                                         const SwitchWorkListItem &W,
10029                                         Value *Cond,
10030                                         MachineBasicBlock *SwitchMBB) {
10031   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10032          "Clusters not sorted?");
10033 
10034   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10035 
10036   // Balance the tree based on branch probabilities to create a near-optimal (in
10037   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10038   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10039   CaseClusterIt LastLeft = W.FirstCluster;
10040   CaseClusterIt FirstRight = W.LastCluster;
10041   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10042   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10043 
10044   // Move LastLeft and FirstRight towards each other from opposite directions to
10045   // find a partitioning of the clusters which balances the probability on both
10046   // sides. If LeftProb and RightProb are equal, alternate which side is
10047   // taken to ensure 0-probability nodes are distributed evenly.
10048   unsigned I = 0;
10049   while (LastLeft + 1 < FirstRight) {
10050     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10051       LeftProb += (++LastLeft)->Prob;
10052     else
10053       RightProb += (--FirstRight)->Prob;
10054     I++;
10055   }
10056 
10057   while (true) {
10058     // Our binary search tree differs from a typical BST in that ours can have up
10059     // to three values in each leaf. The pivot selection above doesn't take that
10060     // into account, which means the tree might require more nodes and be less
10061     // efficient. We compensate for this here.
10062 
10063     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10064     unsigned NumRight = W.LastCluster - FirstRight + 1;
10065 
10066     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10067       // If one side has less than 3 clusters, and the other has more than 3,
10068       // consider taking a cluster from the other side.
10069 
10070       if (NumLeft < NumRight) {
10071         // Consider moving the first cluster on the right to the left side.
10072         CaseCluster &CC = *FirstRight;
10073         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10074         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10075         if (LeftSideRank <= RightSideRank) {
10076           // Moving the cluster to the left does not demote it.
10077           ++LastLeft;
10078           ++FirstRight;
10079           continue;
10080         }
10081       } else {
10082         assert(NumRight < NumLeft);
10083         // Consider moving the last element on the left to the right side.
10084         CaseCluster &CC = *LastLeft;
10085         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10086         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10087         if (RightSideRank <= LeftSideRank) {
10088           // Moving the cluster to the right does not demot it.
10089           --LastLeft;
10090           --FirstRight;
10091           continue;
10092         }
10093       }
10094     }
10095     break;
10096   }
10097 
10098   assert(LastLeft + 1 == FirstRight);
10099   assert(LastLeft >= W.FirstCluster);
10100   assert(FirstRight <= W.LastCluster);
10101 
10102   // Use the first element on the right as pivot since we will make less-than
10103   // comparisons against it.
10104   CaseClusterIt PivotCluster = FirstRight;
10105   assert(PivotCluster > W.FirstCluster);
10106   assert(PivotCluster <= W.LastCluster);
10107 
10108   CaseClusterIt FirstLeft = W.FirstCluster;
10109   CaseClusterIt LastRight = W.LastCluster;
10110 
10111   const ConstantInt *Pivot = PivotCluster->Low;
10112 
10113   // New blocks will be inserted immediately after the current one.
10114   MachineFunction::iterator BBI(W.MBB);
10115   ++BBI;
10116 
10117   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10118   // we can branch to its destination directly if it's squeezed exactly in
10119   // between the known lower bound and Pivot - 1.
10120   MachineBasicBlock *LeftMBB;
10121   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10122       FirstLeft->Low == W.GE &&
10123       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10124     LeftMBB = FirstLeft->MBB;
10125   } else {
10126     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10127     FuncInfo.MF->insert(BBI, LeftMBB);
10128     WorkList.push_back(
10129         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10130     // Put Cond in a virtual register to make it available from the new blocks.
10131     ExportFromCurrentBlock(Cond);
10132   }
10133 
10134   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10135   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10136   // directly if RHS.High equals the current upper bound.
10137   MachineBasicBlock *RightMBB;
10138   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10139       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10140     RightMBB = FirstRight->MBB;
10141   } else {
10142     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10143     FuncInfo.MF->insert(BBI, RightMBB);
10144     WorkList.push_back(
10145         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10146     // Put Cond in a virtual register to make it available from the new blocks.
10147     ExportFromCurrentBlock(Cond);
10148   }
10149 
10150   // Create the CaseBlock record that will be used to lower the branch.
10151   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10152                getCurSDLoc(), LeftProb, RightProb);
10153 
10154   if (W.MBB == SwitchMBB)
10155     visitSwitchCase(CB, SwitchMBB);
10156   else
10157     SwitchCases.push_back(CB);
10158 }
10159 
10160 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10161 // from the swith statement.
10162 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10163                                             BranchProbability PeeledCaseProb) {
10164   if (PeeledCaseProb == BranchProbability::getOne())
10165     return BranchProbability::getZero();
10166   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10167 
10168   uint32_t Numerator = CaseProb.getNumerator();
10169   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10170   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10171 }
10172 
10173 // Try to peel the top probability case if it exceeds the threshold.
10174 // Return current MachineBasicBlock for the switch statement if the peeling
10175 // does not occur.
10176 // If the peeling is performed, return the newly created MachineBasicBlock
10177 // for the peeled switch statement. Also update Clusters to remove the peeled
10178 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10179 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10180     const SwitchInst &SI, CaseClusterVector &Clusters,
10181     BranchProbability &PeeledCaseProb) {
10182   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10183   // Don't perform if there is only one cluster or optimizing for size.
10184   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10185       TM.getOptLevel() == CodeGenOpt::None ||
10186       SwitchMBB->getParent()->getFunction().optForMinSize())
10187     return SwitchMBB;
10188 
10189   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10190   unsigned PeeledCaseIndex = 0;
10191   bool SwitchPeeled = false;
10192   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10193     CaseCluster &CC = Clusters[Index];
10194     if (CC.Prob < TopCaseProb)
10195       continue;
10196     TopCaseProb = CC.Prob;
10197     PeeledCaseIndex = Index;
10198     SwitchPeeled = true;
10199   }
10200   if (!SwitchPeeled)
10201     return SwitchMBB;
10202 
10203   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10204                     << TopCaseProb << "\n");
10205 
10206   // Record the MBB for the peeled switch statement.
10207   MachineFunction::iterator BBI(SwitchMBB);
10208   ++BBI;
10209   MachineBasicBlock *PeeledSwitchMBB =
10210       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10211   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10212 
10213   ExportFromCurrentBlock(SI.getCondition());
10214   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10215   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10216                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10217   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10218 
10219   Clusters.erase(PeeledCaseIt);
10220   for (CaseCluster &CC : Clusters) {
10221     LLVM_DEBUG(
10222         dbgs() << "Scale the probablity for one cluster, before scaling: "
10223                << CC.Prob << "\n");
10224     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10225     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10226   }
10227   PeeledCaseProb = TopCaseProb;
10228   return PeeledSwitchMBB;
10229 }
10230 
10231 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10232   // Extract cases from the switch.
10233   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10234   CaseClusterVector Clusters;
10235   Clusters.reserve(SI.getNumCases());
10236   for (auto I : SI.cases()) {
10237     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10238     const ConstantInt *CaseVal = I.getCaseValue();
10239     BranchProbability Prob =
10240         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10241             : BranchProbability(1, SI.getNumCases() + 1);
10242     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10243   }
10244 
10245   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10246 
10247   // Cluster adjacent cases with the same destination. We do this at all
10248   // optimization levels because it's cheap to do and will make codegen faster
10249   // if there are many clusters.
10250   sortAndRangeify(Clusters);
10251 
10252   if (TM.getOptLevel() != CodeGenOpt::None) {
10253     // Replace an unreachable default with the most popular destination.
10254     // FIXME: Exploit unreachable default more aggressively.
10255     bool UnreachableDefault =
10256         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10257     if (UnreachableDefault && !Clusters.empty()) {
10258       DenseMap<const BasicBlock *, unsigned> Popularity;
10259       unsigned MaxPop = 0;
10260       const BasicBlock *MaxBB = nullptr;
10261       for (auto I : SI.cases()) {
10262         const BasicBlock *BB = I.getCaseSuccessor();
10263         if (++Popularity[BB] > MaxPop) {
10264           MaxPop = Popularity[BB];
10265           MaxBB = BB;
10266         }
10267       }
10268       // Set new default.
10269       assert(MaxPop > 0 && MaxBB);
10270       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10271 
10272       // Remove cases that were pointing to the destination that is now the
10273       // default.
10274       CaseClusterVector New;
10275       New.reserve(Clusters.size());
10276       for (CaseCluster &CC : Clusters) {
10277         if (CC.MBB != DefaultMBB)
10278           New.push_back(CC);
10279       }
10280       Clusters = std::move(New);
10281     }
10282   }
10283 
10284   // The branch probablity of the peeled case.
10285   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10286   MachineBasicBlock *PeeledSwitchMBB =
10287       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10288 
10289   // If there is only the default destination, jump there directly.
10290   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10291   if (Clusters.empty()) {
10292     assert(PeeledSwitchMBB == SwitchMBB);
10293     SwitchMBB->addSuccessor(DefaultMBB);
10294     if (DefaultMBB != NextBlock(SwitchMBB)) {
10295       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10296                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10297     }
10298     return;
10299   }
10300 
10301   findJumpTables(Clusters, &SI, DefaultMBB);
10302   findBitTestClusters(Clusters, &SI);
10303 
10304   LLVM_DEBUG({
10305     dbgs() << "Case clusters: ";
10306     for (const CaseCluster &C : Clusters) {
10307       if (C.Kind == CC_JumpTable)
10308         dbgs() << "JT:";
10309       if (C.Kind == CC_BitTests)
10310         dbgs() << "BT:";
10311 
10312       C.Low->getValue().print(dbgs(), true);
10313       if (C.Low != C.High) {
10314         dbgs() << '-';
10315         C.High->getValue().print(dbgs(), true);
10316       }
10317       dbgs() << ' ';
10318     }
10319     dbgs() << '\n';
10320   });
10321 
10322   assert(!Clusters.empty());
10323   SwitchWorkList WorkList;
10324   CaseClusterIt First = Clusters.begin();
10325   CaseClusterIt Last = Clusters.end() - 1;
10326   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10327   // Scale the branchprobability for DefaultMBB if the peel occurs and
10328   // DefaultMBB is not replaced.
10329   if (PeeledCaseProb != BranchProbability::getZero() &&
10330       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10331     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10332   WorkList.push_back(
10333       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10334 
10335   while (!WorkList.empty()) {
10336     SwitchWorkListItem W = WorkList.back();
10337     WorkList.pop_back();
10338     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10339 
10340     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10341         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10342       // For optimized builds, lower large range as a balanced binary tree.
10343       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10344       continue;
10345     }
10346 
10347     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10348   }
10349 }
10350