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