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