xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision c71adc8040b1e382b195a0096015cb5c39628b23)
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 // True if the Value passed requires ABI mangling as it is a parameter to a
161 // function or a return value from a function which is not an intrinsic.
162 static bool isABIRegCopy(const Value *V) {
163   const bool IsRetInst = V && isa<ReturnInst>(V);
164   const bool IsCallInst = V && isa<CallInst>(V);
165   const bool IsInLineAsm =
166       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
167   const bool IsIndirectFunctionCall =
168       IsCallInst && !IsInLineAsm &&
169       !static_cast<const CallInst *>(V)->getCalledFunction();
170   // It is possible that the call instruction is an inline asm statement or an
171   // indirect function call in which case the return value of
172   // getCalledFunction() would be nullptr.
173   const bool IsInstrinsicCall =
174       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
175       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
176           Intrinsic::not_intrinsic;
177 
178   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
179 }
180 
181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
182                                       const SDValue *Parts, unsigned NumParts,
183                                       MVT PartVT, EVT ValueVT, const Value *V,
184                                       bool IsABIRegCopy);
185 
186 /// getCopyFromParts - Create a value that contains the specified legal parts
187 /// combined into the value they represent.  If the parts combine to a type
188 /// larger than ValueVT then AssertOp can be used to specify whether the extra
189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
190 /// (ISD::AssertSext).
191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
192                                 const SDValue *Parts, unsigned NumParts,
193                                 MVT PartVT, EVT ValueVT, const Value *V,
194                                 Optional<ISD::NodeType> AssertOp = None,
195                                 bool IsABIRegCopy = false) {
196   if (ValueVT.isVector())
197     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
198                                   PartVT, ValueVT, V, IsABIRegCopy);
199 
200   assert(NumParts > 0 && "No parts to assemble!");
201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
202   SDValue Val = Parts[0];
203 
204   if (NumParts > 1) {
205     // Assemble the value from multiple parts.
206     if (ValueVT.isInteger()) {
207       unsigned PartBits = PartVT.getSizeInBits();
208       unsigned ValueBits = ValueVT.getSizeInBits();
209 
210       // Assemble the power of 2 part.
211       unsigned RoundParts = NumParts & (NumParts - 1) ?
212         1 << Log2_32(NumParts) : NumParts;
213       unsigned RoundBits = PartBits * RoundParts;
214       EVT RoundVT = RoundBits == ValueBits ?
215         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
216       SDValue Lo, Hi;
217 
218       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
219 
220       if (RoundParts > 2) {
221         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
222                               PartVT, HalfVT, V);
223         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
224                               RoundParts / 2, PartVT, HalfVT, V);
225       } else {
226         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
227         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
228       }
229 
230       if (DAG.getDataLayout().isBigEndian())
231         std::swap(Lo, Hi);
232 
233       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
234 
235       if (RoundParts < NumParts) {
236         // Assemble the trailing non-power-of-2 part.
237         unsigned OddParts = NumParts - RoundParts;
238         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
239         Hi = getCopyFromParts(DAG, DL,
240                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
241 
242         // Combine the round and odd parts.
243         Lo = Val;
244         if (DAG.getDataLayout().isBigEndian())
245           std::swap(Lo, Hi);
246         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
247         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
248         Hi =
249             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
250                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
251                                         TLI.getPointerTy(DAG.getDataLayout())));
252         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
253         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
254       }
255     } else if (PartVT.isFloatingPoint()) {
256       // FP split into multiple FP parts (for ppcf128)
257       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
258              "Unexpected split");
259       SDValue Lo, Hi;
260       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
261       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
262       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
263         std::swap(Lo, Hi);
264       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
265     } else {
266       // FP split into integer parts (soft fp)
267       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
268              !PartVT.isVector() && "Unexpected split");
269       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
270       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
271     }
272   }
273 
274   // There is now one part, held in Val.  Correct it to match ValueVT.
275   // PartEVT is the type of the register class that holds the value.
276   // ValueVT is the type of the inline asm operation.
277   EVT PartEVT = Val.getValueType();
278 
279   if (PartEVT == ValueVT)
280     return Val;
281 
282   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
283       ValueVT.bitsLT(PartEVT)) {
284     // For an FP value in an integer part, we need to truncate to the right
285     // width first.
286     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
287     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
288   }
289 
290   // Handle types that have the same size.
291   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
292     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
293 
294   // Handle types with different sizes.
295   if (PartEVT.isInteger() && ValueVT.isInteger()) {
296     if (ValueVT.bitsLT(PartEVT)) {
297       // For a truncate, see if we have any information to
298       // indicate whether the truncated bits will always be
299       // zero or sign-extension.
300       if (AssertOp.hasValue())
301         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
302                           DAG.getValueType(ValueVT));
303       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
304     }
305     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
306   }
307 
308   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
309     // FP_ROUND's are always exact here.
310     if (ValueVT.bitsLT(Val.getValueType()))
311       return DAG.getNode(
312           ISD::FP_ROUND, DL, ValueVT, Val,
313           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
314 
315     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
316   }
317 
318   llvm_unreachable("Unknown mismatch!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (isa<InlineAsm>(CI->getCalledValue()))
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       bool IsABIRegCopy) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
347   SDValue Val = Parts[0];
348 
349   // Handle a multi-element vector.
350   if (NumParts > 1) {
351     EVT IntermediateVT;
352     MVT RegisterVT;
353     unsigned NumIntermediates;
354     unsigned NumRegs;
355 
356     if (IsABIRegCopy) {
357       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
358           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
359           RegisterVT);
360     } else {
361       NumRegs =
362           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
363                                      NumIntermediates, RegisterVT);
364     }
365 
366     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
367     NumParts = NumRegs; // Silence a compiler warning.
368     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
369     assert(RegisterVT.getSizeInBits() ==
370            Parts[0].getSimpleValueType().getSizeInBits() &&
371            "Part type sizes don't match!");
372 
373     // Assemble the parts into intermediate operands.
374     SmallVector<SDValue, 8> Ops(NumIntermediates);
375     if (NumIntermediates == NumParts) {
376       // If the register was not expanded, truncate or copy the value,
377       // as appropriate.
378       for (unsigned i = 0; i != NumParts; ++i)
379         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
380                                   PartVT, IntermediateVT, V);
381     } else if (NumParts > 0) {
382       // If the intermediate type was expanded, build the intermediate
383       // operands from the parts.
384       assert(NumParts % NumIntermediates == 0 &&
385              "Must expand into a divisible number of parts!");
386       unsigned Factor = NumParts / NumIntermediates;
387       for (unsigned i = 0; i != NumIntermediates; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
389                                   PartVT, IntermediateVT, V);
390     }
391 
392     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
393     // intermediate operands.
394     EVT BuiltVectorTy =
395         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
396                          (IntermediateVT.isVector()
397                               ? IntermediateVT.getVectorNumElements() * NumParts
398                               : NumIntermediates));
399     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
400                                                 : ISD::BUILD_VECTOR,
401                       DL, BuiltVectorTy, Ops);
402   }
403 
404   // There is now one part, held in Val.  Correct it to match ValueVT.
405   EVT PartEVT = Val.getValueType();
406 
407   if (PartEVT == ValueVT)
408     return Val;
409 
410   if (PartEVT.isVector()) {
411     // If the element type of the source/dest vectors are the same, but the
412     // parts vector has more elements than the value vector, then we have a
413     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
414     // elements we want.
415     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
416       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
417              "Cannot narrow, it would be a lossy transformation");
418       return DAG.getNode(
419           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
420           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
421     }
422 
423     // Vector/Vector bitcast.
424     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
425       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
426 
427     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
428       "Cannot handle this kind of promotion");
429     // Promoted vector extract
430     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
431 
432   }
433 
434   // Trivial bitcast if the types are the same size and the destination
435   // vector type is legal.
436   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
437       TLI.isTypeLegal(ValueVT))
438     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440   if (ValueVT.getVectorNumElements() != 1) {
441      // Certain ABIs require that vectors are passed as integers. For vectors
442      // are the same size, this is an obvious bitcast.
443      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
444        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
446        // Bitcast Val back the original type and extract the corresponding
447        // vector we want.
448        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
449        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
450                                            ValueVT.getVectorElementType(), Elts);
451        Val = DAG.getBitcast(WiderVecType, Val);
452        return DAG.getNode(
453            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
454            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
455      }
456 
457      diagnosePossiblyInvalidConstraint(
458          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
459      return DAG.getUNDEF(ValueVT);
460   }
461 
462   // Handle cases such as i8 -> <1 x i1>
463   EVT ValueSVT = ValueVT.getVectorElementType();
464   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
465     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467 
468   return DAG.getBuildVector(ValueVT, DL, Val);
469 }
470 
471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
472                                  SDValue Val, SDValue *Parts, unsigned NumParts,
473                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
474 
475 /// getCopyToParts - Create a series of nodes that contain the specified value
476 /// split into legal parts.  If the parts contain more bits than Val, then, for
477 /// integers, ExtendKind can be used to specify how to generate the extra bits.
478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
479                            SDValue *Parts, unsigned NumParts, MVT PartVT,
480                            const Value *V,
481                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
482                            bool IsABIRegCopy = false) {
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 IsABIRegCopy);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566                                  DAG.getIntPtrConstant(RoundBits, DL));
567     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
568 
569     if (DAG.getDataLayout().isBigEndian())
570       // The odd parts were reversed by getCopyToParts - unreverse them.
571       std::reverse(Parts + RoundParts, Parts + NumParts);
572 
573     NumParts = RoundParts;
574     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
575     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
576   }
577 
578   // The number of parts is a power of 2.  Repeatedly bisect the value using
579   // EXTRACT_ELEMENT.
580   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
581                          EVT::getIntegerVT(*DAG.getContext(),
582                                            ValueVT.getSizeInBits()),
583                          Val);
584 
585   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
586     for (unsigned i = 0; i < NumParts; i += StepSize) {
587       unsigned ThisBits = StepSize * PartBits / 2;
588       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
589       SDValue &Part0 = Parts[i];
590       SDValue &Part1 = Parts[i+StepSize/2];
591 
592       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
593                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
594       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
596 
597       if (ThisBits == PartBits && ThisVT != PartVT) {
598         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
599         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
600       }
601     }
602   }
603 
604   if (DAG.getDataLayout().isBigEndian())
605     std::reverse(Parts, Parts + OrigNumParts);
606 }
607 
608 
609 /// getCopyToPartsVector - Create a series of nodes that contain the specified
610 /// value split into legal parts.
611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
612                                  SDValue Val, SDValue *Parts, unsigned NumParts,
613                                  MVT PartVT, const Value *V,
614                                  bool IsABIRegCopy) {
615   EVT ValueVT = Val.getValueType();
616   assert(ValueVT.isVector() && "Not a vector");
617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
618 
619   if (NumParts == 1) {
620     EVT PartEVT = PartVT;
621     if (PartEVT == ValueVT) {
622       // Nothing to do.
623     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
624       // Bitconvert vector->vector case.
625       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
626     } else if (PartVT.isVector() &&
627                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
628                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
629       EVT ElementVT = PartVT.getVectorElementType();
630       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631       // undef elements.
632       SmallVector<SDValue, 16> Ops;
633       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
634         Ops.push_back(DAG.getNode(
635             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
636             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
637 
638       for (unsigned i = ValueVT.getVectorNumElements(),
639            e = PartVT.getVectorNumElements(); i != e; ++i)
640         Ops.push_back(DAG.getUNDEF(ElementVT));
641 
642       Val = DAG.getBuildVector(PartVT, DL, Ops);
643 
644       // FIXME: Use CONCAT for 2x -> 4x.
645 
646       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
647       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
648     } else if (PartVT.isVector() &&
649                PartEVT.getVectorElementType().bitsGE(
650                  ValueVT.getVectorElementType()) &&
651                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
652 
653       // Promoted vector extract
654       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
655     } else {
656       if (ValueVT.getVectorNumElements() == 1) {
657         Val = DAG.getNode(
658             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
659             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
660       } else {
661         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
662                "lossy conversion of vector to scalar type");
663         EVT IntermediateType =
664             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
665         Val = DAG.getBitcast(IntermediateType, Val);
666         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667       }
668     }
669 
670     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
671     Parts[0] = Val;
672     return;
673   }
674 
675   // Handle a multi-element vector.
676   EVT IntermediateVT;
677   MVT RegisterVT;
678   unsigned NumIntermediates;
679   unsigned NumRegs;
680   if (IsABIRegCopy) {
681     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
682         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
683         RegisterVT);
684   } else {
685     NumRegs =
686         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
687                                    NumIntermediates, RegisterVT);
688   }
689   unsigned NumElements = ValueVT.getVectorNumElements();
690 
691   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692   NumParts = NumRegs; // Silence a compiler warning.
693   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
694 
695   // Convert the vector to the appropiate type if necessary.
696   unsigned DestVectorNoElts =
697       NumIntermediates *
698       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
699   EVT BuiltVectorTy = EVT::getVectorVT(
700       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
701   if (Val.getValueType() != BuiltVectorTy)
702     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
703 
704   // Split the vector into intermediate operands.
705   SmallVector<SDValue, 8> Ops(NumIntermediates);
706   for (unsigned i = 0; i != NumIntermediates; ++i) {
707     if (IntermediateVT.isVector())
708       Ops[i] =
709           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
710                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
711                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
712     else
713       Ops[i] = DAG.getNode(
714           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
715           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
716   }
717 
718   // Split the intermediate operands into legal parts.
719   if (NumParts == NumIntermediates) {
720     // If the register was not expanded, promote or copy the value,
721     // as appropriate.
722     for (unsigned i = 0; i != NumParts; ++i)
723       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
724   } else if (NumParts > 0) {
725     // If the intermediate type was expanded, split each the value into
726     // legal parts.
727     assert(NumIntermediates != 0 && "division by zero");
728     assert(NumParts % NumIntermediates == 0 &&
729            "Must expand into a divisible number of parts!");
730     unsigned Factor = NumParts / NumIntermediates;
731     for (unsigned i = 0; i != NumIntermediates; ++i)
732       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
733   }
734 }
735 
736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
737                            EVT valuevt, bool IsABIMangledValue)
738     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
739       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
740 
741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
742                            const DataLayout &DL, unsigned Reg, Type *Ty,
743                            bool IsABIMangledValue) {
744   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
745 
746   IsABIMangled = IsABIMangledValue;
747 
748   for (EVT ValueVT : ValueVTs) {
749     unsigned NumRegs = IsABIMangledValue
750                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
751                            : TLI.getNumRegisters(Context, ValueVT);
752     MVT RegisterVT = IsABIMangledValue
753                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
754                          : TLI.getRegisterType(Context, ValueVT);
755     for (unsigned i = 0; i != NumRegs; ++i)
756       Regs.push_back(Reg + i);
757     RegVTs.push_back(RegisterVT);
758     RegCount.push_back(NumRegs);
759     Reg += NumRegs;
760   }
761 }
762 
763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
764                                       FunctionLoweringInfo &FuncInfo,
765                                       const SDLoc &dl, SDValue &Chain,
766                                       SDValue *Flag, const Value *V) const {
767   // A Value with type {} or [0 x %t] needs no registers.
768   if (ValueVTs.empty())
769     return SDValue();
770 
771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 
773   // Assemble the legal parts into the final values.
774   SmallVector<SDValue, 4> Values(ValueVTs.size());
775   SmallVector<SDValue, 8> Parts;
776   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
777     // Copy the legal parts from the registers.
778     EVT ValueVT = ValueVTs[Value];
779     unsigned NumRegs = RegCount[Value];
780     MVT RegisterVT = IsABIMangled
781       ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value])
782       : RegVTs[Value];
783 
784     Parts.resize(NumRegs);
785     for (unsigned i = 0; i != NumRegs; ++i) {
786       SDValue P;
787       if (!Flag) {
788         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
789       } else {
790         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
791         *Flag = P.getValue(2);
792       }
793 
794       Chain = P.getValue(1);
795       Parts[i] = P;
796 
797       // If the source register was virtual and if we know something about it,
798       // add an assert node.
799       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
800           !RegisterVT.isInteger() || RegisterVT.isVector())
801         continue;
802 
803       const FunctionLoweringInfo::LiveOutInfo *LOI =
804         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
805       if (!LOI)
806         continue;
807 
808       unsigned RegSize = RegisterVT.getSizeInBits();
809       unsigned NumSignBits = LOI->NumSignBits;
810       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
811 
812       if (NumZeroBits == RegSize) {
813         // The current value is a zero.
814         // Explicitly express that as it would be easier for
815         // optimizations to kick in.
816         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
817         continue;
818       }
819 
820       // FIXME: We capture more information than the dag can represent.  For
821       // now, just use the tightest assertzext/assertsext possible.
822       bool isSExt;
823       EVT FromVT(MVT::Other);
824       if (NumZeroBits) {
825         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
826         isSExt = false;
827       } else if (NumSignBits > 1) {
828         FromVT =
829             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
830         isSExt = true;
831       } else {
832         continue;
833       }
834       // Add an assertion node.
835       assert(FromVT != MVT::Other);
836       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
837                              RegisterVT, P, DAG.getValueType(FromVT));
838     }
839 
840     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
841                                      NumRegs, RegisterVT, ValueVT, V);
842     Part += NumRegs;
843     Parts.clear();
844   }
845 
846   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
847 }
848 
849 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
850                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
851                                  const Value *V,
852                                  ISD::NodeType PreferredExtendType) const {
853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
854   ISD::NodeType ExtendKind = PreferredExtendType;
855 
856   // Get the list of the values's legal parts.
857   unsigned NumRegs = Regs.size();
858   SmallVector<SDValue, 8> Parts(NumRegs);
859   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
860     unsigned NumParts = RegCount[Value];
861 
862     MVT RegisterVT = IsABIMangled
863       ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value])
864       : RegVTs[Value];
865 
866     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
867       ExtendKind = ISD::ZERO_EXTEND;
868 
869     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
870                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
871     Part += NumParts;
872   }
873 
874   // Copy the parts into the registers.
875   SmallVector<SDValue, 8> Chains(NumRegs);
876   for (unsigned i = 0; i != NumRegs; ++i) {
877     SDValue Part;
878     if (!Flag) {
879       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
880     } else {
881       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
882       *Flag = Part.getValue(1);
883     }
884 
885     Chains[i] = Part.getValue(0);
886   }
887 
888   if (NumRegs == 1 || Flag)
889     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
890     // flagged to it. That is the CopyToReg nodes and the user are considered
891     // a single scheduling unit. If we create a TokenFactor and return it as
892     // chain, then the TokenFactor is both a predecessor (operand) of the
893     // user as well as a successor (the TF operands are flagged to the user).
894     // c1, f1 = CopyToReg
895     // c2, f2 = CopyToReg
896     // c3     = TokenFactor c1, c2
897     // ...
898     //        = op c3, ..., f2
899     Chain = Chains[NumRegs-1];
900   else
901     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
902 }
903 
904 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
905                                         unsigned MatchingIdx, const SDLoc &dl,
906                                         SelectionDAG &DAG,
907                                         std::vector<SDValue> &Ops) const {
908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
909 
910   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
911   if (HasMatching)
912     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
913   else if (!Regs.empty() &&
914            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
915     // Put the register class of the virtual registers in the flag word.  That
916     // way, later passes can recompute register class constraints for inline
917     // assembly as well as normal instructions.
918     // Don't do this for tied operands that can use the regclass information
919     // from the def.
920     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
921     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
922     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
923   }
924 
925   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
926   Ops.push_back(Res);
927 
928   if (Code == InlineAsm::Kind_Clobber) {
929     // Clobbers should always have a 1:1 mapping with registers, and may
930     // reference registers that have illegal (e.g. vector) types. Hence, we
931     // shouldn't try to apply any sort of splitting logic to them.
932     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
933            "No 1:1 mapping from clobbers to regs?");
934     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
935     (void)SP;
936     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
937       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
938       assert(
939           (Regs[I] != SP ||
940            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
941           "If we clobbered the stack pointer, MFI should know about it.");
942     }
943     return;
944   }
945 
946   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
947     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
948     MVT RegisterVT = RegVTs[Value];
949     for (unsigned i = 0; i != NumRegs; ++i) {
950       assert(Reg < Regs.size() && "Mismatch in # registers expected");
951       unsigned TheReg = Regs[Reg++];
952       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
953     }
954   }
955 }
956 
957 SmallVector<std::pair<unsigned, unsigned>, 4>
958 RegsForValue::getRegsAndSizes() const {
959   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
960   unsigned I = 0;
961   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
962     unsigned RegCount = std::get<0>(CountAndVT);
963     MVT RegisterVT = std::get<1>(CountAndVT);
964     unsigned RegisterSize = RegisterVT.getSizeInBits();
965     for (unsigned E = I + RegCount; I != E; ++I)
966       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
967   }
968   return OutVec;
969 }
970 
971 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
972                                const TargetLibraryInfo *li) {
973   AA = aa;
974   GFI = gfi;
975   LibInfo = li;
976   DL = &DAG.getDataLayout();
977   Context = DAG.getContext();
978   LPadToCallSiteMap.clear();
979 }
980 
981 void SelectionDAGBuilder::clear() {
982   NodeMap.clear();
983   UnusedArgNodeMap.clear();
984   PendingLoads.clear();
985   PendingExports.clear();
986   CurInst = nullptr;
987   HasTailCall = false;
988   SDNodeOrder = LowestSDNodeOrder;
989   StatepointLowering.clear();
990 }
991 
992 void SelectionDAGBuilder::clearDanglingDebugInfo() {
993   DanglingDebugInfoMap.clear();
994 }
995 
996 SDValue SelectionDAGBuilder::getRoot() {
997   if (PendingLoads.empty())
998     return DAG.getRoot();
999 
1000   if (PendingLoads.size() == 1) {
1001     SDValue Root = PendingLoads[0];
1002     DAG.setRoot(Root);
1003     PendingLoads.clear();
1004     return Root;
1005   }
1006 
1007   // Otherwise, we have to make a token factor node.
1008   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1009                              PendingLoads);
1010   PendingLoads.clear();
1011   DAG.setRoot(Root);
1012   return Root;
1013 }
1014 
1015 SDValue SelectionDAGBuilder::getControlRoot() {
1016   SDValue Root = DAG.getRoot();
1017 
1018   if (PendingExports.empty())
1019     return Root;
1020 
1021   // Turn all of the CopyToReg chains into one factored node.
1022   if (Root.getOpcode() != ISD::EntryToken) {
1023     unsigned i = 0, e = PendingExports.size();
1024     for (; i != e; ++i) {
1025       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1026       if (PendingExports[i].getNode()->getOperand(0) == Root)
1027         break;  // Don't add the root if we already indirectly depend on it.
1028     }
1029 
1030     if (i == e)
1031       PendingExports.push_back(Root);
1032   }
1033 
1034   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1035                      PendingExports);
1036   PendingExports.clear();
1037   DAG.setRoot(Root);
1038   return Root;
1039 }
1040 
1041 void SelectionDAGBuilder::visit(const Instruction &I) {
1042   // Set up outgoing PHI node register values before emitting the terminator.
1043   if (isa<TerminatorInst>(&I)) {
1044     HandlePHINodesInSuccessorBlocks(I.getParent());
1045   }
1046 
1047   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1048   if (!isa<DbgInfoIntrinsic>(I))
1049     ++SDNodeOrder;
1050 
1051   CurInst = &I;
1052 
1053   visit(I.getOpcode(), I);
1054 
1055   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1056     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1057     // maps to this instruction.
1058     // TODO: We could handle all flags (nsw, etc) here.
1059     // TODO: If an IR instruction maps to >1 node, only the final node will have
1060     //       flags set.
1061     if (SDNode *Node = getNodeForIRValue(&I)) {
1062       SDNodeFlags IncomingFlags;
1063       IncomingFlags.copyFMF(*FPMO);
1064       if (!Node->getFlags().isDefined())
1065         Node->setFlags(IncomingFlags);
1066       else
1067         Node->intersectFlagsWith(IncomingFlags);
1068     }
1069   }
1070 
1071   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1072       !isStatepoint(&I)) // statepoints handle their exports internally
1073     CopyToExportRegsIfNeeded(&I);
1074 
1075   CurInst = nullptr;
1076 }
1077 
1078 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1079   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1080 }
1081 
1082 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1083   // Note: this doesn't use InstVisitor, because it has to work with
1084   // ConstantExpr's in addition to instructions.
1085   switch (Opcode) {
1086   default: llvm_unreachable("Unknown instruction type encountered!");
1087     // Build the switch statement using the Instruction.def file.
1088 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1089     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1090 #include "llvm/IR/Instruction.def"
1091   }
1092 }
1093 
1094 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1095                                                 const DIExpression *Expr) {
1096   for (auto &DDIMI : DanglingDebugInfoMap)
1097     for (auto &DDI : DDIMI.second)
1098       if (DDI.getDI()) {
1099         const DbgValueInst *DI = DDI.getDI();
1100         DIVariable *DanglingVariable = DI->getVariable();
1101         DIExpression *DanglingExpr = DI->getExpression();
1102         if (DanglingVariable == Variable &&
1103             Expr->fragmentsOverlap(DanglingExpr)) {
1104           LLVM_DEBUG(dbgs()
1105                      << "Dropping dangling debug info for " << *DI << "\n");
1106           DDI = DanglingDebugInfo();
1107         }
1108       }
1109 }
1110 
1111 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1112 // generate the debug data structures now that we've seen its definition.
1113 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1114                                                    SDValue Val) {
1115   DanglingDebugInfoVector &DDIV = DanglingDebugInfoMap[V];
1116   for (auto &DDI : DDIV) {
1117     if (!DDI.getDI())
1118       continue;
1119     const DbgValueInst *DI = DDI.getDI();
1120     DebugLoc dl = DDI.getdl();
1121     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1122     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1123     DILocalVariable *Variable = DI->getVariable();
1124     DIExpression *Expr = DI->getExpression();
1125     assert(Variable->isValidLocationForIntrinsic(dl) &&
1126            "Expected inlined-at fields to agree");
1127     SDDbgValue *SDV;
1128     if (Val.getNode()) {
1129       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1130         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1131                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1132         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1133         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1134         // inserted after the definition of Val when emitting the instructions
1135         // after ISel. An alternative could be to teach
1136         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1137         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1138                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1139                    << ValSDNodeOrder << "\n");
1140         SDV = getDbgValue(Val, Variable, Expr, dl,
1141                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1142         DAG.AddDbgValue(SDV, Val.getNode(), false);
1143       } else
1144         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1145                           << "in EmitFuncArgumentDbgValue\n");
1146     } else
1147       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1148   }
1149   DanglingDebugInfoMap[V].clear();
1150 }
1151 
1152 /// getCopyFromRegs - If there was virtual register allocated for the value V
1153 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1154 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1155   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1156   SDValue Result;
1157 
1158   if (It != FuncInfo.ValueMap.end()) {
1159     unsigned InReg = It->second;
1160 
1161     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1162                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
1163     SDValue Chain = DAG.getEntryNode();
1164     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1165                                  V);
1166     resolveDanglingDebugInfo(V, Result);
1167   }
1168 
1169   return Result;
1170 }
1171 
1172 /// getValue - Return an SDValue for the given Value.
1173 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1174   // If we already have an SDValue for this value, use it. It's important
1175   // to do this first, so that we don't create a CopyFromReg if we already
1176   // have a regular SDValue.
1177   SDValue &N = NodeMap[V];
1178   if (N.getNode()) return N;
1179 
1180   // If there's a virtual register allocated and initialized for this
1181   // value, use it.
1182   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1183     return copyFromReg;
1184 
1185   // Otherwise create a new SDValue and remember it.
1186   SDValue Val = getValueImpl(V);
1187   NodeMap[V] = Val;
1188   resolveDanglingDebugInfo(V, Val);
1189   return Val;
1190 }
1191 
1192 // Return true if SDValue exists for the given Value
1193 bool SelectionDAGBuilder::findValue(const Value *V) const {
1194   return (NodeMap.find(V) != NodeMap.end()) ||
1195     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1196 }
1197 
1198 /// getNonRegisterValue - Return an SDValue for the given Value, but
1199 /// don't look in FuncInfo.ValueMap for a virtual register.
1200 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1201   // If we already have an SDValue for this value, use it.
1202   SDValue &N = NodeMap[V];
1203   if (N.getNode()) {
1204     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1205       // Remove the debug location from the node as the node is about to be used
1206       // in a location which may differ from the original debug location.  This
1207       // is relevant to Constant and ConstantFP nodes because they can appear
1208       // as constant expressions inside PHI nodes.
1209       N->setDebugLoc(DebugLoc());
1210     }
1211     return N;
1212   }
1213 
1214   // Otherwise create a new SDValue and remember it.
1215   SDValue Val = getValueImpl(V);
1216   NodeMap[V] = Val;
1217   resolveDanglingDebugInfo(V, Val);
1218   return Val;
1219 }
1220 
1221 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1222 /// Create an SDValue for the given value.
1223 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1225 
1226   if (const Constant *C = dyn_cast<Constant>(V)) {
1227     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1228 
1229     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1230       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1231 
1232     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1233       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1234 
1235     if (isa<ConstantPointerNull>(C)) {
1236       unsigned AS = V->getType()->getPointerAddressSpace();
1237       return DAG.getConstant(0, getCurSDLoc(),
1238                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1239     }
1240 
1241     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1242       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1243 
1244     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1245       return DAG.getUNDEF(VT);
1246 
1247     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1248       visit(CE->getOpcode(), *CE);
1249       SDValue N1 = NodeMap[V];
1250       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1251       return N1;
1252     }
1253 
1254     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1255       SmallVector<SDValue, 4> Constants;
1256       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1257            OI != OE; ++OI) {
1258         SDNode *Val = getValue(*OI).getNode();
1259         // If the operand is an empty aggregate, there are no values.
1260         if (!Val) continue;
1261         // Add each leaf value from the operand to the Constants list
1262         // to form a flattened list of all the values.
1263         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1264           Constants.push_back(SDValue(Val, i));
1265       }
1266 
1267       return DAG.getMergeValues(Constants, getCurSDLoc());
1268     }
1269 
1270     if (const ConstantDataSequential *CDS =
1271           dyn_cast<ConstantDataSequential>(C)) {
1272       SmallVector<SDValue, 4> Ops;
1273       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1274         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1275         // Add each leaf value from the operand to the Constants list
1276         // to form a flattened list of all the values.
1277         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1278           Ops.push_back(SDValue(Val, i));
1279       }
1280 
1281       if (isa<ArrayType>(CDS->getType()))
1282         return DAG.getMergeValues(Ops, getCurSDLoc());
1283       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1284     }
1285 
1286     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1287       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1288              "Unknown struct or array constant!");
1289 
1290       SmallVector<EVT, 4> ValueVTs;
1291       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1292       unsigned NumElts = ValueVTs.size();
1293       if (NumElts == 0)
1294         return SDValue(); // empty struct
1295       SmallVector<SDValue, 4> Constants(NumElts);
1296       for (unsigned i = 0; i != NumElts; ++i) {
1297         EVT EltVT = ValueVTs[i];
1298         if (isa<UndefValue>(C))
1299           Constants[i] = DAG.getUNDEF(EltVT);
1300         else if (EltVT.isFloatingPoint())
1301           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1302         else
1303           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1304       }
1305 
1306       return DAG.getMergeValues(Constants, getCurSDLoc());
1307     }
1308 
1309     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1310       return DAG.getBlockAddress(BA, VT);
1311 
1312     VectorType *VecTy = cast<VectorType>(V->getType());
1313     unsigned NumElements = VecTy->getNumElements();
1314 
1315     // Now that we know the number and type of the elements, get that number of
1316     // elements into the Ops array based on what kind of constant it is.
1317     SmallVector<SDValue, 16> Ops;
1318     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1319       for (unsigned i = 0; i != NumElements; ++i)
1320         Ops.push_back(getValue(CV->getOperand(i)));
1321     } else {
1322       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1323       EVT EltVT =
1324           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1325 
1326       SDValue Op;
1327       if (EltVT.isFloatingPoint())
1328         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1329       else
1330         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1331       Ops.assign(NumElements, Op);
1332     }
1333 
1334     // Create a BUILD_VECTOR node.
1335     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1336   }
1337 
1338   // If this is a static alloca, generate it as the frameindex instead of
1339   // computation.
1340   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1341     DenseMap<const AllocaInst*, int>::iterator SI =
1342       FuncInfo.StaticAllocaMap.find(AI);
1343     if (SI != FuncInfo.StaticAllocaMap.end())
1344       return DAG.getFrameIndex(SI->second,
1345                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1346   }
1347 
1348   // If this is an instruction which fast-isel has deferred, select it now.
1349   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1350     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1351 
1352     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1353                      Inst->getType(), isABIRegCopy(V));
1354     SDValue Chain = DAG.getEntryNode();
1355     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1356   }
1357 
1358   llvm_unreachable("Can't get register for value!");
1359 }
1360 
1361 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1362   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1363   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1364   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1365   bool IsSEH = isAsynchronousEHPersonality(Pers);
1366   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1367   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1368   if (!IsSEH)
1369     CatchPadMBB->setIsEHScopeEntry();
1370   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1371   if (IsMSVCCXX || IsCoreCLR)
1372     CatchPadMBB->setIsEHFuncletEntry();
1373   // Wasm does not need catchpads anymore
1374   if (!IsWasmCXX)
1375     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1376                             getControlRoot()));
1377 }
1378 
1379 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1380   // Update machine-CFG edge.
1381   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1382   FuncInfo.MBB->addSuccessor(TargetMBB);
1383 
1384   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1385   bool IsSEH = isAsynchronousEHPersonality(Pers);
1386   if (IsSEH) {
1387     // If this is not a fall-through branch or optimizations are switched off,
1388     // emit the branch.
1389     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1390         TM.getOptLevel() == CodeGenOpt::None)
1391       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1392                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1393     return;
1394   }
1395 
1396   // Figure out the funclet membership for the catchret's successor.
1397   // This will be used by the FuncletLayout pass to determine how to order the
1398   // BB's.
1399   // A 'catchret' returns to the outer scope's color.
1400   Value *ParentPad = I.getCatchSwitchParentPad();
1401   const BasicBlock *SuccessorColor;
1402   if (isa<ConstantTokenNone>(ParentPad))
1403     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1404   else
1405     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1406   assert(SuccessorColor && "No parent funclet for catchret!");
1407   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1408   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1409 
1410   // Create the terminator node.
1411   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1412                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1413                             DAG.getBasicBlock(SuccessorColorMBB));
1414   DAG.setRoot(Ret);
1415 }
1416 
1417 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1418   // Don't emit any special code for the cleanuppad instruction. It just marks
1419   // the start of an EH scope/funclet.
1420   FuncInfo.MBB->setIsEHScopeEntry();
1421   FuncInfo.MBB->setIsEHFuncletEntry();
1422   FuncInfo.MBB->setIsCleanupFuncletEntry();
1423 }
1424 
1425 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1426 /// many places it could ultimately go. In the IR, we have a single unwind
1427 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1428 /// This function skips over imaginary basic blocks that hold catchswitch
1429 /// instructions, and finds all the "real" machine
1430 /// basic block destinations. As those destinations may not be successors of
1431 /// EHPadBB, here we also calculate the edge probability to those destinations.
1432 /// The passed-in Prob is the edge probability to EHPadBB.
1433 static void findUnwindDestinations(
1434     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1435     BranchProbability Prob,
1436     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1437         &UnwindDests) {
1438   EHPersonality Personality =
1439     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1440   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1441   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1442   bool IsSEH = isAsynchronousEHPersonality(Personality);
1443 
1444   while (EHPadBB) {
1445     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1446     BasicBlock *NewEHPadBB = nullptr;
1447     if (isa<LandingPadInst>(Pad)) {
1448       // Stop on landingpads. They are not funclets.
1449       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1450       break;
1451     } else if (isa<CleanupPadInst>(Pad)) {
1452       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1453       // personalities.
1454       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1455       UnwindDests.back().first->setIsEHScopeEntry();
1456       UnwindDests.back().first->setIsEHFuncletEntry();
1457       break;
1458     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1459       // Add the catchpad handlers to the possible destinations.
1460       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1461         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1462         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1463         if (IsMSVCCXX || IsCoreCLR)
1464           UnwindDests.back().first->setIsEHFuncletEntry();
1465         if (!IsSEH)
1466           UnwindDests.back().first->setIsEHScopeEntry();
1467       }
1468       NewEHPadBB = CatchSwitch->getUnwindDest();
1469     } else {
1470       continue;
1471     }
1472 
1473     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1474     if (BPI && NewEHPadBB)
1475       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1476     EHPadBB = NewEHPadBB;
1477   }
1478 }
1479 
1480 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1481   // Update successor info.
1482   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1483   auto UnwindDest = I.getUnwindDest();
1484   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1485   BranchProbability UnwindDestProb =
1486       (BPI && UnwindDest)
1487           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1488           : BranchProbability::getZero();
1489   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1490   for (auto &UnwindDest : UnwindDests) {
1491     UnwindDest.first->setIsEHPad();
1492     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1493   }
1494   FuncInfo.MBB->normalizeSuccProbs();
1495 
1496   // Create the terminator node.
1497   SDValue Ret =
1498       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1499   DAG.setRoot(Ret);
1500 }
1501 
1502 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1503   report_fatal_error("visitCatchSwitch not yet implemented!");
1504 }
1505 
1506 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1508   auto &DL = DAG.getDataLayout();
1509   SDValue Chain = getControlRoot();
1510   SmallVector<ISD::OutputArg, 8> Outs;
1511   SmallVector<SDValue, 8> OutVals;
1512 
1513   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1514   // lower
1515   //
1516   //   %val = call <ty> @llvm.experimental.deoptimize()
1517   //   ret <ty> %val
1518   //
1519   // differently.
1520   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1521     LowerDeoptimizingReturn();
1522     return;
1523   }
1524 
1525   if (!FuncInfo.CanLowerReturn) {
1526     unsigned DemoteReg = FuncInfo.DemoteRegister;
1527     const Function *F = I.getParent()->getParent();
1528 
1529     // Emit a store of the return value through the virtual register.
1530     // Leave Outs empty so that LowerReturn won't try to load return
1531     // registers the usual way.
1532     SmallVector<EVT, 1> PtrValueVTs;
1533     ComputeValueVTs(TLI, DL,
1534                     F->getReturnType()->getPointerTo(
1535                         DAG.getDataLayout().getAllocaAddrSpace()),
1536                     PtrValueVTs);
1537 
1538     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1539                                         DemoteReg, PtrValueVTs[0]);
1540     SDValue RetOp = getValue(I.getOperand(0));
1541 
1542     SmallVector<EVT, 4> ValueVTs;
1543     SmallVector<uint64_t, 4> Offsets;
1544     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1545     unsigned NumValues = ValueVTs.size();
1546 
1547     SmallVector<SDValue, 4> Chains(NumValues);
1548     for (unsigned i = 0; i != NumValues; ++i) {
1549       // An aggregate return value cannot wrap around the address space, so
1550       // offsets to its parts don't wrap either.
1551       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1552       Chains[i] = DAG.getStore(
1553           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1554           // FIXME: better loc info would be nice.
1555           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1556     }
1557 
1558     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1559                         MVT::Other, Chains);
1560   } else if (I.getNumOperands() != 0) {
1561     SmallVector<EVT, 4> ValueVTs;
1562     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1563     unsigned NumValues = ValueVTs.size();
1564     if (NumValues) {
1565       SDValue RetOp = getValue(I.getOperand(0));
1566 
1567       const Function *F = I.getParent()->getParent();
1568 
1569       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1570       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1571                                           Attribute::SExt))
1572         ExtendKind = ISD::SIGN_EXTEND;
1573       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1574                                                Attribute::ZExt))
1575         ExtendKind = ISD::ZERO_EXTEND;
1576 
1577       LLVMContext &Context = F->getContext();
1578       bool RetInReg = F->getAttributes().hasAttribute(
1579           AttributeList::ReturnIndex, Attribute::InReg);
1580 
1581       for (unsigned j = 0; j != NumValues; ++j) {
1582         EVT VT = ValueVTs[j];
1583 
1584         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1585           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1586 
1587         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1588         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1589         SmallVector<SDValue, 4> Parts(NumParts);
1590         getCopyToParts(DAG, getCurSDLoc(),
1591                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1592                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1593 
1594         // 'inreg' on function refers to return value
1595         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1596         if (RetInReg)
1597           Flags.setInReg();
1598 
1599         // Propagate extension type if any
1600         if (ExtendKind == ISD::SIGN_EXTEND)
1601           Flags.setSExt();
1602         else if (ExtendKind == ISD::ZERO_EXTEND)
1603           Flags.setZExt();
1604 
1605         for (unsigned i = 0; i < NumParts; ++i) {
1606           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1607                                         VT, /*isfixed=*/true, 0, 0));
1608           OutVals.push_back(Parts[i]);
1609         }
1610       }
1611     }
1612   }
1613 
1614   // Push in swifterror virtual register as the last element of Outs. This makes
1615   // sure swifterror virtual register will be returned in the swifterror
1616   // physical register.
1617   const Function *F = I.getParent()->getParent();
1618   if (TLI.supportSwiftError() &&
1619       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1620     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1621     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1622     Flags.setSwiftError();
1623     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1624                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1625                                   true /*isfixed*/, 1 /*origidx*/,
1626                                   0 /*partOffs*/));
1627     // Create SDNode for the swifterror virtual register.
1628     OutVals.push_back(
1629         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1630                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1631                         EVT(TLI.getPointerTy(DL))));
1632   }
1633 
1634   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1635   CallingConv::ID CallConv =
1636     DAG.getMachineFunction().getFunction().getCallingConv();
1637   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1638       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1639 
1640   // Verify that the target's LowerReturn behaved as expected.
1641   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1642          "LowerReturn didn't return a valid chain!");
1643 
1644   // Update the DAG with the new chain value resulting from return lowering.
1645   DAG.setRoot(Chain);
1646 }
1647 
1648 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1649 /// created for it, emit nodes to copy the value into the virtual
1650 /// registers.
1651 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1652   // Skip empty types
1653   if (V->getType()->isEmptyTy())
1654     return;
1655 
1656   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1657   if (VMI != FuncInfo.ValueMap.end()) {
1658     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1659     CopyValueToVirtualRegister(V, VMI->second);
1660   }
1661 }
1662 
1663 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1664 /// the current basic block, add it to ValueMap now so that we'll get a
1665 /// CopyTo/FromReg.
1666 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1667   // No need to export constants.
1668   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1669 
1670   // Already exported?
1671   if (FuncInfo.isExportedInst(V)) return;
1672 
1673   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1674   CopyValueToVirtualRegister(V, Reg);
1675 }
1676 
1677 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1678                                                      const BasicBlock *FromBB) {
1679   // The operands of the setcc have to be in this block.  We don't know
1680   // how to export them from some other block.
1681   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1682     // Can export from current BB.
1683     if (VI->getParent() == FromBB)
1684       return true;
1685 
1686     // Is already exported, noop.
1687     return FuncInfo.isExportedInst(V);
1688   }
1689 
1690   // If this is an argument, we can export it if the BB is the entry block or
1691   // if it is already exported.
1692   if (isa<Argument>(V)) {
1693     if (FromBB == &FromBB->getParent()->getEntryBlock())
1694       return true;
1695 
1696     // Otherwise, can only export this if it is already exported.
1697     return FuncInfo.isExportedInst(V);
1698   }
1699 
1700   // Otherwise, constants can always be exported.
1701   return true;
1702 }
1703 
1704 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1705 BranchProbability
1706 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1707                                         const MachineBasicBlock *Dst) const {
1708   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1709   const BasicBlock *SrcBB = Src->getBasicBlock();
1710   const BasicBlock *DstBB = Dst->getBasicBlock();
1711   if (!BPI) {
1712     // If BPI is not available, set the default probability as 1 / N, where N is
1713     // the number of successors.
1714     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1715     return BranchProbability(1, SuccSize);
1716   }
1717   return BPI->getEdgeProbability(SrcBB, DstBB);
1718 }
1719 
1720 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1721                                                MachineBasicBlock *Dst,
1722                                                BranchProbability Prob) {
1723   if (!FuncInfo.BPI)
1724     Src->addSuccessorWithoutProb(Dst);
1725   else {
1726     if (Prob.isUnknown())
1727       Prob = getEdgeProbability(Src, Dst);
1728     Src->addSuccessor(Dst, Prob);
1729   }
1730 }
1731 
1732 static bool InBlock(const Value *V, const BasicBlock *BB) {
1733   if (const Instruction *I = dyn_cast<Instruction>(V))
1734     return I->getParent() == BB;
1735   return true;
1736 }
1737 
1738 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1739 /// This function emits a branch and is used at the leaves of an OR or an
1740 /// AND operator tree.
1741 void
1742 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1743                                                   MachineBasicBlock *TBB,
1744                                                   MachineBasicBlock *FBB,
1745                                                   MachineBasicBlock *CurBB,
1746                                                   MachineBasicBlock *SwitchBB,
1747                                                   BranchProbability TProb,
1748                                                   BranchProbability FProb,
1749                                                   bool InvertCond) {
1750   const BasicBlock *BB = CurBB->getBasicBlock();
1751 
1752   // If the leaf of the tree is a comparison, merge the condition into
1753   // the caseblock.
1754   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1755     // The operands of the cmp have to be in this block.  We don't know
1756     // how to export them from some other block.  If this is the first block
1757     // of the sequence, no exporting is needed.
1758     if (CurBB == SwitchBB ||
1759         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1760          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1761       ISD::CondCode Condition;
1762       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1763         ICmpInst::Predicate Pred =
1764             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1765         Condition = getICmpCondCode(Pred);
1766       } else {
1767         const FCmpInst *FC = cast<FCmpInst>(Cond);
1768         FCmpInst::Predicate Pred =
1769             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1770         Condition = getFCmpCondCode(Pred);
1771         if (TM.Options.NoNaNsFPMath)
1772           Condition = getFCmpCodeWithoutNaN(Condition);
1773       }
1774 
1775       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1776                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1777       SwitchCases.push_back(CB);
1778       return;
1779     }
1780   }
1781 
1782   // Create a CaseBlock record representing this branch.
1783   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1784   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1785                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1786   SwitchCases.push_back(CB);
1787 }
1788 
1789 /// FindMergedConditions - If Cond is an expression like
1790 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1791                                                MachineBasicBlock *TBB,
1792                                                MachineBasicBlock *FBB,
1793                                                MachineBasicBlock *CurBB,
1794                                                MachineBasicBlock *SwitchBB,
1795                                                Instruction::BinaryOps Opc,
1796                                                BranchProbability TProb,
1797                                                BranchProbability FProb,
1798                                                bool InvertCond) {
1799   // Skip over not part of the tree and remember to invert op and operands at
1800   // next level.
1801   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1802     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1803     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1804       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1805                            !InvertCond);
1806       return;
1807     }
1808   }
1809 
1810   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1811   // Compute the effective opcode for Cond, taking into account whether it needs
1812   // to be inverted, e.g.
1813   //   and (not (or A, B)), C
1814   // gets lowered as
1815   //   and (and (not A, not B), C)
1816   unsigned BOpc = 0;
1817   if (BOp) {
1818     BOpc = BOp->getOpcode();
1819     if (InvertCond) {
1820       if (BOpc == Instruction::And)
1821         BOpc = Instruction::Or;
1822       else if (BOpc == Instruction::Or)
1823         BOpc = Instruction::And;
1824     }
1825   }
1826 
1827   // If this node is not part of the or/and tree, emit it as a branch.
1828   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1829       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1830       BOp->getParent() != CurBB->getBasicBlock() ||
1831       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1832       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1833     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1834                                  TProb, FProb, InvertCond);
1835     return;
1836   }
1837 
1838   //  Create TmpBB after CurBB.
1839   MachineFunction::iterator BBI(CurBB);
1840   MachineFunction &MF = DAG.getMachineFunction();
1841   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1842   CurBB->getParent()->insert(++BBI, TmpBB);
1843 
1844   if (Opc == Instruction::Or) {
1845     // Codegen X | Y as:
1846     // BB1:
1847     //   jmp_if_X TBB
1848     //   jmp TmpBB
1849     // TmpBB:
1850     //   jmp_if_Y TBB
1851     //   jmp FBB
1852     //
1853 
1854     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1855     // The requirement is that
1856     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1857     //     = TrueProb for original BB.
1858     // Assuming the original probabilities are A and B, one choice is to set
1859     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1860     // A/(1+B) and 2B/(1+B). This choice assumes that
1861     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1862     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1863     // TmpBB, but the math is more complicated.
1864 
1865     auto NewTrueProb = TProb / 2;
1866     auto NewFalseProb = TProb / 2 + FProb;
1867     // Emit the LHS condition.
1868     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1869                          NewTrueProb, NewFalseProb, InvertCond);
1870 
1871     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1872     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1873     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1874     // Emit the RHS condition into TmpBB.
1875     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1876                          Probs[0], Probs[1], InvertCond);
1877   } else {
1878     assert(Opc == Instruction::And && "Unknown merge op!");
1879     // Codegen X & Y as:
1880     // BB1:
1881     //   jmp_if_X TmpBB
1882     //   jmp FBB
1883     // TmpBB:
1884     //   jmp_if_Y TBB
1885     //   jmp FBB
1886     //
1887     //  This requires creation of TmpBB after CurBB.
1888 
1889     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1890     // The requirement is that
1891     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1892     //     = FalseProb for original BB.
1893     // Assuming the original probabilities are A and B, one choice is to set
1894     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1895     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1896     // TrueProb for BB1 * FalseProb for TmpBB.
1897 
1898     auto NewTrueProb = TProb + FProb / 2;
1899     auto NewFalseProb = FProb / 2;
1900     // Emit the LHS condition.
1901     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1902                          NewTrueProb, NewFalseProb, InvertCond);
1903 
1904     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1905     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
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   }
1911 }
1912 
1913 /// If the set of cases should be emitted as a series of branches, return true.
1914 /// If we should emit this as a bunch of and/or'd together conditions, return
1915 /// false.
1916 bool
1917 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1918   if (Cases.size() != 2) return true;
1919 
1920   // If this is two comparisons of the same values or'd or and'd together, they
1921   // will get folded into a single comparison, so don't emit two blocks.
1922   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1923        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1924       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1925        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1926     return false;
1927   }
1928 
1929   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1930   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1931   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1932       Cases[0].CC == Cases[1].CC &&
1933       isa<Constant>(Cases[0].CmpRHS) &&
1934       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1935     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1936       return false;
1937     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1938       return false;
1939   }
1940 
1941   return true;
1942 }
1943 
1944 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1945   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1946 
1947   // Update machine-CFG edges.
1948   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1949 
1950   if (I.isUnconditional()) {
1951     // Update machine-CFG edges.
1952     BrMBB->addSuccessor(Succ0MBB);
1953 
1954     // If this is not a fall-through branch or optimizations are switched off,
1955     // emit the branch.
1956     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1957       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1958                               MVT::Other, getControlRoot(),
1959                               DAG.getBasicBlock(Succ0MBB)));
1960 
1961     return;
1962   }
1963 
1964   // If this condition is one of the special cases we handle, do special stuff
1965   // now.
1966   const Value *CondVal = I.getCondition();
1967   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1968 
1969   // If this is a series of conditions that are or'd or and'd together, emit
1970   // this as a sequence of branches instead of setcc's with and/or operations.
1971   // As long as jumps are not expensive, this should improve performance.
1972   // For example, instead of something like:
1973   //     cmp A, B
1974   //     C = seteq
1975   //     cmp D, E
1976   //     F = setle
1977   //     or C, F
1978   //     jnz foo
1979   // Emit:
1980   //     cmp A, B
1981   //     je foo
1982   //     cmp D, E
1983   //     jle foo
1984   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1985     Instruction::BinaryOps Opcode = BOp->getOpcode();
1986     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1987         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1988         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1989       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1990                            Opcode,
1991                            getEdgeProbability(BrMBB, Succ0MBB),
1992                            getEdgeProbability(BrMBB, Succ1MBB),
1993                            /*InvertCond=*/false);
1994       // If the compares in later blocks need to use values not currently
1995       // exported from this block, export them now.  This block should always
1996       // be the first entry.
1997       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1998 
1999       // Allow some cases to be rejected.
2000       if (ShouldEmitAsBranches(SwitchCases)) {
2001         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2002           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2003           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2004         }
2005 
2006         // Emit the branch for this block.
2007         visitSwitchCase(SwitchCases[0], BrMBB);
2008         SwitchCases.erase(SwitchCases.begin());
2009         return;
2010       }
2011 
2012       // Okay, we decided not to do this, remove any inserted MBB's and clear
2013       // SwitchCases.
2014       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2015         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2016 
2017       SwitchCases.clear();
2018     }
2019   }
2020 
2021   // Create a CaseBlock record representing this branch.
2022   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2023                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2024 
2025   // Use visitSwitchCase to actually insert the fast branch sequence for this
2026   // cond branch.
2027   visitSwitchCase(CB, BrMBB);
2028 }
2029 
2030 /// visitSwitchCase - Emits the necessary code to represent a single node in
2031 /// the binary search tree resulting from lowering a switch instruction.
2032 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2033                                           MachineBasicBlock *SwitchBB) {
2034   SDValue Cond;
2035   SDValue CondLHS = getValue(CB.CmpLHS);
2036   SDLoc dl = CB.DL;
2037 
2038   // Build the setcc now.
2039   if (!CB.CmpMHS) {
2040     // Fold "(X == true)" to X and "(X == false)" to !X to
2041     // handle common cases produced by branch lowering.
2042     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2043         CB.CC == ISD::SETEQ)
2044       Cond = CondLHS;
2045     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2046              CB.CC == ISD::SETEQ) {
2047       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2048       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2049     } else
2050       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2051   } else {
2052     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2053 
2054     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2055     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2056 
2057     SDValue CmpOp = getValue(CB.CmpMHS);
2058     EVT VT = CmpOp.getValueType();
2059 
2060     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2061       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2062                           ISD::SETLE);
2063     } else {
2064       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2065                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2066       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2067                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2068     }
2069   }
2070 
2071   // Update successor info
2072   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2073   // TrueBB and FalseBB are always different unless the incoming IR is
2074   // degenerate. This only happens when running llc on weird IR.
2075   if (CB.TrueBB != CB.FalseBB)
2076     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2077   SwitchBB->normalizeSuccProbs();
2078 
2079   // If the lhs block is the next block, invert the condition so that we can
2080   // fall through to the lhs instead of the rhs block.
2081   if (CB.TrueBB == NextBlock(SwitchBB)) {
2082     std::swap(CB.TrueBB, CB.FalseBB);
2083     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2084     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2085   }
2086 
2087   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2088                                MVT::Other, getControlRoot(), Cond,
2089                                DAG.getBasicBlock(CB.TrueBB));
2090 
2091   // Insert the false branch. Do this even if it's a fall through branch,
2092   // this makes it easier to do DAG optimizations which require inverting
2093   // the branch condition.
2094   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2095                        DAG.getBasicBlock(CB.FalseBB));
2096 
2097   DAG.setRoot(BrCond);
2098 }
2099 
2100 /// visitJumpTable - Emit JumpTable node in the current MBB
2101 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2102   // Emit the code for the jump table
2103   assert(JT.Reg != -1U && "Should lower JT Header first!");
2104   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2105   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2106                                      JT.Reg, PTy);
2107   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2108   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2109                                     MVT::Other, Index.getValue(1),
2110                                     Table, Index);
2111   DAG.setRoot(BrJumpTable);
2112 }
2113 
2114 /// visitJumpTableHeader - This function emits necessary code to produce index
2115 /// in the JumpTable from switch case.
2116 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2117                                                JumpTableHeader &JTH,
2118                                                MachineBasicBlock *SwitchBB) {
2119   SDLoc dl = getCurSDLoc();
2120 
2121   // Subtract the lowest switch case value from the value being switched on and
2122   // conditional branch to default mbb if the result is greater than the
2123   // difference between smallest and largest cases.
2124   SDValue SwitchOp = getValue(JTH.SValue);
2125   EVT VT = SwitchOp.getValueType();
2126   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2127                             DAG.getConstant(JTH.First, dl, VT));
2128 
2129   // The SDNode we just created, which holds the value being switched on minus
2130   // the smallest case value, needs to be copied to a virtual register so it
2131   // can be used as an index into the jump table in a subsequent basic block.
2132   // This value may be smaller or larger than the target's pointer type, and
2133   // therefore require extension or truncating.
2134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2135   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2136 
2137   unsigned JumpTableReg =
2138       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2139   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2140                                     JumpTableReg, SwitchOp);
2141   JT.Reg = JumpTableReg;
2142 
2143   // Emit the range check for the jump table, and branch to the default block
2144   // for the switch statement if the value being switched on exceeds the largest
2145   // case in the switch.
2146   SDValue CMP = DAG.getSetCC(
2147       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2148                                  Sub.getValueType()),
2149       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2150 
2151   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2152                                MVT::Other, CopyTo, CMP,
2153                                DAG.getBasicBlock(JT.Default));
2154 
2155   // Avoid emitting unnecessary branches to the next block.
2156   if (JT.MBB != NextBlock(SwitchBB))
2157     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2158                          DAG.getBasicBlock(JT.MBB));
2159 
2160   DAG.setRoot(BrCond);
2161 }
2162 
2163 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2164 /// variable if there exists one.
2165 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2166                                  SDValue &Chain) {
2167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2168   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2169   MachineFunction &MF = DAG.getMachineFunction();
2170   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2171   MachineSDNode *Node =
2172       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2173   if (Global) {
2174     MachinePointerInfo MPInfo(Global);
2175     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2176     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2177                  MachineMemOperand::MODereferenceable;
2178     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2179                                        DAG.getEVTAlignment(PtrTy));
2180     Node->setMemRefs(MemRefs, MemRefs + 1);
2181   }
2182   return SDValue(Node, 0);
2183 }
2184 
2185 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2186 /// tail spliced into a stack protector check success bb.
2187 ///
2188 /// For a high level explanation of how this fits into the stack protector
2189 /// generation see the comment on the declaration of class
2190 /// StackProtectorDescriptor.
2191 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2192                                                   MachineBasicBlock *ParentBB) {
2193 
2194   // First create the loads to the guard/stack slot for the comparison.
2195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2196   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2197 
2198   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2199   int FI = MFI.getStackProtectorIndex();
2200 
2201   SDValue Guard;
2202   SDLoc dl = getCurSDLoc();
2203   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2204   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2205   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2206 
2207   // Generate code to load the content of the guard slot.
2208   SDValue GuardVal = DAG.getLoad(
2209       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2210       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2211       MachineMemOperand::MOVolatile);
2212 
2213   if (TLI.useStackGuardXorFP())
2214     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2215 
2216   // Retrieve guard check function, nullptr if instrumentation is inlined.
2217   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2218     // The target provides a guard check function to validate the guard value.
2219     // Generate a call to that function with the content of the guard slot as
2220     // argument.
2221     auto *Fn = cast<Function>(GuardCheck);
2222     FunctionType *FnTy = Fn->getFunctionType();
2223     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2224 
2225     TargetLowering::ArgListTy Args;
2226     TargetLowering::ArgListEntry Entry;
2227     Entry.Node = GuardVal;
2228     Entry.Ty = FnTy->getParamType(0);
2229     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2230       Entry.IsInReg = true;
2231     Args.push_back(Entry);
2232 
2233     TargetLowering::CallLoweringInfo CLI(DAG);
2234     CLI.setDebugLoc(getCurSDLoc())
2235       .setChain(DAG.getEntryNode())
2236       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2237                  getValue(GuardCheck), std::move(Args));
2238 
2239     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2240     DAG.setRoot(Result.second);
2241     return;
2242   }
2243 
2244   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2245   // Otherwise, emit a volatile load to retrieve the stack guard value.
2246   SDValue Chain = DAG.getEntryNode();
2247   if (TLI.useLoadStackGuardNode()) {
2248     Guard = getLoadStackGuard(DAG, dl, Chain);
2249   } else {
2250     const Value *IRGuard = TLI.getSDagStackGuard(M);
2251     SDValue GuardPtr = getValue(IRGuard);
2252 
2253     Guard =
2254         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2255                     Align, MachineMemOperand::MOVolatile);
2256   }
2257 
2258   // Perform the comparison via a subtract/getsetcc.
2259   EVT VT = Guard.getValueType();
2260   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2261 
2262   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2263                                                         *DAG.getContext(),
2264                                                         Sub.getValueType()),
2265                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2266 
2267   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2268   // branch to failure MBB.
2269   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2270                                MVT::Other, GuardVal.getOperand(0),
2271                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2272   // Otherwise branch to success MBB.
2273   SDValue Br = DAG.getNode(ISD::BR, dl,
2274                            MVT::Other, BrCond,
2275                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2276 
2277   DAG.setRoot(Br);
2278 }
2279 
2280 /// Codegen the failure basic block for a stack protector check.
2281 ///
2282 /// A failure stack protector machine basic block consists simply of a call to
2283 /// __stack_chk_fail().
2284 ///
2285 /// For a high level explanation of how this fits into the stack protector
2286 /// generation see the comment on the declaration of class
2287 /// StackProtectorDescriptor.
2288 void
2289 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2290   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2291   SDValue Chain =
2292       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2293                       None, false, getCurSDLoc(), false, false).second;
2294   DAG.setRoot(Chain);
2295 }
2296 
2297 /// visitBitTestHeader - This function emits necessary code to produce value
2298 /// suitable for "bit tests"
2299 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2300                                              MachineBasicBlock *SwitchBB) {
2301   SDLoc dl = getCurSDLoc();
2302 
2303   // Subtract the minimum value
2304   SDValue SwitchOp = getValue(B.SValue);
2305   EVT VT = SwitchOp.getValueType();
2306   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2307                             DAG.getConstant(B.First, dl, VT));
2308 
2309   // Check range
2310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2311   SDValue RangeCmp = DAG.getSetCC(
2312       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2313                                  Sub.getValueType()),
2314       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2315 
2316   // Determine the type of the test operands.
2317   bool UsePtrType = false;
2318   if (!TLI.isTypeLegal(VT))
2319     UsePtrType = true;
2320   else {
2321     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2322       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2323         // Switch table case range are encoded into series of masks.
2324         // Just use pointer type, it's guaranteed to fit.
2325         UsePtrType = true;
2326         break;
2327       }
2328   }
2329   if (UsePtrType) {
2330     VT = TLI.getPointerTy(DAG.getDataLayout());
2331     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2332   }
2333 
2334   B.RegVT = VT.getSimpleVT();
2335   B.Reg = FuncInfo.CreateReg(B.RegVT);
2336   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2337 
2338   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2339 
2340   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2341   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2342   SwitchBB->normalizeSuccProbs();
2343 
2344   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2345                                 MVT::Other, CopyTo, RangeCmp,
2346                                 DAG.getBasicBlock(B.Default));
2347 
2348   // Avoid emitting unnecessary branches to the next block.
2349   if (MBB != NextBlock(SwitchBB))
2350     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2351                           DAG.getBasicBlock(MBB));
2352 
2353   DAG.setRoot(BrRange);
2354 }
2355 
2356 /// visitBitTestCase - this function produces one "bit test"
2357 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2358                                            MachineBasicBlock* NextMBB,
2359                                            BranchProbability BranchProbToNext,
2360                                            unsigned Reg,
2361                                            BitTestCase &B,
2362                                            MachineBasicBlock *SwitchBB) {
2363   SDLoc dl = getCurSDLoc();
2364   MVT VT = BB.RegVT;
2365   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2366   SDValue Cmp;
2367   unsigned PopCount = countPopulation(B.Mask);
2368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2369   if (PopCount == 1) {
2370     // Testing for a single bit; just compare the shift count with what it
2371     // would need to be to shift a 1 bit in that position.
2372     Cmp = DAG.getSetCC(
2373         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2374         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2375         ISD::SETEQ);
2376   } else if (PopCount == BB.Range) {
2377     // There is only one zero bit in the range, test for it directly.
2378     Cmp = DAG.getSetCC(
2379         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2380         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2381         ISD::SETNE);
2382   } else {
2383     // Make desired shift
2384     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2385                                     DAG.getConstant(1, dl, VT), ShiftOp);
2386 
2387     // Emit bit tests and jumps
2388     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2389                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2390     Cmp = DAG.getSetCC(
2391         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2392         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2393   }
2394 
2395   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2396   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2397   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2398   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2399   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2400   // one as they are relative probabilities (and thus work more like weights),
2401   // and hence we need to normalize them to let the sum of them become one.
2402   SwitchBB->normalizeSuccProbs();
2403 
2404   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2405                               MVT::Other, getControlRoot(),
2406                               Cmp, DAG.getBasicBlock(B.TargetBB));
2407 
2408   // Avoid emitting unnecessary branches to the next block.
2409   if (NextMBB != NextBlock(SwitchBB))
2410     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2411                         DAG.getBasicBlock(NextMBB));
2412 
2413   DAG.setRoot(BrAnd);
2414 }
2415 
2416 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2417   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2418 
2419   // Retrieve successors. Look through artificial IR level blocks like
2420   // catchswitch for successors.
2421   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2422   const BasicBlock *EHPadBB = I.getSuccessor(1);
2423 
2424   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2425   // have to do anything here to lower funclet bundles.
2426   assert(!I.hasOperandBundlesOtherThan(
2427              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2428          "Cannot lower invokes with arbitrary operand bundles yet!");
2429 
2430   const Value *Callee(I.getCalledValue());
2431   const Function *Fn = dyn_cast<Function>(Callee);
2432   if (isa<InlineAsm>(Callee))
2433     visitInlineAsm(&I);
2434   else if (Fn && Fn->isIntrinsic()) {
2435     switch (Fn->getIntrinsicID()) {
2436     default:
2437       llvm_unreachable("Cannot invoke this intrinsic");
2438     case Intrinsic::donothing:
2439       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2440       break;
2441     case Intrinsic::experimental_patchpoint_void:
2442     case Intrinsic::experimental_patchpoint_i64:
2443       visitPatchpoint(&I, EHPadBB);
2444       break;
2445     case Intrinsic::experimental_gc_statepoint:
2446       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2447       break;
2448     }
2449   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2450     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2451     // Eventually we will support lowering the @llvm.experimental.deoptimize
2452     // intrinsic, and right now there are no plans to support other intrinsics
2453     // with deopt state.
2454     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2455   } else {
2456     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2457   }
2458 
2459   // If the value of the invoke is used outside of its defining block, make it
2460   // available as a virtual register.
2461   // We already took care of the exported value for the statepoint instruction
2462   // during call to the LowerStatepoint.
2463   if (!isStatepoint(I)) {
2464     CopyToExportRegsIfNeeded(&I);
2465   }
2466 
2467   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2468   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2469   BranchProbability EHPadBBProb =
2470       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2471           : BranchProbability::getZero();
2472   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2473 
2474   // Update successor info.
2475   addSuccessorWithProb(InvokeMBB, Return);
2476   for (auto &UnwindDest : UnwindDests) {
2477     UnwindDest.first->setIsEHPad();
2478     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2479   }
2480   InvokeMBB->normalizeSuccProbs();
2481 
2482   // Drop into normal successor.
2483   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2484                           MVT::Other, getControlRoot(),
2485                           DAG.getBasicBlock(Return)));
2486 }
2487 
2488 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2489   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2490 }
2491 
2492 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2493   assert(FuncInfo.MBB->isEHPad() &&
2494          "Call to landingpad not in landing pad!");
2495 
2496   MachineBasicBlock *MBB = FuncInfo.MBB;
2497   addLandingPadInfo(LP, *MBB);
2498 
2499   // If there aren't registers to copy the values into (e.g., during SjLj
2500   // exceptions), then don't bother to create these DAG nodes.
2501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2502   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2503   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2504       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2505     return;
2506 
2507   // If landingpad's return type is token type, we don't create DAG nodes
2508   // for its exception pointer and selector value. The extraction of exception
2509   // pointer or selector value from token type landingpads is not currently
2510   // supported.
2511   if (LP.getType()->isTokenTy())
2512     return;
2513 
2514   SmallVector<EVT, 2> ValueVTs;
2515   SDLoc dl = getCurSDLoc();
2516   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2517   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2518 
2519   // Get the two live-in registers as SDValues. The physregs have already been
2520   // copied into virtual registers.
2521   SDValue Ops[2];
2522   if (FuncInfo.ExceptionPointerVirtReg) {
2523     Ops[0] = DAG.getZExtOrTrunc(
2524         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2525                            FuncInfo.ExceptionPointerVirtReg,
2526                            TLI.getPointerTy(DAG.getDataLayout())),
2527         dl, ValueVTs[0]);
2528   } else {
2529     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2530   }
2531   Ops[1] = DAG.getZExtOrTrunc(
2532       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2533                          FuncInfo.ExceptionSelectorVirtReg,
2534                          TLI.getPointerTy(DAG.getDataLayout())),
2535       dl, ValueVTs[1]);
2536 
2537   // Merge into one.
2538   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2539                             DAG.getVTList(ValueVTs), Ops);
2540   setValue(&LP, Res);
2541 }
2542 
2543 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2544 #ifndef NDEBUG
2545   for (const CaseCluster &CC : Clusters)
2546     assert(CC.Low == CC.High && "Input clusters must be single-case");
2547 #endif
2548 
2549   llvm::sort(Clusters.begin(), Clusters.end(),
2550              [](const CaseCluster &a, const CaseCluster &b) {
2551     return a.Low->getValue().slt(b.Low->getValue());
2552   });
2553 
2554   // Merge adjacent clusters with the same destination.
2555   const unsigned N = Clusters.size();
2556   unsigned DstIndex = 0;
2557   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2558     CaseCluster &CC = Clusters[SrcIndex];
2559     const ConstantInt *CaseVal = CC.Low;
2560     MachineBasicBlock *Succ = CC.MBB;
2561 
2562     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2563         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2564       // If this case has the same successor and is a neighbour, merge it into
2565       // the previous cluster.
2566       Clusters[DstIndex - 1].High = CaseVal;
2567       Clusters[DstIndex - 1].Prob += CC.Prob;
2568     } else {
2569       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2570                    sizeof(Clusters[SrcIndex]));
2571     }
2572   }
2573   Clusters.resize(DstIndex);
2574 }
2575 
2576 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2577                                            MachineBasicBlock *Last) {
2578   // Update JTCases.
2579   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2580     if (JTCases[i].first.HeaderBB == First)
2581       JTCases[i].first.HeaderBB = Last;
2582 
2583   // Update BitTestCases.
2584   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2585     if (BitTestCases[i].Parent == First)
2586       BitTestCases[i].Parent = Last;
2587 }
2588 
2589 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2590   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2591 
2592   // Update machine-CFG edges with unique successors.
2593   SmallSet<BasicBlock*, 32> Done;
2594   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2595     BasicBlock *BB = I.getSuccessor(i);
2596     bool Inserted = Done.insert(BB).second;
2597     if (!Inserted)
2598         continue;
2599 
2600     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2601     addSuccessorWithProb(IndirectBrMBB, Succ);
2602   }
2603   IndirectBrMBB->normalizeSuccProbs();
2604 
2605   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2606                           MVT::Other, getControlRoot(),
2607                           getValue(I.getAddress())));
2608 }
2609 
2610 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2611   if (!DAG.getTarget().Options.TrapUnreachable)
2612     return;
2613 
2614   // We may be able to ignore unreachable behind a noreturn call.
2615   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2616     const BasicBlock &BB = *I.getParent();
2617     if (&I != &BB.front()) {
2618       BasicBlock::const_iterator PredI =
2619         std::prev(BasicBlock::const_iterator(&I));
2620       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2621         if (Call->doesNotReturn())
2622           return;
2623       }
2624     }
2625   }
2626 
2627   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2628 }
2629 
2630 void SelectionDAGBuilder::visitFSub(const User &I) {
2631   // -0.0 - X --> fneg
2632   Type *Ty = I.getType();
2633   if (isa<Constant>(I.getOperand(0)) &&
2634       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2635     SDValue Op2 = getValue(I.getOperand(1));
2636     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2637                              Op2.getValueType(), Op2));
2638     return;
2639   }
2640 
2641   visitBinary(I, ISD::FSUB);
2642 }
2643 
2644 /// Checks if the given instruction performs a vector reduction, in which case
2645 /// we have the freedom to alter the elements in the result as long as the
2646 /// reduction of them stays unchanged.
2647 static bool isVectorReductionOp(const User *I) {
2648   const Instruction *Inst = dyn_cast<Instruction>(I);
2649   if (!Inst || !Inst->getType()->isVectorTy())
2650     return false;
2651 
2652   auto OpCode = Inst->getOpcode();
2653   switch (OpCode) {
2654   case Instruction::Add:
2655   case Instruction::Mul:
2656   case Instruction::And:
2657   case Instruction::Or:
2658   case Instruction::Xor:
2659     break;
2660   case Instruction::FAdd:
2661   case Instruction::FMul:
2662     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2663       if (FPOp->getFastMathFlags().isFast())
2664         break;
2665     LLVM_FALLTHROUGH;
2666   default:
2667     return false;
2668   }
2669 
2670   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2671   unsigned ElemNumToReduce = ElemNum;
2672 
2673   // Do DFS search on the def-use chain from the given instruction. We only
2674   // allow four kinds of operations during the search until we reach the
2675   // instruction that extracts the first element from the vector:
2676   //
2677   //   1. The reduction operation of the same opcode as the given instruction.
2678   //
2679   //   2. PHI node.
2680   //
2681   //   3. ShuffleVector instruction together with a reduction operation that
2682   //      does a partial reduction.
2683   //
2684   //   4. ExtractElement that extracts the first element from the vector, and we
2685   //      stop searching the def-use chain here.
2686   //
2687   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2688   // from 1-3 to the stack to continue the DFS. The given instruction is not
2689   // a reduction operation if we meet any other instructions other than those
2690   // listed above.
2691 
2692   SmallVector<const User *, 16> UsersToVisit{Inst};
2693   SmallPtrSet<const User *, 16> Visited;
2694   bool ReduxExtracted = false;
2695 
2696   while (!UsersToVisit.empty()) {
2697     auto User = UsersToVisit.back();
2698     UsersToVisit.pop_back();
2699     if (!Visited.insert(User).second)
2700       continue;
2701 
2702     for (const auto &U : User->users()) {
2703       auto Inst = dyn_cast<Instruction>(U);
2704       if (!Inst)
2705         return false;
2706 
2707       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2708         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2709           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2710             return false;
2711         UsersToVisit.push_back(U);
2712       } else if (const ShuffleVectorInst *ShufInst =
2713                      dyn_cast<ShuffleVectorInst>(U)) {
2714         // Detect the following pattern: A ShuffleVector instruction together
2715         // with a reduction that do partial reduction on the first and second
2716         // ElemNumToReduce / 2 elements, and store the result in
2717         // ElemNumToReduce / 2 elements in another vector.
2718 
2719         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2720         if (ResultElements < ElemNum)
2721           return false;
2722 
2723         if (ElemNumToReduce == 1)
2724           return false;
2725         if (!isa<UndefValue>(U->getOperand(1)))
2726           return false;
2727         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2728           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2729             return false;
2730         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2731           if (ShufInst->getMaskValue(i) != -1)
2732             return false;
2733 
2734         // There is only one user of this ShuffleVector instruction, which
2735         // must be a reduction operation.
2736         if (!U->hasOneUse())
2737           return false;
2738 
2739         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2740         if (!U2 || U2->getOpcode() != OpCode)
2741           return false;
2742 
2743         // Check operands of the reduction operation.
2744         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2745             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2746           UsersToVisit.push_back(U2);
2747           ElemNumToReduce /= 2;
2748         } else
2749           return false;
2750       } else if (isa<ExtractElementInst>(U)) {
2751         // At this moment we should have reduced all elements in the vector.
2752         if (ElemNumToReduce != 1)
2753           return false;
2754 
2755         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2756         if (!Val || Val->getZExtValue() != 0)
2757           return false;
2758 
2759         ReduxExtracted = true;
2760       } else
2761         return false;
2762     }
2763   }
2764   return ReduxExtracted;
2765 }
2766 
2767 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2768   SDNodeFlags Flags;
2769   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2770     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2771     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2772   }
2773   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2774     Flags.setExact(ExactOp->isExact());
2775   }
2776   if (isVectorReductionOp(&I)) {
2777     Flags.setVectorReduction(true);
2778     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2779   }
2780 
2781   SDValue Op1 = getValue(I.getOperand(0));
2782   SDValue Op2 = getValue(I.getOperand(1));
2783   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2784                                      Op1, Op2, Flags);
2785   setValue(&I, BinNodeValue);
2786 }
2787 
2788 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2789   SDValue Op1 = getValue(I.getOperand(0));
2790   SDValue Op2 = getValue(I.getOperand(1));
2791 
2792   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2793       Op2.getValueType(), DAG.getDataLayout());
2794 
2795   // Coerce the shift amount to the right type if we can.
2796   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2797     unsigned ShiftSize = ShiftTy.getSizeInBits();
2798     unsigned Op2Size = Op2.getValueSizeInBits();
2799     SDLoc DL = getCurSDLoc();
2800 
2801     // If the operand is smaller than the shift count type, promote it.
2802     if (ShiftSize > Op2Size)
2803       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2804 
2805     // If the operand is larger than the shift count type but the shift
2806     // count type has enough bits to represent any shift value, truncate
2807     // it now. This is a common case and it exposes the truncate to
2808     // optimization early.
2809     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2810       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2811     // Otherwise we'll need to temporarily settle for some other convenient
2812     // type.  Type legalization will make adjustments once the shiftee is split.
2813     else
2814       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2815   }
2816 
2817   bool nuw = false;
2818   bool nsw = false;
2819   bool exact = false;
2820 
2821   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2822 
2823     if (const OverflowingBinaryOperator *OFBinOp =
2824             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2825       nuw = OFBinOp->hasNoUnsignedWrap();
2826       nsw = OFBinOp->hasNoSignedWrap();
2827     }
2828     if (const PossiblyExactOperator *ExactOp =
2829             dyn_cast<const PossiblyExactOperator>(&I))
2830       exact = ExactOp->isExact();
2831   }
2832   SDNodeFlags Flags;
2833   Flags.setExact(exact);
2834   Flags.setNoSignedWrap(nsw);
2835   Flags.setNoUnsignedWrap(nuw);
2836   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2837                             Flags);
2838   setValue(&I, Res);
2839 }
2840 
2841 void SelectionDAGBuilder::visitSDiv(const User &I) {
2842   SDValue Op1 = getValue(I.getOperand(0));
2843   SDValue Op2 = getValue(I.getOperand(1));
2844 
2845   SDNodeFlags Flags;
2846   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2847                  cast<PossiblyExactOperator>(&I)->isExact());
2848   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2849                            Op2, Flags));
2850 }
2851 
2852 void SelectionDAGBuilder::visitICmp(const User &I) {
2853   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2854   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2855     predicate = IC->getPredicate();
2856   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2857     predicate = ICmpInst::Predicate(IC->getPredicate());
2858   SDValue Op1 = getValue(I.getOperand(0));
2859   SDValue Op2 = getValue(I.getOperand(1));
2860   ISD::CondCode Opcode = getICmpCondCode(predicate);
2861 
2862   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2863                                                         I.getType());
2864   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2865 }
2866 
2867 void SelectionDAGBuilder::visitFCmp(const User &I) {
2868   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2869   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2870     predicate = FC->getPredicate();
2871   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2872     predicate = FCmpInst::Predicate(FC->getPredicate());
2873   SDValue Op1 = getValue(I.getOperand(0));
2874   SDValue Op2 = getValue(I.getOperand(1));
2875 
2876   ISD::CondCode Condition = getFCmpCondCode(predicate);
2877   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2878   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2879     Condition = getFCmpCodeWithoutNaN(Condition);
2880 
2881   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2882                                                         I.getType());
2883   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2884 }
2885 
2886 // Check if the condition of the select has one use or two users that are both
2887 // selects with the same condition.
2888 static bool hasOnlySelectUsers(const Value *Cond) {
2889   return llvm::all_of(Cond->users(), [](const Value *V) {
2890     return isa<SelectInst>(V);
2891   });
2892 }
2893 
2894 void SelectionDAGBuilder::visitSelect(const User &I) {
2895   SmallVector<EVT, 4> ValueVTs;
2896   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2897                   ValueVTs);
2898   unsigned NumValues = ValueVTs.size();
2899   if (NumValues == 0) return;
2900 
2901   SmallVector<SDValue, 4> Values(NumValues);
2902   SDValue Cond     = getValue(I.getOperand(0));
2903   SDValue LHSVal   = getValue(I.getOperand(1));
2904   SDValue RHSVal   = getValue(I.getOperand(2));
2905   auto BaseOps = {Cond};
2906   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2907     ISD::VSELECT : ISD::SELECT;
2908 
2909   // Min/max matching is only viable if all output VTs are the same.
2910   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2911     EVT VT = ValueVTs[0];
2912     LLVMContext &Ctx = *DAG.getContext();
2913     auto &TLI = DAG.getTargetLoweringInfo();
2914 
2915     // We care about the legality of the operation after it has been type
2916     // legalized.
2917     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2918            VT != TLI.getTypeToTransformTo(Ctx, VT))
2919       VT = TLI.getTypeToTransformTo(Ctx, VT);
2920 
2921     // If the vselect is legal, assume we want to leave this as a vector setcc +
2922     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2923     // min/max is legal on the scalar type.
2924     bool UseScalarMinMax = VT.isVector() &&
2925       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2926 
2927     Value *LHS, *RHS;
2928     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2929     ISD::NodeType Opc = ISD::DELETED_NODE;
2930     switch (SPR.Flavor) {
2931     case SPF_UMAX:    Opc = ISD::UMAX; break;
2932     case SPF_UMIN:    Opc = ISD::UMIN; break;
2933     case SPF_SMAX:    Opc = ISD::SMAX; break;
2934     case SPF_SMIN:    Opc = ISD::SMIN; break;
2935     case SPF_FMINNUM:
2936       switch (SPR.NaNBehavior) {
2937       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2938       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2939       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2940       case SPNB_RETURNS_ANY: {
2941         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2942           Opc = ISD::FMINNUM;
2943         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2944           Opc = ISD::FMINNAN;
2945         else if (UseScalarMinMax)
2946           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2947             ISD::FMINNUM : ISD::FMINNAN;
2948         break;
2949       }
2950       }
2951       break;
2952     case SPF_FMAXNUM:
2953       switch (SPR.NaNBehavior) {
2954       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2955       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2956       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2957       case SPNB_RETURNS_ANY:
2958 
2959         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2960           Opc = ISD::FMAXNUM;
2961         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2962           Opc = ISD::FMAXNAN;
2963         else if (UseScalarMinMax)
2964           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2965             ISD::FMAXNUM : ISD::FMAXNAN;
2966         break;
2967       }
2968       break;
2969     default: break;
2970     }
2971 
2972     if (Opc != ISD::DELETED_NODE &&
2973         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2974          (UseScalarMinMax &&
2975           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2976         // If the underlying comparison instruction is used by any other
2977         // instruction, the consumed instructions won't be destroyed, so it is
2978         // not profitable to convert to a min/max.
2979         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2980       OpCode = Opc;
2981       LHSVal = getValue(LHS);
2982       RHSVal = getValue(RHS);
2983       BaseOps = {};
2984     }
2985   }
2986 
2987   for (unsigned i = 0; i != NumValues; ++i) {
2988     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2989     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2990     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2991     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2992                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2993                             Ops);
2994   }
2995 
2996   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2997                            DAG.getVTList(ValueVTs), Values));
2998 }
2999 
3000 void SelectionDAGBuilder::visitTrunc(const User &I) {
3001   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3002   SDValue N = getValue(I.getOperand(0));
3003   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3004                                                         I.getType());
3005   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3006 }
3007 
3008 void SelectionDAGBuilder::visitZExt(const User &I) {
3009   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3010   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3011   SDValue N = getValue(I.getOperand(0));
3012   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3013                                                         I.getType());
3014   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3015 }
3016 
3017 void SelectionDAGBuilder::visitSExt(const User &I) {
3018   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3019   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3020   SDValue N = getValue(I.getOperand(0));
3021   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3022                                                         I.getType());
3023   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3024 }
3025 
3026 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3027   // FPTrunc is never a no-op cast, no need to check
3028   SDValue N = getValue(I.getOperand(0));
3029   SDLoc dl = getCurSDLoc();
3030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3031   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3032   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3033                            DAG.getTargetConstant(
3034                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3035 }
3036 
3037 void SelectionDAGBuilder::visitFPExt(const User &I) {
3038   // FPExt is never a no-op cast, no need to check
3039   SDValue N = getValue(I.getOperand(0));
3040   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3041                                                         I.getType());
3042   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3043 }
3044 
3045 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3046   // FPToUI is never a no-op cast, no need to check
3047   SDValue N = getValue(I.getOperand(0));
3048   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3049                                                         I.getType());
3050   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3051 }
3052 
3053 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3054   // FPToSI is never a no-op cast, no need to check
3055   SDValue N = getValue(I.getOperand(0));
3056   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3057                                                         I.getType());
3058   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3059 }
3060 
3061 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3062   // UIToFP is never a no-op cast, no need to check
3063   SDValue N = getValue(I.getOperand(0));
3064   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3065                                                         I.getType());
3066   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3067 }
3068 
3069 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3070   // SIToFP is never a no-op cast, no need to check
3071   SDValue N = getValue(I.getOperand(0));
3072   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3073                                                         I.getType());
3074   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3075 }
3076 
3077 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3078   // What to do depends on the size of the integer and the size of the pointer.
3079   // We can either truncate, zero extend, or no-op, accordingly.
3080   SDValue N = getValue(I.getOperand(0));
3081   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3082                                                         I.getType());
3083   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3084 }
3085 
3086 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3087   // What to do depends on the size of the integer and the size of the pointer.
3088   // We can either truncate, zero extend, or no-op, accordingly.
3089   SDValue N = getValue(I.getOperand(0));
3090   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3091                                                         I.getType());
3092   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3093 }
3094 
3095 void SelectionDAGBuilder::visitBitCast(const User &I) {
3096   SDValue N = getValue(I.getOperand(0));
3097   SDLoc dl = getCurSDLoc();
3098   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3099                                                         I.getType());
3100 
3101   // BitCast assures us that source and destination are the same size so this is
3102   // either a BITCAST or a no-op.
3103   if (DestVT != N.getValueType())
3104     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3105                              DestVT, N)); // convert types.
3106   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3107   // might fold any kind of constant expression to an integer constant and that
3108   // is not what we are looking for. Only recognize a bitcast of a genuine
3109   // constant integer as an opaque constant.
3110   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3111     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3112                                  /*isOpaque*/true));
3113   else
3114     setValue(&I, N);            // noop cast.
3115 }
3116 
3117 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3119   const Value *SV = I.getOperand(0);
3120   SDValue N = getValue(SV);
3121   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3122 
3123   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3124   unsigned DestAS = I.getType()->getPointerAddressSpace();
3125 
3126   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3127     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3128 
3129   setValue(&I, N);
3130 }
3131 
3132 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3134   SDValue InVec = getValue(I.getOperand(0));
3135   SDValue InVal = getValue(I.getOperand(1));
3136   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3137                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3138   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3139                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3140                            InVec, InVal, InIdx));
3141 }
3142 
3143 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3145   SDValue InVec = getValue(I.getOperand(0));
3146   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3147                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3148   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3149                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3150                            InVec, InIdx));
3151 }
3152 
3153 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3154   SDValue Src1 = getValue(I.getOperand(0));
3155   SDValue Src2 = getValue(I.getOperand(1));
3156   SDLoc DL = getCurSDLoc();
3157 
3158   SmallVector<int, 8> Mask;
3159   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3160   unsigned MaskNumElts = Mask.size();
3161 
3162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3163   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3164   EVT SrcVT = Src1.getValueType();
3165   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3166 
3167   if (SrcNumElts == MaskNumElts) {
3168     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3169     return;
3170   }
3171 
3172   // Normalize the shuffle vector since mask and vector length don't match.
3173   if (SrcNumElts < MaskNumElts) {
3174     // Mask is longer than the source vectors. We can use concatenate vector to
3175     // make the mask and vectors lengths match.
3176 
3177     if (MaskNumElts % SrcNumElts == 0) {
3178       // Mask length is a multiple of the source vector length.
3179       // Check if the shuffle is some kind of concatenation of the input
3180       // vectors.
3181       unsigned NumConcat = MaskNumElts / SrcNumElts;
3182       bool IsConcat = true;
3183       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3184       for (unsigned i = 0; i != MaskNumElts; ++i) {
3185         int Idx = Mask[i];
3186         if (Idx < 0)
3187           continue;
3188         // Ensure the indices in each SrcVT sized piece are sequential and that
3189         // the same source is used for the whole piece.
3190         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3191             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3192              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3193           IsConcat = false;
3194           break;
3195         }
3196         // Remember which source this index came from.
3197         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3198       }
3199 
3200       // The shuffle is concatenating multiple vectors together. Just emit
3201       // a CONCAT_VECTORS operation.
3202       if (IsConcat) {
3203         SmallVector<SDValue, 8> ConcatOps;
3204         for (auto Src : ConcatSrcs) {
3205           if (Src < 0)
3206             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3207           else if (Src == 0)
3208             ConcatOps.push_back(Src1);
3209           else
3210             ConcatOps.push_back(Src2);
3211         }
3212         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3213         return;
3214       }
3215     }
3216 
3217     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3218     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3219     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3220                                     PaddedMaskNumElts);
3221 
3222     // Pad both vectors with undefs to make them the same length as the mask.
3223     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3224 
3225     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3226     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3227     MOps1[0] = Src1;
3228     MOps2[0] = Src2;
3229 
3230     Src1 = Src1.isUndef()
3231                ? DAG.getUNDEF(PaddedVT)
3232                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3233     Src2 = Src2.isUndef()
3234                ? DAG.getUNDEF(PaddedVT)
3235                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3236 
3237     // Readjust mask for new input vector length.
3238     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3239     for (unsigned i = 0; i != MaskNumElts; ++i) {
3240       int Idx = Mask[i];
3241       if (Idx >= (int)SrcNumElts)
3242         Idx -= SrcNumElts - PaddedMaskNumElts;
3243       MappedOps[i] = Idx;
3244     }
3245 
3246     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3247 
3248     // If the concatenated vector was padded, extract a subvector with the
3249     // correct number of elements.
3250     if (MaskNumElts != PaddedMaskNumElts)
3251       Result = DAG.getNode(
3252           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3253           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3254 
3255     setValue(&I, Result);
3256     return;
3257   }
3258 
3259   if (SrcNumElts > MaskNumElts) {
3260     // Analyze the access pattern of the vector to see if we can extract
3261     // two subvectors and do the shuffle.
3262     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3263     bool CanExtract = true;
3264     for (int Idx : Mask) {
3265       unsigned Input = 0;
3266       if (Idx < 0)
3267         continue;
3268 
3269       if (Idx >= (int)SrcNumElts) {
3270         Input = 1;
3271         Idx -= SrcNumElts;
3272       }
3273 
3274       // If all the indices come from the same MaskNumElts sized portion of
3275       // the sources we can use extract. Also make sure the extract wouldn't
3276       // extract past the end of the source.
3277       int NewStartIdx = alignDown(Idx, MaskNumElts);
3278       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3279           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3280         CanExtract = false;
3281       // Make sure we always update StartIdx as we use it to track if all
3282       // elements are undef.
3283       StartIdx[Input] = NewStartIdx;
3284     }
3285 
3286     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3287       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3288       return;
3289     }
3290     if (CanExtract) {
3291       // Extract appropriate subvector and generate a vector shuffle
3292       for (unsigned Input = 0; Input < 2; ++Input) {
3293         SDValue &Src = Input == 0 ? Src1 : Src2;
3294         if (StartIdx[Input] < 0)
3295           Src = DAG.getUNDEF(VT);
3296         else {
3297           Src = DAG.getNode(
3298               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3299               DAG.getConstant(StartIdx[Input], DL,
3300                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3301         }
3302       }
3303 
3304       // Calculate new mask.
3305       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3306       for (int &Idx : MappedOps) {
3307         if (Idx >= (int)SrcNumElts)
3308           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3309         else if (Idx >= 0)
3310           Idx -= StartIdx[0];
3311       }
3312 
3313       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3314       return;
3315     }
3316   }
3317 
3318   // We can't use either concat vectors or extract subvectors so fall back to
3319   // replacing the shuffle with extract and build vector.
3320   // to insert and build vector.
3321   EVT EltVT = VT.getVectorElementType();
3322   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3323   SmallVector<SDValue,8> Ops;
3324   for (int Idx : Mask) {
3325     SDValue Res;
3326 
3327     if (Idx < 0) {
3328       Res = DAG.getUNDEF(EltVT);
3329     } else {
3330       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3331       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3332 
3333       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3334                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3335     }
3336 
3337     Ops.push_back(Res);
3338   }
3339 
3340   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3341 }
3342 
3343 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3344   ArrayRef<unsigned> Indices;
3345   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3346     Indices = IV->getIndices();
3347   else
3348     Indices = cast<ConstantExpr>(&I)->getIndices();
3349 
3350   const Value *Op0 = I.getOperand(0);
3351   const Value *Op1 = I.getOperand(1);
3352   Type *AggTy = I.getType();
3353   Type *ValTy = Op1->getType();
3354   bool IntoUndef = isa<UndefValue>(Op0);
3355   bool FromUndef = isa<UndefValue>(Op1);
3356 
3357   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3358 
3359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3360   SmallVector<EVT, 4> AggValueVTs;
3361   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3362   SmallVector<EVT, 4> ValValueVTs;
3363   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3364 
3365   unsigned NumAggValues = AggValueVTs.size();
3366   unsigned NumValValues = ValValueVTs.size();
3367   SmallVector<SDValue, 4> Values(NumAggValues);
3368 
3369   // Ignore an insertvalue that produces an empty object
3370   if (!NumAggValues) {
3371     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3372     return;
3373   }
3374 
3375   SDValue Agg = getValue(Op0);
3376   unsigned i = 0;
3377   // Copy the beginning value(s) from the original aggregate.
3378   for (; i != LinearIndex; ++i)
3379     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3380                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3381   // Copy values from the inserted value(s).
3382   if (NumValValues) {
3383     SDValue Val = getValue(Op1);
3384     for (; i != LinearIndex + NumValValues; ++i)
3385       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3386                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3387   }
3388   // Copy remaining value(s) from the original aggregate.
3389   for (; i != NumAggValues; ++i)
3390     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3391                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3392 
3393   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3394                            DAG.getVTList(AggValueVTs), Values));
3395 }
3396 
3397 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3398   ArrayRef<unsigned> Indices;
3399   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3400     Indices = EV->getIndices();
3401   else
3402     Indices = cast<ConstantExpr>(&I)->getIndices();
3403 
3404   const Value *Op0 = I.getOperand(0);
3405   Type *AggTy = Op0->getType();
3406   Type *ValTy = I.getType();
3407   bool OutOfUndef = isa<UndefValue>(Op0);
3408 
3409   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3410 
3411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3412   SmallVector<EVT, 4> ValValueVTs;
3413   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3414 
3415   unsigned NumValValues = ValValueVTs.size();
3416 
3417   // Ignore a extractvalue that produces an empty object
3418   if (!NumValValues) {
3419     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3420     return;
3421   }
3422 
3423   SmallVector<SDValue, 4> Values(NumValValues);
3424 
3425   SDValue Agg = getValue(Op0);
3426   // Copy out the selected value(s).
3427   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3428     Values[i - LinearIndex] =
3429       OutOfUndef ?
3430         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3431         SDValue(Agg.getNode(), Agg.getResNo() + i);
3432 
3433   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3434                            DAG.getVTList(ValValueVTs), Values));
3435 }
3436 
3437 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3438   Value *Op0 = I.getOperand(0);
3439   // Note that the pointer operand may be a vector of pointers. Take the scalar
3440   // element which holds a pointer.
3441   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3442   SDValue N = getValue(Op0);
3443   SDLoc dl = getCurSDLoc();
3444 
3445   // Normalize Vector GEP - all scalar operands should be converted to the
3446   // splat vector.
3447   unsigned VectorWidth = I.getType()->isVectorTy() ?
3448     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3449 
3450   if (VectorWidth && !N.getValueType().isVector()) {
3451     LLVMContext &Context = *DAG.getContext();
3452     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3453     N = DAG.getSplatBuildVector(VT, dl, N);
3454   }
3455 
3456   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3457        GTI != E; ++GTI) {
3458     const Value *Idx = GTI.getOperand();
3459     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3460       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3461       if (Field) {
3462         // N = N + Offset
3463         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3464 
3465         // In an inbounds GEP with an offset that is nonnegative even when
3466         // interpreted as signed, assume there is no unsigned overflow.
3467         SDNodeFlags Flags;
3468         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3469           Flags.setNoUnsignedWrap(true);
3470 
3471         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3472                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3473       }
3474     } else {
3475       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3476       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3477       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3478 
3479       // If this is a scalar constant or a splat vector of constants,
3480       // handle it quickly.
3481       const auto *CI = dyn_cast<ConstantInt>(Idx);
3482       if (!CI && isa<ConstantDataVector>(Idx) &&
3483           cast<ConstantDataVector>(Idx)->getSplatValue())
3484         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3485 
3486       if (CI) {
3487         if (CI->isZero())
3488           continue;
3489         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3490         LLVMContext &Context = *DAG.getContext();
3491         SDValue OffsVal = VectorWidth ?
3492           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3493           DAG.getConstant(Offs, dl, IdxTy);
3494 
3495         // In an inbouds GEP with an offset that is nonnegative even when
3496         // interpreted as signed, assume there is no unsigned overflow.
3497         SDNodeFlags Flags;
3498         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3499           Flags.setNoUnsignedWrap(true);
3500 
3501         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3502         continue;
3503       }
3504 
3505       // N = N + Idx * ElementSize;
3506       SDValue IdxN = getValue(Idx);
3507 
3508       if (!IdxN.getValueType().isVector() && VectorWidth) {
3509         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3510         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3511       }
3512 
3513       // If the index is smaller or larger than intptr_t, truncate or extend
3514       // it.
3515       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3516 
3517       // If this is a multiply by a power of two, turn it into a shl
3518       // immediately.  This is a very common case.
3519       if (ElementSize != 1) {
3520         if (ElementSize.isPowerOf2()) {
3521           unsigned Amt = ElementSize.logBase2();
3522           IdxN = DAG.getNode(ISD::SHL, dl,
3523                              N.getValueType(), IdxN,
3524                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3525         } else {
3526           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3527           IdxN = DAG.getNode(ISD::MUL, dl,
3528                              N.getValueType(), IdxN, Scale);
3529         }
3530       }
3531 
3532       N = DAG.getNode(ISD::ADD, dl,
3533                       N.getValueType(), N, IdxN);
3534     }
3535   }
3536 
3537   setValue(&I, N);
3538 }
3539 
3540 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3541   // If this is a fixed sized alloca in the entry block of the function,
3542   // allocate it statically on the stack.
3543   if (FuncInfo.StaticAllocaMap.count(&I))
3544     return;   // getValue will auto-populate this.
3545 
3546   SDLoc dl = getCurSDLoc();
3547   Type *Ty = I.getAllocatedType();
3548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3549   auto &DL = DAG.getDataLayout();
3550   uint64_t TySize = DL.getTypeAllocSize(Ty);
3551   unsigned Align =
3552       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3553 
3554   SDValue AllocSize = getValue(I.getArraySize());
3555 
3556   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3557   if (AllocSize.getValueType() != IntPtr)
3558     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3559 
3560   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3561                           AllocSize,
3562                           DAG.getConstant(TySize, dl, IntPtr));
3563 
3564   // Handle alignment.  If the requested alignment is less than or equal to
3565   // the stack alignment, ignore it.  If the size is greater than or equal to
3566   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3567   unsigned StackAlign =
3568       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3569   if (Align <= StackAlign)
3570     Align = 0;
3571 
3572   // Round the size of the allocation up to the stack alignment size
3573   // by add SA-1 to the size. This doesn't overflow because we're computing
3574   // an address inside an alloca.
3575   SDNodeFlags Flags;
3576   Flags.setNoUnsignedWrap(true);
3577   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3578                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3579 
3580   // Mask out the low bits for alignment purposes.
3581   AllocSize =
3582       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3583                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3584 
3585   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3586   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3587   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3588   setValue(&I, DSA);
3589   DAG.setRoot(DSA.getValue(1));
3590 
3591   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3592 }
3593 
3594 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3595   if (I.isAtomic())
3596     return visitAtomicLoad(I);
3597 
3598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3599   const Value *SV = I.getOperand(0);
3600   if (TLI.supportSwiftError()) {
3601     // Swifterror values can come from either a function parameter with
3602     // swifterror attribute or an alloca with swifterror attribute.
3603     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3604       if (Arg->hasSwiftErrorAttr())
3605         return visitLoadFromSwiftError(I);
3606     }
3607 
3608     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3609       if (Alloca->isSwiftError())
3610         return visitLoadFromSwiftError(I);
3611     }
3612   }
3613 
3614   SDValue Ptr = getValue(SV);
3615 
3616   Type *Ty = I.getType();
3617 
3618   bool isVolatile = I.isVolatile();
3619   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3620   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3621   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3622   unsigned Alignment = I.getAlignment();
3623 
3624   AAMDNodes AAInfo;
3625   I.getAAMetadata(AAInfo);
3626   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3627 
3628   SmallVector<EVT, 4> ValueVTs;
3629   SmallVector<uint64_t, 4> Offsets;
3630   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3631   unsigned NumValues = ValueVTs.size();
3632   if (NumValues == 0)
3633     return;
3634 
3635   SDValue Root;
3636   bool ConstantMemory = false;
3637   if (isVolatile || NumValues > MaxParallelChains)
3638     // Serialize volatile loads with other side effects.
3639     Root = getRoot();
3640   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3641                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3642     // Do not serialize (non-volatile) loads of constant memory with anything.
3643     Root = DAG.getEntryNode();
3644     ConstantMemory = true;
3645   } else {
3646     // Do not serialize non-volatile loads against each other.
3647     Root = DAG.getRoot();
3648   }
3649 
3650   SDLoc dl = getCurSDLoc();
3651 
3652   if (isVolatile)
3653     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3654 
3655   // An aggregate load cannot wrap around the address space, so offsets to its
3656   // parts don't wrap either.
3657   SDNodeFlags Flags;
3658   Flags.setNoUnsignedWrap(true);
3659 
3660   SmallVector<SDValue, 4> Values(NumValues);
3661   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3662   EVT PtrVT = Ptr.getValueType();
3663   unsigned ChainI = 0;
3664   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3665     // Serializing loads here may result in excessive register pressure, and
3666     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3667     // could recover a bit by hoisting nodes upward in the chain by recognizing
3668     // they are side-effect free or do not alias. The optimizer should really
3669     // avoid this case by converting large object/array copies to llvm.memcpy
3670     // (MaxParallelChains should always remain as failsafe).
3671     if (ChainI == MaxParallelChains) {
3672       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3673       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3674                                   makeArrayRef(Chains.data(), ChainI));
3675       Root = Chain;
3676       ChainI = 0;
3677     }
3678     SDValue A = DAG.getNode(ISD::ADD, dl,
3679                             PtrVT, Ptr,
3680                             DAG.getConstant(Offsets[i], dl, PtrVT),
3681                             Flags);
3682     auto MMOFlags = MachineMemOperand::MONone;
3683     if (isVolatile)
3684       MMOFlags |= MachineMemOperand::MOVolatile;
3685     if (isNonTemporal)
3686       MMOFlags |= MachineMemOperand::MONonTemporal;
3687     if (isInvariant)
3688       MMOFlags |= MachineMemOperand::MOInvariant;
3689     if (isDereferenceable)
3690       MMOFlags |= MachineMemOperand::MODereferenceable;
3691     MMOFlags |= TLI.getMMOFlags(I);
3692 
3693     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3694                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3695                             MMOFlags, AAInfo, Ranges);
3696 
3697     Values[i] = L;
3698     Chains[ChainI] = L.getValue(1);
3699   }
3700 
3701   if (!ConstantMemory) {
3702     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3703                                 makeArrayRef(Chains.data(), ChainI));
3704     if (isVolatile)
3705       DAG.setRoot(Chain);
3706     else
3707       PendingLoads.push_back(Chain);
3708   }
3709 
3710   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3711                            DAG.getVTList(ValueVTs), Values));
3712 }
3713 
3714 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3715   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3716          "call visitStoreToSwiftError when backend supports swifterror");
3717 
3718   SmallVector<EVT, 4> ValueVTs;
3719   SmallVector<uint64_t, 4> Offsets;
3720   const Value *SrcV = I.getOperand(0);
3721   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3722                   SrcV->getType(), ValueVTs, &Offsets);
3723   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3724          "expect a single EVT for swifterror");
3725 
3726   SDValue Src = getValue(SrcV);
3727   // Create a virtual register, then update the virtual register.
3728   unsigned VReg; bool CreatedVReg;
3729   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3730   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3731   // Chain can be getRoot or getControlRoot.
3732   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3733                                       SDValue(Src.getNode(), Src.getResNo()));
3734   DAG.setRoot(CopyNode);
3735   if (CreatedVReg)
3736     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3737 }
3738 
3739 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3740   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3741          "call visitLoadFromSwiftError when backend supports swifterror");
3742 
3743   assert(!I.isVolatile() &&
3744          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3745          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3746          "Support volatile, non temporal, invariant for load_from_swift_error");
3747 
3748   const Value *SV = I.getOperand(0);
3749   Type *Ty = I.getType();
3750   AAMDNodes AAInfo;
3751   I.getAAMetadata(AAInfo);
3752   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3753              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3754          "load_from_swift_error should not be constant memory");
3755 
3756   SmallVector<EVT, 4> ValueVTs;
3757   SmallVector<uint64_t, 4> Offsets;
3758   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3759                   ValueVTs, &Offsets);
3760   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3761          "expect a single EVT for swifterror");
3762 
3763   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3764   SDValue L = DAG.getCopyFromReg(
3765       getRoot(), getCurSDLoc(),
3766       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3767       ValueVTs[0]);
3768 
3769   setValue(&I, L);
3770 }
3771 
3772 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3773   if (I.isAtomic())
3774     return visitAtomicStore(I);
3775 
3776   const Value *SrcV = I.getOperand(0);
3777   const Value *PtrV = I.getOperand(1);
3778 
3779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3780   if (TLI.supportSwiftError()) {
3781     // Swifterror values can come from either a function parameter with
3782     // swifterror attribute or an alloca with swifterror attribute.
3783     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3784       if (Arg->hasSwiftErrorAttr())
3785         return visitStoreToSwiftError(I);
3786     }
3787 
3788     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3789       if (Alloca->isSwiftError())
3790         return visitStoreToSwiftError(I);
3791     }
3792   }
3793 
3794   SmallVector<EVT, 4> ValueVTs;
3795   SmallVector<uint64_t, 4> Offsets;
3796   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3797                   SrcV->getType(), ValueVTs, &Offsets);
3798   unsigned NumValues = ValueVTs.size();
3799   if (NumValues == 0)
3800     return;
3801 
3802   // Get the lowered operands. Note that we do this after
3803   // checking if NumResults is zero, because with zero results
3804   // the operands won't have values in the map.
3805   SDValue Src = getValue(SrcV);
3806   SDValue Ptr = getValue(PtrV);
3807 
3808   SDValue Root = getRoot();
3809   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3810   SDLoc dl = getCurSDLoc();
3811   EVT PtrVT = Ptr.getValueType();
3812   unsigned Alignment = I.getAlignment();
3813   AAMDNodes AAInfo;
3814   I.getAAMetadata(AAInfo);
3815 
3816   auto MMOFlags = MachineMemOperand::MONone;
3817   if (I.isVolatile())
3818     MMOFlags |= MachineMemOperand::MOVolatile;
3819   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3820     MMOFlags |= MachineMemOperand::MONonTemporal;
3821   MMOFlags |= TLI.getMMOFlags(I);
3822 
3823   // An aggregate load cannot wrap around the address space, so offsets to its
3824   // parts don't wrap either.
3825   SDNodeFlags Flags;
3826   Flags.setNoUnsignedWrap(true);
3827 
3828   unsigned ChainI = 0;
3829   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3830     // See visitLoad comments.
3831     if (ChainI == MaxParallelChains) {
3832       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3833                                   makeArrayRef(Chains.data(), ChainI));
3834       Root = Chain;
3835       ChainI = 0;
3836     }
3837     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3838                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3839     SDValue St = DAG.getStore(
3840         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3841         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3842     Chains[ChainI] = St;
3843   }
3844 
3845   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3846                                   makeArrayRef(Chains.data(), ChainI));
3847   DAG.setRoot(StoreNode);
3848 }
3849 
3850 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3851                                            bool IsCompressing) {
3852   SDLoc sdl = getCurSDLoc();
3853 
3854   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3855                            unsigned& Alignment) {
3856     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3857     Src0 = I.getArgOperand(0);
3858     Ptr = I.getArgOperand(1);
3859     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3860     Mask = I.getArgOperand(3);
3861   };
3862   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3863                            unsigned& Alignment) {
3864     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3865     Src0 = I.getArgOperand(0);
3866     Ptr = I.getArgOperand(1);
3867     Mask = I.getArgOperand(2);
3868     Alignment = 0;
3869   };
3870 
3871   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3872   unsigned Alignment;
3873   if (IsCompressing)
3874     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3875   else
3876     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3877 
3878   SDValue Ptr = getValue(PtrOperand);
3879   SDValue Src0 = getValue(Src0Operand);
3880   SDValue Mask = getValue(MaskOperand);
3881 
3882   EVT VT = Src0.getValueType();
3883   if (!Alignment)
3884     Alignment = DAG.getEVTAlignment(VT);
3885 
3886   AAMDNodes AAInfo;
3887   I.getAAMetadata(AAInfo);
3888 
3889   MachineMemOperand *MMO =
3890     DAG.getMachineFunction().
3891     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3892                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3893                           Alignment, AAInfo);
3894   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3895                                          MMO, false /* Truncating */,
3896                                          IsCompressing);
3897   DAG.setRoot(StoreNode);
3898   setValue(&I, StoreNode);
3899 }
3900 
3901 // Get a uniform base for the Gather/Scatter intrinsic.
3902 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3903 // We try to represent it as a base pointer + vector of indices.
3904 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3905 // The first operand of the GEP may be a single pointer or a vector of pointers
3906 // Example:
3907 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3908 //  or
3909 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3910 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3911 //
3912 // When the first GEP operand is a single pointer - it is the uniform base we
3913 // are looking for. If first operand of the GEP is a splat vector - we
3914 // extract the splat value and use it as a uniform base.
3915 // In all other cases the function returns 'false'.
3916 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3917                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3918   SelectionDAG& DAG = SDB->DAG;
3919   LLVMContext &Context = *DAG.getContext();
3920 
3921   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3922   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3923   if (!GEP)
3924     return false;
3925 
3926   const Value *GEPPtr = GEP->getPointerOperand();
3927   if (!GEPPtr->getType()->isVectorTy())
3928     Ptr = GEPPtr;
3929   else if (!(Ptr = getSplatValue(GEPPtr)))
3930     return false;
3931 
3932   unsigned FinalIndex = GEP->getNumOperands() - 1;
3933   Value *IndexVal = GEP->getOperand(FinalIndex);
3934 
3935   // Ensure all the other indices are 0.
3936   for (unsigned i = 1; i < FinalIndex; ++i) {
3937     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3938     if (!C || !C->isZero())
3939       return false;
3940   }
3941 
3942   // The operands of the GEP may be defined in another basic block.
3943   // In this case we'll not find nodes for the operands.
3944   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3945     return false;
3946 
3947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3948   const DataLayout &DL = DAG.getDataLayout();
3949   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3950                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3951   Base = SDB->getValue(Ptr);
3952   Index = SDB->getValue(IndexVal);
3953 
3954   if (!Index.getValueType().isVector()) {
3955     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3956     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3957     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3958   }
3959   return true;
3960 }
3961 
3962 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3963   SDLoc sdl = getCurSDLoc();
3964 
3965   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3966   const Value *Ptr = I.getArgOperand(1);
3967   SDValue Src0 = getValue(I.getArgOperand(0));
3968   SDValue Mask = getValue(I.getArgOperand(3));
3969   EVT VT = Src0.getValueType();
3970   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3971   if (!Alignment)
3972     Alignment = DAG.getEVTAlignment(VT);
3973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3974 
3975   AAMDNodes AAInfo;
3976   I.getAAMetadata(AAInfo);
3977 
3978   SDValue Base;
3979   SDValue Index;
3980   SDValue Scale;
3981   const Value *BasePtr = Ptr;
3982   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
3983 
3984   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3985   MachineMemOperand *MMO = DAG.getMachineFunction().
3986     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3987                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3988                          Alignment, AAInfo);
3989   if (!UniformBase) {
3990     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3991     Index = getValue(Ptr);
3992     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3993   }
3994   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
3995   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3996                                          Ops, MMO);
3997   DAG.setRoot(Scatter);
3998   setValue(&I, Scatter);
3999 }
4000 
4001 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4002   SDLoc sdl = getCurSDLoc();
4003 
4004   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4005                            unsigned& Alignment) {
4006     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4007     Ptr = I.getArgOperand(0);
4008     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4009     Mask = I.getArgOperand(2);
4010     Src0 = I.getArgOperand(3);
4011   };
4012   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4013                            unsigned& Alignment) {
4014     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4015     Ptr = I.getArgOperand(0);
4016     Alignment = 0;
4017     Mask = I.getArgOperand(1);
4018     Src0 = I.getArgOperand(2);
4019   };
4020 
4021   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4022   unsigned Alignment;
4023   if (IsExpanding)
4024     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4025   else
4026     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4027 
4028   SDValue Ptr = getValue(PtrOperand);
4029   SDValue Src0 = getValue(Src0Operand);
4030   SDValue Mask = getValue(MaskOperand);
4031 
4032   EVT VT = Src0.getValueType();
4033   if (!Alignment)
4034     Alignment = DAG.getEVTAlignment(VT);
4035 
4036   AAMDNodes AAInfo;
4037   I.getAAMetadata(AAInfo);
4038   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4039 
4040   // Do not serialize masked loads of constant memory with anything.
4041   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4042       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4043   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4044 
4045   MachineMemOperand *MMO =
4046     DAG.getMachineFunction().
4047     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4048                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4049                           Alignment, AAInfo, Ranges);
4050 
4051   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4052                                    ISD::NON_EXTLOAD, IsExpanding);
4053   if (AddToChain) {
4054     SDValue OutChain = Load.getValue(1);
4055     DAG.setRoot(OutChain);
4056   }
4057   setValue(&I, Load);
4058 }
4059 
4060 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4061   SDLoc sdl = getCurSDLoc();
4062 
4063   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4064   const Value *Ptr = I.getArgOperand(0);
4065   SDValue Src0 = getValue(I.getArgOperand(3));
4066   SDValue Mask = getValue(I.getArgOperand(2));
4067 
4068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4069   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4070   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4071   if (!Alignment)
4072     Alignment = DAG.getEVTAlignment(VT);
4073 
4074   AAMDNodes AAInfo;
4075   I.getAAMetadata(AAInfo);
4076   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4077 
4078   SDValue Root = DAG.getRoot();
4079   SDValue Base;
4080   SDValue Index;
4081   SDValue Scale;
4082   const Value *BasePtr = Ptr;
4083   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4084   bool ConstantMemory = false;
4085   if (UniformBase &&
4086       AA && AA->pointsToConstantMemory(MemoryLocation(
4087           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4088           AAInfo))) {
4089     // Do not serialize (non-volatile) loads of constant memory with anything.
4090     Root = DAG.getEntryNode();
4091     ConstantMemory = true;
4092   }
4093 
4094   MachineMemOperand *MMO =
4095     DAG.getMachineFunction().
4096     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4097                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4098                          Alignment, AAInfo, Ranges);
4099 
4100   if (!UniformBase) {
4101     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4102     Index = getValue(Ptr);
4103     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4104   }
4105   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4106   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4107                                        Ops, MMO);
4108 
4109   SDValue OutChain = Gather.getValue(1);
4110   if (!ConstantMemory)
4111     PendingLoads.push_back(OutChain);
4112   setValue(&I, Gather);
4113 }
4114 
4115 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4116   SDLoc dl = getCurSDLoc();
4117   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4118   AtomicOrdering FailureOrder = I.getFailureOrdering();
4119   SyncScope::ID SSID = I.getSyncScopeID();
4120 
4121   SDValue InChain = getRoot();
4122 
4123   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4124   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4125   SDValue L = DAG.getAtomicCmpSwap(
4126       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4127       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4128       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4129       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4130 
4131   SDValue OutChain = L.getValue(2);
4132 
4133   setValue(&I, L);
4134   DAG.setRoot(OutChain);
4135 }
4136 
4137 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4138   SDLoc dl = getCurSDLoc();
4139   ISD::NodeType NT;
4140   switch (I.getOperation()) {
4141   default: llvm_unreachable("Unknown atomicrmw operation");
4142   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4143   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4144   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4145   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4146   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4147   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4148   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4149   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4150   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4151   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4152   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4153   }
4154   AtomicOrdering Order = I.getOrdering();
4155   SyncScope::ID SSID = I.getSyncScopeID();
4156 
4157   SDValue InChain = getRoot();
4158 
4159   SDValue L =
4160     DAG.getAtomic(NT, dl,
4161                   getValue(I.getValOperand()).getSimpleValueType(),
4162                   InChain,
4163                   getValue(I.getPointerOperand()),
4164                   getValue(I.getValOperand()),
4165                   I.getPointerOperand(),
4166                   /* Alignment=*/ 0, Order, SSID);
4167 
4168   SDValue OutChain = L.getValue(1);
4169 
4170   setValue(&I, L);
4171   DAG.setRoot(OutChain);
4172 }
4173 
4174 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4175   SDLoc dl = getCurSDLoc();
4176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4177   SDValue Ops[3];
4178   Ops[0] = getRoot();
4179   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4180                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4181   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4182                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4183   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4184 }
4185 
4186 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4187   SDLoc dl = getCurSDLoc();
4188   AtomicOrdering Order = I.getOrdering();
4189   SyncScope::ID SSID = I.getSyncScopeID();
4190 
4191   SDValue InChain = getRoot();
4192 
4193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4194   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4195 
4196   if (!TLI.supportsUnalignedAtomics() &&
4197       I.getAlignment() < VT.getStoreSize())
4198     report_fatal_error("Cannot generate unaligned atomic load");
4199 
4200   MachineMemOperand *MMO =
4201       DAG.getMachineFunction().
4202       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4203                            MachineMemOperand::MOVolatile |
4204                            MachineMemOperand::MOLoad,
4205                            VT.getStoreSize(),
4206                            I.getAlignment() ? I.getAlignment() :
4207                                               DAG.getEVTAlignment(VT),
4208                            AAMDNodes(), nullptr, SSID, Order);
4209 
4210   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4211   SDValue L =
4212       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4213                     getValue(I.getPointerOperand()), MMO);
4214 
4215   SDValue OutChain = L.getValue(1);
4216 
4217   setValue(&I, L);
4218   DAG.setRoot(OutChain);
4219 }
4220 
4221 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4222   SDLoc dl = getCurSDLoc();
4223 
4224   AtomicOrdering Order = I.getOrdering();
4225   SyncScope::ID SSID = I.getSyncScopeID();
4226 
4227   SDValue InChain = getRoot();
4228 
4229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4230   EVT VT =
4231       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4232 
4233   if (I.getAlignment() < VT.getStoreSize())
4234     report_fatal_error("Cannot generate unaligned atomic store");
4235 
4236   SDValue OutChain =
4237     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4238                   InChain,
4239                   getValue(I.getPointerOperand()),
4240                   getValue(I.getValueOperand()),
4241                   I.getPointerOperand(), I.getAlignment(),
4242                   Order, SSID);
4243 
4244   DAG.setRoot(OutChain);
4245 }
4246 
4247 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4248 /// node.
4249 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4250                                                unsigned Intrinsic) {
4251   // Ignore the callsite's attributes. A specific call site may be marked with
4252   // readnone, but the lowering code will expect the chain based on the
4253   // definition.
4254   const Function *F = I.getCalledFunction();
4255   bool HasChain = !F->doesNotAccessMemory();
4256   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4257 
4258   // Build the operand list.
4259   SmallVector<SDValue, 8> Ops;
4260   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4261     if (OnlyLoad) {
4262       // We don't need to serialize loads against other loads.
4263       Ops.push_back(DAG.getRoot());
4264     } else {
4265       Ops.push_back(getRoot());
4266     }
4267   }
4268 
4269   // Info is set by getTgtMemInstrinsic
4270   TargetLowering::IntrinsicInfo Info;
4271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4272   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4273                                                DAG.getMachineFunction(),
4274                                                Intrinsic);
4275 
4276   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4277   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4278       Info.opc == ISD::INTRINSIC_W_CHAIN)
4279     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4280                                         TLI.getPointerTy(DAG.getDataLayout())));
4281 
4282   // Add all operands of the call to the operand list.
4283   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4284     SDValue Op = getValue(I.getArgOperand(i));
4285     Ops.push_back(Op);
4286   }
4287 
4288   SmallVector<EVT, 4> ValueVTs;
4289   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4290 
4291   if (HasChain)
4292     ValueVTs.push_back(MVT::Other);
4293 
4294   SDVTList VTs = DAG.getVTList(ValueVTs);
4295 
4296   // Create the node.
4297   SDValue Result;
4298   if (IsTgtIntrinsic) {
4299     // This is target intrinsic that touches memory
4300     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4301       Ops, Info.memVT,
4302       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4303       Info.flags, Info.size);
4304   } else if (!HasChain) {
4305     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4306   } else if (!I.getType()->isVoidTy()) {
4307     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4308   } else {
4309     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4310   }
4311 
4312   if (HasChain) {
4313     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4314     if (OnlyLoad)
4315       PendingLoads.push_back(Chain);
4316     else
4317       DAG.setRoot(Chain);
4318   }
4319 
4320   if (!I.getType()->isVoidTy()) {
4321     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4322       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4323       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4324     } else
4325       Result = lowerRangeToAssertZExt(DAG, I, Result);
4326 
4327     setValue(&I, Result);
4328   }
4329 }
4330 
4331 /// GetSignificand - Get the significand and build it into a floating-point
4332 /// number with exponent of 1:
4333 ///
4334 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4335 ///
4336 /// where Op is the hexadecimal representation of floating point value.
4337 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4338   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4339                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4340   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4341                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4342   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4343 }
4344 
4345 /// GetExponent - Get the exponent:
4346 ///
4347 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4348 ///
4349 /// where Op is the hexadecimal representation of floating point value.
4350 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4351                            const TargetLowering &TLI, const SDLoc &dl) {
4352   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4353                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4354   SDValue t1 = DAG.getNode(
4355       ISD::SRL, dl, MVT::i32, t0,
4356       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4357   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4358                            DAG.getConstant(127, dl, MVT::i32));
4359   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4360 }
4361 
4362 /// getF32Constant - Get 32-bit floating point constant.
4363 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4364                               const SDLoc &dl) {
4365   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4366                            MVT::f32);
4367 }
4368 
4369 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4370                                        SelectionDAG &DAG) {
4371   // TODO: What fast-math-flags should be set on the floating-point nodes?
4372 
4373   //   IntegerPartOfX = ((int32_t)(t0);
4374   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4375 
4376   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4377   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4378   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4379 
4380   //   IntegerPartOfX <<= 23;
4381   IntegerPartOfX = DAG.getNode(
4382       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4383       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4384                                   DAG.getDataLayout())));
4385 
4386   SDValue TwoToFractionalPartOfX;
4387   if (LimitFloatPrecision <= 6) {
4388     // For floating-point precision of 6:
4389     //
4390     //   TwoToFractionalPartOfX =
4391     //     0.997535578f +
4392     //       (0.735607626f + 0.252464424f * x) * x;
4393     //
4394     // error 0.0144103317, which is 6 bits
4395     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4396                              getF32Constant(DAG, 0x3e814304, dl));
4397     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4398                              getF32Constant(DAG, 0x3f3c50c8, dl));
4399     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4400     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4401                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4402   } else if (LimitFloatPrecision <= 12) {
4403     // For floating-point precision of 12:
4404     //
4405     //   TwoToFractionalPartOfX =
4406     //     0.999892986f +
4407     //       (0.696457318f +
4408     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4409     //
4410     // error 0.000107046256, which is 13 to 14 bits
4411     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4412                              getF32Constant(DAG, 0x3da235e3, dl));
4413     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4414                              getF32Constant(DAG, 0x3e65b8f3, dl));
4415     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4416     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4417                              getF32Constant(DAG, 0x3f324b07, dl));
4418     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4419     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4420                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4421   } else { // LimitFloatPrecision <= 18
4422     // For floating-point precision of 18:
4423     //
4424     //   TwoToFractionalPartOfX =
4425     //     0.999999982f +
4426     //       (0.693148872f +
4427     //         (0.240227044f +
4428     //           (0.554906021e-1f +
4429     //             (0.961591928e-2f +
4430     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4431     // error 2.47208000*10^(-7), which is better than 18 bits
4432     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4433                              getF32Constant(DAG, 0x3924b03e, dl));
4434     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4435                              getF32Constant(DAG, 0x3ab24b87, dl));
4436     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4437     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4438                              getF32Constant(DAG, 0x3c1d8c17, dl));
4439     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4440     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4441                              getF32Constant(DAG, 0x3d634a1d, dl));
4442     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4443     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4444                              getF32Constant(DAG, 0x3e75fe14, dl));
4445     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4446     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4447                               getF32Constant(DAG, 0x3f317234, dl));
4448     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4449     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4450                                          getF32Constant(DAG, 0x3f800000, dl));
4451   }
4452 
4453   // Add the exponent into the result in integer domain.
4454   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4455   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4456                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4457 }
4458 
4459 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4460 /// limited-precision mode.
4461 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4462                          const TargetLowering &TLI) {
4463   if (Op.getValueType() == MVT::f32 &&
4464       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4465 
4466     // Put the exponent in the right bit position for later addition to the
4467     // final result:
4468     //
4469     //   #define LOG2OFe 1.4426950f
4470     //   t0 = Op * LOG2OFe
4471 
4472     // TODO: What fast-math-flags should be set here?
4473     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4474                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4475     return getLimitedPrecisionExp2(t0, dl, DAG);
4476   }
4477 
4478   // No special expansion.
4479   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4480 }
4481 
4482 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4483 /// limited-precision mode.
4484 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4485                          const TargetLowering &TLI) {
4486   // TODO: What fast-math-flags should be set on the floating-point nodes?
4487 
4488   if (Op.getValueType() == MVT::f32 &&
4489       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4490     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4491 
4492     // Scale the exponent by log(2) [0.69314718f].
4493     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4494     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4495                                         getF32Constant(DAG, 0x3f317218, dl));
4496 
4497     // Get the significand and build it into a floating-point number with
4498     // exponent of 1.
4499     SDValue X = GetSignificand(DAG, Op1, dl);
4500 
4501     SDValue LogOfMantissa;
4502     if (LimitFloatPrecision <= 6) {
4503       // For floating-point precision of 6:
4504       //
4505       //   LogofMantissa =
4506       //     -1.1609546f +
4507       //       (1.4034025f - 0.23903021f * x) * x;
4508       //
4509       // error 0.0034276066, which is better than 8 bits
4510       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4511                                getF32Constant(DAG, 0xbe74c456, dl));
4512       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4513                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4514       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4515       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4516                                   getF32Constant(DAG, 0x3f949a29, dl));
4517     } else if (LimitFloatPrecision <= 12) {
4518       // For floating-point precision of 12:
4519       //
4520       //   LogOfMantissa =
4521       //     -1.7417939f +
4522       //       (2.8212026f +
4523       //         (-1.4699568f +
4524       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4525       //
4526       // error 0.000061011436, which is 14 bits
4527       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4528                                getF32Constant(DAG, 0xbd67b6d6, dl));
4529       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4530                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4531       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4532       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4533                                getF32Constant(DAG, 0x3fbc278b, dl));
4534       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4535       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4536                                getF32Constant(DAG, 0x40348e95, dl));
4537       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4538       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4539                                   getF32Constant(DAG, 0x3fdef31a, dl));
4540     } else { // LimitFloatPrecision <= 18
4541       // For floating-point precision of 18:
4542       //
4543       //   LogOfMantissa =
4544       //     -2.1072184f +
4545       //       (4.2372794f +
4546       //         (-3.7029485f +
4547       //           (2.2781945f +
4548       //             (-0.87823314f +
4549       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4550       //
4551       // error 0.0000023660568, which is better than 18 bits
4552       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4553                                getF32Constant(DAG, 0xbc91e5ac, dl));
4554       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4555                                getF32Constant(DAG, 0x3e4350aa, dl));
4556       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4557       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4558                                getF32Constant(DAG, 0x3f60d3e3, dl));
4559       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4560       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4561                                getF32Constant(DAG, 0x4011cdf0, dl));
4562       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4563       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4564                                getF32Constant(DAG, 0x406cfd1c, dl));
4565       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4566       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4567                                getF32Constant(DAG, 0x408797cb, dl));
4568       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4569       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4570                                   getF32Constant(DAG, 0x4006dcab, dl));
4571     }
4572 
4573     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4574   }
4575 
4576   // No special expansion.
4577   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4578 }
4579 
4580 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4581 /// limited-precision mode.
4582 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4583                           const TargetLowering &TLI) {
4584   // TODO: What fast-math-flags should be set on the floating-point nodes?
4585 
4586   if (Op.getValueType() == MVT::f32 &&
4587       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4588     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4589 
4590     // Get the exponent.
4591     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4592 
4593     // Get the significand and build it into a floating-point number with
4594     // exponent of 1.
4595     SDValue X = GetSignificand(DAG, Op1, dl);
4596 
4597     // Different possible minimax approximations of significand in
4598     // floating-point for various degrees of accuracy over [1,2].
4599     SDValue Log2ofMantissa;
4600     if (LimitFloatPrecision <= 6) {
4601       // For floating-point precision of 6:
4602       //
4603       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4604       //
4605       // error 0.0049451742, which is more than 7 bits
4606       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4607                                getF32Constant(DAG, 0xbeb08fe0, dl));
4608       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4609                                getF32Constant(DAG, 0x40019463, dl));
4610       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4611       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4612                                    getF32Constant(DAG, 0x3fd6633d, dl));
4613     } else if (LimitFloatPrecision <= 12) {
4614       // For floating-point precision of 12:
4615       //
4616       //   Log2ofMantissa =
4617       //     -2.51285454f +
4618       //       (4.07009056f +
4619       //         (-2.12067489f +
4620       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4621       //
4622       // error 0.0000876136000, which is better than 13 bits
4623       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4624                                getF32Constant(DAG, 0xbda7262e, dl));
4625       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4626                                getF32Constant(DAG, 0x3f25280b, dl));
4627       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4628       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4629                                getF32Constant(DAG, 0x4007b923, dl));
4630       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4631       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4632                                getF32Constant(DAG, 0x40823e2f, dl));
4633       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4634       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4635                                    getF32Constant(DAG, 0x4020d29c, dl));
4636     } else { // LimitFloatPrecision <= 18
4637       // For floating-point precision of 18:
4638       //
4639       //   Log2ofMantissa =
4640       //     -3.0400495f +
4641       //       (6.1129976f +
4642       //         (-5.3420409f +
4643       //           (3.2865683f +
4644       //             (-1.2669343f +
4645       //               (0.27515199f -
4646       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4647       //
4648       // error 0.0000018516, which is better than 18 bits
4649       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4650                                getF32Constant(DAG, 0xbcd2769e, dl));
4651       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4652                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4653       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4654       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4655                                getF32Constant(DAG, 0x3fa22ae7, dl));
4656       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4657       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4658                                getF32Constant(DAG, 0x40525723, dl));
4659       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4660       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4661                                getF32Constant(DAG, 0x40aaf200, dl));
4662       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4663       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4664                                getF32Constant(DAG, 0x40c39dad, dl));
4665       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4666       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4667                                    getF32Constant(DAG, 0x4042902c, dl));
4668     }
4669 
4670     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4671   }
4672 
4673   // No special expansion.
4674   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4675 }
4676 
4677 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4678 /// limited-precision mode.
4679 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4680                            const TargetLowering &TLI) {
4681   // TODO: What fast-math-flags should be set on the floating-point nodes?
4682 
4683   if (Op.getValueType() == MVT::f32 &&
4684       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4685     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4686 
4687     // Scale the exponent by log10(2) [0.30102999f].
4688     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4689     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4690                                         getF32Constant(DAG, 0x3e9a209a, dl));
4691 
4692     // Get the significand and build it into a floating-point number with
4693     // exponent of 1.
4694     SDValue X = GetSignificand(DAG, Op1, dl);
4695 
4696     SDValue Log10ofMantissa;
4697     if (LimitFloatPrecision <= 6) {
4698       // For floating-point precision of 6:
4699       //
4700       //   Log10ofMantissa =
4701       //     -0.50419619f +
4702       //       (0.60948995f - 0.10380950f * x) * x;
4703       //
4704       // error 0.0014886165, which is 6 bits
4705       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4706                                getF32Constant(DAG, 0xbdd49a13, dl));
4707       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4708                                getF32Constant(DAG, 0x3f1c0789, dl));
4709       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4710       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4711                                     getF32Constant(DAG, 0x3f011300, dl));
4712     } else if (LimitFloatPrecision <= 12) {
4713       // For floating-point precision of 12:
4714       //
4715       //   Log10ofMantissa =
4716       //     -0.64831180f +
4717       //       (0.91751397f +
4718       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4719       //
4720       // error 0.00019228036, which is better than 12 bits
4721       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4722                                getF32Constant(DAG, 0x3d431f31, dl));
4723       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4724                                getF32Constant(DAG, 0x3ea21fb2, dl));
4725       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4726       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4727                                getF32Constant(DAG, 0x3f6ae232, dl));
4728       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4729       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4730                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4731     } else { // LimitFloatPrecision <= 18
4732       // For floating-point precision of 18:
4733       //
4734       //   Log10ofMantissa =
4735       //     -0.84299375f +
4736       //       (1.5327582f +
4737       //         (-1.0688956f +
4738       //           (0.49102474f +
4739       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4740       //
4741       // error 0.0000037995730, which is better than 18 bits
4742       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4743                                getF32Constant(DAG, 0x3c5d51ce, dl));
4744       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4745                                getF32Constant(DAG, 0x3e00685a, dl));
4746       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4747       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4748                                getF32Constant(DAG, 0x3efb6798, dl));
4749       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4750       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4751                                getF32Constant(DAG, 0x3f88d192, dl));
4752       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4753       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4754                                getF32Constant(DAG, 0x3fc4316c, dl));
4755       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4756       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4757                                     getF32Constant(DAG, 0x3f57ce70, dl));
4758     }
4759 
4760     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4761   }
4762 
4763   // No special expansion.
4764   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4765 }
4766 
4767 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4768 /// limited-precision mode.
4769 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4770                           const TargetLowering &TLI) {
4771   if (Op.getValueType() == MVT::f32 &&
4772       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4773     return getLimitedPrecisionExp2(Op, dl, DAG);
4774 
4775   // No special expansion.
4776   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4777 }
4778 
4779 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4780 /// limited-precision mode with x == 10.0f.
4781 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4782                          SelectionDAG &DAG, const TargetLowering &TLI) {
4783   bool IsExp10 = false;
4784   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4785       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4786     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4787       APFloat Ten(10.0f);
4788       IsExp10 = LHSC->isExactlyValue(Ten);
4789     }
4790   }
4791 
4792   // TODO: What fast-math-flags should be set on the FMUL node?
4793   if (IsExp10) {
4794     // Put the exponent in the right bit position for later addition to the
4795     // final result:
4796     //
4797     //   #define LOG2OF10 3.3219281f
4798     //   t0 = Op * LOG2OF10;
4799     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4800                              getF32Constant(DAG, 0x40549a78, dl));
4801     return getLimitedPrecisionExp2(t0, dl, DAG);
4802   }
4803 
4804   // No special expansion.
4805   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4806 }
4807 
4808 /// ExpandPowI - Expand a llvm.powi intrinsic.
4809 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4810                           SelectionDAG &DAG) {
4811   // If RHS is a constant, we can expand this out to a multiplication tree,
4812   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4813   // optimizing for size, we only want to do this if the expansion would produce
4814   // a small number of multiplies, otherwise we do the full expansion.
4815   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4816     // Get the exponent as a positive value.
4817     unsigned Val = RHSC->getSExtValue();
4818     if ((int)Val < 0) Val = -Val;
4819 
4820     // powi(x, 0) -> 1.0
4821     if (Val == 0)
4822       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4823 
4824     const Function &F = DAG.getMachineFunction().getFunction();
4825     if (!F.optForSize() ||
4826         // If optimizing for size, don't insert too many multiplies.
4827         // This inserts up to 5 multiplies.
4828         countPopulation(Val) + Log2_32(Val) < 7) {
4829       // We use the simple binary decomposition method to generate the multiply
4830       // sequence.  There are more optimal ways to do this (for example,
4831       // powi(x,15) generates one more multiply than it should), but this has
4832       // the benefit of being both really simple and much better than a libcall.
4833       SDValue Res;  // Logically starts equal to 1.0
4834       SDValue CurSquare = LHS;
4835       // TODO: Intrinsics should have fast-math-flags that propagate to these
4836       // nodes.
4837       while (Val) {
4838         if (Val & 1) {
4839           if (Res.getNode())
4840             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4841           else
4842             Res = CurSquare;  // 1.0*CurSquare.
4843         }
4844 
4845         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4846                                 CurSquare, CurSquare);
4847         Val >>= 1;
4848       }
4849 
4850       // If the original was negative, invert the result, producing 1/(x*x*x).
4851       if (RHSC->getSExtValue() < 0)
4852         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4853                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4854       return Res;
4855     }
4856   }
4857 
4858   // Otherwise, expand to a libcall.
4859   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4860 }
4861 
4862 // getUnderlyingArgReg - Find underlying register used for a truncated or
4863 // bitcasted argument.
4864 static unsigned getUnderlyingArgReg(const SDValue &N) {
4865   switch (N.getOpcode()) {
4866   case ISD::CopyFromReg:
4867     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4868   case ISD::BITCAST:
4869   case ISD::AssertZext:
4870   case ISD::AssertSext:
4871   case ISD::TRUNCATE:
4872     return getUnderlyingArgReg(N.getOperand(0));
4873   default:
4874     return 0;
4875   }
4876 }
4877 
4878 /// If the DbgValueInst is a dbg_value of a function argument, create the
4879 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4880 /// instruction selection, they will be inserted to the entry BB.
4881 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4882     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4883     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4884   const Argument *Arg = dyn_cast<Argument>(V);
4885   if (!Arg)
4886     return false;
4887 
4888   MachineFunction &MF = DAG.getMachineFunction();
4889   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4890 
4891   bool IsIndirect = false;
4892   Optional<MachineOperand> Op;
4893   // Some arguments' frame index is recorded during argument lowering.
4894   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4895   if (FI != std::numeric_limits<int>::max())
4896     Op = MachineOperand::CreateFI(FI);
4897 
4898   if (!Op && N.getNode()) {
4899     unsigned Reg = getUnderlyingArgReg(N);
4900     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4901       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4902       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4903       if (PR)
4904         Reg = PR;
4905     }
4906     if (Reg) {
4907       Op = MachineOperand::CreateReg(Reg, false);
4908       IsIndirect = IsDbgDeclare;
4909     }
4910   }
4911 
4912   if (!Op && N.getNode())
4913     // Check if frame index is available.
4914     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4915       if (FrameIndexSDNode *FINode =
4916           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4917         Op = MachineOperand::CreateFI(FINode->getIndex());
4918 
4919   if (!Op) {
4920     // Check if ValueMap has reg number.
4921     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4922     if (VMI != FuncInfo.ValueMap.end()) {
4923       const auto &TLI = DAG.getTargetLoweringInfo();
4924       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4925                        V->getType(), isABIRegCopy(V));
4926       if (RFV.occupiesMultipleRegs()) {
4927         unsigned Offset = 0;
4928         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4929           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4930           auto FragmentExpr = DIExpression::createFragmentExpression(
4931               Expr, Offset, RegAndSize.second);
4932           if (!FragmentExpr)
4933             continue;
4934           FuncInfo.ArgDbgValues.push_back(
4935               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4936                       Op->getReg(), Variable, *FragmentExpr));
4937           Offset += RegAndSize.second;
4938         }
4939         return true;
4940       }
4941       Op = MachineOperand::CreateReg(VMI->second, false);
4942       IsIndirect = IsDbgDeclare;
4943     }
4944   }
4945 
4946   if (!Op)
4947     return false;
4948 
4949   assert(Variable->isValidLocationForIntrinsic(DL) &&
4950          "Expected inlined-at fields to agree");
4951   IsIndirect = (Op->isReg()) ? IsIndirect : true;
4952   FuncInfo.ArgDbgValues.push_back(
4953       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4954               *Op, Variable, Expr));
4955 
4956   return true;
4957 }
4958 
4959 /// Return the appropriate SDDbgValue based on N.
4960 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4961                                              DILocalVariable *Variable,
4962                                              DIExpression *Expr,
4963                                              const DebugLoc &dl,
4964                                              unsigned DbgSDNodeOrder) {
4965   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4966     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4967     // stack slot locations as such instead of as indirectly addressed
4968     // locations.
4969     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
4970                                      DbgSDNodeOrder);
4971   }
4972   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4973                          DbgSDNodeOrder);
4974 }
4975 
4976 // VisualStudio defines setjmp as _setjmp
4977 #if defined(_MSC_VER) && defined(setjmp) && \
4978                          !defined(setjmp_undefined_for_msvc)
4979 #  pragma push_macro("setjmp")
4980 #  undef setjmp
4981 #  define setjmp_undefined_for_msvc
4982 #endif
4983 
4984 /// Lower the call to the specified intrinsic function. If we want to emit this
4985 /// as a call to a named external function, return the name. Otherwise, lower it
4986 /// and return null.
4987 const char *
4988 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4989   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4990   SDLoc sdl = getCurSDLoc();
4991   DebugLoc dl = getCurDebugLoc();
4992   SDValue Res;
4993 
4994   switch (Intrinsic) {
4995   default:
4996     // By default, turn this into a target intrinsic node.
4997     visitTargetIntrinsic(I, Intrinsic);
4998     return nullptr;
4999   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5000   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5001   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5002   case Intrinsic::returnaddress:
5003     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5004                              TLI.getPointerTy(DAG.getDataLayout()),
5005                              getValue(I.getArgOperand(0))));
5006     return nullptr;
5007   case Intrinsic::addressofreturnaddress:
5008     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5009                              TLI.getPointerTy(DAG.getDataLayout())));
5010     return nullptr;
5011   case Intrinsic::frameaddress:
5012     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5013                              TLI.getPointerTy(DAG.getDataLayout()),
5014                              getValue(I.getArgOperand(0))));
5015     return nullptr;
5016   case Intrinsic::read_register: {
5017     Value *Reg = I.getArgOperand(0);
5018     SDValue Chain = getRoot();
5019     SDValue RegName =
5020         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5021     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5022     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5023       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5024     setValue(&I, Res);
5025     DAG.setRoot(Res.getValue(1));
5026     return nullptr;
5027   }
5028   case Intrinsic::write_register: {
5029     Value *Reg = I.getArgOperand(0);
5030     Value *RegValue = I.getArgOperand(1);
5031     SDValue Chain = getRoot();
5032     SDValue RegName =
5033         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5034     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5035                             RegName, getValue(RegValue)));
5036     return nullptr;
5037   }
5038   case Intrinsic::setjmp:
5039     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5040   case Intrinsic::longjmp:
5041     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5042   case Intrinsic::memcpy: {
5043     const auto &MCI = cast<MemCpyInst>(I);
5044     SDValue Op1 = getValue(I.getArgOperand(0));
5045     SDValue Op2 = getValue(I.getArgOperand(1));
5046     SDValue Op3 = getValue(I.getArgOperand(2));
5047     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5048     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5049     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5050     unsigned Align = MinAlign(DstAlign, SrcAlign);
5051     bool isVol = MCI.isVolatile();
5052     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5053     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5054     // node.
5055     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5056                                false, isTC,
5057                                MachinePointerInfo(I.getArgOperand(0)),
5058                                MachinePointerInfo(I.getArgOperand(1)));
5059     updateDAGForMaybeTailCall(MC);
5060     return nullptr;
5061   }
5062   case Intrinsic::memset: {
5063     const auto &MSI = cast<MemSetInst>(I);
5064     SDValue Op1 = getValue(I.getArgOperand(0));
5065     SDValue Op2 = getValue(I.getArgOperand(1));
5066     SDValue Op3 = getValue(I.getArgOperand(2));
5067     // @llvm.memset defines 0 and 1 to both mean no alignment.
5068     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5069     bool isVol = MSI.isVolatile();
5070     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5071     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5072                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5073     updateDAGForMaybeTailCall(MS);
5074     return nullptr;
5075   }
5076   case Intrinsic::memmove: {
5077     const auto &MMI = cast<MemMoveInst>(I);
5078     SDValue Op1 = getValue(I.getArgOperand(0));
5079     SDValue Op2 = getValue(I.getArgOperand(1));
5080     SDValue Op3 = getValue(I.getArgOperand(2));
5081     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5082     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5083     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5084     unsigned Align = MinAlign(DstAlign, SrcAlign);
5085     bool isVol = MMI.isVolatile();
5086     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5087     // FIXME: Support passing different dest/src alignments to the memmove DAG
5088     // node.
5089     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5090                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5091                                 MachinePointerInfo(I.getArgOperand(1)));
5092     updateDAGForMaybeTailCall(MM);
5093     return nullptr;
5094   }
5095   case Intrinsic::memcpy_element_unordered_atomic: {
5096     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5097     SDValue Dst = getValue(MI.getRawDest());
5098     SDValue Src = getValue(MI.getRawSource());
5099     SDValue Length = getValue(MI.getLength());
5100 
5101     unsigned DstAlign = MI.getDestAlignment();
5102     unsigned SrcAlign = MI.getSourceAlignment();
5103     Type *LengthTy = MI.getLength()->getType();
5104     unsigned ElemSz = MI.getElementSizeInBytes();
5105     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5106     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5107                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5108                                      MachinePointerInfo(MI.getRawDest()),
5109                                      MachinePointerInfo(MI.getRawSource()));
5110     updateDAGForMaybeTailCall(MC);
5111     return nullptr;
5112   }
5113   case Intrinsic::memmove_element_unordered_atomic: {
5114     auto &MI = cast<AtomicMemMoveInst>(I);
5115     SDValue Dst = getValue(MI.getRawDest());
5116     SDValue Src = getValue(MI.getRawSource());
5117     SDValue Length = getValue(MI.getLength());
5118 
5119     unsigned DstAlign = MI.getDestAlignment();
5120     unsigned SrcAlign = MI.getSourceAlignment();
5121     Type *LengthTy = MI.getLength()->getType();
5122     unsigned ElemSz = MI.getElementSizeInBytes();
5123     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5124     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5125                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5126                                       MachinePointerInfo(MI.getRawDest()),
5127                                       MachinePointerInfo(MI.getRawSource()));
5128     updateDAGForMaybeTailCall(MC);
5129     return nullptr;
5130   }
5131   case Intrinsic::memset_element_unordered_atomic: {
5132     auto &MI = cast<AtomicMemSetInst>(I);
5133     SDValue Dst = getValue(MI.getRawDest());
5134     SDValue Val = getValue(MI.getValue());
5135     SDValue Length = getValue(MI.getLength());
5136 
5137     unsigned DstAlign = MI.getDestAlignment();
5138     Type *LengthTy = MI.getLength()->getType();
5139     unsigned ElemSz = MI.getElementSizeInBytes();
5140     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5141     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5142                                      LengthTy, ElemSz, isTC,
5143                                      MachinePointerInfo(MI.getRawDest()));
5144     updateDAGForMaybeTailCall(MC);
5145     return nullptr;
5146   }
5147   case Intrinsic::dbg_addr:
5148   case Intrinsic::dbg_declare: {
5149     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
5150     DILocalVariable *Variable = DI.getVariable();
5151     DIExpression *Expression = DI.getExpression();
5152     dropDanglingDebugInfo(Variable, Expression);
5153     assert(Variable && "Missing variable");
5154 
5155     // Check if address has undef value.
5156     const Value *Address = DI.getVariableLocation();
5157     if (!Address || isa<UndefValue>(Address) ||
5158         (Address->use_empty() && !isa<Argument>(Address))) {
5159       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5160       return nullptr;
5161     }
5162 
5163     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5164 
5165     // Check if this variable can be described by a frame index, typically
5166     // either as a static alloca or a byval parameter.
5167     int FI = std::numeric_limits<int>::max();
5168     if (const auto *AI =
5169             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5170       if (AI->isStaticAlloca()) {
5171         auto I = FuncInfo.StaticAllocaMap.find(AI);
5172         if (I != FuncInfo.StaticAllocaMap.end())
5173           FI = I->second;
5174       }
5175     } else if (const auto *Arg = dyn_cast<Argument>(
5176                    Address->stripInBoundsConstantOffsets())) {
5177       FI = FuncInfo.getArgumentFrameIndex(Arg);
5178     }
5179 
5180     // llvm.dbg.addr is control dependent and always generates indirect
5181     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5182     // the MachineFunction variable table.
5183     if (FI != std::numeric_limits<int>::max()) {
5184       if (Intrinsic == Intrinsic::dbg_addr) {
5185          SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5186                                                      FI, dl, SDNodeOrder);
5187          DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5188       }
5189       return nullptr;
5190     }
5191 
5192     SDValue &N = NodeMap[Address];
5193     if (!N.getNode() && isa<Argument>(Address))
5194       // Check unused arguments map.
5195       N = UnusedArgNodeMap[Address];
5196     SDDbgValue *SDV;
5197     if (N.getNode()) {
5198       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5199         Address = BCI->getOperand(0);
5200       // Parameters are handled specially.
5201       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5202       if (isParameter && FINode) {
5203         // Byval parameter. We have a frame index at this point.
5204         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5205                                         FINode->getIndex(), dl, SDNodeOrder);
5206       } else if (isa<Argument>(Address)) {
5207         // Address is an argument, so try to emit its dbg value using
5208         // virtual register info from the FuncInfo.ValueMap.
5209         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5210         return nullptr;
5211       } else {
5212         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5213                               true, dl, SDNodeOrder);
5214       }
5215       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5216     } else {
5217       // If Address is an argument then try to emit its dbg value using
5218       // virtual register info from the FuncInfo.ValueMap.
5219       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5220                                     N)) {
5221         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5222       }
5223     }
5224     return nullptr;
5225   }
5226   case Intrinsic::dbg_label: {
5227     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5228     DILabel *Label = DI.getLabel();
5229     assert(Label && "Missing label");
5230 
5231     SDDbgLabel *SDV;
5232     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5233     DAG.AddDbgLabel(SDV);
5234     return nullptr;
5235   }
5236   case Intrinsic::dbg_value: {
5237     const DbgValueInst &DI = cast<DbgValueInst>(I);
5238     assert(DI.getVariable() && "Missing variable");
5239 
5240     DILocalVariable *Variable = DI.getVariable();
5241     DIExpression *Expression = DI.getExpression();
5242     dropDanglingDebugInfo(Variable, Expression);
5243     const Value *V = DI.getValue();
5244     if (!V)
5245       return nullptr;
5246 
5247     SDDbgValue *SDV;
5248     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5249       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5250       DAG.AddDbgValue(SDV, nullptr, false);
5251       return nullptr;
5252     }
5253 
5254     // Do not use getValue() in here; we don't want to generate code at
5255     // this point if it hasn't been done yet.
5256     SDValue N = NodeMap[V];
5257     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5258       N = UnusedArgNodeMap[V];
5259     if (N.getNode()) {
5260       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5261         return nullptr;
5262       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5263       DAG.AddDbgValue(SDV, N.getNode(), false);
5264       return nullptr;
5265     }
5266 
5267     // PHI nodes have already been selected, so we should know which VReg that
5268     // is assigns to already.
5269     if (isa<PHINode>(V)) {
5270       auto VMI = FuncInfo.ValueMap.find(V);
5271       if (VMI != FuncInfo.ValueMap.end()) {
5272         unsigned Reg = VMI->second;
5273         // The PHI node may be split up into several MI PHI nodes (in
5274         // FunctionLoweringInfo::set).
5275         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5276                          V->getType(), false);
5277         if (RFV.occupiesMultipleRegs()) {
5278           unsigned Offset = 0;
5279           unsigned BitsToDescribe = 0;
5280           if (auto VarSize = Variable->getSizeInBits())
5281             BitsToDescribe = *VarSize;
5282           if (auto Fragment = Expression->getFragmentInfo())
5283             BitsToDescribe = Fragment->SizeInBits;
5284           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5285             unsigned RegisterSize = RegAndSize.second;
5286             // Bail out if all bits are described already.
5287             if (Offset >= BitsToDescribe)
5288               break;
5289             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5290                 ? BitsToDescribe - Offset
5291                 : RegisterSize;
5292             auto FragmentExpr = DIExpression::createFragmentExpression(
5293                 Expression, Offset, FragmentSize);
5294             if (!FragmentExpr)
5295                 continue;
5296             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5297                                       false, dl, SDNodeOrder);
5298             DAG.AddDbgValue(SDV, nullptr, false);
5299             Offset += RegisterSize;
5300           }
5301         } else {
5302           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5303                                     SDNodeOrder);
5304           DAG.AddDbgValue(SDV, nullptr, false);
5305         }
5306         return nullptr;
5307       }
5308     }
5309 
5310     // TODO: When we get here we will either drop the dbg.value completely, or
5311     // we try to move it forward by letting it dangle for awhile. So we should
5312     // probably add an extra DbgValue to the DAG here, with a reference to
5313     // "noreg", to indicate that we have lost the debug location for the
5314     // variable.
5315 
5316     if (!V->use_empty() ) {
5317       // Do not call getValue(V) yet, as we don't want to generate code.
5318       // Remember it for later.
5319       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5320       DanglingDebugInfoMap[V].push_back(DDI);
5321       return nullptr;
5322     }
5323 
5324     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5325     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5326     return nullptr;
5327   }
5328 
5329   case Intrinsic::eh_typeid_for: {
5330     // Find the type id for the given typeinfo.
5331     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5332     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5333     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5334     setValue(&I, Res);
5335     return nullptr;
5336   }
5337 
5338   case Intrinsic::eh_return_i32:
5339   case Intrinsic::eh_return_i64:
5340     DAG.getMachineFunction().setCallsEHReturn(true);
5341     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5342                             MVT::Other,
5343                             getControlRoot(),
5344                             getValue(I.getArgOperand(0)),
5345                             getValue(I.getArgOperand(1))));
5346     return nullptr;
5347   case Intrinsic::eh_unwind_init:
5348     DAG.getMachineFunction().setCallsUnwindInit(true);
5349     return nullptr;
5350   case Intrinsic::eh_dwarf_cfa:
5351     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5352                              TLI.getPointerTy(DAG.getDataLayout()),
5353                              getValue(I.getArgOperand(0))));
5354     return nullptr;
5355   case Intrinsic::eh_sjlj_callsite: {
5356     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5357     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5358     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5359     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5360 
5361     MMI.setCurrentCallSite(CI->getZExtValue());
5362     return nullptr;
5363   }
5364   case Intrinsic::eh_sjlj_functioncontext: {
5365     // Get and store the index of the function context.
5366     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5367     AllocaInst *FnCtx =
5368       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5369     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5370     MFI.setFunctionContextIndex(FI);
5371     return nullptr;
5372   }
5373   case Intrinsic::eh_sjlj_setjmp: {
5374     SDValue Ops[2];
5375     Ops[0] = getRoot();
5376     Ops[1] = getValue(I.getArgOperand(0));
5377     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5378                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5379     setValue(&I, Op.getValue(0));
5380     DAG.setRoot(Op.getValue(1));
5381     return nullptr;
5382   }
5383   case Intrinsic::eh_sjlj_longjmp:
5384     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5385                             getRoot(), getValue(I.getArgOperand(0))));
5386     return nullptr;
5387   case Intrinsic::eh_sjlj_setup_dispatch:
5388     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5389                             getRoot()));
5390     return nullptr;
5391   case Intrinsic::masked_gather:
5392     visitMaskedGather(I);
5393     return nullptr;
5394   case Intrinsic::masked_load:
5395     visitMaskedLoad(I);
5396     return nullptr;
5397   case Intrinsic::masked_scatter:
5398     visitMaskedScatter(I);
5399     return nullptr;
5400   case Intrinsic::masked_store:
5401     visitMaskedStore(I);
5402     return nullptr;
5403   case Intrinsic::masked_expandload:
5404     visitMaskedLoad(I, true /* IsExpanding */);
5405     return nullptr;
5406   case Intrinsic::masked_compressstore:
5407     visitMaskedStore(I, true /* IsCompressing */);
5408     return nullptr;
5409   case Intrinsic::x86_mmx_pslli_w:
5410   case Intrinsic::x86_mmx_pslli_d:
5411   case Intrinsic::x86_mmx_pslli_q:
5412   case Intrinsic::x86_mmx_psrli_w:
5413   case Intrinsic::x86_mmx_psrli_d:
5414   case Intrinsic::x86_mmx_psrli_q:
5415   case Intrinsic::x86_mmx_psrai_w:
5416   case Intrinsic::x86_mmx_psrai_d: {
5417     SDValue ShAmt = getValue(I.getArgOperand(1));
5418     if (isa<ConstantSDNode>(ShAmt)) {
5419       visitTargetIntrinsic(I, Intrinsic);
5420       return nullptr;
5421     }
5422     unsigned NewIntrinsic = 0;
5423     EVT ShAmtVT = MVT::v2i32;
5424     switch (Intrinsic) {
5425     case Intrinsic::x86_mmx_pslli_w:
5426       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5427       break;
5428     case Intrinsic::x86_mmx_pslli_d:
5429       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5430       break;
5431     case Intrinsic::x86_mmx_pslli_q:
5432       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5433       break;
5434     case Intrinsic::x86_mmx_psrli_w:
5435       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5436       break;
5437     case Intrinsic::x86_mmx_psrli_d:
5438       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5439       break;
5440     case Intrinsic::x86_mmx_psrli_q:
5441       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5442       break;
5443     case Intrinsic::x86_mmx_psrai_w:
5444       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5445       break;
5446     case Intrinsic::x86_mmx_psrai_d:
5447       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5448       break;
5449     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5450     }
5451 
5452     // The vector shift intrinsics with scalars uses 32b shift amounts but
5453     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5454     // to be zero.
5455     // We must do this early because v2i32 is not a legal type.
5456     SDValue ShOps[2];
5457     ShOps[0] = ShAmt;
5458     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5459     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5460     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5461     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5462     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5463                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5464                        getValue(I.getArgOperand(0)), ShAmt);
5465     setValue(&I, Res);
5466     return nullptr;
5467   }
5468   case Intrinsic::powi:
5469     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5470                             getValue(I.getArgOperand(1)), DAG));
5471     return nullptr;
5472   case Intrinsic::log:
5473     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5474     return nullptr;
5475   case Intrinsic::log2:
5476     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5477     return nullptr;
5478   case Intrinsic::log10:
5479     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5480     return nullptr;
5481   case Intrinsic::exp:
5482     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5483     return nullptr;
5484   case Intrinsic::exp2:
5485     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5486     return nullptr;
5487   case Intrinsic::pow:
5488     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5489                            getValue(I.getArgOperand(1)), DAG, TLI));
5490     return nullptr;
5491   case Intrinsic::sqrt:
5492   case Intrinsic::fabs:
5493   case Intrinsic::sin:
5494   case Intrinsic::cos:
5495   case Intrinsic::floor:
5496   case Intrinsic::ceil:
5497   case Intrinsic::trunc:
5498   case Intrinsic::rint:
5499   case Intrinsic::nearbyint:
5500   case Intrinsic::round:
5501   case Intrinsic::canonicalize: {
5502     unsigned Opcode;
5503     switch (Intrinsic) {
5504     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5505     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5506     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5507     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5508     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5509     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5510     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5511     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5512     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5513     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5514     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5515     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5516     }
5517 
5518     setValue(&I, DAG.getNode(Opcode, sdl,
5519                              getValue(I.getArgOperand(0)).getValueType(),
5520                              getValue(I.getArgOperand(0))));
5521     return nullptr;
5522   }
5523   case Intrinsic::minnum: {
5524     auto VT = getValue(I.getArgOperand(0)).getValueType();
5525     unsigned Opc =
5526         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5527             ? ISD::FMINNAN
5528             : ISD::FMINNUM;
5529     setValue(&I, DAG.getNode(Opc, sdl, VT,
5530                              getValue(I.getArgOperand(0)),
5531                              getValue(I.getArgOperand(1))));
5532     return nullptr;
5533   }
5534   case Intrinsic::maxnum: {
5535     auto VT = getValue(I.getArgOperand(0)).getValueType();
5536     unsigned Opc =
5537         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5538             ? ISD::FMAXNAN
5539             : ISD::FMAXNUM;
5540     setValue(&I, DAG.getNode(Opc, sdl, VT,
5541                              getValue(I.getArgOperand(0)),
5542                              getValue(I.getArgOperand(1))));
5543     return nullptr;
5544   }
5545   case Intrinsic::copysign:
5546     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5547                              getValue(I.getArgOperand(0)).getValueType(),
5548                              getValue(I.getArgOperand(0)),
5549                              getValue(I.getArgOperand(1))));
5550     return nullptr;
5551   case Intrinsic::fma:
5552     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5553                              getValue(I.getArgOperand(0)).getValueType(),
5554                              getValue(I.getArgOperand(0)),
5555                              getValue(I.getArgOperand(1)),
5556                              getValue(I.getArgOperand(2))));
5557     return nullptr;
5558   case Intrinsic::experimental_constrained_fadd:
5559   case Intrinsic::experimental_constrained_fsub:
5560   case Intrinsic::experimental_constrained_fmul:
5561   case Intrinsic::experimental_constrained_fdiv:
5562   case Intrinsic::experimental_constrained_frem:
5563   case Intrinsic::experimental_constrained_fma:
5564   case Intrinsic::experimental_constrained_sqrt:
5565   case Intrinsic::experimental_constrained_pow:
5566   case Intrinsic::experimental_constrained_powi:
5567   case Intrinsic::experimental_constrained_sin:
5568   case Intrinsic::experimental_constrained_cos:
5569   case Intrinsic::experimental_constrained_exp:
5570   case Intrinsic::experimental_constrained_exp2:
5571   case Intrinsic::experimental_constrained_log:
5572   case Intrinsic::experimental_constrained_log10:
5573   case Intrinsic::experimental_constrained_log2:
5574   case Intrinsic::experimental_constrained_rint:
5575   case Intrinsic::experimental_constrained_nearbyint:
5576     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5577     return nullptr;
5578   case Intrinsic::fmuladd: {
5579     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5580     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5581         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5582       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5583                                getValue(I.getArgOperand(0)).getValueType(),
5584                                getValue(I.getArgOperand(0)),
5585                                getValue(I.getArgOperand(1)),
5586                                getValue(I.getArgOperand(2))));
5587     } else {
5588       // TODO: Intrinsic calls should have fast-math-flags.
5589       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5590                                 getValue(I.getArgOperand(0)).getValueType(),
5591                                 getValue(I.getArgOperand(0)),
5592                                 getValue(I.getArgOperand(1)));
5593       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5594                                 getValue(I.getArgOperand(0)).getValueType(),
5595                                 Mul,
5596                                 getValue(I.getArgOperand(2)));
5597       setValue(&I, Add);
5598     }
5599     return nullptr;
5600   }
5601   case Intrinsic::convert_to_fp16:
5602     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5603                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5604                                          getValue(I.getArgOperand(0)),
5605                                          DAG.getTargetConstant(0, sdl,
5606                                                                MVT::i32))));
5607     return nullptr;
5608   case Intrinsic::convert_from_fp16:
5609     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5610                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5611                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5612                                          getValue(I.getArgOperand(0)))));
5613     return nullptr;
5614   case Intrinsic::pcmarker: {
5615     SDValue Tmp = getValue(I.getArgOperand(0));
5616     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5617     return nullptr;
5618   }
5619   case Intrinsic::readcyclecounter: {
5620     SDValue Op = getRoot();
5621     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5622                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5623     setValue(&I, Res);
5624     DAG.setRoot(Res.getValue(1));
5625     return nullptr;
5626   }
5627   case Intrinsic::bitreverse:
5628     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5629                              getValue(I.getArgOperand(0)).getValueType(),
5630                              getValue(I.getArgOperand(0))));
5631     return nullptr;
5632   case Intrinsic::bswap:
5633     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5634                              getValue(I.getArgOperand(0)).getValueType(),
5635                              getValue(I.getArgOperand(0))));
5636     return nullptr;
5637   case Intrinsic::cttz: {
5638     SDValue Arg = getValue(I.getArgOperand(0));
5639     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5640     EVT Ty = Arg.getValueType();
5641     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5642                              sdl, Ty, Arg));
5643     return nullptr;
5644   }
5645   case Intrinsic::ctlz: {
5646     SDValue Arg = getValue(I.getArgOperand(0));
5647     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5648     EVT Ty = Arg.getValueType();
5649     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5650                              sdl, Ty, Arg));
5651     return nullptr;
5652   }
5653   case Intrinsic::ctpop: {
5654     SDValue Arg = getValue(I.getArgOperand(0));
5655     EVT Ty = Arg.getValueType();
5656     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5657     return nullptr;
5658   }
5659   case Intrinsic::fshl:
5660   case Intrinsic::fshr: {
5661     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5662     SDValue X = getValue(I.getArgOperand(0));
5663     SDValue Y = getValue(I.getArgOperand(1));
5664     SDValue Z = getValue(I.getArgOperand(2));
5665     EVT VT = X.getValueType();
5666 
5667     // TODO: When X == Y, this is rotate. Create the node directly if legal.
5668 
5669     // Get the shift amount and inverse shift amount, modulo the bit-width.
5670     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5671     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5672     SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, Z);
5673     SDValue InvShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5674 
5675     // fshl: (X << (Z % BW)) | (Y >> ((BW - Z) % BW))
5676     // fshr: (X << ((BW - Z) % BW)) | (Y >> (Z % BW))
5677     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5678     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5679     SDValue Res = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5680 
5681     // If (Z % BW == 0), then (BW - Z) % BW is also zero, so the result would
5682     // be X | Y. If X == Y (rotate), that's fine. If not, we have to select.
5683     if (X != Y) {
5684       SDValue Zero = DAG.getConstant(0, sdl, VT);
5685       EVT CCVT = MVT::i1;
5686       if (VT.isVector())
5687         CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5688       // For fshl, 0 shift returns the 1st arg (X).
5689       // For fshr, 0 shift returns the 2nd arg (Y).
5690       SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5691       Res = DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Res);
5692     }
5693     setValue(&I, Res);
5694     return nullptr;
5695   }
5696   case Intrinsic::stacksave: {
5697     SDValue Op = getRoot();
5698     Res = DAG.getNode(
5699         ISD::STACKSAVE, sdl,
5700         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5701     setValue(&I, Res);
5702     DAG.setRoot(Res.getValue(1));
5703     return nullptr;
5704   }
5705   case Intrinsic::stackrestore:
5706     Res = getValue(I.getArgOperand(0));
5707     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5708     return nullptr;
5709   case Intrinsic::get_dynamic_area_offset: {
5710     SDValue Op = getRoot();
5711     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5712     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5713     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5714     // target.
5715     if (PtrTy != ResTy)
5716       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5717                          " intrinsic!");
5718     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5719                       Op);
5720     DAG.setRoot(Op);
5721     setValue(&I, Res);
5722     return nullptr;
5723   }
5724   case Intrinsic::stackguard: {
5725     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5726     MachineFunction &MF = DAG.getMachineFunction();
5727     const Module &M = *MF.getFunction().getParent();
5728     SDValue Chain = getRoot();
5729     if (TLI.useLoadStackGuardNode()) {
5730       Res = getLoadStackGuard(DAG, sdl, Chain);
5731     } else {
5732       const Value *Global = TLI.getSDagStackGuard(M);
5733       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5734       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5735                         MachinePointerInfo(Global, 0), Align,
5736                         MachineMemOperand::MOVolatile);
5737     }
5738     if (TLI.useStackGuardXorFP())
5739       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5740     DAG.setRoot(Chain);
5741     setValue(&I, Res);
5742     return nullptr;
5743   }
5744   case Intrinsic::stackprotector: {
5745     // Emit code into the DAG to store the stack guard onto the stack.
5746     MachineFunction &MF = DAG.getMachineFunction();
5747     MachineFrameInfo &MFI = MF.getFrameInfo();
5748     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5749     SDValue Src, Chain = getRoot();
5750 
5751     if (TLI.useLoadStackGuardNode())
5752       Src = getLoadStackGuard(DAG, sdl, Chain);
5753     else
5754       Src = getValue(I.getArgOperand(0));   // The guard's value.
5755 
5756     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5757 
5758     int FI = FuncInfo.StaticAllocaMap[Slot];
5759     MFI.setStackProtectorIndex(FI);
5760 
5761     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5762 
5763     // Store the stack protector onto the stack.
5764     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5765                                                  DAG.getMachineFunction(), FI),
5766                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5767     setValue(&I, Res);
5768     DAG.setRoot(Res);
5769     return nullptr;
5770   }
5771   case Intrinsic::objectsize: {
5772     // If we don't know by now, we're never going to know.
5773     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5774 
5775     assert(CI && "Non-constant type in __builtin_object_size?");
5776 
5777     SDValue Arg = getValue(I.getCalledValue());
5778     EVT Ty = Arg.getValueType();
5779 
5780     if (CI->isZero())
5781       Res = DAG.getConstant(-1ULL, sdl, Ty);
5782     else
5783       Res = DAG.getConstant(0, sdl, Ty);
5784 
5785     setValue(&I, Res);
5786     return nullptr;
5787   }
5788   case Intrinsic::annotation:
5789   case Intrinsic::ptr_annotation:
5790   case Intrinsic::launder_invariant_group:
5791   case Intrinsic::strip_invariant_group:
5792     // Drop the intrinsic, but forward the value
5793     setValue(&I, getValue(I.getOperand(0)));
5794     return nullptr;
5795   case Intrinsic::assume:
5796   case Intrinsic::var_annotation:
5797   case Intrinsic::sideeffect:
5798     // Discard annotate attributes, assumptions, and artificial side-effects.
5799     return nullptr;
5800 
5801   case Intrinsic::codeview_annotation: {
5802     // Emit a label associated with this metadata.
5803     MachineFunction &MF = DAG.getMachineFunction();
5804     MCSymbol *Label =
5805         MF.getMMI().getContext().createTempSymbol("annotation", true);
5806     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5807     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5808     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5809     DAG.setRoot(Res);
5810     return nullptr;
5811   }
5812 
5813   case Intrinsic::init_trampoline: {
5814     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5815 
5816     SDValue Ops[6];
5817     Ops[0] = getRoot();
5818     Ops[1] = getValue(I.getArgOperand(0));
5819     Ops[2] = getValue(I.getArgOperand(1));
5820     Ops[3] = getValue(I.getArgOperand(2));
5821     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5822     Ops[5] = DAG.getSrcValue(F);
5823 
5824     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5825 
5826     DAG.setRoot(Res);
5827     return nullptr;
5828   }
5829   case Intrinsic::adjust_trampoline:
5830     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5831                              TLI.getPointerTy(DAG.getDataLayout()),
5832                              getValue(I.getArgOperand(0))));
5833     return nullptr;
5834   case Intrinsic::gcroot: {
5835     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5836            "only valid in functions with gc specified, enforced by Verifier");
5837     assert(GFI && "implied by previous");
5838     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5839     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5840 
5841     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5842     GFI->addStackRoot(FI->getIndex(), TypeMap);
5843     return nullptr;
5844   }
5845   case Intrinsic::gcread:
5846   case Intrinsic::gcwrite:
5847     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5848   case Intrinsic::flt_rounds:
5849     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5850     return nullptr;
5851 
5852   case Intrinsic::expect:
5853     // Just replace __builtin_expect(exp, c) with EXP.
5854     setValue(&I, getValue(I.getArgOperand(0)));
5855     return nullptr;
5856 
5857   case Intrinsic::debugtrap:
5858   case Intrinsic::trap: {
5859     StringRef TrapFuncName =
5860         I.getAttributes()
5861             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5862             .getValueAsString();
5863     if (TrapFuncName.empty()) {
5864       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5865         ISD::TRAP : ISD::DEBUGTRAP;
5866       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5867       return nullptr;
5868     }
5869     TargetLowering::ArgListTy Args;
5870 
5871     TargetLowering::CallLoweringInfo CLI(DAG);
5872     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5873         CallingConv::C, I.getType(),
5874         DAG.getExternalSymbol(TrapFuncName.data(),
5875                               TLI.getPointerTy(DAG.getDataLayout())),
5876         std::move(Args));
5877 
5878     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5879     DAG.setRoot(Result.second);
5880     return nullptr;
5881   }
5882 
5883   case Intrinsic::uadd_with_overflow:
5884   case Intrinsic::sadd_with_overflow:
5885   case Intrinsic::usub_with_overflow:
5886   case Intrinsic::ssub_with_overflow:
5887   case Intrinsic::umul_with_overflow:
5888   case Intrinsic::smul_with_overflow: {
5889     ISD::NodeType Op;
5890     switch (Intrinsic) {
5891     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5892     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5893     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5894     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5895     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5896     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5897     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5898     }
5899     SDValue Op1 = getValue(I.getArgOperand(0));
5900     SDValue Op2 = getValue(I.getArgOperand(1));
5901 
5902     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5903     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5904     return nullptr;
5905   }
5906   case Intrinsic::prefetch: {
5907     SDValue Ops[5];
5908     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5909     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5910     Ops[0] = DAG.getRoot();
5911     Ops[1] = getValue(I.getArgOperand(0));
5912     Ops[2] = getValue(I.getArgOperand(1));
5913     Ops[3] = getValue(I.getArgOperand(2));
5914     Ops[4] = getValue(I.getArgOperand(3));
5915     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5916                                              DAG.getVTList(MVT::Other), Ops,
5917                                              EVT::getIntegerVT(*Context, 8),
5918                                              MachinePointerInfo(I.getArgOperand(0)),
5919                                              0, /* align */
5920                                              Flags);
5921 
5922     // Chain the prefetch in parallell with any pending loads, to stay out of
5923     // the way of later optimizations.
5924     PendingLoads.push_back(Result);
5925     Result = getRoot();
5926     DAG.setRoot(Result);
5927     return nullptr;
5928   }
5929   case Intrinsic::lifetime_start:
5930   case Intrinsic::lifetime_end: {
5931     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5932     // Stack coloring is not enabled in O0, discard region information.
5933     if (TM.getOptLevel() == CodeGenOpt::None)
5934       return nullptr;
5935 
5936     SmallVector<Value *, 4> Allocas;
5937     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5938 
5939     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5940            E = Allocas.end(); Object != E; ++Object) {
5941       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5942 
5943       // Could not find an Alloca.
5944       if (!LifetimeObject)
5945         continue;
5946 
5947       // First check that the Alloca is static, otherwise it won't have a
5948       // valid frame index.
5949       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5950       if (SI == FuncInfo.StaticAllocaMap.end())
5951         return nullptr;
5952 
5953       int FI = SI->second;
5954 
5955       SDValue Ops[2];
5956       Ops[0] = getRoot();
5957       Ops[1] =
5958           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5959       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5960 
5961       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5962       DAG.setRoot(Res);
5963     }
5964     return nullptr;
5965   }
5966   case Intrinsic::invariant_start:
5967     // Discard region information.
5968     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5969     return nullptr;
5970   case Intrinsic::invariant_end:
5971     // Discard region information.
5972     return nullptr;
5973   case Intrinsic::clear_cache:
5974     return TLI.getClearCacheBuiltinName();
5975   case Intrinsic::donothing:
5976     // ignore
5977     return nullptr;
5978   case Intrinsic::experimental_stackmap:
5979     visitStackmap(I);
5980     return nullptr;
5981   case Intrinsic::experimental_patchpoint_void:
5982   case Intrinsic::experimental_patchpoint_i64:
5983     visitPatchpoint(&I);
5984     return nullptr;
5985   case Intrinsic::experimental_gc_statepoint:
5986     LowerStatepoint(ImmutableStatepoint(&I));
5987     return nullptr;
5988   case Intrinsic::experimental_gc_result:
5989     visitGCResult(cast<GCResultInst>(I));
5990     return nullptr;
5991   case Intrinsic::experimental_gc_relocate:
5992     visitGCRelocate(cast<GCRelocateInst>(I));
5993     return nullptr;
5994   case Intrinsic::instrprof_increment:
5995     llvm_unreachable("instrprof failed to lower an increment");
5996   case Intrinsic::instrprof_value_profile:
5997     llvm_unreachable("instrprof failed to lower a value profiling call");
5998   case Intrinsic::localescape: {
5999     MachineFunction &MF = DAG.getMachineFunction();
6000     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6001 
6002     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6003     // is the same on all targets.
6004     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6005       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6006       if (isa<ConstantPointerNull>(Arg))
6007         continue; // Skip null pointers. They represent a hole in index space.
6008       AllocaInst *Slot = cast<AllocaInst>(Arg);
6009       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6010              "can only escape static allocas");
6011       int FI = FuncInfo.StaticAllocaMap[Slot];
6012       MCSymbol *FrameAllocSym =
6013           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6014               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6015       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6016               TII->get(TargetOpcode::LOCAL_ESCAPE))
6017           .addSym(FrameAllocSym)
6018           .addFrameIndex(FI);
6019     }
6020 
6021     return nullptr;
6022   }
6023 
6024   case Intrinsic::localrecover: {
6025     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6026     MachineFunction &MF = DAG.getMachineFunction();
6027     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6028 
6029     // Get the symbol that defines the frame offset.
6030     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6031     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6032     unsigned IdxVal =
6033         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6034     MCSymbol *FrameAllocSym =
6035         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6036             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6037 
6038     // Create a MCSymbol for the label to avoid any target lowering
6039     // that would make this PC relative.
6040     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6041     SDValue OffsetVal =
6042         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6043 
6044     // Add the offset to the FP.
6045     Value *FP = I.getArgOperand(1);
6046     SDValue FPVal = getValue(FP);
6047     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6048     setValue(&I, Add);
6049 
6050     return nullptr;
6051   }
6052 
6053   case Intrinsic::eh_exceptionpointer:
6054   case Intrinsic::eh_exceptioncode: {
6055     // Get the exception pointer vreg, copy from it, and resize it to fit.
6056     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6057     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6058     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6059     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6060     SDValue N =
6061         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6062     if (Intrinsic == Intrinsic::eh_exceptioncode)
6063       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6064     setValue(&I, N);
6065     return nullptr;
6066   }
6067   case Intrinsic::xray_customevent: {
6068     // Here we want to make sure that the intrinsic behaves as if it has a
6069     // specific calling convention, and only for x86_64.
6070     // FIXME: Support other platforms later.
6071     const auto &Triple = DAG.getTarget().getTargetTriple();
6072     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6073       return nullptr;
6074 
6075     SDLoc DL = getCurSDLoc();
6076     SmallVector<SDValue, 8> Ops;
6077 
6078     // We want to say that we always want the arguments in registers.
6079     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6080     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6081     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6082     SDValue Chain = getRoot();
6083     Ops.push_back(LogEntryVal);
6084     Ops.push_back(StrSizeVal);
6085     Ops.push_back(Chain);
6086 
6087     // We need to enforce the calling convention for the callsite, so that
6088     // argument ordering is enforced correctly, and that register allocation can
6089     // see that some registers may be assumed clobbered and have to preserve
6090     // them across calls to the intrinsic.
6091     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6092                                            DL, NodeTys, Ops);
6093     SDValue patchableNode = SDValue(MN, 0);
6094     DAG.setRoot(patchableNode);
6095     setValue(&I, patchableNode);
6096     return nullptr;
6097   }
6098   case Intrinsic::xray_typedevent: {
6099     // Here we want to make sure that the intrinsic behaves as if it has a
6100     // specific calling convention, and only for x86_64.
6101     // FIXME: Support other platforms later.
6102     const auto &Triple = DAG.getTarget().getTargetTriple();
6103     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6104       return nullptr;
6105 
6106     SDLoc DL = getCurSDLoc();
6107     SmallVector<SDValue, 8> Ops;
6108 
6109     // We want to say that we always want the arguments in registers.
6110     // It's unclear to me how manipulating the selection DAG here forces callers
6111     // to provide arguments in registers instead of on the stack.
6112     SDValue LogTypeId = getValue(I.getArgOperand(0));
6113     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6114     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6115     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6116     SDValue Chain = getRoot();
6117     Ops.push_back(LogTypeId);
6118     Ops.push_back(LogEntryVal);
6119     Ops.push_back(StrSizeVal);
6120     Ops.push_back(Chain);
6121 
6122     // We need to enforce the calling convention for the callsite, so that
6123     // argument ordering is enforced correctly, and that register allocation can
6124     // see that some registers may be assumed clobbered and have to preserve
6125     // them across calls to the intrinsic.
6126     MachineSDNode *MN = DAG.getMachineNode(
6127         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6128     SDValue patchableNode = SDValue(MN, 0);
6129     DAG.setRoot(patchableNode);
6130     setValue(&I, patchableNode);
6131     return nullptr;
6132   }
6133   case Intrinsic::experimental_deoptimize:
6134     LowerDeoptimizeCall(&I);
6135     return nullptr;
6136 
6137   case Intrinsic::experimental_vector_reduce_fadd:
6138   case Intrinsic::experimental_vector_reduce_fmul:
6139   case Intrinsic::experimental_vector_reduce_add:
6140   case Intrinsic::experimental_vector_reduce_mul:
6141   case Intrinsic::experimental_vector_reduce_and:
6142   case Intrinsic::experimental_vector_reduce_or:
6143   case Intrinsic::experimental_vector_reduce_xor:
6144   case Intrinsic::experimental_vector_reduce_smax:
6145   case Intrinsic::experimental_vector_reduce_smin:
6146   case Intrinsic::experimental_vector_reduce_umax:
6147   case Intrinsic::experimental_vector_reduce_umin:
6148   case Intrinsic::experimental_vector_reduce_fmax:
6149   case Intrinsic::experimental_vector_reduce_fmin:
6150     visitVectorReduce(I, Intrinsic);
6151     return nullptr;
6152 
6153   case Intrinsic::icall_branch_funnel: {
6154     SmallVector<SDValue, 16> Ops;
6155     Ops.push_back(DAG.getRoot());
6156     Ops.push_back(getValue(I.getArgOperand(0)));
6157 
6158     int64_t Offset;
6159     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6160         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6161     if (!Base)
6162       report_fatal_error(
6163           "llvm.icall.branch.funnel operand must be a GlobalValue");
6164     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6165 
6166     struct BranchFunnelTarget {
6167       int64_t Offset;
6168       SDValue Target;
6169     };
6170     SmallVector<BranchFunnelTarget, 8> Targets;
6171 
6172     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6173       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6174           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6175       if (ElemBase != Base)
6176         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6177                            "to the same GlobalValue");
6178 
6179       SDValue Val = getValue(I.getArgOperand(Op + 1));
6180       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6181       if (!GA)
6182         report_fatal_error(
6183             "llvm.icall.branch.funnel operand must be a GlobalValue");
6184       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6185                                      GA->getGlobal(), getCurSDLoc(),
6186                                      Val.getValueType(), GA->getOffset())});
6187     }
6188     llvm::sort(Targets.begin(), Targets.end(),
6189                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6190                  return T1.Offset < T2.Offset;
6191                });
6192 
6193     for (auto &T : Targets) {
6194       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6195       Ops.push_back(T.Target);
6196     }
6197 
6198     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6199                                  getCurSDLoc(), MVT::Other, Ops),
6200               0);
6201     DAG.setRoot(N);
6202     setValue(&I, N);
6203     HasTailCall = true;
6204     return nullptr;
6205   }
6206 
6207   case Intrinsic::wasm_landingpad_index: {
6208     // TODO store landing pad index in a map, which will be used when generating
6209     // LSDA information
6210     return nullptr;
6211   }
6212   }
6213 }
6214 
6215 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6216     const ConstrainedFPIntrinsic &FPI) {
6217   SDLoc sdl = getCurSDLoc();
6218   unsigned Opcode;
6219   switch (FPI.getIntrinsicID()) {
6220   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6221   case Intrinsic::experimental_constrained_fadd:
6222     Opcode = ISD::STRICT_FADD;
6223     break;
6224   case Intrinsic::experimental_constrained_fsub:
6225     Opcode = ISD::STRICT_FSUB;
6226     break;
6227   case Intrinsic::experimental_constrained_fmul:
6228     Opcode = ISD::STRICT_FMUL;
6229     break;
6230   case Intrinsic::experimental_constrained_fdiv:
6231     Opcode = ISD::STRICT_FDIV;
6232     break;
6233   case Intrinsic::experimental_constrained_frem:
6234     Opcode = ISD::STRICT_FREM;
6235     break;
6236   case Intrinsic::experimental_constrained_fma:
6237     Opcode = ISD::STRICT_FMA;
6238     break;
6239   case Intrinsic::experimental_constrained_sqrt:
6240     Opcode = ISD::STRICT_FSQRT;
6241     break;
6242   case Intrinsic::experimental_constrained_pow:
6243     Opcode = ISD::STRICT_FPOW;
6244     break;
6245   case Intrinsic::experimental_constrained_powi:
6246     Opcode = ISD::STRICT_FPOWI;
6247     break;
6248   case Intrinsic::experimental_constrained_sin:
6249     Opcode = ISD::STRICT_FSIN;
6250     break;
6251   case Intrinsic::experimental_constrained_cos:
6252     Opcode = ISD::STRICT_FCOS;
6253     break;
6254   case Intrinsic::experimental_constrained_exp:
6255     Opcode = ISD::STRICT_FEXP;
6256     break;
6257   case Intrinsic::experimental_constrained_exp2:
6258     Opcode = ISD::STRICT_FEXP2;
6259     break;
6260   case Intrinsic::experimental_constrained_log:
6261     Opcode = ISD::STRICT_FLOG;
6262     break;
6263   case Intrinsic::experimental_constrained_log10:
6264     Opcode = ISD::STRICT_FLOG10;
6265     break;
6266   case Intrinsic::experimental_constrained_log2:
6267     Opcode = ISD::STRICT_FLOG2;
6268     break;
6269   case Intrinsic::experimental_constrained_rint:
6270     Opcode = ISD::STRICT_FRINT;
6271     break;
6272   case Intrinsic::experimental_constrained_nearbyint:
6273     Opcode = ISD::STRICT_FNEARBYINT;
6274     break;
6275   }
6276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6277   SDValue Chain = getRoot();
6278   SmallVector<EVT, 4> ValueVTs;
6279   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6280   ValueVTs.push_back(MVT::Other); // Out chain
6281 
6282   SDVTList VTs = DAG.getVTList(ValueVTs);
6283   SDValue Result;
6284   if (FPI.isUnaryOp())
6285     Result = DAG.getNode(Opcode, sdl, VTs,
6286                          { Chain, getValue(FPI.getArgOperand(0)) });
6287   else if (FPI.isTernaryOp())
6288     Result = DAG.getNode(Opcode, sdl, VTs,
6289                          { Chain, getValue(FPI.getArgOperand(0)),
6290                                   getValue(FPI.getArgOperand(1)),
6291                                   getValue(FPI.getArgOperand(2)) });
6292   else
6293     Result = DAG.getNode(Opcode, sdl, VTs,
6294                          { Chain, getValue(FPI.getArgOperand(0)),
6295                            getValue(FPI.getArgOperand(1))  });
6296 
6297   assert(Result.getNode()->getNumValues() == 2);
6298   SDValue OutChain = Result.getValue(1);
6299   DAG.setRoot(OutChain);
6300   SDValue FPResult = Result.getValue(0);
6301   setValue(&FPI, FPResult);
6302 }
6303 
6304 std::pair<SDValue, SDValue>
6305 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6306                                     const BasicBlock *EHPadBB) {
6307   MachineFunction &MF = DAG.getMachineFunction();
6308   MachineModuleInfo &MMI = MF.getMMI();
6309   MCSymbol *BeginLabel = nullptr;
6310 
6311   if (EHPadBB) {
6312     // Insert a label before the invoke call to mark the try range.  This can be
6313     // used to detect deletion of the invoke via the MachineModuleInfo.
6314     BeginLabel = MMI.getContext().createTempSymbol();
6315 
6316     // For SjLj, keep track of which landing pads go with which invokes
6317     // so as to maintain the ordering of pads in the LSDA.
6318     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6319     if (CallSiteIndex) {
6320       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6321       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6322 
6323       // Now that the call site is handled, stop tracking it.
6324       MMI.setCurrentCallSite(0);
6325     }
6326 
6327     // Both PendingLoads and PendingExports must be flushed here;
6328     // this call might not return.
6329     (void)getRoot();
6330     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6331 
6332     CLI.setChain(getRoot());
6333   }
6334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6335   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6336 
6337   assert((CLI.IsTailCall || Result.second.getNode()) &&
6338          "Non-null chain expected with non-tail call!");
6339   assert((Result.second.getNode() || !Result.first.getNode()) &&
6340          "Null value expected with tail call!");
6341 
6342   if (!Result.second.getNode()) {
6343     // As a special case, a null chain means that a tail call has been emitted
6344     // and the DAG root is already updated.
6345     HasTailCall = true;
6346 
6347     // Since there's no actual continuation from this block, nothing can be
6348     // relying on us setting vregs for them.
6349     PendingExports.clear();
6350   } else {
6351     DAG.setRoot(Result.second);
6352   }
6353 
6354   if (EHPadBB) {
6355     // Insert a label at the end of the invoke call to mark the try range.  This
6356     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6357     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6358     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6359 
6360     // Inform MachineModuleInfo of range.
6361     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6362     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6363     // actually use outlined funclets and their LSDA info style.
6364     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6365       assert(CLI.CS);
6366       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6367       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6368                                 BeginLabel, EndLabel);
6369     } else {
6370       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6371     }
6372   }
6373 
6374   return Result;
6375 }
6376 
6377 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6378                                       bool isTailCall,
6379                                       const BasicBlock *EHPadBB) {
6380   auto &DL = DAG.getDataLayout();
6381   FunctionType *FTy = CS.getFunctionType();
6382   Type *RetTy = CS.getType();
6383 
6384   TargetLowering::ArgListTy Args;
6385   Args.reserve(CS.arg_size());
6386 
6387   const Value *SwiftErrorVal = nullptr;
6388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6389 
6390   // We can't tail call inside a function with a swifterror argument. Lowering
6391   // does not support this yet. It would have to move into the swifterror
6392   // register before the call.
6393   auto *Caller = CS.getInstruction()->getParent()->getParent();
6394   if (TLI.supportSwiftError() &&
6395       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6396     isTailCall = false;
6397 
6398   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6399        i != e; ++i) {
6400     TargetLowering::ArgListEntry Entry;
6401     const Value *V = *i;
6402 
6403     // Skip empty types
6404     if (V->getType()->isEmptyTy())
6405       continue;
6406 
6407     SDValue ArgNode = getValue(V);
6408     Entry.Node = ArgNode; Entry.Ty = V->getType();
6409 
6410     Entry.setAttributes(&CS, i - CS.arg_begin());
6411 
6412     // Use swifterror virtual register as input to the call.
6413     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6414       SwiftErrorVal = V;
6415       // We find the virtual register for the actual swifterror argument.
6416       // Instead of using the Value, we use the virtual register instead.
6417       Entry.Node = DAG.getRegister(FuncInfo
6418                                        .getOrCreateSwiftErrorVRegUseAt(
6419                                            CS.getInstruction(), FuncInfo.MBB, V)
6420                                        .first,
6421                                    EVT(TLI.getPointerTy(DL)));
6422     }
6423 
6424     Args.push_back(Entry);
6425 
6426     // If we have an explicit sret argument that is an Instruction, (i.e., it
6427     // might point to function-local memory), we can't meaningfully tail-call.
6428     if (Entry.IsSRet && isa<Instruction>(V))
6429       isTailCall = false;
6430   }
6431 
6432   // Check if target-independent constraints permit a tail call here.
6433   // Target-dependent constraints are checked within TLI->LowerCallTo.
6434   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6435     isTailCall = false;
6436 
6437   // Disable tail calls if there is an swifterror argument. Targets have not
6438   // been updated to support tail calls.
6439   if (TLI.supportSwiftError() && SwiftErrorVal)
6440     isTailCall = false;
6441 
6442   TargetLowering::CallLoweringInfo CLI(DAG);
6443   CLI.setDebugLoc(getCurSDLoc())
6444       .setChain(getRoot())
6445       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6446       .setTailCall(isTailCall)
6447       .setConvergent(CS.isConvergent());
6448   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6449 
6450   if (Result.first.getNode()) {
6451     const Instruction *Inst = CS.getInstruction();
6452     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6453     setValue(Inst, Result.first);
6454   }
6455 
6456   // The last element of CLI.InVals has the SDValue for swifterror return.
6457   // Here we copy it to a virtual register and update SwiftErrorMap for
6458   // book-keeping.
6459   if (SwiftErrorVal && TLI.supportSwiftError()) {
6460     // Get the last element of InVals.
6461     SDValue Src = CLI.InVals.back();
6462     unsigned VReg; bool CreatedVReg;
6463     std::tie(VReg, CreatedVReg) =
6464         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6465     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6466     // We update the virtual register for the actual swifterror argument.
6467     if (CreatedVReg)
6468       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6469     DAG.setRoot(CopyNode);
6470   }
6471 }
6472 
6473 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6474                              SelectionDAGBuilder &Builder) {
6475   // Check to see if this load can be trivially constant folded, e.g. if the
6476   // input is from a string literal.
6477   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6478     // Cast pointer to the type we really want to load.
6479     Type *LoadTy =
6480         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6481     if (LoadVT.isVector())
6482       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6483 
6484     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6485                                          PointerType::getUnqual(LoadTy));
6486 
6487     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6488             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6489       return Builder.getValue(LoadCst);
6490   }
6491 
6492   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6493   // still constant memory, the input chain can be the entry node.
6494   SDValue Root;
6495   bool ConstantMemory = false;
6496 
6497   // Do not serialize (non-volatile) loads of constant memory with anything.
6498   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6499     Root = Builder.DAG.getEntryNode();
6500     ConstantMemory = true;
6501   } else {
6502     // Do not serialize non-volatile loads against each other.
6503     Root = Builder.DAG.getRoot();
6504   }
6505 
6506   SDValue Ptr = Builder.getValue(PtrVal);
6507   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6508                                         Ptr, MachinePointerInfo(PtrVal),
6509                                         /* Alignment = */ 1);
6510 
6511   if (!ConstantMemory)
6512     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6513   return LoadVal;
6514 }
6515 
6516 /// Record the value for an instruction that produces an integer result,
6517 /// converting the type where necessary.
6518 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6519                                                   SDValue Value,
6520                                                   bool IsSigned) {
6521   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6522                                                     I.getType(), true);
6523   if (IsSigned)
6524     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6525   else
6526     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6527   setValue(&I, Value);
6528 }
6529 
6530 /// See if we can lower a memcmp call into an optimized form. If so, return
6531 /// true and lower it. Otherwise return false, and it will be lowered like a
6532 /// normal call.
6533 /// The caller already checked that \p I calls the appropriate LibFunc with a
6534 /// correct prototype.
6535 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6536   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6537   const Value *Size = I.getArgOperand(2);
6538   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6539   if (CSize && CSize->getZExtValue() == 0) {
6540     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6541                                                           I.getType(), true);
6542     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6543     return true;
6544   }
6545 
6546   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6547   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6548       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6549       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6550   if (Res.first.getNode()) {
6551     processIntegerCallValue(I, Res.first, true);
6552     PendingLoads.push_back(Res.second);
6553     return true;
6554   }
6555 
6556   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6557   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6558   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6559     return false;
6560 
6561   // If the target has a fast compare for the given size, it will return a
6562   // preferred load type for that size. Require that the load VT is legal and
6563   // that the target supports unaligned loads of that type. Otherwise, return
6564   // INVALID.
6565   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6566     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6567     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6568     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6569       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6570       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6571       // TODO: Check alignment of src and dest ptrs.
6572       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6573       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6574       if (!TLI.isTypeLegal(LVT) ||
6575           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6576           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6577         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6578     }
6579 
6580     return LVT;
6581   };
6582 
6583   // This turns into unaligned loads. We only do this if the target natively
6584   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6585   // we'll only produce a small number of byte loads.
6586   MVT LoadVT;
6587   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6588   switch (NumBitsToCompare) {
6589   default:
6590     return false;
6591   case 16:
6592     LoadVT = MVT::i16;
6593     break;
6594   case 32:
6595     LoadVT = MVT::i32;
6596     break;
6597   case 64:
6598   case 128:
6599   case 256:
6600     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6601     break;
6602   }
6603 
6604   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6605     return false;
6606 
6607   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6608   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6609 
6610   // Bitcast to a wide integer type if the loads are vectors.
6611   if (LoadVT.isVector()) {
6612     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6613     LoadL = DAG.getBitcast(CmpVT, LoadL);
6614     LoadR = DAG.getBitcast(CmpVT, LoadR);
6615   }
6616 
6617   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6618   processIntegerCallValue(I, Cmp, false);
6619   return true;
6620 }
6621 
6622 /// See if we can lower a memchr call into an optimized form. If so, return
6623 /// true and lower it. Otherwise return false, and it will be lowered like a
6624 /// normal call.
6625 /// The caller already checked that \p I calls the appropriate LibFunc with a
6626 /// correct prototype.
6627 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6628   const Value *Src = I.getArgOperand(0);
6629   const Value *Char = I.getArgOperand(1);
6630   const Value *Length = I.getArgOperand(2);
6631 
6632   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6633   std::pair<SDValue, SDValue> Res =
6634     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6635                                 getValue(Src), getValue(Char), getValue(Length),
6636                                 MachinePointerInfo(Src));
6637   if (Res.first.getNode()) {
6638     setValue(&I, Res.first);
6639     PendingLoads.push_back(Res.second);
6640     return true;
6641   }
6642 
6643   return false;
6644 }
6645 
6646 /// See if we can lower a mempcpy call into an optimized form. If so, return
6647 /// true and lower it. Otherwise return false, and it will be lowered like a
6648 /// normal call.
6649 /// The caller already checked that \p I calls the appropriate LibFunc with a
6650 /// correct prototype.
6651 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6652   SDValue Dst = getValue(I.getArgOperand(0));
6653   SDValue Src = getValue(I.getArgOperand(1));
6654   SDValue Size = getValue(I.getArgOperand(2));
6655 
6656   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6657   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6658   unsigned Align = std::min(DstAlign, SrcAlign);
6659   if (Align == 0) // Alignment of one or both could not be inferred.
6660     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6661 
6662   bool isVol = false;
6663   SDLoc sdl = getCurSDLoc();
6664 
6665   // In the mempcpy context we need to pass in a false value for isTailCall
6666   // because the return pointer needs to be adjusted by the size of
6667   // the copied memory.
6668   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6669                              false, /*isTailCall=*/false,
6670                              MachinePointerInfo(I.getArgOperand(0)),
6671                              MachinePointerInfo(I.getArgOperand(1)));
6672   assert(MC.getNode() != nullptr &&
6673          "** memcpy should not be lowered as TailCall in mempcpy context **");
6674   DAG.setRoot(MC);
6675 
6676   // Check if Size needs to be truncated or extended.
6677   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6678 
6679   // Adjust return pointer to point just past the last dst byte.
6680   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6681                                     Dst, Size);
6682   setValue(&I, DstPlusSize);
6683   return true;
6684 }
6685 
6686 /// See if we can lower a strcpy call into an optimized form.  If so, return
6687 /// true and lower it, otherwise return false and it will be lowered like a
6688 /// normal call.
6689 /// The caller already checked that \p I calls the appropriate LibFunc with a
6690 /// correct prototype.
6691 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6692   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6693 
6694   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6695   std::pair<SDValue, SDValue> Res =
6696     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6697                                 getValue(Arg0), getValue(Arg1),
6698                                 MachinePointerInfo(Arg0),
6699                                 MachinePointerInfo(Arg1), isStpcpy);
6700   if (Res.first.getNode()) {
6701     setValue(&I, Res.first);
6702     DAG.setRoot(Res.second);
6703     return true;
6704   }
6705 
6706   return false;
6707 }
6708 
6709 /// See if we can lower a strcmp call into an optimized form.  If so, return
6710 /// true and lower it, otherwise return false and it will be lowered like a
6711 /// normal call.
6712 /// The caller already checked that \p I calls the appropriate LibFunc with a
6713 /// correct prototype.
6714 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6715   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6716 
6717   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6718   std::pair<SDValue, SDValue> Res =
6719     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6720                                 getValue(Arg0), getValue(Arg1),
6721                                 MachinePointerInfo(Arg0),
6722                                 MachinePointerInfo(Arg1));
6723   if (Res.first.getNode()) {
6724     processIntegerCallValue(I, Res.first, true);
6725     PendingLoads.push_back(Res.second);
6726     return true;
6727   }
6728 
6729   return false;
6730 }
6731 
6732 /// See if we can lower a strlen call into an optimized form.  If so, return
6733 /// true and lower it, otherwise return false and it will be lowered like a
6734 /// normal call.
6735 /// The caller already checked that \p I calls the appropriate LibFunc with a
6736 /// correct prototype.
6737 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6738   const Value *Arg0 = I.getArgOperand(0);
6739 
6740   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6741   std::pair<SDValue, SDValue> Res =
6742     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6743                                 getValue(Arg0), MachinePointerInfo(Arg0));
6744   if (Res.first.getNode()) {
6745     processIntegerCallValue(I, Res.first, false);
6746     PendingLoads.push_back(Res.second);
6747     return true;
6748   }
6749 
6750   return false;
6751 }
6752 
6753 /// See if we can lower a strnlen call into an optimized form.  If so, return
6754 /// true and lower it, otherwise return false and it will be lowered like a
6755 /// normal call.
6756 /// The caller already checked that \p I calls the appropriate LibFunc with a
6757 /// correct prototype.
6758 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6759   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6760 
6761   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6762   std::pair<SDValue, SDValue> Res =
6763     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6764                                  getValue(Arg0), getValue(Arg1),
6765                                  MachinePointerInfo(Arg0));
6766   if (Res.first.getNode()) {
6767     processIntegerCallValue(I, Res.first, false);
6768     PendingLoads.push_back(Res.second);
6769     return true;
6770   }
6771 
6772   return false;
6773 }
6774 
6775 /// See if we can lower a unary floating-point operation into an SDNode with
6776 /// the specified Opcode.  If so, return true and lower it, otherwise return
6777 /// false and it will be lowered like a normal call.
6778 /// The caller already checked that \p I calls the appropriate LibFunc with a
6779 /// correct prototype.
6780 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6781                                               unsigned Opcode) {
6782   // We already checked this call's prototype; verify it doesn't modify errno.
6783   if (!I.onlyReadsMemory())
6784     return false;
6785 
6786   SDValue Tmp = getValue(I.getArgOperand(0));
6787   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6788   return true;
6789 }
6790 
6791 /// See if we can lower a binary floating-point operation into an SDNode with
6792 /// the specified Opcode. If so, return true and lower it. Otherwise return
6793 /// false, and it will be lowered like a normal call.
6794 /// The caller already checked that \p I calls the appropriate LibFunc with a
6795 /// correct prototype.
6796 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6797                                                unsigned Opcode) {
6798   // We already checked this call's prototype; verify it doesn't modify errno.
6799   if (!I.onlyReadsMemory())
6800     return false;
6801 
6802   SDValue Tmp0 = getValue(I.getArgOperand(0));
6803   SDValue Tmp1 = getValue(I.getArgOperand(1));
6804   EVT VT = Tmp0.getValueType();
6805   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6806   return true;
6807 }
6808 
6809 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6810   // Handle inline assembly differently.
6811   if (isa<InlineAsm>(I.getCalledValue())) {
6812     visitInlineAsm(&I);
6813     return;
6814   }
6815 
6816   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6817   computeUsesVAFloatArgument(I, MMI);
6818 
6819   const char *RenameFn = nullptr;
6820   if (Function *F = I.getCalledFunction()) {
6821     if (F->isDeclaration()) {
6822       // Is this an LLVM intrinsic or a target-specific intrinsic?
6823       unsigned IID = F->getIntrinsicID();
6824       if (!IID)
6825         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6826           IID = II->getIntrinsicID(F);
6827 
6828       if (IID) {
6829         RenameFn = visitIntrinsicCall(I, IID);
6830         if (!RenameFn)
6831           return;
6832       }
6833     }
6834 
6835     // Check for well-known libc/libm calls.  If the function is internal, it
6836     // can't be a library call.  Don't do the check if marked as nobuiltin for
6837     // some reason or the call site requires strict floating point semantics.
6838     LibFunc Func;
6839     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6840         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6841         LibInfo->hasOptimizedCodeGen(Func)) {
6842       switch (Func) {
6843       default: break;
6844       case LibFunc_copysign:
6845       case LibFunc_copysignf:
6846       case LibFunc_copysignl:
6847         // We already checked this call's prototype; verify it doesn't modify
6848         // errno.
6849         if (I.onlyReadsMemory()) {
6850           SDValue LHS = getValue(I.getArgOperand(0));
6851           SDValue RHS = getValue(I.getArgOperand(1));
6852           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6853                                    LHS.getValueType(), LHS, RHS));
6854           return;
6855         }
6856         break;
6857       case LibFunc_fabs:
6858       case LibFunc_fabsf:
6859       case LibFunc_fabsl:
6860         if (visitUnaryFloatCall(I, ISD::FABS))
6861           return;
6862         break;
6863       case LibFunc_fmin:
6864       case LibFunc_fminf:
6865       case LibFunc_fminl:
6866         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6867           return;
6868         break;
6869       case LibFunc_fmax:
6870       case LibFunc_fmaxf:
6871       case LibFunc_fmaxl:
6872         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6873           return;
6874         break;
6875       case LibFunc_sin:
6876       case LibFunc_sinf:
6877       case LibFunc_sinl:
6878         if (visitUnaryFloatCall(I, ISD::FSIN))
6879           return;
6880         break;
6881       case LibFunc_cos:
6882       case LibFunc_cosf:
6883       case LibFunc_cosl:
6884         if (visitUnaryFloatCall(I, ISD::FCOS))
6885           return;
6886         break;
6887       case LibFunc_sqrt:
6888       case LibFunc_sqrtf:
6889       case LibFunc_sqrtl:
6890       case LibFunc_sqrt_finite:
6891       case LibFunc_sqrtf_finite:
6892       case LibFunc_sqrtl_finite:
6893         if (visitUnaryFloatCall(I, ISD::FSQRT))
6894           return;
6895         break;
6896       case LibFunc_floor:
6897       case LibFunc_floorf:
6898       case LibFunc_floorl:
6899         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6900           return;
6901         break;
6902       case LibFunc_nearbyint:
6903       case LibFunc_nearbyintf:
6904       case LibFunc_nearbyintl:
6905         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6906           return;
6907         break;
6908       case LibFunc_ceil:
6909       case LibFunc_ceilf:
6910       case LibFunc_ceill:
6911         if (visitUnaryFloatCall(I, ISD::FCEIL))
6912           return;
6913         break;
6914       case LibFunc_rint:
6915       case LibFunc_rintf:
6916       case LibFunc_rintl:
6917         if (visitUnaryFloatCall(I, ISD::FRINT))
6918           return;
6919         break;
6920       case LibFunc_round:
6921       case LibFunc_roundf:
6922       case LibFunc_roundl:
6923         if (visitUnaryFloatCall(I, ISD::FROUND))
6924           return;
6925         break;
6926       case LibFunc_trunc:
6927       case LibFunc_truncf:
6928       case LibFunc_truncl:
6929         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6930           return;
6931         break;
6932       case LibFunc_log2:
6933       case LibFunc_log2f:
6934       case LibFunc_log2l:
6935         if (visitUnaryFloatCall(I, ISD::FLOG2))
6936           return;
6937         break;
6938       case LibFunc_exp2:
6939       case LibFunc_exp2f:
6940       case LibFunc_exp2l:
6941         if (visitUnaryFloatCall(I, ISD::FEXP2))
6942           return;
6943         break;
6944       case LibFunc_memcmp:
6945         if (visitMemCmpCall(I))
6946           return;
6947         break;
6948       case LibFunc_mempcpy:
6949         if (visitMemPCpyCall(I))
6950           return;
6951         break;
6952       case LibFunc_memchr:
6953         if (visitMemChrCall(I))
6954           return;
6955         break;
6956       case LibFunc_strcpy:
6957         if (visitStrCpyCall(I, false))
6958           return;
6959         break;
6960       case LibFunc_stpcpy:
6961         if (visitStrCpyCall(I, true))
6962           return;
6963         break;
6964       case LibFunc_strcmp:
6965         if (visitStrCmpCall(I))
6966           return;
6967         break;
6968       case LibFunc_strlen:
6969         if (visitStrLenCall(I))
6970           return;
6971         break;
6972       case LibFunc_strnlen:
6973         if (visitStrNLenCall(I))
6974           return;
6975         break;
6976       }
6977     }
6978   }
6979 
6980   SDValue Callee;
6981   if (!RenameFn)
6982     Callee = getValue(I.getCalledValue());
6983   else
6984     Callee = DAG.getExternalSymbol(
6985         RenameFn,
6986         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6987 
6988   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6989   // have to do anything here to lower funclet bundles.
6990   assert(!I.hasOperandBundlesOtherThan(
6991              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6992          "Cannot lower calls with arbitrary operand bundles!");
6993 
6994   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6995     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6996   else
6997     // Check if we can potentially perform a tail call. More detailed checking
6998     // is be done within LowerCallTo, after more information about the call is
6999     // known.
7000     LowerCallTo(&I, Callee, I.isTailCall());
7001 }
7002 
7003 namespace {
7004 
7005 /// AsmOperandInfo - This contains information for each constraint that we are
7006 /// lowering.
7007 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7008 public:
7009   /// CallOperand - If this is the result output operand or a clobber
7010   /// this is null, otherwise it is the incoming operand to the CallInst.
7011   /// This gets modified as the asm is processed.
7012   SDValue CallOperand;
7013 
7014   /// AssignedRegs - If this is a register or register class operand, this
7015   /// contains the set of register corresponding to the operand.
7016   RegsForValue AssignedRegs;
7017 
7018   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7019     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7020   }
7021 
7022   /// Whether or not this operand accesses memory
7023   bool hasMemory(const TargetLowering &TLI) const {
7024     // Indirect operand accesses access memory.
7025     if (isIndirect)
7026       return true;
7027 
7028     for (const auto &Code : Codes)
7029       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7030         return true;
7031 
7032     return false;
7033   }
7034 
7035   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7036   /// corresponds to.  If there is no Value* for this operand, it returns
7037   /// MVT::Other.
7038   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7039                            const DataLayout &DL) const {
7040     if (!CallOperandVal) return MVT::Other;
7041 
7042     if (isa<BasicBlock>(CallOperandVal))
7043       return TLI.getPointerTy(DL);
7044 
7045     llvm::Type *OpTy = CallOperandVal->getType();
7046 
7047     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7048     // If this is an indirect operand, the operand is a pointer to the
7049     // accessed type.
7050     if (isIndirect) {
7051       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7052       if (!PtrTy)
7053         report_fatal_error("Indirect operand for inline asm not a pointer!");
7054       OpTy = PtrTy->getElementType();
7055     }
7056 
7057     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7058     if (StructType *STy = dyn_cast<StructType>(OpTy))
7059       if (STy->getNumElements() == 1)
7060         OpTy = STy->getElementType(0);
7061 
7062     // If OpTy is not a single value, it may be a struct/union that we
7063     // can tile with integers.
7064     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7065       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7066       switch (BitSize) {
7067       default: break;
7068       case 1:
7069       case 8:
7070       case 16:
7071       case 32:
7072       case 64:
7073       case 128:
7074         OpTy = IntegerType::get(Context, BitSize);
7075         break;
7076       }
7077     }
7078 
7079     return TLI.getValueType(DL, OpTy, true);
7080   }
7081 };
7082 
7083 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7084 
7085 } // end anonymous namespace
7086 
7087 /// Make sure that the output operand \p OpInfo and its corresponding input
7088 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7089 /// out).
7090 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7091                                SDISelAsmOperandInfo &MatchingOpInfo,
7092                                SelectionDAG &DAG) {
7093   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7094     return;
7095 
7096   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7097   const auto &TLI = DAG.getTargetLoweringInfo();
7098 
7099   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7100       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7101                                        OpInfo.ConstraintVT);
7102   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7103       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7104                                        MatchingOpInfo.ConstraintVT);
7105   if ((OpInfo.ConstraintVT.isInteger() !=
7106        MatchingOpInfo.ConstraintVT.isInteger()) ||
7107       (MatchRC.second != InputRC.second)) {
7108     // FIXME: error out in a more elegant fashion
7109     report_fatal_error("Unsupported asm: input constraint"
7110                        " with a matching output constraint of"
7111                        " incompatible type!");
7112   }
7113   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7114 }
7115 
7116 /// Get a direct memory input to behave well as an indirect operand.
7117 /// This may introduce stores, hence the need for a \p Chain.
7118 /// \return The (possibly updated) chain.
7119 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7120                                         SDISelAsmOperandInfo &OpInfo,
7121                                         SelectionDAG &DAG) {
7122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7123 
7124   // If we don't have an indirect input, put it in the constpool if we can,
7125   // otherwise spill it to a stack slot.
7126   // TODO: This isn't quite right. We need to handle these according to
7127   // the addressing mode that the constraint wants. Also, this may take
7128   // an additional register for the computation and we don't want that
7129   // either.
7130 
7131   // If the operand is a float, integer, or vector constant, spill to a
7132   // constant pool entry to get its address.
7133   const Value *OpVal = OpInfo.CallOperandVal;
7134   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7135       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7136     OpInfo.CallOperand = DAG.getConstantPool(
7137         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7138     return Chain;
7139   }
7140 
7141   // Otherwise, create a stack slot and emit a store to it before the asm.
7142   Type *Ty = OpVal->getType();
7143   auto &DL = DAG.getDataLayout();
7144   uint64_t TySize = DL.getTypeAllocSize(Ty);
7145   unsigned Align = DL.getPrefTypeAlignment(Ty);
7146   MachineFunction &MF = DAG.getMachineFunction();
7147   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7148   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7149   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7150                        MachinePointerInfo::getFixedStack(MF, SSFI));
7151   OpInfo.CallOperand = StackSlot;
7152 
7153   return Chain;
7154 }
7155 
7156 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7157 /// specified operand.  We prefer to assign virtual registers, to allow the
7158 /// register allocator to handle the assignment process.  However, if the asm
7159 /// uses features that we can't model on machineinstrs, we have SDISel do the
7160 /// allocation.  This produces generally horrible, but correct, code.
7161 ///
7162 ///   OpInfo describes the operand.
7163 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7164                                  const SDLoc &DL,
7165                                  SDISelAsmOperandInfo &OpInfo) {
7166   LLVMContext &Context = *DAG.getContext();
7167 
7168   MachineFunction &MF = DAG.getMachineFunction();
7169   SmallVector<unsigned, 4> Regs;
7170   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7171 
7172   // If this is a constraint for a single physreg, or a constraint for a
7173   // register class, find it.
7174   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7175       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
7176                                        OpInfo.ConstraintVT);
7177 
7178   unsigned NumRegs = 1;
7179   if (OpInfo.ConstraintVT != MVT::Other) {
7180     // If this is a FP input in an integer register (or visa versa) insert a bit
7181     // cast of the input value.  More generally, handle any case where the input
7182     // value disagrees with the register class we plan to stick this in.
7183     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
7184         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7185       // Try to convert to the first EVT that the reg class contains.  If the
7186       // types are identical size, use a bitcast to convert (e.g. two differing
7187       // vector types).
7188       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7189       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
7190         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7191                                          RegVT, OpInfo.CallOperand);
7192         OpInfo.ConstraintVT = RegVT;
7193       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7194         // If the input is a FP value and we want it in FP registers, do a
7195         // bitcast to the corresponding integer type.  This turns an f64 value
7196         // into i64, which can be passed with two i32 values on a 32-bit
7197         // machine.
7198         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7199         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7200                                          RegVT, OpInfo.CallOperand);
7201         OpInfo.ConstraintVT = RegVT;
7202       }
7203     }
7204 
7205     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7206   }
7207 
7208   MVT RegVT;
7209   EVT ValueVT = OpInfo.ConstraintVT;
7210 
7211   // If this is a constraint for a specific physical register, like {r17},
7212   // assign it now.
7213   if (unsigned AssignedReg = PhysReg.first) {
7214     const TargetRegisterClass *RC = PhysReg.second;
7215     if (OpInfo.ConstraintVT == MVT::Other)
7216       ValueVT = *TRI.legalclasstypes_begin(*RC);
7217 
7218     // Get the actual register value type.  This is important, because the user
7219     // may have asked for (e.g.) the AX register in i32 type.  We need to
7220     // remember that AX is actually i16 to get the right extension.
7221     RegVT = *TRI.legalclasstypes_begin(*RC);
7222 
7223     // This is a explicit reference to a physical register.
7224     Regs.push_back(AssignedReg);
7225 
7226     // If this is an expanded reference, add the rest of the regs to Regs.
7227     if (NumRegs != 1) {
7228       TargetRegisterClass::iterator I = RC->begin();
7229       for (; *I != AssignedReg; ++I)
7230         assert(I != RC->end() && "Didn't find reg!");
7231 
7232       // Already added the first reg.
7233       --NumRegs; ++I;
7234       for (; NumRegs; --NumRegs, ++I) {
7235         assert(I != RC->end() && "Ran out of registers to allocate!");
7236         Regs.push_back(*I);
7237       }
7238     }
7239 
7240     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7241     return;
7242   }
7243 
7244   // Otherwise, if this was a reference to an LLVM register class, create vregs
7245   // for this reference.
7246   if (const TargetRegisterClass *RC = PhysReg.second) {
7247     RegVT = *TRI.legalclasstypes_begin(*RC);
7248     if (OpInfo.ConstraintVT == MVT::Other)
7249       ValueVT = RegVT;
7250 
7251     // Create the appropriate number of virtual registers.
7252     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7253     for (; NumRegs; --NumRegs)
7254       Regs.push_back(RegInfo.createVirtualRegister(RC));
7255 
7256     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7257     return;
7258   }
7259 
7260   // Otherwise, we couldn't allocate enough registers for this.
7261 }
7262 
7263 static unsigned
7264 findMatchingInlineAsmOperand(unsigned OperandNo,
7265                              const std::vector<SDValue> &AsmNodeOperands) {
7266   // Scan until we find the definition we already emitted of this operand.
7267   unsigned CurOp = InlineAsm::Op_FirstOperand;
7268   for (; OperandNo; --OperandNo) {
7269     // Advance to the next operand.
7270     unsigned OpFlag =
7271         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7272     assert((InlineAsm::isRegDefKind(OpFlag) ||
7273             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7274             InlineAsm::isMemKind(OpFlag)) &&
7275            "Skipped past definitions?");
7276     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7277   }
7278   return CurOp;
7279 }
7280 
7281 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7282 /// \return true if it has succeeded, false otherwise
7283 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7284                               MVT RegVT, SelectionDAG &DAG) {
7285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7286   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7287   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7288     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7289       Regs.push_back(RegInfo.createVirtualRegister(RC));
7290     else
7291       return false;
7292   }
7293   return true;
7294 }
7295 
7296 namespace {
7297 
7298 class ExtraFlags {
7299   unsigned Flags = 0;
7300 
7301 public:
7302   explicit ExtraFlags(ImmutableCallSite CS) {
7303     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7304     if (IA->hasSideEffects())
7305       Flags |= InlineAsm::Extra_HasSideEffects;
7306     if (IA->isAlignStack())
7307       Flags |= InlineAsm::Extra_IsAlignStack;
7308     if (CS.isConvergent())
7309       Flags |= InlineAsm::Extra_IsConvergent;
7310     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7311   }
7312 
7313   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7314     // Ideally, we would only check against memory constraints.  However, the
7315     // meaning of an Other constraint can be target-specific and we can't easily
7316     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7317     // for Other constraints as well.
7318     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7319         OpInfo.ConstraintType == TargetLowering::C_Other) {
7320       if (OpInfo.Type == InlineAsm::isInput)
7321         Flags |= InlineAsm::Extra_MayLoad;
7322       else if (OpInfo.Type == InlineAsm::isOutput)
7323         Flags |= InlineAsm::Extra_MayStore;
7324       else if (OpInfo.Type == InlineAsm::isClobber)
7325         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7326     }
7327   }
7328 
7329   unsigned get() const { return Flags; }
7330 };
7331 
7332 } // end anonymous namespace
7333 
7334 /// visitInlineAsm - Handle a call to an InlineAsm object.
7335 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7336   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7337 
7338   /// ConstraintOperands - Information about all of the constraints.
7339   SDISelAsmOperandInfoVector ConstraintOperands;
7340 
7341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7342   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7343       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7344 
7345   bool hasMemory = false;
7346 
7347   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7348   ExtraFlags ExtraInfo(CS);
7349 
7350   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7351   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7352   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7353     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7354     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7355 
7356     MVT OpVT = MVT::Other;
7357 
7358     // Compute the value type for each operand.
7359     if (OpInfo.Type == InlineAsm::isInput ||
7360         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7361       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7362 
7363       // Process the call argument. BasicBlocks are labels, currently appearing
7364       // only in asm's.
7365       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7366         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7367       } else {
7368         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7369       }
7370 
7371       OpVT =
7372           OpInfo
7373               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7374               .getSimpleVT();
7375     }
7376 
7377     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7378       // The return value of the call is this value.  As such, there is no
7379       // corresponding argument.
7380       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7381       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7382         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7383                                       STy->getElementType(ResNo));
7384       } else {
7385         assert(ResNo == 0 && "Asm only has one result!");
7386         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7387       }
7388       ++ResNo;
7389     }
7390 
7391     OpInfo.ConstraintVT = OpVT;
7392 
7393     if (!hasMemory)
7394       hasMemory = OpInfo.hasMemory(TLI);
7395 
7396     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7397     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7398     auto TargetConstraint = TargetConstraints[i];
7399 
7400     // Compute the constraint code and ConstraintType to use.
7401     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7402 
7403     ExtraInfo.update(TargetConstraint);
7404   }
7405 
7406   SDValue Chain, Flag;
7407 
7408   // We won't need to flush pending loads if this asm doesn't touch
7409   // memory and is nonvolatile.
7410   if (hasMemory || IA->hasSideEffects())
7411     Chain = getRoot();
7412   else
7413     Chain = DAG.getRoot();
7414 
7415   // Second pass over the constraints: compute which constraint option to use
7416   // and assign registers to constraints that want a specific physreg.
7417   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7418     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7419 
7420     // If this is an output operand with a matching input operand, look up the
7421     // matching input. If their types mismatch, e.g. one is an integer, the
7422     // other is floating point, or their sizes are different, flag it as an
7423     // error.
7424     if (OpInfo.hasMatchingInput()) {
7425       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7426       patchMatchingInput(OpInfo, Input, DAG);
7427     }
7428 
7429     // Compute the constraint code and ConstraintType to use.
7430     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7431 
7432     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7433         OpInfo.Type == InlineAsm::isClobber)
7434       continue;
7435 
7436     // If this is a memory input, and if the operand is not indirect, do what we
7437     // need to provide an address for the memory input.
7438     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7439         !OpInfo.isIndirect) {
7440       assert((OpInfo.isMultipleAlternative ||
7441               (OpInfo.Type == InlineAsm::isInput)) &&
7442              "Can only indirectify direct input operands!");
7443 
7444       // Memory operands really want the address of the value.
7445       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7446 
7447       // There is no longer a Value* corresponding to this operand.
7448       OpInfo.CallOperandVal = nullptr;
7449 
7450       // It is now an indirect operand.
7451       OpInfo.isIndirect = true;
7452     }
7453 
7454     // If this constraint is for a specific register, allocate it before
7455     // anything else.
7456     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7457       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7458   }
7459 
7460   // Third pass - Loop over all of the operands, assigning virtual or physregs
7461   // to register class operands.
7462   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7463     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7464 
7465     // C_Register operands have already been allocated, Other/Memory don't need
7466     // to be.
7467     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7468       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7469   }
7470 
7471   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7472   std::vector<SDValue> AsmNodeOperands;
7473   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7474   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7475       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7476 
7477   // If we have a !srcloc metadata node associated with it, we want to attach
7478   // this to the ultimately generated inline asm machineinstr.  To do this, we
7479   // pass in the third operand as this (potentially null) inline asm MDNode.
7480   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7481   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7482 
7483   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7484   // bits as operand 3.
7485   AsmNodeOperands.push_back(DAG.getTargetConstant(
7486       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7487 
7488   // Loop over all of the inputs, copying the operand values into the
7489   // appropriate registers and processing the output regs.
7490   RegsForValue RetValRegs;
7491 
7492   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7493   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7494 
7495   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7496     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7497 
7498     switch (OpInfo.Type) {
7499     case InlineAsm::isOutput:
7500       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7501           OpInfo.ConstraintType != TargetLowering::C_Register) {
7502         // Memory output, or 'other' output (e.g. 'X' constraint).
7503         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7504 
7505         unsigned ConstraintID =
7506             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7507         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7508                "Failed to convert memory constraint code to constraint id.");
7509 
7510         // Add information to the INLINEASM node to know about this output.
7511         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7512         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7513         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7514                                                         MVT::i32));
7515         AsmNodeOperands.push_back(OpInfo.CallOperand);
7516         break;
7517       }
7518 
7519       // Otherwise, this is a register or register class output.
7520 
7521       // Copy the output from the appropriate register.  Find a register that
7522       // we can use.
7523       if (OpInfo.AssignedRegs.Regs.empty()) {
7524         emitInlineAsmError(
7525             CS, "couldn't allocate output register for constraint '" +
7526                     Twine(OpInfo.ConstraintCode) + "'");
7527         return;
7528       }
7529 
7530       // If this is an indirect operand, store through the pointer after the
7531       // asm.
7532       if (OpInfo.isIndirect) {
7533         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7534                                                       OpInfo.CallOperandVal));
7535       } else {
7536         // This is the result value of the call.
7537         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7538         // Concatenate this output onto the outputs list.
7539         RetValRegs.append(OpInfo.AssignedRegs);
7540       }
7541 
7542       // Add information to the INLINEASM node to know that this register is
7543       // set.
7544       OpInfo.AssignedRegs
7545           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7546                                     ? InlineAsm::Kind_RegDefEarlyClobber
7547                                     : InlineAsm::Kind_RegDef,
7548                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7549       break;
7550 
7551     case InlineAsm::isInput: {
7552       SDValue InOperandVal = OpInfo.CallOperand;
7553 
7554       if (OpInfo.isMatchingInputConstraint()) {
7555         // If this is required to match an output register we have already set,
7556         // just use its register.
7557         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7558                                                   AsmNodeOperands);
7559         unsigned OpFlag =
7560           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7561         if (InlineAsm::isRegDefKind(OpFlag) ||
7562             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7563           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7564           if (OpInfo.isIndirect) {
7565             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7566             emitInlineAsmError(CS, "inline asm not supported yet:"
7567                                    " don't know how to handle tied "
7568                                    "indirect register inputs");
7569             return;
7570           }
7571 
7572           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7573           SmallVector<unsigned, 4> Regs;
7574 
7575           if (!createVirtualRegs(Regs,
7576                                  InlineAsm::getNumOperandRegisters(OpFlag),
7577                                  RegVT, DAG)) {
7578             emitInlineAsmError(CS, "inline asm error: This value type register "
7579                                    "class is not natively supported!");
7580             return;
7581           }
7582 
7583           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7584 
7585           SDLoc dl = getCurSDLoc();
7586           // Use the produced MatchedRegs object to
7587           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7588                                     CS.getInstruction());
7589           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7590                                            true, OpInfo.getMatchedOperand(), dl,
7591                                            DAG, AsmNodeOperands);
7592           break;
7593         }
7594 
7595         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7596         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7597                "Unexpected number of operands");
7598         // Add information to the INLINEASM node to know about this input.
7599         // See InlineAsm.h isUseOperandTiedToDef.
7600         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7601         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7602                                                     OpInfo.getMatchedOperand());
7603         AsmNodeOperands.push_back(DAG.getTargetConstant(
7604             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7605         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7606         break;
7607       }
7608 
7609       // Treat indirect 'X' constraint as memory.
7610       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7611           OpInfo.isIndirect)
7612         OpInfo.ConstraintType = TargetLowering::C_Memory;
7613 
7614       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7615         std::vector<SDValue> Ops;
7616         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7617                                           Ops, DAG);
7618         if (Ops.empty()) {
7619           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7620                                      Twine(OpInfo.ConstraintCode) + "'");
7621           return;
7622         }
7623 
7624         // Add information to the INLINEASM node to know about this input.
7625         unsigned ResOpType =
7626           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7627         AsmNodeOperands.push_back(DAG.getTargetConstant(
7628             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7629         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7630         break;
7631       }
7632 
7633       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7634         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7635         assert(InOperandVal.getValueType() ==
7636                    TLI.getPointerTy(DAG.getDataLayout()) &&
7637                "Memory operands expect pointer values");
7638 
7639         unsigned ConstraintID =
7640             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7641         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7642                "Failed to convert memory constraint code to constraint id.");
7643 
7644         // Add information to the INLINEASM node to know about this input.
7645         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7646         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7647         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7648                                                         getCurSDLoc(),
7649                                                         MVT::i32));
7650         AsmNodeOperands.push_back(InOperandVal);
7651         break;
7652       }
7653 
7654       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7655               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7656              "Unknown constraint type!");
7657 
7658       // TODO: Support this.
7659       if (OpInfo.isIndirect) {
7660         emitInlineAsmError(
7661             CS, "Don't know how to handle indirect register inputs yet "
7662                 "for constraint '" +
7663                     Twine(OpInfo.ConstraintCode) + "'");
7664         return;
7665       }
7666 
7667       // Copy the input into the appropriate registers.
7668       if (OpInfo.AssignedRegs.Regs.empty()) {
7669         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7670                                    Twine(OpInfo.ConstraintCode) + "'");
7671         return;
7672       }
7673 
7674       SDLoc dl = getCurSDLoc();
7675 
7676       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7677                                         Chain, &Flag, CS.getInstruction());
7678 
7679       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7680                                                dl, DAG, AsmNodeOperands);
7681       break;
7682     }
7683     case InlineAsm::isClobber:
7684       // Add the clobbered value to the operand list, so that the register
7685       // allocator is aware that the physreg got clobbered.
7686       if (!OpInfo.AssignedRegs.Regs.empty())
7687         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7688                                                  false, 0, getCurSDLoc(), DAG,
7689                                                  AsmNodeOperands);
7690       break;
7691     }
7692   }
7693 
7694   // Finish up input operands.  Set the input chain and add the flag last.
7695   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7696   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7697 
7698   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7699                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7700   Flag = Chain.getValue(1);
7701 
7702   // If this asm returns a register value, copy the result from that register
7703   // and set it as the value of the call.
7704   if (!RetValRegs.Regs.empty()) {
7705     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7706                                              Chain, &Flag, CS.getInstruction());
7707 
7708     // FIXME: Why don't we do this for inline asms with MRVs?
7709     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7710       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7711 
7712       // If any of the results of the inline asm is a vector, it may have the
7713       // wrong width/num elts.  This can happen for register classes that can
7714       // contain multiple different value types.  The preg or vreg allocated may
7715       // not have the same VT as was expected.  Convert it to the right type
7716       // with bit_convert.
7717       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7718         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7719                           ResultType, Val);
7720 
7721       } else if (ResultType != Val.getValueType() &&
7722                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7723         // If a result value was tied to an input value, the computed result may
7724         // have a wider width than the expected result.  Extract the relevant
7725         // portion.
7726         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7727       }
7728 
7729       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7730     }
7731 
7732     setValue(CS.getInstruction(), Val);
7733     // Don't need to use this as a chain in this case.
7734     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7735       return;
7736   }
7737 
7738   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7739 
7740   // Process indirect outputs, first output all of the flagged copies out of
7741   // physregs.
7742   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7743     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7744     const Value *Ptr = IndirectStoresToEmit[i].second;
7745     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7746                                              Chain, &Flag, IA);
7747     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7748   }
7749 
7750   // Emit the non-flagged stores from the physregs.
7751   SmallVector<SDValue, 8> OutChains;
7752   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7753     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7754                                getValue(StoresToEmit[i].second),
7755                                MachinePointerInfo(StoresToEmit[i].second));
7756     OutChains.push_back(Val);
7757   }
7758 
7759   if (!OutChains.empty())
7760     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7761 
7762   DAG.setRoot(Chain);
7763 }
7764 
7765 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7766                                              const Twine &Message) {
7767   LLVMContext &Ctx = *DAG.getContext();
7768   Ctx.emitError(CS.getInstruction(), Message);
7769 
7770   // Make sure we leave the DAG in a valid state
7771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7772   SmallVector<EVT, 1> ValueVTs;
7773   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7774 
7775   if (ValueVTs.empty())
7776     return;
7777 
7778   SmallVector<SDValue, 1> Ops;
7779   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7780     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7781 
7782   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7783 }
7784 
7785 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7786   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7787                           MVT::Other, getRoot(),
7788                           getValue(I.getArgOperand(0)),
7789                           DAG.getSrcValue(I.getArgOperand(0))));
7790 }
7791 
7792 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7794   const DataLayout &DL = DAG.getDataLayout();
7795   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7796                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7797                            DAG.getSrcValue(I.getOperand(0)),
7798                            DL.getABITypeAlignment(I.getType()));
7799   setValue(&I, V);
7800   DAG.setRoot(V.getValue(1));
7801 }
7802 
7803 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7804   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7805                           MVT::Other, getRoot(),
7806                           getValue(I.getArgOperand(0)),
7807                           DAG.getSrcValue(I.getArgOperand(0))));
7808 }
7809 
7810 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7811   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7812                           MVT::Other, getRoot(),
7813                           getValue(I.getArgOperand(0)),
7814                           getValue(I.getArgOperand(1)),
7815                           DAG.getSrcValue(I.getArgOperand(0)),
7816                           DAG.getSrcValue(I.getArgOperand(1))));
7817 }
7818 
7819 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7820                                                     const Instruction &I,
7821                                                     SDValue Op) {
7822   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7823   if (!Range)
7824     return Op;
7825 
7826   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7827   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7828     return Op;
7829 
7830   APInt Lo = CR.getUnsignedMin();
7831   if (!Lo.isMinValue())
7832     return Op;
7833 
7834   APInt Hi = CR.getUnsignedMax();
7835   unsigned Bits = Hi.getActiveBits();
7836 
7837   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7838 
7839   SDLoc SL = getCurSDLoc();
7840 
7841   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7842                              DAG.getValueType(SmallVT));
7843   unsigned NumVals = Op.getNode()->getNumValues();
7844   if (NumVals == 1)
7845     return ZExt;
7846 
7847   SmallVector<SDValue, 4> Ops;
7848 
7849   Ops.push_back(ZExt);
7850   for (unsigned I = 1; I != NumVals; ++I)
7851     Ops.push_back(Op.getValue(I));
7852 
7853   return DAG.getMergeValues(Ops, SL);
7854 }
7855 
7856 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
7857 /// the call being lowered.
7858 ///
7859 /// This is a helper for lowering intrinsics that follow a target calling
7860 /// convention or require stack pointer adjustment. Only a subset of the
7861 /// intrinsic's operands need to participate in the calling convention.
7862 void SelectionDAGBuilder::populateCallLoweringInfo(
7863     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7864     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7865     bool IsPatchPoint) {
7866   TargetLowering::ArgListTy Args;
7867   Args.reserve(NumArgs);
7868 
7869   // Populate the argument list.
7870   // Attributes for args start at offset 1, after the return attribute.
7871   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7872        ArgI != ArgE; ++ArgI) {
7873     const Value *V = CS->getOperand(ArgI);
7874 
7875     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7876 
7877     TargetLowering::ArgListEntry Entry;
7878     Entry.Node = getValue(V);
7879     Entry.Ty = V->getType();
7880     Entry.setAttributes(&CS, ArgI);
7881     Args.push_back(Entry);
7882   }
7883 
7884   CLI.setDebugLoc(getCurSDLoc())
7885       .setChain(getRoot())
7886       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7887       .setDiscardResult(CS->use_empty())
7888       .setIsPatchPoint(IsPatchPoint);
7889 }
7890 
7891 /// Add a stack map intrinsic call's live variable operands to a stackmap
7892 /// or patchpoint target node's operand list.
7893 ///
7894 /// Constants are converted to TargetConstants purely as an optimization to
7895 /// avoid constant materialization and register allocation.
7896 ///
7897 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7898 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7899 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7900 /// address materialization and register allocation, but may also be required
7901 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7902 /// alloca in the entry block, then the runtime may assume that the alloca's
7903 /// StackMap location can be read immediately after compilation and that the
7904 /// location is valid at any point during execution (this is similar to the
7905 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7906 /// only available in a register, then the runtime would need to trap when
7907 /// execution reaches the StackMap in order to read the alloca's location.
7908 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7909                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7910                                 SelectionDAGBuilder &Builder) {
7911   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7912     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7913     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7914       Ops.push_back(
7915         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7916       Ops.push_back(
7917         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7918     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7919       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7920       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7921           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7922     } else
7923       Ops.push_back(OpVal);
7924   }
7925 }
7926 
7927 /// Lower llvm.experimental.stackmap directly to its target opcode.
7928 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7929   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7930   //                                  [live variables...])
7931 
7932   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7933 
7934   SDValue Chain, InFlag, Callee, NullPtr;
7935   SmallVector<SDValue, 32> Ops;
7936 
7937   SDLoc DL = getCurSDLoc();
7938   Callee = getValue(CI.getCalledValue());
7939   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7940 
7941   // The stackmap intrinsic only records the live variables (the arguemnts
7942   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7943   // intrinsic, this won't be lowered to a function call. This means we don't
7944   // have to worry about calling conventions and target specific lowering code.
7945   // Instead we perform the call lowering right here.
7946   //
7947   // chain, flag = CALLSEQ_START(chain, 0, 0)
7948   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7949   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7950   //
7951   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7952   InFlag = Chain.getValue(1);
7953 
7954   // Add the <id> and <numBytes> constants.
7955   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7956   Ops.push_back(DAG.getTargetConstant(
7957                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7958   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7959   Ops.push_back(DAG.getTargetConstant(
7960                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7961                   MVT::i32));
7962 
7963   // Push live variables for the stack map.
7964   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7965 
7966   // We are not pushing any register mask info here on the operands list,
7967   // because the stackmap doesn't clobber anything.
7968 
7969   // Push the chain and the glue flag.
7970   Ops.push_back(Chain);
7971   Ops.push_back(InFlag);
7972 
7973   // Create the STACKMAP node.
7974   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7975   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7976   Chain = SDValue(SM, 0);
7977   InFlag = Chain.getValue(1);
7978 
7979   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7980 
7981   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7982 
7983   // Set the root to the target-lowered call chain.
7984   DAG.setRoot(Chain);
7985 
7986   // Inform the Frame Information that we have a stackmap in this function.
7987   FuncInfo.MF->getFrameInfo().setHasStackMap();
7988 }
7989 
7990 /// Lower llvm.experimental.patchpoint directly to its target opcode.
7991 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7992                                           const BasicBlock *EHPadBB) {
7993   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7994   //                                                 i32 <numBytes>,
7995   //                                                 i8* <target>,
7996   //                                                 i32 <numArgs>,
7997   //                                                 [Args...],
7998   //                                                 [live variables...])
7999 
8000   CallingConv::ID CC = CS.getCallingConv();
8001   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8002   bool HasDef = !CS->getType()->isVoidTy();
8003   SDLoc dl = getCurSDLoc();
8004   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8005 
8006   // Handle immediate and symbolic callees.
8007   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8008     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8009                                    /*isTarget=*/true);
8010   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8011     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8012                                          SDLoc(SymbolicCallee),
8013                                          SymbolicCallee->getValueType(0));
8014 
8015   // Get the real number of arguments participating in the call <numArgs>
8016   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8017   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8018 
8019   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8020   // Intrinsics include all meta-operands up to but not including CC.
8021   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8022   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8023          "Not enough arguments provided to the patchpoint intrinsic");
8024 
8025   // For AnyRegCC the arguments are lowered later on manually.
8026   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8027   Type *ReturnTy =
8028     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8029 
8030   TargetLowering::CallLoweringInfo CLI(DAG);
8031   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8032                            true);
8033   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8034 
8035   SDNode *CallEnd = Result.second.getNode();
8036   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8037     CallEnd = CallEnd->getOperand(0).getNode();
8038 
8039   /// Get a call instruction from the call sequence chain.
8040   /// Tail calls are not allowed.
8041   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8042          "Expected a callseq node.");
8043   SDNode *Call = CallEnd->getOperand(0).getNode();
8044   bool HasGlue = Call->getGluedNode();
8045 
8046   // Replace the target specific call node with the patchable intrinsic.
8047   SmallVector<SDValue, 8> Ops;
8048 
8049   // Add the <id> and <numBytes> constants.
8050   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8051   Ops.push_back(DAG.getTargetConstant(
8052                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8053   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8054   Ops.push_back(DAG.getTargetConstant(
8055                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8056                   MVT::i32));
8057 
8058   // Add the callee.
8059   Ops.push_back(Callee);
8060 
8061   // Adjust <numArgs> to account for any arguments that have been passed on the
8062   // stack instead.
8063   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8064   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8065   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8066   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8067 
8068   // Add the calling convention
8069   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8070 
8071   // Add the arguments we omitted previously. The register allocator should
8072   // place these in any free register.
8073   if (IsAnyRegCC)
8074     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8075       Ops.push_back(getValue(CS.getArgument(i)));
8076 
8077   // Push the arguments from the call instruction up to the register mask.
8078   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8079   Ops.append(Call->op_begin() + 2, e);
8080 
8081   // Push live variables for the stack map.
8082   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8083 
8084   // Push the register mask info.
8085   if (HasGlue)
8086     Ops.push_back(*(Call->op_end()-2));
8087   else
8088     Ops.push_back(*(Call->op_end()-1));
8089 
8090   // Push the chain (this is originally the first operand of the call, but
8091   // becomes now the last or second to last operand).
8092   Ops.push_back(*(Call->op_begin()));
8093 
8094   // Push the glue flag (last operand).
8095   if (HasGlue)
8096     Ops.push_back(*(Call->op_end()-1));
8097 
8098   SDVTList NodeTys;
8099   if (IsAnyRegCC && HasDef) {
8100     // Create the return types based on the intrinsic definition
8101     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8102     SmallVector<EVT, 3> ValueVTs;
8103     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8104     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8105 
8106     // There is always a chain and a glue type at the end
8107     ValueVTs.push_back(MVT::Other);
8108     ValueVTs.push_back(MVT::Glue);
8109     NodeTys = DAG.getVTList(ValueVTs);
8110   } else
8111     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8112 
8113   // Replace the target specific call node with a PATCHPOINT node.
8114   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8115                                          dl, NodeTys, Ops);
8116 
8117   // Update the NodeMap.
8118   if (HasDef) {
8119     if (IsAnyRegCC)
8120       setValue(CS.getInstruction(), SDValue(MN, 0));
8121     else
8122       setValue(CS.getInstruction(), Result.first);
8123   }
8124 
8125   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8126   // call sequence. Furthermore the location of the chain and glue can change
8127   // when the AnyReg calling convention is used and the intrinsic returns a
8128   // value.
8129   if (IsAnyRegCC && HasDef) {
8130     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8131     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8132     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8133   } else
8134     DAG.ReplaceAllUsesWith(Call, MN);
8135   DAG.DeleteNode(Call);
8136 
8137   // Inform the Frame Information that we have a patchpoint in this function.
8138   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8139 }
8140 
8141 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8142                                             unsigned Intrinsic) {
8143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8144   SDValue Op1 = getValue(I.getArgOperand(0));
8145   SDValue Op2;
8146   if (I.getNumArgOperands() > 1)
8147     Op2 = getValue(I.getArgOperand(1));
8148   SDLoc dl = getCurSDLoc();
8149   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8150   SDValue Res;
8151   FastMathFlags FMF;
8152   if (isa<FPMathOperator>(I))
8153     FMF = I.getFastMathFlags();
8154 
8155   switch (Intrinsic) {
8156   case Intrinsic::experimental_vector_reduce_fadd:
8157     if (FMF.isFast())
8158       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8159     else
8160       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8161     break;
8162   case Intrinsic::experimental_vector_reduce_fmul:
8163     if (FMF.isFast())
8164       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8165     else
8166       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8167     break;
8168   case Intrinsic::experimental_vector_reduce_add:
8169     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8170     break;
8171   case Intrinsic::experimental_vector_reduce_mul:
8172     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8173     break;
8174   case Intrinsic::experimental_vector_reduce_and:
8175     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8176     break;
8177   case Intrinsic::experimental_vector_reduce_or:
8178     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8179     break;
8180   case Intrinsic::experimental_vector_reduce_xor:
8181     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8182     break;
8183   case Intrinsic::experimental_vector_reduce_smax:
8184     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8185     break;
8186   case Intrinsic::experimental_vector_reduce_smin:
8187     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8188     break;
8189   case Intrinsic::experimental_vector_reduce_umax:
8190     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8191     break;
8192   case Intrinsic::experimental_vector_reduce_umin:
8193     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8194     break;
8195   case Intrinsic::experimental_vector_reduce_fmax:
8196     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8197     break;
8198   case Intrinsic::experimental_vector_reduce_fmin:
8199     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8200     break;
8201   default:
8202     llvm_unreachable("Unhandled vector reduce intrinsic");
8203   }
8204   setValue(&I, Res);
8205 }
8206 
8207 /// Returns an AttributeList representing the attributes applied to the return
8208 /// value of the given call.
8209 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8210   SmallVector<Attribute::AttrKind, 2> Attrs;
8211   if (CLI.RetSExt)
8212     Attrs.push_back(Attribute::SExt);
8213   if (CLI.RetZExt)
8214     Attrs.push_back(Attribute::ZExt);
8215   if (CLI.IsInReg)
8216     Attrs.push_back(Attribute::InReg);
8217 
8218   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8219                             Attrs);
8220 }
8221 
8222 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8223 /// implementation, which just calls LowerCall.
8224 /// FIXME: When all targets are
8225 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8226 std::pair<SDValue, SDValue>
8227 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8228   // Handle the incoming return values from the call.
8229   CLI.Ins.clear();
8230   Type *OrigRetTy = CLI.RetTy;
8231   SmallVector<EVT, 4> RetTys;
8232   SmallVector<uint64_t, 4> Offsets;
8233   auto &DL = CLI.DAG.getDataLayout();
8234   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8235 
8236   if (CLI.IsPostTypeLegalization) {
8237     // If we are lowering a libcall after legalization, split the return type.
8238     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8239     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8240     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8241       EVT RetVT = OldRetTys[i];
8242       uint64_t Offset = OldOffsets[i];
8243       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8244       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8245       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8246       RetTys.append(NumRegs, RegisterVT);
8247       for (unsigned j = 0; j != NumRegs; ++j)
8248         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8249     }
8250   }
8251 
8252   SmallVector<ISD::OutputArg, 4> Outs;
8253   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8254 
8255   bool CanLowerReturn =
8256       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8257                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8258 
8259   SDValue DemoteStackSlot;
8260   int DemoteStackIdx = -100;
8261   if (!CanLowerReturn) {
8262     // FIXME: equivalent assert?
8263     // assert(!CS.hasInAllocaArgument() &&
8264     //        "sret demotion is incompatible with inalloca");
8265     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8266     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8267     MachineFunction &MF = CLI.DAG.getMachineFunction();
8268     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8269     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
8270 
8271     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8272     ArgListEntry Entry;
8273     Entry.Node = DemoteStackSlot;
8274     Entry.Ty = StackSlotPtrType;
8275     Entry.IsSExt = false;
8276     Entry.IsZExt = false;
8277     Entry.IsInReg = false;
8278     Entry.IsSRet = true;
8279     Entry.IsNest = false;
8280     Entry.IsByVal = false;
8281     Entry.IsReturned = false;
8282     Entry.IsSwiftSelf = false;
8283     Entry.IsSwiftError = false;
8284     Entry.Alignment = Align;
8285     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8286     CLI.NumFixedArgs += 1;
8287     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8288 
8289     // sret demotion isn't compatible with tail-calls, since the sret argument
8290     // points into the callers stack frame.
8291     CLI.IsTailCall = false;
8292   } else {
8293     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8294       EVT VT = RetTys[I];
8295       MVT RegisterVT =
8296           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8297       unsigned NumRegs =
8298           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8299       for (unsigned i = 0; i != NumRegs; ++i) {
8300         ISD::InputArg MyFlags;
8301         MyFlags.VT = RegisterVT;
8302         MyFlags.ArgVT = VT;
8303         MyFlags.Used = CLI.IsReturnValueUsed;
8304         if (CLI.RetSExt)
8305           MyFlags.Flags.setSExt();
8306         if (CLI.RetZExt)
8307           MyFlags.Flags.setZExt();
8308         if (CLI.IsInReg)
8309           MyFlags.Flags.setInReg();
8310         CLI.Ins.push_back(MyFlags);
8311       }
8312     }
8313   }
8314 
8315   // We push in swifterror return as the last element of CLI.Ins.
8316   ArgListTy &Args = CLI.getArgs();
8317   if (supportSwiftError()) {
8318     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8319       if (Args[i].IsSwiftError) {
8320         ISD::InputArg MyFlags;
8321         MyFlags.VT = getPointerTy(DL);
8322         MyFlags.ArgVT = EVT(getPointerTy(DL));
8323         MyFlags.Flags.setSwiftError();
8324         CLI.Ins.push_back(MyFlags);
8325       }
8326     }
8327   }
8328 
8329   // Handle all of the outgoing arguments.
8330   CLI.Outs.clear();
8331   CLI.OutVals.clear();
8332   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8333     SmallVector<EVT, 4> ValueVTs;
8334     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8335     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8336     Type *FinalType = Args[i].Ty;
8337     if (Args[i].IsByVal)
8338       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8339     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8340         FinalType, CLI.CallConv, CLI.IsVarArg);
8341     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8342          ++Value) {
8343       EVT VT = ValueVTs[Value];
8344       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8345       SDValue Op = SDValue(Args[i].Node.getNode(),
8346                            Args[i].Node.getResNo() + Value);
8347       ISD::ArgFlagsTy Flags;
8348 
8349       // Certain targets (such as MIPS), may have a different ABI alignment
8350       // for a type depending on the context. Give the target a chance to
8351       // specify the alignment it wants.
8352       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8353 
8354       if (Args[i].IsZExt)
8355         Flags.setZExt();
8356       if (Args[i].IsSExt)
8357         Flags.setSExt();
8358       if (Args[i].IsInReg) {
8359         // If we are using vectorcall calling convention, a structure that is
8360         // passed InReg - is surely an HVA
8361         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8362             isa<StructType>(FinalType)) {
8363           // The first value of a structure is marked
8364           if (0 == Value)
8365             Flags.setHvaStart();
8366           Flags.setHva();
8367         }
8368         // Set InReg Flag
8369         Flags.setInReg();
8370       }
8371       if (Args[i].IsSRet)
8372         Flags.setSRet();
8373       if (Args[i].IsSwiftSelf)
8374         Flags.setSwiftSelf();
8375       if (Args[i].IsSwiftError)
8376         Flags.setSwiftError();
8377       if (Args[i].IsByVal)
8378         Flags.setByVal();
8379       if (Args[i].IsInAlloca) {
8380         Flags.setInAlloca();
8381         // Set the byval flag for CCAssignFn callbacks that don't know about
8382         // inalloca.  This way we can know how many bytes we should've allocated
8383         // and how many bytes a callee cleanup function will pop.  If we port
8384         // inalloca to more targets, we'll have to add custom inalloca handling
8385         // in the various CC lowering callbacks.
8386         Flags.setByVal();
8387       }
8388       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8389         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8390         Type *ElementTy = Ty->getElementType();
8391         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8392         // For ByVal, alignment should come from FE.  BE will guess if this
8393         // info is not there but there are cases it cannot get right.
8394         unsigned FrameAlign;
8395         if (Args[i].Alignment)
8396           FrameAlign = Args[i].Alignment;
8397         else
8398           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8399         Flags.setByValAlign(FrameAlign);
8400       }
8401       if (Args[i].IsNest)
8402         Flags.setNest();
8403       if (NeedsRegBlock)
8404         Flags.setInConsecutiveRegs();
8405       Flags.setOrigAlign(OriginalAlignment);
8406 
8407       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8408       unsigned NumParts =
8409           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8410       SmallVector<SDValue, 4> Parts(NumParts);
8411       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8412 
8413       if (Args[i].IsSExt)
8414         ExtendKind = ISD::SIGN_EXTEND;
8415       else if (Args[i].IsZExt)
8416         ExtendKind = ISD::ZERO_EXTEND;
8417 
8418       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8419       // for now.
8420       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8421           CanLowerReturn) {
8422         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8423                "unexpected use of 'returned'");
8424         // Before passing 'returned' to the target lowering code, ensure that
8425         // either the register MVT and the actual EVT are the same size or that
8426         // the return value and argument are extended in the same way; in these
8427         // cases it's safe to pass the argument register value unchanged as the
8428         // return register value (although it's at the target's option whether
8429         // to do so)
8430         // TODO: allow code generation to take advantage of partially preserved
8431         // registers rather than clobbering the entire register when the
8432         // parameter extension method is not compatible with the return
8433         // extension method
8434         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8435             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8436              CLI.RetZExt == Args[i].IsZExt))
8437           Flags.setReturned();
8438       }
8439 
8440       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8441                      CLI.CS.getInstruction(), ExtendKind, true);
8442 
8443       for (unsigned j = 0; j != NumParts; ++j) {
8444         // if it isn't first piece, alignment must be 1
8445         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8446                                i < CLI.NumFixedArgs,
8447                                i, j*Parts[j].getValueType().getStoreSize());
8448         if (NumParts > 1 && j == 0)
8449           MyFlags.Flags.setSplit();
8450         else if (j != 0) {
8451           MyFlags.Flags.setOrigAlign(1);
8452           if (j == NumParts - 1)
8453             MyFlags.Flags.setSplitEnd();
8454         }
8455 
8456         CLI.Outs.push_back(MyFlags);
8457         CLI.OutVals.push_back(Parts[j]);
8458       }
8459 
8460       if (NeedsRegBlock && Value == NumValues - 1)
8461         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8462     }
8463   }
8464 
8465   SmallVector<SDValue, 4> InVals;
8466   CLI.Chain = LowerCall(CLI, InVals);
8467 
8468   // Update CLI.InVals to use outside of this function.
8469   CLI.InVals = InVals;
8470 
8471   // Verify that the target's LowerCall behaved as expected.
8472   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8473          "LowerCall didn't return a valid chain!");
8474   assert((!CLI.IsTailCall || InVals.empty()) &&
8475          "LowerCall emitted a return value for a tail call!");
8476   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8477          "LowerCall didn't emit the correct number of values!");
8478 
8479   // For a tail call, the return value is merely live-out and there aren't
8480   // any nodes in the DAG representing it. Return a special value to
8481   // indicate that a tail call has been emitted and no more Instructions
8482   // should be processed in the current block.
8483   if (CLI.IsTailCall) {
8484     CLI.DAG.setRoot(CLI.Chain);
8485     return std::make_pair(SDValue(), SDValue());
8486   }
8487 
8488 #ifndef NDEBUG
8489   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8490     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8491     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8492            "LowerCall emitted a value with the wrong type!");
8493   }
8494 #endif
8495 
8496   SmallVector<SDValue, 4> ReturnValues;
8497   if (!CanLowerReturn) {
8498     // The instruction result is the result of loading from the
8499     // hidden sret parameter.
8500     SmallVector<EVT, 1> PVTs;
8501     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8502 
8503     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8504     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8505     EVT PtrVT = PVTs[0];
8506 
8507     unsigned NumValues = RetTys.size();
8508     ReturnValues.resize(NumValues);
8509     SmallVector<SDValue, 4> Chains(NumValues);
8510 
8511     // An aggregate return value cannot wrap around the address space, so
8512     // offsets to its parts don't wrap either.
8513     SDNodeFlags Flags;
8514     Flags.setNoUnsignedWrap(true);
8515 
8516     for (unsigned i = 0; i < NumValues; ++i) {
8517       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8518                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8519                                                         PtrVT), Flags);
8520       SDValue L = CLI.DAG.getLoad(
8521           RetTys[i], CLI.DL, CLI.Chain, Add,
8522           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8523                                             DemoteStackIdx, Offsets[i]),
8524           /* Alignment = */ 1);
8525       ReturnValues[i] = L;
8526       Chains[i] = L.getValue(1);
8527     }
8528 
8529     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8530   } else {
8531     // Collect the legal value parts into potentially illegal values
8532     // that correspond to the original function's return values.
8533     Optional<ISD::NodeType> AssertOp;
8534     if (CLI.RetSExt)
8535       AssertOp = ISD::AssertSext;
8536     else if (CLI.RetZExt)
8537       AssertOp = ISD::AssertZext;
8538     unsigned CurReg = 0;
8539     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8540       EVT VT = RetTys[I];
8541       MVT RegisterVT =
8542           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8543       unsigned NumRegs =
8544           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8545 
8546       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8547                                               NumRegs, RegisterVT, VT, nullptr,
8548                                               AssertOp, true));
8549       CurReg += NumRegs;
8550     }
8551 
8552     // For a function returning void, there is no return value. We can't create
8553     // such a node, so we just return a null return value in that case. In
8554     // that case, nothing will actually look at the value.
8555     if (ReturnValues.empty())
8556       return std::make_pair(SDValue(), CLI.Chain);
8557   }
8558 
8559   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8560                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8561   return std::make_pair(Res, CLI.Chain);
8562 }
8563 
8564 void TargetLowering::LowerOperationWrapper(SDNode *N,
8565                                            SmallVectorImpl<SDValue> &Results,
8566                                            SelectionDAG &DAG) const {
8567   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8568     Results.push_back(Res);
8569 }
8570 
8571 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8572   llvm_unreachable("LowerOperation not implemented for this target!");
8573 }
8574 
8575 void
8576 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8577   SDValue Op = getNonRegisterValue(V);
8578   assert((Op.getOpcode() != ISD::CopyFromReg ||
8579           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8580          "Copy from a reg to the same reg!");
8581   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8582 
8583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8584   // If this is an InlineAsm we have to match the registers required, not the
8585   // notional registers required by the type.
8586 
8587   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8588                    V->getType(), isABIRegCopy(V));
8589   SDValue Chain = DAG.getEntryNode();
8590 
8591   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8592                               FuncInfo.PreferredExtendType.end())
8593                                  ? ISD::ANY_EXTEND
8594                                  : FuncInfo.PreferredExtendType[V];
8595   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8596   PendingExports.push_back(Chain);
8597 }
8598 
8599 #include "llvm/CodeGen/SelectionDAGISel.h"
8600 
8601 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8602 /// entry block, return true.  This includes arguments used by switches, since
8603 /// the switch may expand into multiple basic blocks.
8604 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8605   // With FastISel active, we may be splitting blocks, so force creation
8606   // of virtual registers for all non-dead arguments.
8607   if (FastISel)
8608     return A->use_empty();
8609 
8610   const BasicBlock &Entry = A->getParent()->front();
8611   for (const User *U : A->users())
8612     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8613       return false;  // Use not in entry block.
8614 
8615   return true;
8616 }
8617 
8618 using ArgCopyElisionMapTy =
8619     DenseMap<const Argument *,
8620              std::pair<const AllocaInst *, const StoreInst *>>;
8621 
8622 /// Scan the entry block of the function in FuncInfo for arguments that look
8623 /// like copies into a local alloca. Record any copied arguments in
8624 /// ArgCopyElisionCandidates.
8625 static void
8626 findArgumentCopyElisionCandidates(const DataLayout &DL,
8627                                   FunctionLoweringInfo *FuncInfo,
8628                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8629   // Record the state of every static alloca used in the entry block. Argument
8630   // allocas are all used in the entry block, so we need approximately as many
8631   // entries as we have arguments.
8632   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8633   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8634   unsigned NumArgs = FuncInfo->Fn->arg_size();
8635   StaticAllocas.reserve(NumArgs * 2);
8636 
8637   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8638     if (!V)
8639       return nullptr;
8640     V = V->stripPointerCasts();
8641     const auto *AI = dyn_cast<AllocaInst>(V);
8642     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8643       return nullptr;
8644     auto Iter = StaticAllocas.insert({AI, Unknown});
8645     return &Iter.first->second;
8646   };
8647 
8648   // Look for stores of arguments to static allocas. Look through bitcasts and
8649   // GEPs to handle type coercions, as long as the alloca is fully initialized
8650   // by the store. Any non-store use of an alloca escapes it and any subsequent
8651   // unanalyzed store might write it.
8652   // FIXME: Handle structs initialized with multiple stores.
8653   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8654     // Look for stores, and handle non-store uses conservatively.
8655     const auto *SI = dyn_cast<StoreInst>(&I);
8656     if (!SI) {
8657       // We will look through cast uses, so ignore them completely.
8658       if (I.isCast())
8659         continue;
8660       // Ignore debug info intrinsics, they don't escape or store to allocas.
8661       if (isa<DbgInfoIntrinsic>(I))
8662         continue;
8663       // This is an unknown instruction. Assume it escapes or writes to all
8664       // static alloca operands.
8665       for (const Use &U : I.operands()) {
8666         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8667           *Info = StaticAllocaInfo::Clobbered;
8668       }
8669       continue;
8670     }
8671 
8672     // If the stored value is a static alloca, mark it as escaped.
8673     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8674       *Info = StaticAllocaInfo::Clobbered;
8675 
8676     // Check if the destination is a static alloca.
8677     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8678     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8679     if (!Info)
8680       continue;
8681     const AllocaInst *AI = cast<AllocaInst>(Dst);
8682 
8683     // Skip allocas that have been initialized or clobbered.
8684     if (*Info != StaticAllocaInfo::Unknown)
8685       continue;
8686 
8687     // Check if the stored value is an argument, and that this store fully
8688     // initializes the alloca. Don't elide copies from the same argument twice.
8689     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8690     const auto *Arg = dyn_cast<Argument>(Val);
8691     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8692         Arg->getType()->isEmptyTy() ||
8693         DL.getTypeStoreSize(Arg->getType()) !=
8694             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8695         ArgCopyElisionCandidates.count(Arg)) {
8696       *Info = StaticAllocaInfo::Clobbered;
8697       continue;
8698     }
8699 
8700     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8701                       << '\n');
8702 
8703     // Mark this alloca and store for argument copy elision.
8704     *Info = StaticAllocaInfo::Elidable;
8705     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8706 
8707     // Stop scanning if we've seen all arguments. This will happen early in -O0
8708     // builds, which is useful, because -O0 builds have large entry blocks and
8709     // many allocas.
8710     if (ArgCopyElisionCandidates.size() == NumArgs)
8711       break;
8712   }
8713 }
8714 
8715 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8716 /// ArgVal is a load from a suitable fixed stack object.
8717 static void tryToElideArgumentCopy(
8718     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8719     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8720     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8721     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8722     SDValue ArgVal, bool &ArgHasUses) {
8723   // Check if this is a load from a fixed stack object.
8724   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8725   if (!LNode)
8726     return;
8727   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8728   if (!FINode)
8729     return;
8730 
8731   // Check that the fixed stack object is the right size and alignment.
8732   // Look at the alignment that the user wrote on the alloca instead of looking
8733   // at the stack object.
8734   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8735   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8736   const AllocaInst *AI = ArgCopyIter->second.first;
8737   int FixedIndex = FINode->getIndex();
8738   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8739   int OldIndex = AllocaIndex;
8740   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8741   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8742     LLVM_DEBUG(
8743         dbgs() << "  argument copy elision failed due to bad fixed stack "
8744                   "object size\n");
8745     return;
8746   }
8747   unsigned RequiredAlignment = AI->getAlignment();
8748   if (!RequiredAlignment) {
8749     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8750         AI->getAllocatedType());
8751   }
8752   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8753     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8754                          "greater than stack argument alignment ("
8755                       << RequiredAlignment << " vs "
8756                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8757     return;
8758   }
8759 
8760   // Perform the elision. Delete the old stack object and replace its only use
8761   // in the variable info map. Mark the stack object as mutable.
8762   LLVM_DEBUG({
8763     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8764            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8765            << '\n';
8766   });
8767   MFI.RemoveStackObject(OldIndex);
8768   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8769   AllocaIndex = FixedIndex;
8770   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8771   Chains.push_back(ArgVal.getValue(1));
8772 
8773   // Avoid emitting code for the store implementing the copy.
8774   const StoreInst *SI = ArgCopyIter->second.second;
8775   ElidedArgCopyInstrs.insert(SI);
8776 
8777   // Check for uses of the argument again so that we can avoid exporting ArgVal
8778   // if it is't used by anything other than the store.
8779   for (const Value *U : Arg.users()) {
8780     if (U != SI) {
8781       ArgHasUses = true;
8782       break;
8783     }
8784   }
8785 }
8786 
8787 void SelectionDAGISel::LowerArguments(const Function &F) {
8788   SelectionDAG &DAG = SDB->DAG;
8789   SDLoc dl = SDB->getCurSDLoc();
8790   const DataLayout &DL = DAG.getDataLayout();
8791   SmallVector<ISD::InputArg, 16> Ins;
8792 
8793   if (!FuncInfo->CanLowerReturn) {
8794     // Put in an sret pointer parameter before all the other parameters.
8795     SmallVector<EVT, 1> ValueVTs;
8796     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8797                     F.getReturnType()->getPointerTo(
8798                         DAG.getDataLayout().getAllocaAddrSpace()),
8799                     ValueVTs);
8800 
8801     // NOTE: Assuming that a pointer will never break down to more than one VT
8802     // or one register.
8803     ISD::ArgFlagsTy Flags;
8804     Flags.setSRet();
8805     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8806     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8807                          ISD::InputArg::NoArgIndex, 0);
8808     Ins.push_back(RetArg);
8809   }
8810 
8811   // Look for stores of arguments to static allocas. Mark such arguments with a
8812   // flag to ask the target to give us the memory location of that argument if
8813   // available.
8814   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8815   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8816 
8817   // Set up the incoming argument description vector.
8818   for (const Argument &Arg : F.args()) {
8819     unsigned ArgNo = Arg.getArgNo();
8820     SmallVector<EVT, 4> ValueVTs;
8821     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8822     bool isArgValueUsed = !Arg.use_empty();
8823     unsigned PartBase = 0;
8824     Type *FinalType = Arg.getType();
8825     if (Arg.hasAttribute(Attribute::ByVal))
8826       FinalType = cast<PointerType>(FinalType)->getElementType();
8827     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8828         FinalType, F.getCallingConv(), F.isVarArg());
8829     for (unsigned Value = 0, NumValues = ValueVTs.size();
8830          Value != NumValues; ++Value) {
8831       EVT VT = ValueVTs[Value];
8832       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8833       ISD::ArgFlagsTy Flags;
8834 
8835       // Certain targets (such as MIPS), may have a different ABI alignment
8836       // for a type depending on the context. Give the target a chance to
8837       // specify the alignment it wants.
8838       unsigned OriginalAlignment =
8839           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8840 
8841       if (Arg.hasAttribute(Attribute::ZExt))
8842         Flags.setZExt();
8843       if (Arg.hasAttribute(Attribute::SExt))
8844         Flags.setSExt();
8845       if (Arg.hasAttribute(Attribute::InReg)) {
8846         // If we are using vectorcall calling convention, a structure that is
8847         // passed InReg - is surely an HVA
8848         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8849             isa<StructType>(Arg.getType())) {
8850           // The first value of a structure is marked
8851           if (0 == Value)
8852             Flags.setHvaStart();
8853           Flags.setHva();
8854         }
8855         // Set InReg Flag
8856         Flags.setInReg();
8857       }
8858       if (Arg.hasAttribute(Attribute::StructRet))
8859         Flags.setSRet();
8860       if (Arg.hasAttribute(Attribute::SwiftSelf))
8861         Flags.setSwiftSelf();
8862       if (Arg.hasAttribute(Attribute::SwiftError))
8863         Flags.setSwiftError();
8864       if (Arg.hasAttribute(Attribute::ByVal))
8865         Flags.setByVal();
8866       if (Arg.hasAttribute(Attribute::InAlloca)) {
8867         Flags.setInAlloca();
8868         // Set the byval flag for CCAssignFn callbacks that don't know about
8869         // inalloca.  This way we can know how many bytes we should've allocated
8870         // and how many bytes a callee cleanup function will pop.  If we port
8871         // inalloca to more targets, we'll have to add custom inalloca handling
8872         // in the various CC lowering callbacks.
8873         Flags.setByVal();
8874       }
8875       if (F.getCallingConv() == CallingConv::X86_INTR) {
8876         // IA Interrupt passes frame (1st parameter) by value in the stack.
8877         if (ArgNo == 0)
8878           Flags.setByVal();
8879       }
8880       if (Flags.isByVal() || Flags.isInAlloca()) {
8881         PointerType *Ty = cast<PointerType>(Arg.getType());
8882         Type *ElementTy = Ty->getElementType();
8883         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8884         // For ByVal, alignment should be passed from FE.  BE will guess if
8885         // this info is not there but there are cases it cannot get right.
8886         unsigned FrameAlign;
8887         if (Arg.getParamAlignment())
8888           FrameAlign = Arg.getParamAlignment();
8889         else
8890           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8891         Flags.setByValAlign(FrameAlign);
8892       }
8893       if (Arg.hasAttribute(Attribute::Nest))
8894         Flags.setNest();
8895       if (NeedsRegBlock)
8896         Flags.setInConsecutiveRegs();
8897       Flags.setOrigAlign(OriginalAlignment);
8898       if (ArgCopyElisionCandidates.count(&Arg))
8899         Flags.setCopyElisionCandidate();
8900 
8901       MVT RegisterVT =
8902           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8903       unsigned NumRegs =
8904           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8905       for (unsigned i = 0; i != NumRegs; ++i) {
8906         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8907                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8908         if (NumRegs > 1 && i == 0)
8909           MyFlags.Flags.setSplit();
8910         // if it isn't first piece, alignment must be 1
8911         else if (i > 0) {
8912           MyFlags.Flags.setOrigAlign(1);
8913           if (i == NumRegs - 1)
8914             MyFlags.Flags.setSplitEnd();
8915         }
8916         Ins.push_back(MyFlags);
8917       }
8918       if (NeedsRegBlock && Value == NumValues - 1)
8919         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8920       PartBase += VT.getStoreSize();
8921     }
8922   }
8923 
8924   // Call the target to set up the argument values.
8925   SmallVector<SDValue, 8> InVals;
8926   SDValue NewRoot = TLI->LowerFormalArguments(
8927       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8928 
8929   // Verify that the target's LowerFormalArguments behaved as expected.
8930   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8931          "LowerFormalArguments didn't return a valid chain!");
8932   assert(InVals.size() == Ins.size() &&
8933          "LowerFormalArguments didn't emit the correct number of values!");
8934   LLVM_DEBUG({
8935     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8936       assert(InVals[i].getNode() &&
8937              "LowerFormalArguments emitted a null value!");
8938       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8939              "LowerFormalArguments emitted a value with the wrong type!");
8940     }
8941   });
8942 
8943   // Update the DAG with the new chain value resulting from argument lowering.
8944   DAG.setRoot(NewRoot);
8945 
8946   // Set up the argument values.
8947   unsigned i = 0;
8948   if (!FuncInfo->CanLowerReturn) {
8949     // Create a virtual register for the sret pointer, and put in a copy
8950     // from the sret argument into it.
8951     SmallVector<EVT, 1> ValueVTs;
8952     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8953                     F.getReturnType()->getPointerTo(
8954                         DAG.getDataLayout().getAllocaAddrSpace()),
8955                     ValueVTs);
8956     MVT VT = ValueVTs[0].getSimpleVT();
8957     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8958     Optional<ISD::NodeType> AssertOp = None;
8959     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8960                                         RegVT, VT, nullptr, AssertOp);
8961 
8962     MachineFunction& MF = SDB->DAG.getMachineFunction();
8963     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8964     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8965     FuncInfo->DemoteRegister = SRetReg;
8966     NewRoot =
8967         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8968     DAG.setRoot(NewRoot);
8969 
8970     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8971     ++i;
8972   }
8973 
8974   SmallVector<SDValue, 4> Chains;
8975   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8976   for (const Argument &Arg : F.args()) {
8977     SmallVector<SDValue, 4> ArgValues;
8978     SmallVector<EVT, 4> ValueVTs;
8979     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8980     unsigned NumValues = ValueVTs.size();
8981     if (NumValues == 0)
8982       continue;
8983 
8984     bool ArgHasUses = !Arg.use_empty();
8985 
8986     // Elide the copying store if the target loaded this argument from a
8987     // suitable fixed stack object.
8988     if (Ins[i].Flags.isCopyElisionCandidate()) {
8989       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8990                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8991                              InVals[i], ArgHasUses);
8992     }
8993 
8994     // If this argument is unused then remember its value. It is used to generate
8995     // debugging information.
8996     bool isSwiftErrorArg =
8997         TLI->supportSwiftError() &&
8998         Arg.hasAttribute(Attribute::SwiftError);
8999     if (!ArgHasUses && !isSwiftErrorArg) {
9000       SDB->setUnusedArgValue(&Arg, InVals[i]);
9001 
9002       // Also remember any frame index for use in FastISel.
9003       if (FrameIndexSDNode *FI =
9004           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9005         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9006     }
9007 
9008     for (unsigned Val = 0; Val != NumValues; ++Val) {
9009       EVT VT = ValueVTs[Val];
9010       MVT PartVT =
9011           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
9012       unsigned NumParts =
9013           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
9014 
9015       // Even an apparant 'unused' swifterror argument needs to be returned. So
9016       // we do generate a copy for it that can be used on return from the
9017       // function.
9018       if (ArgHasUses || isSwiftErrorArg) {
9019         Optional<ISD::NodeType> AssertOp;
9020         if (Arg.hasAttribute(Attribute::SExt))
9021           AssertOp = ISD::AssertSext;
9022         else if (Arg.hasAttribute(Attribute::ZExt))
9023           AssertOp = ISD::AssertZext;
9024 
9025         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9026                                              PartVT, VT, nullptr, AssertOp,
9027                                              true));
9028       }
9029 
9030       i += NumParts;
9031     }
9032 
9033     // We don't need to do anything else for unused arguments.
9034     if (ArgValues.empty())
9035       continue;
9036 
9037     // Note down frame index.
9038     if (FrameIndexSDNode *FI =
9039         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9040       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9041 
9042     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9043                                      SDB->getCurSDLoc());
9044 
9045     SDB->setValue(&Arg, Res);
9046     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9047       // We want to associate the argument with the frame index, among
9048       // involved operands, that correspond to the lowest address. The
9049       // getCopyFromParts function, called earlier, is swapping the order of
9050       // the operands to BUILD_PAIR depending on endianness. The result of
9051       // that swapping is that the least significant bits of the argument will
9052       // be in the first operand of the BUILD_PAIR node, and the most
9053       // significant bits will be in the second operand.
9054       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9055       if (LoadSDNode *LNode =
9056           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9057         if (FrameIndexSDNode *FI =
9058             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9059           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9060     }
9061 
9062     // Update the SwiftErrorVRegDefMap.
9063     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9064       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9065       if (TargetRegisterInfo::isVirtualRegister(Reg))
9066         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9067                                            FuncInfo->SwiftErrorArg, Reg);
9068     }
9069 
9070     // If this argument is live outside of the entry block, insert a copy from
9071     // wherever we got it to the vreg that other BB's will reference it as.
9072     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9073       // If we can, though, try to skip creating an unnecessary vreg.
9074       // FIXME: This isn't very clean... it would be nice to make this more
9075       // general.  It's also subtly incompatible with the hacks FastISel
9076       // uses with vregs.
9077       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9078       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9079         FuncInfo->ValueMap[&Arg] = Reg;
9080         continue;
9081       }
9082     }
9083     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9084       FuncInfo->InitializeRegForValue(&Arg);
9085       SDB->CopyToExportRegsIfNeeded(&Arg);
9086     }
9087   }
9088 
9089   if (!Chains.empty()) {
9090     Chains.push_back(NewRoot);
9091     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9092   }
9093 
9094   DAG.setRoot(NewRoot);
9095 
9096   assert(i == InVals.size() && "Argument register count mismatch!");
9097 
9098   // If any argument copy elisions occurred and we have debug info, update the
9099   // stale frame indices used in the dbg.declare variable info table.
9100   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9101   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9102     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9103       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9104       if (I != ArgCopyElisionFrameIndexMap.end())
9105         VI.Slot = I->second;
9106     }
9107   }
9108 
9109   // Finally, if the target has anything special to do, allow it to do so.
9110   EmitFunctionEntryCode();
9111 }
9112 
9113 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9114 /// ensure constants are generated when needed.  Remember the virtual registers
9115 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9116 /// directly add them, because expansion might result in multiple MBB's for one
9117 /// BB.  As such, the start of the BB might correspond to a different MBB than
9118 /// the end.
9119 void
9120 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9121   const TerminatorInst *TI = LLVMBB->getTerminator();
9122 
9123   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9124 
9125   // Check PHI nodes in successors that expect a value to be available from this
9126   // block.
9127   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9128     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9129     if (!isa<PHINode>(SuccBB->begin())) continue;
9130     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9131 
9132     // If this terminator has multiple identical successors (common for
9133     // switches), only handle each succ once.
9134     if (!SuccsHandled.insert(SuccMBB).second)
9135       continue;
9136 
9137     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9138 
9139     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9140     // nodes and Machine PHI nodes, but the incoming operands have not been
9141     // emitted yet.
9142     for (const PHINode &PN : SuccBB->phis()) {
9143       // Ignore dead phi's.
9144       if (PN.use_empty())
9145         continue;
9146 
9147       // Skip empty types
9148       if (PN.getType()->isEmptyTy())
9149         continue;
9150 
9151       unsigned Reg;
9152       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9153 
9154       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9155         unsigned &RegOut = ConstantsOut[C];
9156         if (RegOut == 0) {
9157           RegOut = FuncInfo.CreateRegs(C->getType());
9158           CopyValueToVirtualRegister(C, RegOut);
9159         }
9160         Reg = RegOut;
9161       } else {
9162         DenseMap<const Value *, unsigned>::iterator I =
9163           FuncInfo.ValueMap.find(PHIOp);
9164         if (I != FuncInfo.ValueMap.end())
9165           Reg = I->second;
9166         else {
9167           assert(isa<AllocaInst>(PHIOp) &&
9168                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9169                  "Didn't codegen value into a register!??");
9170           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9171           CopyValueToVirtualRegister(PHIOp, Reg);
9172         }
9173       }
9174 
9175       // Remember that this register needs to added to the machine PHI node as
9176       // the input for this MBB.
9177       SmallVector<EVT, 4> ValueVTs;
9178       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9179       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9180       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9181         EVT VT = ValueVTs[vti];
9182         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9183         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9184           FuncInfo.PHINodesToUpdate.push_back(
9185               std::make_pair(&*MBBI++, Reg + i));
9186         Reg += NumRegisters;
9187       }
9188     }
9189   }
9190 
9191   ConstantsOut.clear();
9192 }
9193 
9194 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9195 /// is 0.
9196 MachineBasicBlock *
9197 SelectionDAGBuilder::StackProtectorDescriptor::
9198 AddSuccessorMBB(const BasicBlock *BB,
9199                 MachineBasicBlock *ParentMBB,
9200                 bool IsLikely,
9201                 MachineBasicBlock *SuccMBB) {
9202   // If SuccBB has not been created yet, create it.
9203   if (!SuccMBB) {
9204     MachineFunction *MF = ParentMBB->getParent();
9205     MachineFunction::iterator BBI(ParentMBB);
9206     SuccMBB = MF->CreateMachineBasicBlock(BB);
9207     MF->insert(++BBI, SuccMBB);
9208   }
9209   // Add it as a successor of ParentMBB.
9210   ParentMBB->addSuccessor(
9211       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9212   return SuccMBB;
9213 }
9214 
9215 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9216   MachineFunction::iterator I(MBB);
9217   if (++I == FuncInfo.MF->end())
9218     return nullptr;
9219   return &*I;
9220 }
9221 
9222 /// During lowering new call nodes can be created (such as memset, etc.).
9223 /// Those will become new roots of the current DAG, but complications arise
9224 /// when they are tail calls. In such cases, the call lowering will update
9225 /// the root, but the builder still needs to know that a tail call has been
9226 /// lowered in order to avoid generating an additional return.
9227 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9228   // If the node is null, we do have a tail call.
9229   if (MaybeTC.getNode() != nullptr)
9230     DAG.setRoot(MaybeTC);
9231   else
9232     HasTailCall = true;
9233 }
9234 
9235 uint64_t
9236 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9237                                        unsigned First, unsigned Last) const {
9238   assert(Last >= First);
9239   const APInt &LowCase = Clusters[First].Low->getValue();
9240   const APInt &HighCase = Clusters[Last].High->getValue();
9241   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9242 
9243   // FIXME: A range of consecutive cases has 100% density, but only requires one
9244   // comparison to lower. We should discriminate against such consecutive ranges
9245   // in jump tables.
9246 
9247   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9248 }
9249 
9250 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9251     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9252     unsigned Last) const {
9253   assert(Last >= First);
9254   assert(TotalCases[Last] >= TotalCases[First]);
9255   uint64_t NumCases =
9256       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9257   return NumCases;
9258 }
9259 
9260 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9261                                          unsigned First, unsigned Last,
9262                                          const SwitchInst *SI,
9263                                          MachineBasicBlock *DefaultMBB,
9264                                          CaseCluster &JTCluster) {
9265   assert(First <= Last);
9266 
9267   auto Prob = BranchProbability::getZero();
9268   unsigned NumCmps = 0;
9269   std::vector<MachineBasicBlock*> Table;
9270   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9271 
9272   // Initialize probabilities in JTProbs.
9273   for (unsigned I = First; I <= Last; ++I)
9274     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9275 
9276   for (unsigned I = First; I <= Last; ++I) {
9277     assert(Clusters[I].Kind == CC_Range);
9278     Prob += Clusters[I].Prob;
9279     const APInt &Low = Clusters[I].Low->getValue();
9280     const APInt &High = Clusters[I].High->getValue();
9281     NumCmps += (Low == High) ? 1 : 2;
9282     if (I != First) {
9283       // Fill the gap between this and the previous cluster.
9284       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9285       assert(PreviousHigh.slt(Low));
9286       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9287       for (uint64_t J = 0; J < Gap; J++)
9288         Table.push_back(DefaultMBB);
9289     }
9290     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9291     for (uint64_t J = 0; J < ClusterSize; ++J)
9292       Table.push_back(Clusters[I].MBB);
9293     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9294   }
9295 
9296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9297   unsigned NumDests = JTProbs.size();
9298   if (TLI.isSuitableForBitTests(
9299           NumDests, NumCmps, Clusters[First].Low->getValue(),
9300           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9301     // Clusters[First..Last] should be lowered as bit tests instead.
9302     return false;
9303   }
9304 
9305   // Create the MBB that will load from and jump through the table.
9306   // Note: We create it here, but it's not inserted into the function yet.
9307   MachineFunction *CurMF = FuncInfo.MF;
9308   MachineBasicBlock *JumpTableMBB =
9309       CurMF->CreateMachineBasicBlock(SI->getParent());
9310 
9311   // Add successors. Note: use table order for determinism.
9312   SmallPtrSet<MachineBasicBlock *, 8> Done;
9313   for (MachineBasicBlock *Succ : Table) {
9314     if (Done.count(Succ))
9315       continue;
9316     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9317     Done.insert(Succ);
9318   }
9319   JumpTableMBB->normalizeSuccProbs();
9320 
9321   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9322                      ->createJumpTableIndex(Table);
9323 
9324   // Set up the jump table info.
9325   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9326   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9327                       Clusters[Last].High->getValue(), SI->getCondition(),
9328                       nullptr, false);
9329   JTCases.emplace_back(std::move(JTH), std::move(JT));
9330 
9331   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9332                                      JTCases.size() - 1, Prob);
9333   return true;
9334 }
9335 
9336 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9337                                          const SwitchInst *SI,
9338                                          MachineBasicBlock *DefaultMBB) {
9339 #ifndef NDEBUG
9340   // Clusters must be non-empty, sorted, and only contain Range clusters.
9341   assert(!Clusters.empty());
9342   for (CaseCluster &C : Clusters)
9343     assert(C.Kind == CC_Range);
9344   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9345     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9346 #endif
9347 
9348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9349   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9350     return;
9351 
9352   const int64_t N = Clusters.size();
9353   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9354   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9355 
9356   if (N < 2 || N < MinJumpTableEntries)
9357     return;
9358 
9359   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9360   SmallVector<unsigned, 8> TotalCases(N);
9361   for (unsigned i = 0; i < N; ++i) {
9362     const APInt &Hi = Clusters[i].High->getValue();
9363     const APInt &Lo = Clusters[i].Low->getValue();
9364     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9365     if (i != 0)
9366       TotalCases[i] += TotalCases[i - 1];
9367   }
9368 
9369   // Cheap case: the whole range may be suitable for jump table.
9370   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9371   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9372   assert(NumCases < UINT64_MAX / 100);
9373   assert(Range >= NumCases);
9374   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9375     CaseCluster JTCluster;
9376     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9377       Clusters[0] = JTCluster;
9378       Clusters.resize(1);
9379       return;
9380     }
9381   }
9382 
9383   // The algorithm below is not suitable for -O0.
9384   if (TM.getOptLevel() == CodeGenOpt::None)
9385     return;
9386 
9387   // Split Clusters into minimum number of dense partitions. The algorithm uses
9388   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9389   // for the Case Statement'" (1994), but builds the MinPartitions array in
9390   // reverse order to make it easier to reconstruct the partitions in ascending
9391   // order. In the choice between two optimal partitionings, it picks the one
9392   // which yields more jump tables.
9393 
9394   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9395   SmallVector<unsigned, 8> MinPartitions(N);
9396   // LastElement[i] is the last element of the partition starting at i.
9397   SmallVector<unsigned, 8> LastElement(N);
9398   // PartitionsScore[i] is used to break ties when choosing between two
9399   // partitionings resulting in the same number of partitions.
9400   SmallVector<unsigned, 8> PartitionsScore(N);
9401   // For PartitionsScore, a small number of comparisons is considered as good as
9402   // a jump table and a single comparison is considered better than a jump
9403   // table.
9404   enum PartitionScores : unsigned {
9405     NoTable = 0,
9406     Table = 1,
9407     FewCases = 1,
9408     SingleCase = 2
9409   };
9410 
9411   // Base case: There is only one way to partition Clusters[N-1].
9412   MinPartitions[N - 1] = 1;
9413   LastElement[N - 1] = N - 1;
9414   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9415 
9416   // Note: loop indexes are signed to avoid underflow.
9417   for (int64_t i = N - 2; i >= 0; i--) {
9418     // Find optimal partitioning of Clusters[i..N-1].
9419     // Baseline: Put Clusters[i] into a partition on its own.
9420     MinPartitions[i] = MinPartitions[i + 1] + 1;
9421     LastElement[i] = i;
9422     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9423 
9424     // Search for a solution that results in fewer partitions.
9425     for (int64_t j = N - 1; j > i; j--) {
9426       // Try building a partition from Clusters[i..j].
9427       uint64_t Range = getJumpTableRange(Clusters, i, j);
9428       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9429       assert(NumCases < UINT64_MAX / 100);
9430       assert(Range >= NumCases);
9431       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9432         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9433         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9434         int64_t NumEntries = j - i + 1;
9435 
9436         if (NumEntries == 1)
9437           Score += PartitionScores::SingleCase;
9438         else if (NumEntries <= SmallNumberOfEntries)
9439           Score += PartitionScores::FewCases;
9440         else if (NumEntries >= MinJumpTableEntries)
9441           Score += PartitionScores::Table;
9442 
9443         // If this leads to fewer partitions, or to the same number of
9444         // partitions with better score, it is a better partitioning.
9445         if (NumPartitions < MinPartitions[i] ||
9446             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9447           MinPartitions[i] = NumPartitions;
9448           LastElement[i] = j;
9449           PartitionsScore[i] = Score;
9450         }
9451       }
9452     }
9453   }
9454 
9455   // Iterate over the partitions, replacing some with jump tables in-place.
9456   unsigned DstIndex = 0;
9457   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9458     Last = LastElement[First];
9459     assert(Last >= First);
9460     assert(DstIndex <= First);
9461     unsigned NumClusters = Last - First + 1;
9462 
9463     CaseCluster JTCluster;
9464     if (NumClusters >= MinJumpTableEntries &&
9465         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9466       Clusters[DstIndex++] = JTCluster;
9467     } else {
9468       for (unsigned I = First; I <= Last; ++I)
9469         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9470     }
9471   }
9472   Clusters.resize(DstIndex);
9473 }
9474 
9475 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9476                                         unsigned First, unsigned Last,
9477                                         const SwitchInst *SI,
9478                                         CaseCluster &BTCluster) {
9479   assert(First <= Last);
9480   if (First == Last)
9481     return false;
9482 
9483   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9484   unsigned NumCmps = 0;
9485   for (int64_t I = First; I <= Last; ++I) {
9486     assert(Clusters[I].Kind == CC_Range);
9487     Dests.set(Clusters[I].MBB->getNumber());
9488     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9489   }
9490   unsigned NumDests = Dests.count();
9491 
9492   APInt Low = Clusters[First].Low->getValue();
9493   APInt High = Clusters[Last].High->getValue();
9494   assert(Low.slt(High));
9495 
9496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9497   const DataLayout &DL = DAG.getDataLayout();
9498   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9499     return false;
9500 
9501   APInt LowBound;
9502   APInt CmpRange;
9503 
9504   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9505   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9506          "Case range must fit in bit mask!");
9507 
9508   // Check if the clusters cover a contiguous range such that no value in the
9509   // range will jump to the default statement.
9510   bool ContiguousRange = true;
9511   for (int64_t I = First + 1; I <= Last; ++I) {
9512     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9513       ContiguousRange = false;
9514       break;
9515     }
9516   }
9517 
9518   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9519     // Optimize the case where all the case values fit in a word without having
9520     // to subtract minValue. In this case, we can optimize away the subtraction.
9521     LowBound = APInt::getNullValue(Low.getBitWidth());
9522     CmpRange = High;
9523     ContiguousRange = false;
9524   } else {
9525     LowBound = Low;
9526     CmpRange = High - Low;
9527   }
9528 
9529   CaseBitsVector CBV;
9530   auto TotalProb = BranchProbability::getZero();
9531   for (unsigned i = First; i <= Last; ++i) {
9532     // Find the CaseBits for this destination.
9533     unsigned j;
9534     for (j = 0; j < CBV.size(); ++j)
9535       if (CBV[j].BB == Clusters[i].MBB)
9536         break;
9537     if (j == CBV.size())
9538       CBV.push_back(
9539           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9540     CaseBits *CB = &CBV[j];
9541 
9542     // Update Mask, Bits and ExtraProb.
9543     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9544     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9545     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9546     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9547     CB->Bits += Hi - Lo + 1;
9548     CB->ExtraProb += Clusters[i].Prob;
9549     TotalProb += Clusters[i].Prob;
9550   }
9551 
9552   BitTestInfo BTI;
9553   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9554     // Sort by probability first, number of bits second, bit mask third.
9555     if (a.ExtraProb != b.ExtraProb)
9556       return a.ExtraProb > b.ExtraProb;
9557     if (a.Bits != b.Bits)
9558       return a.Bits > b.Bits;
9559     return a.Mask < b.Mask;
9560   });
9561 
9562   for (auto &CB : CBV) {
9563     MachineBasicBlock *BitTestBB =
9564         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9565     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9566   }
9567   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9568                             SI->getCondition(), -1U, MVT::Other, false,
9569                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9570                             TotalProb);
9571 
9572   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9573                                     BitTestCases.size() - 1, TotalProb);
9574   return true;
9575 }
9576 
9577 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9578                                               const SwitchInst *SI) {
9579 // Partition Clusters into as few subsets as possible, where each subset has a
9580 // range that fits in a machine word and has <= 3 unique destinations.
9581 
9582 #ifndef NDEBUG
9583   // Clusters must be sorted and contain Range or JumpTable clusters.
9584   assert(!Clusters.empty());
9585   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9586   for (const CaseCluster &C : Clusters)
9587     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9588   for (unsigned i = 1; i < Clusters.size(); ++i)
9589     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9590 #endif
9591 
9592   // The algorithm below is not suitable for -O0.
9593   if (TM.getOptLevel() == CodeGenOpt::None)
9594     return;
9595 
9596   // If target does not have legal shift left, do not emit bit tests at all.
9597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9598   const DataLayout &DL = DAG.getDataLayout();
9599 
9600   EVT PTy = TLI.getPointerTy(DL);
9601   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9602     return;
9603 
9604   int BitWidth = PTy.getSizeInBits();
9605   const int64_t N = Clusters.size();
9606 
9607   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9608   SmallVector<unsigned, 8> MinPartitions(N);
9609   // LastElement[i] is the last element of the partition starting at i.
9610   SmallVector<unsigned, 8> LastElement(N);
9611 
9612   // FIXME: This might not be the best algorithm for finding bit test clusters.
9613 
9614   // Base case: There is only one way to partition Clusters[N-1].
9615   MinPartitions[N - 1] = 1;
9616   LastElement[N - 1] = N - 1;
9617 
9618   // Note: loop indexes are signed to avoid underflow.
9619   for (int64_t i = N - 2; i >= 0; --i) {
9620     // Find optimal partitioning of Clusters[i..N-1].
9621     // Baseline: Put Clusters[i] into a partition on its own.
9622     MinPartitions[i] = MinPartitions[i + 1] + 1;
9623     LastElement[i] = i;
9624 
9625     // Search for a solution that results in fewer partitions.
9626     // Note: the search is limited by BitWidth, reducing time complexity.
9627     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9628       // Try building a partition from Clusters[i..j].
9629 
9630       // Check the range.
9631       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9632                                Clusters[j].High->getValue(), DL))
9633         continue;
9634 
9635       // Check nbr of destinations and cluster types.
9636       // FIXME: This works, but doesn't seem very efficient.
9637       bool RangesOnly = true;
9638       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9639       for (int64_t k = i; k <= j; k++) {
9640         if (Clusters[k].Kind != CC_Range) {
9641           RangesOnly = false;
9642           break;
9643         }
9644         Dests.set(Clusters[k].MBB->getNumber());
9645       }
9646       if (!RangesOnly || Dests.count() > 3)
9647         break;
9648 
9649       // Check if it's a better partition.
9650       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9651       if (NumPartitions < MinPartitions[i]) {
9652         // Found a better partition.
9653         MinPartitions[i] = NumPartitions;
9654         LastElement[i] = j;
9655       }
9656     }
9657   }
9658 
9659   // Iterate over the partitions, replacing with bit-test clusters in-place.
9660   unsigned DstIndex = 0;
9661   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9662     Last = LastElement[First];
9663     assert(First <= Last);
9664     assert(DstIndex <= First);
9665 
9666     CaseCluster BitTestCluster;
9667     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9668       Clusters[DstIndex++] = BitTestCluster;
9669     } else {
9670       size_t NumClusters = Last - First + 1;
9671       std::memmove(&Clusters[DstIndex], &Clusters[First],
9672                    sizeof(Clusters[0]) * NumClusters);
9673       DstIndex += NumClusters;
9674     }
9675   }
9676   Clusters.resize(DstIndex);
9677 }
9678 
9679 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9680                                         MachineBasicBlock *SwitchMBB,
9681                                         MachineBasicBlock *DefaultMBB) {
9682   MachineFunction *CurMF = FuncInfo.MF;
9683   MachineBasicBlock *NextMBB = nullptr;
9684   MachineFunction::iterator BBI(W.MBB);
9685   if (++BBI != FuncInfo.MF->end())
9686     NextMBB = &*BBI;
9687 
9688   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9689 
9690   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9691 
9692   if (Size == 2 && W.MBB == SwitchMBB) {
9693     // If any two of the cases has the same destination, and if one value
9694     // is the same as the other, but has one bit unset that the other has set,
9695     // use bit manipulation to do two compares at once.  For example:
9696     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9697     // TODO: This could be extended to merge any 2 cases in switches with 3
9698     // cases.
9699     // TODO: Handle cases where W.CaseBB != SwitchBB.
9700     CaseCluster &Small = *W.FirstCluster;
9701     CaseCluster &Big = *W.LastCluster;
9702 
9703     if (Small.Low == Small.High && Big.Low == Big.High &&
9704         Small.MBB == Big.MBB) {
9705       const APInt &SmallValue = Small.Low->getValue();
9706       const APInt &BigValue = Big.Low->getValue();
9707 
9708       // Check that there is only one bit different.
9709       APInt CommonBit = BigValue ^ SmallValue;
9710       if (CommonBit.isPowerOf2()) {
9711         SDValue CondLHS = getValue(Cond);
9712         EVT VT = CondLHS.getValueType();
9713         SDLoc DL = getCurSDLoc();
9714 
9715         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9716                                  DAG.getConstant(CommonBit, DL, VT));
9717         SDValue Cond = DAG.getSetCC(
9718             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9719             ISD::SETEQ);
9720 
9721         // Update successor info.
9722         // Both Small and Big will jump to Small.BB, so we sum up the
9723         // probabilities.
9724         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9725         if (BPI)
9726           addSuccessorWithProb(
9727               SwitchMBB, DefaultMBB,
9728               // The default destination is the first successor in IR.
9729               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9730         else
9731           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9732 
9733         // Insert the true branch.
9734         SDValue BrCond =
9735             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9736                         DAG.getBasicBlock(Small.MBB));
9737         // Insert the false branch.
9738         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9739                              DAG.getBasicBlock(DefaultMBB));
9740 
9741         DAG.setRoot(BrCond);
9742         return;
9743       }
9744     }
9745   }
9746 
9747   if (TM.getOptLevel() != CodeGenOpt::None) {
9748     // Here, we order cases by probability so the most likely case will be
9749     // checked first. However, two clusters can have the same probability in
9750     // which case their relative ordering is non-deterministic. So we use Low
9751     // as a tie-breaker as clusters are guaranteed to never overlap.
9752     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9753                [](const CaseCluster &a, const CaseCluster &b) {
9754       return a.Prob != b.Prob ?
9755              a.Prob > b.Prob :
9756              a.Low->getValue().slt(b.Low->getValue());
9757     });
9758 
9759     // Rearrange the case blocks so that the last one falls through if possible
9760     // without changing the order of probabilities.
9761     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9762       --I;
9763       if (I->Prob > W.LastCluster->Prob)
9764         break;
9765       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9766         std::swap(*I, *W.LastCluster);
9767         break;
9768       }
9769     }
9770   }
9771 
9772   // Compute total probability.
9773   BranchProbability DefaultProb = W.DefaultProb;
9774   BranchProbability UnhandledProbs = DefaultProb;
9775   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9776     UnhandledProbs += I->Prob;
9777 
9778   MachineBasicBlock *CurMBB = W.MBB;
9779   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9780     MachineBasicBlock *Fallthrough;
9781     if (I == W.LastCluster) {
9782       // For the last cluster, fall through to the default destination.
9783       Fallthrough = DefaultMBB;
9784     } else {
9785       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9786       CurMF->insert(BBI, Fallthrough);
9787       // Put Cond in a virtual register to make it available from the new blocks.
9788       ExportFromCurrentBlock(Cond);
9789     }
9790     UnhandledProbs -= I->Prob;
9791 
9792     switch (I->Kind) {
9793       case CC_JumpTable: {
9794         // FIXME: Optimize away range check based on pivot comparisons.
9795         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9796         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9797 
9798         // The jump block hasn't been inserted yet; insert it here.
9799         MachineBasicBlock *JumpMBB = JT->MBB;
9800         CurMF->insert(BBI, JumpMBB);
9801 
9802         auto JumpProb = I->Prob;
9803         auto FallthroughProb = UnhandledProbs;
9804 
9805         // If the default statement is a target of the jump table, we evenly
9806         // distribute the default probability to successors of CurMBB. Also
9807         // update the probability on the edge from JumpMBB to Fallthrough.
9808         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9809                                               SE = JumpMBB->succ_end();
9810              SI != SE; ++SI) {
9811           if (*SI == DefaultMBB) {
9812             JumpProb += DefaultProb / 2;
9813             FallthroughProb -= DefaultProb / 2;
9814             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9815             JumpMBB->normalizeSuccProbs();
9816             break;
9817           }
9818         }
9819 
9820         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9821         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9822         CurMBB->normalizeSuccProbs();
9823 
9824         // The jump table header will be inserted in our current block, do the
9825         // range check, and fall through to our fallthrough block.
9826         JTH->HeaderBB = CurMBB;
9827         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9828 
9829         // If we're in the right place, emit the jump table header right now.
9830         if (CurMBB == SwitchMBB) {
9831           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9832           JTH->Emitted = true;
9833         }
9834         break;
9835       }
9836       case CC_BitTests: {
9837         // FIXME: Optimize away range check based on pivot comparisons.
9838         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9839 
9840         // The bit test blocks haven't been inserted yet; insert them here.
9841         for (BitTestCase &BTC : BTB->Cases)
9842           CurMF->insert(BBI, BTC.ThisBB);
9843 
9844         // Fill in fields of the BitTestBlock.
9845         BTB->Parent = CurMBB;
9846         BTB->Default = Fallthrough;
9847 
9848         BTB->DefaultProb = UnhandledProbs;
9849         // If the cases in bit test don't form a contiguous range, we evenly
9850         // distribute the probability on the edge to Fallthrough to two
9851         // successors of CurMBB.
9852         if (!BTB->ContiguousRange) {
9853           BTB->Prob += DefaultProb / 2;
9854           BTB->DefaultProb -= DefaultProb / 2;
9855         }
9856 
9857         // If we're in the right place, emit the bit test header right now.
9858         if (CurMBB == SwitchMBB) {
9859           visitBitTestHeader(*BTB, SwitchMBB);
9860           BTB->Emitted = true;
9861         }
9862         break;
9863       }
9864       case CC_Range: {
9865         const Value *RHS, *LHS, *MHS;
9866         ISD::CondCode CC;
9867         if (I->Low == I->High) {
9868           // Check Cond == I->Low.
9869           CC = ISD::SETEQ;
9870           LHS = Cond;
9871           RHS=I->Low;
9872           MHS = nullptr;
9873         } else {
9874           // Check I->Low <= Cond <= I->High.
9875           CC = ISD::SETLE;
9876           LHS = I->Low;
9877           MHS = Cond;
9878           RHS = I->High;
9879         }
9880 
9881         // The false probability is the sum of all unhandled cases.
9882         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9883                      getCurSDLoc(), I->Prob, UnhandledProbs);
9884 
9885         if (CurMBB == SwitchMBB)
9886           visitSwitchCase(CB, SwitchMBB);
9887         else
9888           SwitchCases.push_back(CB);
9889 
9890         break;
9891       }
9892     }
9893     CurMBB = Fallthrough;
9894   }
9895 }
9896 
9897 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9898                                               CaseClusterIt First,
9899                                               CaseClusterIt Last) {
9900   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9901     if (X.Prob != CC.Prob)
9902       return X.Prob > CC.Prob;
9903 
9904     // Ties are broken by comparing the case value.
9905     return X.Low->getValue().slt(CC.Low->getValue());
9906   });
9907 }
9908 
9909 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9910                                         const SwitchWorkListItem &W,
9911                                         Value *Cond,
9912                                         MachineBasicBlock *SwitchMBB) {
9913   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9914          "Clusters not sorted?");
9915 
9916   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9917 
9918   // Balance the tree based on branch probabilities to create a near-optimal (in
9919   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9920   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9921   CaseClusterIt LastLeft = W.FirstCluster;
9922   CaseClusterIt FirstRight = W.LastCluster;
9923   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9924   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9925 
9926   // Move LastLeft and FirstRight towards each other from opposite directions to
9927   // find a partitioning of the clusters which balances the probability on both
9928   // sides. If LeftProb and RightProb are equal, alternate which side is
9929   // taken to ensure 0-probability nodes are distributed evenly.
9930   unsigned I = 0;
9931   while (LastLeft + 1 < FirstRight) {
9932     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9933       LeftProb += (++LastLeft)->Prob;
9934     else
9935       RightProb += (--FirstRight)->Prob;
9936     I++;
9937   }
9938 
9939   while (true) {
9940     // Our binary search tree differs from a typical BST in that ours can have up
9941     // to three values in each leaf. The pivot selection above doesn't take that
9942     // into account, which means the tree might require more nodes and be less
9943     // efficient. We compensate for this here.
9944 
9945     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9946     unsigned NumRight = W.LastCluster - FirstRight + 1;
9947 
9948     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9949       // If one side has less than 3 clusters, and the other has more than 3,
9950       // consider taking a cluster from the other side.
9951 
9952       if (NumLeft < NumRight) {
9953         // Consider moving the first cluster on the right to the left side.
9954         CaseCluster &CC = *FirstRight;
9955         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9956         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9957         if (LeftSideRank <= RightSideRank) {
9958           // Moving the cluster to the left does not demote it.
9959           ++LastLeft;
9960           ++FirstRight;
9961           continue;
9962         }
9963       } else {
9964         assert(NumRight < NumLeft);
9965         // Consider moving the last element on the left to the right side.
9966         CaseCluster &CC = *LastLeft;
9967         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9968         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9969         if (RightSideRank <= LeftSideRank) {
9970           // Moving the cluster to the right does not demot it.
9971           --LastLeft;
9972           --FirstRight;
9973           continue;
9974         }
9975       }
9976     }
9977     break;
9978   }
9979 
9980   assert(LastLeft + 1 == FirstRight);
9981   assert(LastLeft >= W.FirstCluster);
9982   assert(FirstRight <= W.LastCluster);
9983 
9984   // Use the first element on the right as pivot since we will make less-than
9985   // comparisons against it.
9986   CaseClusterIt PivotCluster = FirstRight;
9987   assert(PivotCluster > W.FirstCluster);
9988   assert(PivotCluster <= W.LastCluster);
9989 
9990   CaseClusterIt FirstLeft = W.FirstCluster;
9991   CaseClusterIt LastRight = W.LastCluster;
9992 
9993   const ConstantInt *Pivot = PivotCluster->Low;
9994 
9995   // New blocks will be inserted immediately after the current one.
9996   MachineFunction::iterator BBI(W.MBB);
9997   ++BBI;
9998 
9999   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10000   // we can branch to its destination directly if it's squeezed exactly in
10001   // between the known lower bound and Pivot - 1.
10002   MachineBasicBlock *LeftMBB;
10003   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10004       FirstLeft->Low == W.GE &&
10005       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10006     LeftMBB = FirstLeft->MBB;
10007   } else {
10008     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10009     FuncInfo.MF->insert(BBI, LeftMBB);
10010     WorkList.push_back(
10011         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10012     // Put Cond in a virtual register to make it available from the new blocks.
10013     ExportFromCurrentBlock(Cond);
10014   }
10015 
10016   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10017   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10018   // directly if RHS.High equals the current upper bound.
10019   MachineBasicBlock *RightMBB;
10020   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10021       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10022     RightMBB = FirstRight->MBB;
10023   } else {
10024     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10025     FuncInfo.MF->insert(BBI, RightMBB);
10026     WorkList.push_back(
10027         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10028     // Put Cond in a virtual register to make it available from the new blocks.
10029     ExportFromCurrentBlock(Cond);
10030   }
10031 
10032   // Create the CaseBlock record that will be used to lower the branch.
10033   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10034                getCurSDLoc(), LeftProb, RightProb);
10035 
10036   if (W.MBB == SwitchMBB)
10037     visitSwitchCase(CB, SwitchMBB);
10038   else
10039     SwitchCases.push_back(CB);
10040 }
10041 
10042 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10043 // from the swith statement.
10044 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10045                                             BranchProbability PeeledCaseProb) {
10046   if (PeeledCaseProb == BranchProbability::getOne())
10047     return BranchProbability::getZero();
10048   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10049 
10050   uint32_t Numerator = CaseProb.getNumerator();
10051   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10052   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10053 }
10054 
10055 // Try to peel the top probability case if it exceeds the threshold.
10056 // Return current MachineBasicBlock for the switch statement if the peeling
10057 // does not occur.
10058 // If the peeling is performed, return the newly created MachineBasicBlock
10059 // for the peeled switch statement. Also update Clusters to remove the peeled
10060 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10061 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10062     const SwitchInst &SI, CaseClusterVector &Clusters,
10063     BranchProbability &PeeledCaseProb) {
10064   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10065   // Don't perform if there is only one cluster or optimizing for size.
10066   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10067       TM.getOptLevel() == CodeGenOpt::None ||
10068       SwitchMBB->getParent()->getFunction().optForMinSize())
10069     return SwitchMBB;
10070 
10071   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10072   unsigned PeeledCaseIndex = 0;
10073   bool SwitchPeeled = false;
10074   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10075     CaseCluster &CC = Clusters[Index];
10076     if (CC.Prob < TopCaseProb)
10077       continue;
10078     TopCaseProb = CC.Prob;
10079     PeeledCaseIndex = Index;
10080     SwitchPeeled = true;
10081   }
10082   if (!SwitchPeeled)
10083     return SwitchMBB;
10084 
10085   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10086                     << TopCaseProb << "\n");
10087 
10088   // Record the MBB for the peeled switch statement.
10089   MachineFunction::iterator BBI(SwitchMBB);
10090   ++BBI;
10091   MachineBasicBlock *PeeledSwitchMBB =
10092       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10093   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10094 
10095   ExportFromCurrentBlock(SI.getCondition());
10096   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10097   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10098                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10099   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10100 
10101   Clusters.erase(PeeledCaseIt);
10102   for (CaseCluster &CC : Clusters) {
10103     LLVM_DEBUG(
10104         dbgs() << "Scale the probablity for one cluster, before scaling: "
10105                << CC.Prob << "\n");
10106     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10107     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10108   }
10109   PeeledCaseProb = TopCaseProb;
10110   return PeeledSwitchMBB;
10111 }
10112 
10113 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10114   // Extract cases from the switch.
10115   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10116   CaseClusterVector Clusters;
10117   Clusters.reserve(SI.getNumCases());
10118   for (auto I : SI.cases()) {
10119     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10120     const ConstantInt *CaseVal = I.getCaseValue();
10121     BranchProbability Prob =
10122         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10123             : BranchProbability(1, SI.getNumCases() + 1);
10124     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10125   }
10126 
10127   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10128 
10129   // Cluster adjacent cases with the same destination. We do this at all
10130   // optimization levels because it's cheap to do and will make codegen faster
10131   // if there are many clusters.
10132   sortAndRangeify(Clusters);
10133 
10134   if (TM.getOptLevel() != CodeGenOpt::None) {
10135     // Replace an unreachable default with the most popular destination.
10136     // FIXME: Exploit unreachable default more aggressively.
10137     bool UnreachableDefault =
10138         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10139     if (UnreachableDefault && !Clusters.empty()) {
10140       DenseMap<const BasicBlock *, unsigned> Popularity;
10141       unsigned MaxPop = 0;
10142       const BasicBlock *MaxBB = nullptr;
10143       for (auto I : SI.cases()) {
10144         const BasicBlock *BB = I.getCaseSuccessor();
10145         if (++Popularity[BB] > MaxPop) {
10146           MaxPop = Popularity[BB];
10147           MaxBB = BB;
10148         }
10149       }
10150       // Set new default.
10151       assert(MaxPop > 0 && MaxBB);
10152       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10153 
10154       // Remove cases that were pointing to the destination that is now the
10155       // default.
10156       CaseClusterVector New;
10157       New.reserve(Clusters.size());
10158       for (CaseCluster &CC : Clusters) {
10159         if (CC.MBB != DefaultMBB)
10160           New.push_back(CC);
10161       }
10162       Clusters = std::move(New);
10163     }
10164   }
10165 
10166   // The branch probablity of the peeled case.
10167   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10168   MachineBasicBlock *PeeledSwitchMBB =
10169       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10170 
10171   // If there is only the default destination, jump there directly.
10172   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10173   if (Clusters.empty()) {
10174     assert(PeeledSwitchMBB == SwitchMBB);
10175     SwitchMBB->addSuccessor(DefaultMBB);
10176     if (DefaultMBB != NextBlock(SwitchMBB)) {
10177       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10178                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10179     }
10180     return;
10181   }
10182 
10183   findJumpTables(Clusters, &SI, DefaultMBB);
10184   findBitTestClusters(Clusters, &SI);
10185 
10186   LLVM_DEBUG({
10187     dbgs() << "Case clusters: ";
10188     for (const CaseCluster &C : Clusters) {
10189       if (C.Kind == CC_JumpTable)
10190         dbgs() << "JT:";
10191       if (C.Kind == CC_BitTests)
10192         dbgs() << "BT:";
10193 
10194       C.Low->getValue().print(dbgs(), true);
10195       if (C.Low != C.High) {
10196         dbgs() << '-';
10197         C.High->getValue().print(dbgs(), true);
10198       }
10199       dbgs() << ' ';
10200     }
10201     dbgs() << '\n';
10202   });
10203 
10204   assert(!Clusters.empty());
10205   SwitchWorkList WorkList;
10206   CaseClusterIt First = Clusters.begin();
10207   CaseClusterIt Last = Clusters.end() - 1;
10208   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10209   // Scale the branchprobability for DefaultMBB if the peel occurs and
10210   // DefaultMBB is not replaced.
10211   if (PeeledCaseProb != BranchProbability::getZero() &&
10212       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10213     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10214   WorkList.push_back(
10215       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10216 
10217   while (!WorkList.empty()) {
10218     SwitchWorkListItem W = WorkList.back();
10219     WorkList.pop_back();
10220     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10221 
10222     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10223         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10224       // For optimized builds, lower large range as a balanced binary tree.
10225       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10226       continue;
10227     }
10228 
10229     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10230   }
10231 }
10232