xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision cd070cdc94ef5f2da3d3a9724c4fcde778fcd163)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/FunctionLoweringInfo.h"
41 #include "llvm/CodeGen/GCMetadata.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineJumpTableInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RuntimeLibcalls.h"
54 #include "llvm/CodeGen/SelectionDAG.h"
55 #include "llvm/CodeGen/SelectionDAGNodes.h"
56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 
125 #define DEBUG_TYPE "isel"
126 
127 /// LimitFloatPrecision - Generate low-precision inline sequences for
128 /// some float libcalls (6, 8 or 12 bits).
129 static unsigned LimitFloatPrecision;
130 
131 static cl::opt<unsigned, true>
132     LimitFPPrecision("limit-float-precision",
133                      cl::desc("Generate low-precision inline sequences "
134                               "for some float libcalls"),
135                      cl::location(LimitFloatPrecision), cl::Hidden,
136                      cl::init(0));
137 
138 static cl::opt<unsigned> SwitchPeelThreshold(
139     "switch-peel-threshold", cl::Hidden, cl::init(66),
140     cl::desc("Set the case probability threshold for peeling the case from a "
141              "switch statement. A value greater than 100 will void this "
142              "optimization"));
143 
144 // Limit the width of DAG chains. This is important in general to prevent
145 // DAG-based analysis from blowing up. For example, alias analysis and
146 // load clustering may not complete in reasonable time. It is difficult to
147 // recognize and avoid this situation within each individual analysis, and
148 // future analyses are likely to have the same behavior. Limiting DAG width is
149 // the safe approach and will be especially important with global DAGs.
150 //
151 // MaxParallelChains default is arbitrarily high to avoid affecting
152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
153 // sequence over this should have been converted to llvm.memcpy by the
154 // frontend. It is easy to induce this behavior with .ll code such as:
155 // %buffer = alloca [4096 x i8]
156 // %data = load [4096 x i8]* %argPtr
157 // store [4096 x i8] %data, [4096 x i8]* %buffer
158 static const unsigned MaxParallelChains = 64;
159 
160 // True if the Value passed requires ABI mangling as it is a parameter to a
161 // function or a return value from a function which is not an intrinsic.
162 static bool isABIRegCopy(const Value *V) {
163   const bool IsRetInst = V && isa<ReturnInst>(V);
164   const bool IsCallInst = V && isa<CallInst>(V);
165   const bool IsInLineAsm =
166       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
167   const bool IsIndirectFunctionCall =
168       IsCallInst && !IsInLineAsm &&
169       !static_cast<const CallInst *>(V)->getCalledFunction();
170   // It is possible that the call instruction is an inline asm statement or an
171   // indirect function call in which case the return value of
172   // getCalledFunction() would be nullptr.
173   const bool IsInstrinsicCall =
174       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
175       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
176           Intrinsic::not_intrinsic;
177 
178   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
179 }
180 
181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
182                                       const SDValue *Parts, unsigned NumParts,
183                                       MVT PartVT, EVT ValueVT, const Value *V,
184                                       bool IsABIRegCopy);
185 
186 /// getCopyFromParts - Create a value that contains the specified legal parts
187 /// combined into the value they represent.  If the parts combine to a type
188 /// larger than ValueVT then AssertOp can be used to specify whether the extra
189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
190 /// (ISD::AssertSext).
191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
192                                 const SDValue *Parts, unsigned NumParts,
193                                 MVT PartVT, EVT ValueVT, const Value *V,
194                                 Optional<ISD::NodeType> AssertOp = None,
195                                 bool IsABIRegCopy = false) {
196   if (ValueVT.isVector())
197     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
198                                   PartVT, ValueVT, V, IsABIRegCopy);
199 
200   assert(NumParts > 0 && "No parts to assemble!");
201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
202   SDValue Val = Parts[0];
203 
204   if (NumParts > 1) {
205     // Assemble the value from multiple parts.
206     if (ValueVT.isInteger()) {
207       unsigned PartBits = PartVT.getSizeInBits();
208       unsigned ValueBits = ValueVT.getSizeInBits();
209 
210       // Assemble the power of 2 part.
211       unsigned RoundParts = NumParts & (NumParts - 1) ?
212         1 << Log2_32(NumParts) : NumParts;
213       unsigned RoundBits = PartBits * RoundParts;
214       EVT RoundVT = RoundBits == ValueBits ?
215         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
216       SDValue Lo, Hi;
217 
218       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
219 
220       if (RoundParts > 2) {
221         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
222                               PartVT, HalfVT, V);
223         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
224                               RoundParts / 2, PartVT, HalfVT, V);
225       } else {
226         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
227         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
228       }
229 
230       if (DAG.getDataLayout().isBigEndian())
231         std::swap(Lo, Hi);
232 
233       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
234 
235       if (RoundParts < NumParts) {
236         // Assemble the trailing non-power-of-2 part.
237         unsigned OddParts = NumParts - RoundParts;
238         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
239         Hi = getCopyFromParts(DAG, DL,
240                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
241 
242         // Combine the round and odd parts.
243         Lo = Val;
244         if (DAG.getDataLayout().isBigEndian())
245           std::swap(Lo, Hi);
246         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
247         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
248         Hi =
249             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
250                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
251                                         TLI.getPointerTy(DAG.getDataLayout())));
252         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
253         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
254       }
255     } else if (PartVT.isFloatingPoint()) {
256       // FP split into multiple FP parts (for ppcf128)
257       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
258              "Unexpected split");
259       SDValue Lo, Hi;
260       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
261       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
262       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
263         std::swap(Lo, Hi);
264       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
265     } else {
266       // FP split into integer parts (soft fp)
267       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
268              !PartVT.isVector() && "Unexpected split");
269       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
270       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
271     }
272   }
273 
274   // There is now one part, held in Val.  Correct it to match ValueVT.
275   // PartEVT is the type of the register class that holds the value.
276   // ValueVT is the type of the inline asm operation.
277   EVT PartEVT = Val.getValueType();
278 
279   if (PartEVT == ValueVT)
280     return Val;
281 
282   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
283       ValueVT.bitsLT(PartEVT)) {
284     // For an FP value in an integer part, we need to truncate to the right
285     // width first.
286     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
287     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
288   }
289 
290   // Handle types that have the same size.
291   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
292     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
293 
294   // Handle types with different sizes.
295   if (PartEVT.isInteger() && ValueVT.isInteger()) {
296     if (ValueVT.bitsLT(PartEVT)) {
297       // For a truncate, see if we have any information to
298       // indicate whether the truncated bits will always be
299       // zero or sign-extension.
300       if (AssertOp.hasValue())
301         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
302                           DAG.getValueType(ValueVT));
303       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
304     }
305     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
306   }
307 
308   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
309     // FP_ROUND's are always exact here.
310     if (ValueVT.bitsLT(Val.getValueType()))
311       return DAG.getNode(
312           ISD::FP_ROUND, DL, ValueVT, Val,
313           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
314 
315     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
316   }
317 
318   llvm_unreachable("Unknown mismatch!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (isa<InlineAsm>(CI->getCalledValue()))
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       bool IsABIRegCopy) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
347   SDValue Val = Parts[0];
348 
349   // Handle a multi-element vector.
350   if (NumParts > 1) {
351     EVT IntermediateVT;
352     MVT RegisterVT;
353     unsigned NumIntermediates;
354     unsigned NumRegs;
355 
356     if (IsABIRegCopy) {
357       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
358           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
359           RegisterVT);
360     } else {
361       NumRegs =
362           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
363                                      NumIntermediates, RegisterVT);
364     }
365 
366     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
367     NumParts = NumRegs; // Silence a compiler warning.
368     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
369     assert(RegisterVT.getSizeInBits() ==
370            Parts[0].getSimpleValueType().getSizeInBits() &&
371            "Part type sizes don't match!");
372 
373     // Assemble the parts into intermediate operands.
374     SmallVector<SDValue, 8> Ops(NumIntermediates);
375     if (NumIntermediates == NumParts) {
376       // If the register was not expanded, truncate or copy the value,
377       // as appropriate.
378       for (unsigned i = 0; i != NumParts; ++i)
379         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
380                                   PartVT, IntermediateVT, V);
381     } else if (NumParts > 0) {
382       // If the intermediate type was expanded, build the intermediate
383       // operands from the parts.
384       assert(NumParts % NumIntermediates == 0 &&
385              "Must expand into a divisible number of parts!");
386       unsigned Factor = NumParts / NumIntermediates;
387       for (unsigned i = 0; i != NumIntermediates; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
389                                   PartVT, IntermediateVT, V);
390     }
391 
392     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
393     // intermediate operands.
394     EVT BuiltVectorTy =
395         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
396                          (IntermediateVT.isVector()
397                               ? IntermediateVT.getVectorNumElements() * NumParts
398                               : NumIntermediates));
399     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
400                                                 : ISD::BUILD_VECTOR,
401                       DL, BuiltVectorTy, Ops);
402   }
403 
404   // There is now one part, held in Val.  Correct it to match ValueVT.
405   EVT PartEVT = Val.getValueType();
406 
407   if (PartEVT == ValueVT)
408     return Val;
409 
410   if (PartEVT.isVector()) {
411     // If the element type of the source/dest vectors are the same, but the
412     // parts vector has more elements than the value vector, then we have a
413     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
414     // elements we want.
415     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
416       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
417              "Cannot narrow, it would be a lossy transformation");
418       return DAG.getNode(
419           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
420           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
421     }
422 
423     // Vector/Vector bitcast.
424     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
425       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
426 
427     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
428       "Cannot handle this kind of promotion");
429     // Promoted vector extract
430     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
431 
432   }
433 
434   // Trivial bitcast if the types are the same size and the destination
435   // vector type is legal.
436   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
437       TLI.isTypeLegal(ValueVT))
438     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440   if (ValueVT.getVectorNumElements() != 1) {
441      // Certain ABIs require that vectors are passed as integers. For vectors
442      // are the same size, this is an obvious bitcast.
443      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
444        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
446        // Bitcast Val back the original type and extract the corresponding
447        // vector we want.
448        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
449        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
450                                            ValueVT.getVectorElementType(), Elts);
451        Val = DAG.getBitcast(WiderVecType, Val);
452        return DAG.getNode(
453            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
454            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
455      }
456 
457      diagnosePossiblyInvalidConstraint(
458          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
459      return DAG.getUNDEF(ValueVT);
460   }
461 
462   // Handle cases such as i8 -> <1 x i1>
463   EVT ValueSVT = ValueVT.getVectorElementType();
464   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
465     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467 
468   return DAG.getBuildVector(ValueVT, DL, Val);
469 }
470 
471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
472                                  SDValue Val, SDValue *Parts, unsigned NumParts,
473                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
474 
475 /// getCopyToParts - Create a series of nodes that contain the specified value
476 /// split into legal parts.  If the parts contain more bits than Val, then, for
477 /// integers, ExtendKind can be used to specify how to generate the extra bits.
478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
479                            SDValue *Parts, unsigned NumParts, MVT PartVT,
480                            const Value *V,
481                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
482                            bool IsABIRegCopy = false) {
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 IsABIRegCopy);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566                                  DAG.getIntPtrConstant(RoundBits, DL));
567     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
568 
569     if (DAG.getDataLayout().isBigEndian())
570       // The odd parts were reversed by getCopyToParts - unreverse them.
571       std::reverse(Parts + RoundParts, Parts + NumParts);
572 
573     NumParts = RoundParts;
574     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
575     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
576   }
577 
578   // The number of parts is a power of 2.  Repeatedly bisect the value using
579   // EXTRACT_ELEMENT.
580   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
581                          EVT::getIntegerVT(*DAG.getContext(),
582                                            ValueVT.getSizeInBits()),
583                          Val);
584 
585   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
586     for (unsigned i = 0; i < NumParts; i += StepSize) {
587       unsigned ThisBits = StepSize * PartBits / 2;
588       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
589       SDValue &Part0 = Parts[i];
590       SDValue &Part1 = Parts[i+StepSize/2];
591 
592       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
593                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
594       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
596 
597       if (ThisBits == PartBits && ThisVT != PartVT) {
598         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
599         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
600       }
601     }
602   }
603 
604   if (DAG.getDataLayout().isBigEndian())
605     std::reverse(Parts, Parts + OrigNumParts);
606 }
607 
608 
609 /// getCopyToPartsVector - Create a series of nodes that contain the specified
610 /// value split into legal parts.
611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
612                                  SDValue Val, SDValue *Parts, unsigned NumParts,
613                                  MVT PartVT, const Value *V,
614                                  bool IsABIRegCopy) {
615   EVT ValueVT = Val.getValueType();
616   assert(ValueVT.isVector() && "Not a vector");
617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
618 
619   if (NumParts == 1) {
620     EVT PartEVT = PartVT;
621     if (PartEVT == ValueVT) {
622       // Nothing to do.
623     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
624       // Bitconvert vector->vector case.
625       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
626     } else if (PartVT.isVector() &&
627                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
628                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
629       EVT ElementVT = PartVT.getVectorElementType();
630       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631       // undef elements.
632       SmallVector<SDValue, 16> Ops;
633       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
634         Ops.push_back(DAG.getNode(
635             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
636             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
637 
638       for (unsigned i = ValueVT.getVectorNumElements(),
639            e = PartVT.getVectorNumElements(); i != e; ++i)
640         Ops.push_back(DAG.getUNDEF(ElementVT));
641 
642       Val = DAG.getBuildVector(PartVT, DL, Ops);
643 
644       // FIXME: Use CONCAT for 2x -> 4x.
645 
646       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
647       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
648     } else if (PartVT.isVector() &&
649                PartEVT.getVectorElementType().bitsGE(
650                  ValueVT.getVectorElementType()) &&
651                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
652 
653       // Promoted vector extract
654       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
655     } else {
656       if (ValueVT.getVectorNumElements() == 1) {
657         Val = DAG.getNode(
658             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
659             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
660       } else {
661         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
662                "lossy conversion of vector to scalar type");
663         EVT IntermediateType =
664             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
665         Val = DAG.getBitcast(IntermediateType, Val);
666         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667       }
668     }
669 
670     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
671     Parts[0] = Val;
672     return;
673   }
674 
675   // Handle a multi-element vector.
676   EVT IntermediateVT;
677   MVT RegisterVT;
678   unsigned NumIntermediates;
679   unsigned NumRegs;
680   if (IsABIRegCopy) {
681     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
682         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
683         RegisterVT);
684   } else {
685     NumRegs =
686         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
687                                    NumIntermediates, RegisterVT);
688   }
689   unsigned NumElements = ValueVT.getVectorNumElements();
690 
691   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692   NumParts = NumRegs; // Silence a compiler warning.
693   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
694 
695   // Convert the vector to the appropiate type if necessary.
696   unsigned DestVectorNoElts =
697       NumIntermediates *
698       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
699   EVT BuiltVectorTy = EVT::getVectorVT(
700       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
701   if (Val.getValueType() != BuiltVectorTy)
702     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
703 
704   // Split the vector into intermediate operands.
705   SmallVector<SDValue, 8> Ops(NumIntermediates);
706   for (unsigned i = 0; i != NumIntermediates; ++i) {
707     if (IntermediateVT.isVector())
708       Ops[i] =
709           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
710                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
711                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
712     else
713       Ops[i] = DAG.getNode(
714           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
715           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
716   }
717 
718   // Split the intermediate operands into legal parts.
719   if (NumParts == NumIntermediates) {
720     // If the register was not expanded, promote or copy the value,
721     // as appropriate.
722     for (unsigned i = 0; i != NumParts; ++i)
723       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
724   } else if (NumParts > 0) {
725     // If the intermediate type was expanded, split each the value into
726     // legal parts.
727     assert(NumIntermediates != 0 && "division by zero");
728     assert(NumParts % NumIntermediates == 0 &&
729            "Must expand into a divisible number of parts!");
730     unsigned Factor = NumParts / NumIntermediates;
731     for (unsigned i = 0; i != NumIntermediates; ++i)
732       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
733   }
734 }
735 
736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
737                            EVT valuevt, bool IsABIMangledValue)
738     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
739       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
740 
741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
742                            const DataLayout &DL, unsigned Reg, Type *Ty,
743                            bool IsABIMangledValue) {
744   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
745 
746   IsABIMangled = IsABIMangledValue;
747 
748   for (EVT ValueVT : ValueVTs) {
749     unsigned NumRegs = IsABIMangledValue
750                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
751                            : TLI.getNumRegisters(Context, ValueVT);
752     MVT RegisterVT = IsABIMangledValue
753                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
754                          : TLI.getRegisterType(Context, ValueVT);
755     for (unsigned i = 0; i != NumRegs; ++i)
756       Regs.push_back(Reg + i);
757     RegVTs.push_back(RegisterVT);
758     RegCount.push_back(NumRegs);
759     Reg += NumRegs;
760   }
761 }
762 
763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
764                                       FunctionLoweringInfo &FuncInfo,
765                                       const SDLoc &dl, SDValue &Chain,
766                                       SDValue *Flag, const Value *V) const {
767   // A Value with type {} or [0 x %t] needs no registers.
768   if (ValueVTs.empty())
769     return SDValue();
770 
771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 
773   // Assemble the legal parts into the final values.
774   SmallVector<SDValue, 4> Values(ValueVTs.size());
775   SmallVector<SDValue, 8> Parts;
776   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
777     // Copy the legal parts from the registers.
778     EVT ValueVT = ValueVTs[Value];
779     unsigned NumRegs = RegCount[Value];
780     MVT RegisterVT = IsABIMangled
781                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
782                          : RegVTs[Value];
783 
784     Parts.resize(NumRegs);
785     for (unsigned i = 0; i != NumRegs; ++i) {
786       SDValue P;
787       if (!Flag) {
788         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
789       } else {
790         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
791         *Flag = P.getValue(2);
792       }
793 
794       Chain = P.getValue(1);
795       Parts[i] = P;
796 
797       // If the source register was virtual and if we know something about it,
798       // add an assert node.
799       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
800           !RegisterVT.isInteger() || RegisterVT.isVector())
801         continue;
802 
803       const FunctionLoweringInfo::LiveOutInfo *LOI =
804         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
805       if (!LOI)
806         continue;
807 
808       unsigned RegSize = RegisterVT.getSizeInBits();
809       unsigned NumSignBits = LOI->NumSignBits;
810       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
811 
812       if (NumZeroBits == RegSize) {
813         // The current value is a zero.
814         // Explicitly express that as it would be easier for
815         // optimizations to kick in.
816         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
817         continue;
818       }
819 
820       // FIXME: We capture more information than the dag can represent.  For
821       // now, just use the tightest assertzext/assertsext possible.
822       bool isSExt = true;
823       EVT FromVT(MVT::Other);
824       if (NumSignBits == RegSize) {
825         isSExt = true;   // ASSERT SEXT 1
826         FromVT = MVT::i1;
827       } else if (NumZeroBits >= RegSize - 1) {
828         isSExt = false;  // ASSERT ZEXT 1
829         FromVT = MVT::i1;
830       } else if (NumSignBits > RegSize - 8) {
831         isSExt = true;   // ASSERT SEXT 8
832         FromVT = MVT::i8;
833       } else if (NumZeroBits >= RegSize - 8) {
834         isSExt = false;  // ASSERT ZEXT 8
835         FromVT = MVT::i8;
836       } else if (NumSignBits > RegSize - 16) {
837         isSExt = true;   // ASSERT SEXT 16
838         FromVT = MVT::i16;
839       } else if (NumZeroBits >= RegSize - 16) {
840         isSExt = false;  // ASSERT ZEXT 16
841         FromVT = MVT::i16;
842       } else if (NumSignBits > RegSize - 32) {
843         isSExt = true;   // ASSERT SEXT 32
844         FromVT = MVT::i32;
845       } else if (NumZeroBits >= RegSize - 32) {
846         isSExt = false;  // ASSERT ZEXT 32
847         FromVT = MVT::i32;
848       } else {
849         continue;
850       }
851       // Add an assertion node.
852       assert(FromVT != MVT::Other);
853       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
854                              RegisterVT, P, DAG.getValueType(FromVT));
855     }
856 
857     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
858                                      NumRegs, RegisterVT, ValueVT, V);
859     Part += NumRegs;
860     Parts.clear();
861   }
862 
863   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
864 }
865 
866 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
867                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
868                                  const Value *V,
869                                  ISD::NodeType PreferredExtendType) const {
870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
871   ISD::NodeType ExtendKind = PreferredExtendType;
872 
873   // Get the list of the values's legal parts.
874   unsigned NumRegs = Regs.size();
875   SmallVector<SDValue, 8> Parts(NumRegs);
876   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
877     unsigned NumParts = RegCount[Value];
878 
879     MVT RegisterVT = IsABIMangled
880                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
881                          : RegVTs[Value];
882 
883     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
884       ExtendKind = ISD::ZERO_EXTEND;
885 
886     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
887                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
888     Part += NumParts;
889   }
890 
891   // Copy the parts into the registers.
892   SmallVector<SDValue, 8> Chains(NumRegs);
893   for (unsigned i = 0; i != NumRegs; ++i) {
894     SDValue Part;
895     if (!Flag) {
896       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
897     } else {
898       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
899       *Flag = Part.getValue(1);
900     }
901 
902     Chains[i] = Part.getValue(0);
903   }
904 
905   if (NumRegs == 1 || Flag)
906     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
907     // flagged to it. That is the CopyToReg nodes and the user are considered
908     // a single scheduling unit. If we create a TokenFactor and return it as
909     // chain, then the TokenFactor is both a predecessor (operand) of the
910     // user as well as a successor (the TF operands are flagged to the user).
911     // c1, f1 = CopyToReg
912     // c2, f2 = CopyToReg
913     // c3     = TokenFactor c1, c2
914     // ...
915     //        = op c3, ..., f2
916     Chain = Chains[NumRegs-1];
917   else
918     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
919 }
920 
921 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
922                                         unsigned MatchingIdx, const SDLoc &dl,
923                                         SelectionDAG &DAG,
924                                         std::vector<SDValue> &Ops) const {
925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926 
927   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
928   if (HasMatching)
929     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
930   else if (!Regs.empty() &&
931            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
932     // Put the register class of the virtual registers in the flag word.  That
933     // way, later passes can recompute register class constraints for inline
934     // assembly as well as normal instructions.
935     // Don't do this for tied operands that can use the regclass information
936     // from the def.
937     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
938     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
939     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
940   }
941 
942   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
943   Ops.push_back(Res);
944 
945   if (Code == InlineAsm::Kind_Clobber) {
946     // Clobbers should always have a 1:1 mapping with registers, and may
947     // reference registers that have illegal (e.g. vector) types. Hence, we
948     // shouldn't try to apply any sort of splitting logic to them.
949     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
950            "No 1:1 mapping from clobbers to regs?");
951     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
952     (void)SP;
953     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
954       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
955       assert(
956           (Regs[I] != SP ||
957            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
958           "If we clobbered the stack pointer, MFI should know about it.");
959     }
960     return;
961   }
962 
963   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
964     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
965     MVT RegisterVT = RegVTs[Value];
966     for (unsigned i = 0; i != NumRegs; ++i) {
967       assert(Reg < Regs.size() && "Mismatch in # registers expected");
968       unsigned TheReg = Regs[Reg++];
969       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
970     }
971   }
972 }
973 
974 SmallVector<std::pair<unsigned, unsigned>, 4>
975 RegsForValue::getRegsAndSizes() const {
976   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
977   unsigned I = 0;
978   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
979     unsigned RegCount = std::get<0>(CountAndVT);
980     MVT RegisterVT = std::get<1>(CountAndVT);
981     unsigned RegisterSize = RegisterVT.getSizeInBits();
982     for (unsigned E = I + RegCount; I != E; ++I)
983       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
984   }
985   return OutVec;
986 }
987 
988 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
989                                const TargetLibraryInfo *li) {
990   AA = aa;
991   GFI = gfi;
992   LibInfo = li;
993   DL = &DAG.getDataLayout();
994   Context = DAG.getContext();
995   LPadToCallSiteMap.clear();
996 }
997 
998 void SelectionDAGBuilder::clear() {
999   NodeMap.clear();
1000   UnusedArgNodeMap.clear();
1001   PendingLoads.clear();
1002   PendingExports.clear();
1003   CurInst = nullptr;
1004   HasTailCall = false;
1005   SDNodeOrder = LowestSDNodeOrder;
1006   StatepointLowering.clear();
1007 }
1008 
1009 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1010   DanglingDebugInfoMap.clear();
1011 }
1012 
1013 SDValue SelectionDAGBuilder::getRoot() {
1014   if (PendingLoads.empty())
1015     return DAG.getRoot();
1016 
1017   if (PendingLoads.size() == 1) {
1018     SDValue Root = PendingLoads[0];
1019     DAG.setRoot(Root);
1020     PendingLoads.clear();
1021     return Root;
1022   }
1023 
1024   // Otherwise, we have to make a token factor node.
1025   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1026                              PendingLoads);
1027   PendingLoads.clear();
1028   DAG.setRoot(Root);
1029   return Root;
1030 }
1031 
1032 SDValue SelectionDAGBuilder::getControlRoot() {
1033   SDValue Root = DAG.getRoot();
1034 
1035   if (PendingExports.empty())
1036     return Root;
1037 
1038   // Turn all of the CopyToReg chains into one factored node.
1039   if (Root.getOpcode() != ISD::EntryToken) {
1040     unsigned i = 0, e = PendingExports.size();
1041     for (; i != e; ++i) {
1042       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1043       if (PendingExports[i].getNode()->getOperand(0) == Root)
1044         break;  // Don't add the root if we already indirectly depend on it.
1045     }
1046 
1047     if (i == e)
1048       PendingExports.push_back(Root);
1049   }
1050 
1051   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1052                      PendingExports);
1053   PendingExports.clear();
1054   DAG.setRoot(Root);
1055   return Root;
1056 }
1057 
1058 void SelectionDAGBuilder::visit(const Instruction &I) {
1059   // Set up outgoing PHI node register values before emitting the terminator.
1060   if (isa<TerminatorInst>(&I)) {
1061     HandlePHINodesInSuccessorBlocks(I.getParent());
1062   }
1063 
1064   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1065   if (!isa<DbgInfoIntrinsic>(I))
1066     ++SDNodeOrder;
1067 
1068   CurInst = &I;
1069 
1070   visit(I.getOpcode(), I);
1071 
1072   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1073       !isStatepoint(&I)) // statepoints handle their exports internally
1074     CopyToExportRegsIfNeeded(&I);
1075 
1076   CurInst = nullptr;
1077 }
1078 
1079 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1080   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1081 }
1082 
1083 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1084   // Note: this doesn't use InstVisitor, because it has to work with
1085   // ConstantExpr's in addition to instructions.
1086   switch (Opcode) {
1087   default: llvm_unreachable("Unknown instruction type encountered!");
1088     // Build the switch statement using the Instruction.def file.
1089 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1090     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1091 #include "llvm/IR/Instruction.def"
1092   }
1093 }
1094 
1095 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1096                                                 const DIExpression *Expr) {
1097   for (auto &DDIMI : DanglingDebugInfoMap)
1098     for (auto &DDI : DDIMI.second)
1099       if (DDI.getDI()) {
1100         const DbgValueInst *DI = DDI.getDI();
1101         DIVariable *DanglingVariable = DI->getVariable();
1102         DIExpression *DanglingExpr = DI->getExpression();
1103         if (DanglingVariable == Variable &&
1104             Expr->fragmentsOverlap(DanglingExpr)) {
1105           DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1106           DDI = DanglingDebugInfo();
1107         }
1108       }
1109 }
1110 
1111 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1112 // generate the debug data structures now that we've seen its definition.
1113 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1114                                                    SDValue Val) {
1115   DanglingDebugInfoVector &DDIV = DanglingDebugInfoMap[V];
1116   for (auto &DDI : DDIV) {
1117     if (!DDI.getDI())
1118       continue;
1119     const DbgValueInst *DI = DDI.getDI();
1120     DebugLoc dl = DDI.getdl();
1121     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1122     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1123     DILocalVariable *Variable = DI->getVariable();
1124     DIExpression *Expr = DI->getExpression();
1125     assert(Variable->isValidLocationForIntrinsic(dl) &&
1126            "Expected inlined-at fields to agree");
1127     SDDbgValue *SDV;
1128     if (Val.getNode()) {
1129       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1130         DEBUG(dbgs() << "Resolve dangling debug info [order=" << DbgSDNodeOrder
1131               << "] for:\n  " << *DI << "\n");
1132         DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1133         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1134         // inserted after the definition of Val when emitting the instructions
1135         // after ISel. An alternative could be to teach
1136         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1137         DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder)
1138                 dbgs() << "changing SDNodeOrder from " << DbgSDNodeOrder
1139                        << " to " << ValSDNodeOrder << "\n");
1140         SDV = getDbgValue(Val, Variable, Expr, dl,
1141                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1142         DAG.AddDbgValue(SDV, Val.getNode(), false);
1143       } else
1144         DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1145               << "in EmitFuncArgumentDbgValue\n");
1146     } else
1147       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1148   }
1149   DanglingDebugInfoMap[V].clear();
1150 }
1151 
1152 /// getCopyFromRegs - If there was virtual register allocated for the value V
1153 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1154 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1155   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1156   SDValue Result;
1157 
1158   if (It != FuncInfo.ValueMap.end()) {
1159     unsigned InReg = It->second;
1160 
1161     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1162                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
1163     SDValue Chain = DAG.getEntryNode();
1164     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1165                                  V);
1166     resolveDanglingDebugInfo(V, Result);
1167   }
1168 
1169   return Result;
1170 }
1171 
1172 /// getValue - Return an SDValue for the given Value.
1173 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1174   // If we already have an SDValue for this value, use it. It's important
1175   // to do this first, so that we don't create a CopyFromReg if we already
1176   // have a regular SDValue.
1177   SDValue &N = NodeMap[V];
1178   if (N.getNode()) return N;
1179 
1180   // If there's a virtual register allocated and initialized for this
1181   // value, use it.
1182   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1183     return copyFromReg;
1184 
1185   // Otherwise create a new SDValue and remember it.
1186   SDValue Val = getValueImpl(V);
1187   NodeMap[V] = Val;
1188   resolveDanglingDebugInfo(V, Val);
1189   return Val;
1190 }
1191 
1192 // Return true if SDValue exists for the given Value
1193 bool SelectionDAGBuilder::findValue(const Value *V) const {
1194   return (NodeMap.find(V) != NodeMap.end()) ||
1195     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1196 }
1197 
1198 /// getNonRegisterValue - Return an SDValue for the given Value, but
1199 /// don't look in FuncInfo.ValueMap for a virtual register.
1200 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1201   // If we already have an SDValue for this value, use it.
1202   SDValue &N = NodeMap[V];
1203   if (N.getNode()) {
1204     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1205       // Remove the debug location from the node as the node is about to be used
1206       // in a location which may differ from the original debug location.  This
1207       // is relevant to Constant and ConstantFP nodes because they can appear
1208       // as constant expressions inside PHI nodes.
1209       N->setDebugLoc(DebugLoc());
1210     }
1211     return N;
1212   }
1213 
1214   // Otherwise create a new SDValue and remember it.
1215   SDValue Val = getValueImpl(V);
1216   NodeMap[V] = Val;
1217   resolveDanglingDebugInfo(V, Val);
1218   return Val;
1219 }
1220 
1221 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1222 /// Create an SDValue for the given value.
1223 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1225 
1226   if (const Constant *C = dyn_cast<Constant>(V)) {
1227     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1228 
1229     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1230       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1231 
1232     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1233       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1234 
1235     if (isa<ConstantPointerNull>(C)) {
1236       unsigned AS = V->getType()->getPointerAddressSpace();
1237       return DAG.getConstant(0, getCurSDLoc(),
1238                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1239     }
1240 
1241     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1242       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1243 
1244     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1245       return DAG.getUNDEF(VT);
1246 
1247     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1248       visit(CE->getOpcode(), *CE);
1249       SDValue N1 = NodeMap[V];
1250       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1251       return N1;
1252     }
1253 
1254     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1255       SmallVector<SDValue, 4> Constants;
1256       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1257            OI != OE; ++OI) {
1258         SDNode *Val = getValue(*OI).getNode();
1259         // If the operand is an empty aggregate, there are no values.
1260         if (!Val) continue;
1261         // Add each leaf value from the operand to the Constants list
1262         // to form a flattened list of all the values.
1263         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1264           Constants.push_back(SDValue(Val, i));
1265       }
1266 
1267       return DAG.getMergeValues(Constants, getCurSDLoc());
1268     }
1269 
1270     if (const ConstantDataSequential *CDS =
1271           dyn_cast<ConstantDataSequential>(C)) {
1272       SmallVector<SDValue, 4> Ops;
1273       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1274         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1275         // Add each leaf value from the operand to the Constants list
1276         // to form a flattened list of all the values.
1277         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1278           Ops.push_back(SDValue(Val, i));
1279       }
1280 
1281       if (isa<ArrayType>(CDS->getType()))
1282         return DAG.getMergeValues(Ops, getCurSDLoc());
1283       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1284     }
1285 
1286     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1287       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1288              "Unknown struct or array constant!");
1289 
1290       SmallVector<EVT, 4> ValueVTs;
1291       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1292       unsigned NumElts = ValueVTs.size();
1293       if (NumElts == 0)
1294         return SDValue(); // empty struct
1295       SmallVector<SDValue, 4> Constants(NumElts);
1296       for (unsigned i = 0; i != NumElts; ++i) {
1297         EVT EltVT = ValueVTs[i];
1298         if (isa<UndefValue>(C))
1299           Constants[i] = DAG.getUNDEF(EltVT);
1300         else if (EltVT.isFloatingPoint())
1301           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1302         else
1303           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1304       }
1305 
1306       return DAG.getMergeValues(Constants, getCurSDLoc());
1307     }
1308 
1309     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1310       return DAG.getBlockAddress(BA, VT);
1311 
1312     VectorType *VecTy = cast<VectorType>(V->getType());
1313     unsigned NumElements = VecTy->getNumElements();
1314 
1315     // Now that we know the number and type of the elements, get that number of
1316     // elements into the Ops array based on what kind of constant it is.
1317     SmallVector<SDValue, 16> Ops;
1318     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1319       for (unsigned i = 0; i != NumElements; ++i)
1320         Ops.push_back(getValue(CV->getOperand(i)));
1321     } else {
1322       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1323       EVT EltVT =
1324           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1325 
1326       SDValue Op;
1327       if (EltVT.isFloatingPoint())
1328         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1329       else
1330         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1331       Ops.assign(NumElements, Op);
1332     }
1333 
1334     // Create a BUILD_VECTOR node.
1335     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1336   }
1337 
1338   // If this is a static alloca, generate it as the frameindex instead of
1339   // computation.
1340   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1341     DenseMap<const AllocaInst*, int>::iterator SI =
1342       FuncInfo.StaticAllocaMap.find(AI);
1343     if (SI != FuncInfo.StaticAllocaMap.end())
1344       return DAG.getFrameIndex(SI->second,
1345                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1346   }
1347 
1348   // If this is an instruction which fast-isel has deferred, select it now.
1349   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1350     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1351 
1352     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1353                      Inst->getType(), isABIRegCopy(V));
1354     SDValue Chain = DAG.getEntryNode();
1355     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1356   }
1357 
1358   llvm_unreachable("Can't get register for value!");
1359 }
1360 
1361 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1362   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1363   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1364   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1365   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1366   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1367   if (IsMSVCCXX || IsCoreCLR)
1368     CatchPadMBB->setIsEHFuncletEntry();
1369 
1370   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1371 }
1372 
1373 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1374   // Update machine-CFG edge.
1375   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1376   FuncInfo.MBB->addSuccessor(TargetMBB);
1377 
1378   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1379   bool IsSEH = isAsynchronousEHPersonality(Pers);
1380   if (IsSEH) {
1381     // If this is not a fall-through branch or optimizations are switched off,
1382     // emit the branch.
1383     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1384         TM.getOptLevel() == CodeGenOpt::None)
1385       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1386                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1387     return;
1388   }
1389 
1390   // Figure out the funclet membership for the catchret's successor.
1391   // This will be used by the FuncletLayout pass to determine how to order the
1392   // BB's.
1393   // A 'catchret' returns to the outer scope's color.
1394   Value *ParentPad = I.getCatchSwitchParentPad();
1395   const BasicBlock *SuccessorColor;
1396   if (isa<ConstantTokenNone>(ParentPad))
1397     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1398   else
1399     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1400   assert(SuccessorColor && "No parent funclet for catchret!");
1401   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1402   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1403 
1404   // Create the terminator node.
1405   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1406                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1407                             DAG.getBasicBlock(SuccessorColorMBB));
1408   DAG.setRoot(Ret);
1409 }
1410 
1411 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1412   // Don't emit any special code for the cleanuppad instruction. It just marks
1413   // the start of a funclet.
1414   FuncInfo.MBB->setIsEHFuncletEntry();
1415   FuncInfo.MBB->setIsCleanupFuncletEntry();
1416 }
1417 
1418 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1419 /// many places it could ultimately go. In the IR, we have a single unwind
1420 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1421 /// This function skips over imaginary basic blocks that hold catchswitch
1422 /// instructions, and finds all the "real" machine
1423 /// basic block destinations. As those destinations may not be successors of
1424 /// EHPadBB, here we also calculate the edge probability to those destinations.
1425 /// The passed-in Prob is the edge probability to EHPadBB.
1426 static void findUnwindDestinations(
1427     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1428     BranchProbability Prob,
1429     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1430         &UnwindDests) {
1431   EHPersonality Personality =
1432     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1433   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1434   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1435 
1436   while (EHPadBB) {
1437     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1438     BasicBlock *NewEHPadBB = nullptr;
1439     if (isa<LandingPadInst>(Pad)) {
1440       // Stop on landingpads. They are not funclets.
1441       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1442       break;
1443     } else if (isa<CleanupPadInst>(Pad)) {
1444       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1445       // personalities.
1446       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1447       UnwindDests.back().first->setIsEHFuncletEntry();
1448       break;
1449     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1450       // Add the catchpad handlers to the possible destinations.
1451       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1452         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1453         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1454         if (IsMSVCCXX || IsCoreCLR)
1455           UnwindDests.back().first->setIsEHFuncletEntry();
1456       }
1457       NewEHPadBB = CatchSwitch->getUnwindDest();
1458     } else {
1459       continue;
1460     }
1461 
1462     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1463     if (BPI && NewEHPadBB)
1464       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1465     EHPadBB = NewEHPadBB;
1466   }
1467 }
1468 
1469 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1470   // Update successor info.
1471   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1472   auto UnwindDest = I.getUnwindDest();
1473   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1474   BranchProbability UnwindDestProb =
1475       (BPI && UnwindDest)
1476           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1477           : BranchProbability::getZero();
1478   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1479   for (auto &UnwindDest : UnwindDests) {
1480     UnwindDest.first->setIsEHPad();
1481     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1482   }
1483   FuncInfo.MBB->normalizeSuccProbs();
1484 
1485   // Create the terminator node.
1486   SDValue Ret =
1487       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1488   DAG.setRoot(Ret);
1489 }
1490 
1491 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1492   report_fatal_error("visitCatchSwitch not yet implemented!");
1493 }
1494 
1495 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1497   auto &DL = DAG.getDataLayout();
1498   SDValue Chain = getControlRoot();
1499   SmallVector<ISD::OutputArg, 8> Outs;
1500   SmallVector<SDValue, 8> OutVals;
1501 
1502   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1503   // lower
1504   //
1505   //   %val = call <ty> @llvm.experimental.deoptimize()
1506   //   ret <ty> %val
1507   //
1508   // differently.
1509   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1510     LowerDeoptimizingReturn();
1511     return;
1512   }
1513 
1514   if (!FuncInfo.CanLowerReturn) {
1515     unsigned DemoteReg = FuncInfo.DemoteRegister;
1516     const Function *F = I.getParent()->getParent();
1517 
1518     // Emit a store of the return value through the virtual register.
1519     // Leave Outs empty so that LowerReturn won't try to load return
1520     // registers the usual way.
1521     SmallVector<EVT, 1> PtrValueVTs;
1522     ComputeValueVTs(TLI, DL,
1523                     F->getReturnType()->getPointerTo(
1524                         DAG.getDataLayout().getAllocaAddrSpace()),
1525                     PtrValueVTs);
1526 
1527     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1528                                         DemoteReg, PtrValueVTs[0]);
1529     SDValue RetOp = getValue(I.getOperand(0));
1530 
1531     SmallVector<EVT, 4> ValueVTs;
1532     SmallVector<uint64_t, 4> Offsets;
1533     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1534     unsigned NumValues = ValueVTs.size();
1535 
1536     SmallVector<SDValue, 4> Chains(NumValues);
1537     for (unsigned i = 0; i != NumValues; ++i) {
1538       // An aggregate return value cannot wrap around the address space, so
1539       // offsets to its parts don't wrap either.
1540       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1541       Chains[i] = DAG.getStore(
1542           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1543           // FIXME: better loc info would be nice.
1544           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1545     }
1546 
1547     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1548                         MVT::Other, Chains);
1549   } else if (I.getNumOperands() != 0) {
1550     SmallVector<EVT, 4> ValueVTs;
1551     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1552     unsigned NumValues = ValueVTs.size();
1553     if (NumValues) {
1554       SDValue RetOp = getValue(I.getOperand(0));
1555 
1556       const Function *F = I.getParent()->getParent();
1557 
1558       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1559       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1560                                           Attribute::SExt))
1561         ExtendKind = ISD::SIGN_EXTEND;
1562       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1563                                                Attribute::ZExt))
1564         ExtendKind = ISD::ZERO_EXTEND;
1565 
1566       LLVMContext &Context = F->getContext();
1567       bool RetInReg = F->getAttributes().hasAttribute(
1568           AttributeList::ReturnIndex, Attribute::InReg);
1569 
1570       for (unsigned j = 0; j != NumValues; ++j) {
1571         EVT VT = ValueVTs[j];
1572 
1573         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1574           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1575 
1576         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1577         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1578         SmallVector<SDValue, 4> Parts(NumParts);
1579         getCopyToParts(DAG, getCurSDLoc(),
1580                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1581                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1582 
1583         // 'inreg' on function refers to return value
1584         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1585         if (RetInReg)
1586           Flags.setInReg();
1587 
1588         // Propagate extension type if any
1589         if (ExtendKind == ISD::SIGN_EXTEND)
1590           Flags.setSExt();
1591         else if (ExtendKind == ISD::ZERO_EXTEND)
1592           Flags.setZExt();
1593 
1594         for (unsigned i = 0; i < NumParts; ++i) {
1595           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1596                                         VT, /*isfixed=*/true, 0, 0));
1597           OutVals.push_back(Parts[i]);
1598         }
1599       }
1600     }
1601   }
1602 
1603   // Push in swifterror virtual register as the last element of Outs. This makes
1604   // sure swifterror virtual register will be returned in the swifterror
1605   // physical register.
1606   const Function *F = I.getParent()->getParent();
1607   if (TLI.supportSwiftError() &&
1608       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1609     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1610     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1611     Flags.setSwiftError();
1612     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1613                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1614                                   true /*isfixed*/, 1 /*origidx*/,
1615                                   0 /*partOffs*/));
1616     // Create SDNode for the swifterror virtual register.
1617     OutVals.push_back(
1618         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1619                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1620                         EVT(TLI.getPointerTy(DL))));
1621   }
1622 
1623   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1624   CallingConv::ID CallConv =
1625     DAG.getMachineFunction().getFunction().getCallingConv();
1626   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1627       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1628 
1629   // Verify that the target's LowerReturn behaved as expected.
1630   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1631          "LowerReturn didn't return a valid chain!");
1632 
1633   // Update the DAG with the new chain value resulting from return lowering.
1634   DAG.setRoot(Chain);
1635 }
1636 
1637 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1638 /// created for it, emit nodes to copy the value into the virtual
1639 /// registers.
1640 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1641   // Skip empty types
1642   if (V->getType()->isEmptyTy())
1643     return;
1644 
1645   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1646   if (VMI != FuncInfo.ValueMap.end()) {
1647     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1648     CopyValueToVirtualRegister(V, VMI->second);
1649   }
1650 }
1651 
1652 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1653 /// the current basic block, add it to ValueMap now so that we'll get a
1654 /// CopyTo/FromReg.
1655 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1656   // No need to export constants.
1657   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1658 
1659   // Already exported?
1660   if (FuncInfo.isExportedInst(V)) return;
1661 
1662   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1663   CopyValueToVirtualRegister(V, Reg);
1664 }
1665 
1666 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1667                                                      const BasicBlock *FromBB) {
1668   // The operands of the setcc have to be in this block.  We don't know
1669   // how to export them from some other block.
1670   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1671     // Can export from current BB.
1672     if (VI->getParent() == FromBB)
1673       return true;
1674 
1675     // Is already exported, noop.
1676     return FuncInfo.isExportedInst(V);
1677   }
1678 
1679   // If this is an argument, we can export it if the BB is the entry block or
1680   // if it is already exported.
1681   if (isa<Argument>(V)) {
1682     if (FromBB == &FromBB->getParent()->getEntryBlock())
1683       return true;
1684 
1685     // Otherwise, can only export this if it is already exported.
1686     return FuncInfo.isExportedInst(V);
1687   }
1688 
1689   // Otherwise, constants can always be exported.
1690   return true;
1691 }
1692 
1693 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1694 BranchProbability
1695 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1696                                         const MachineBasicBlock *Dst) const {
1697   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1698   const BasicBlock *SrcBB = Src->getBasicBlock();
1699   const BasicBlock *DstBB = Dst->getBasicBlock();
1700   if (!BPI) {
1701     // If BPI is not available, set the default probability as 1 / N, where N is
1702     // the number of successors.
1703     auto SuccSize = std::max<uint32_t>(
1704         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1705     return BranchProbability(1, SuccSize);
1706   }
1707   return BPI->getEdgeProbability(SrcBB, DstBB);
1708 }
1709 
1710 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1711                                                MachineBasicBlock *Dst,
1712                                                BranchProbability Prob) {
1713   if (!FuncInfo.BPI)
1714     Src->addSuccessorWithoutProb(Dst);
1715   else {
1716     if (Prob.isUnknown())
1717       Prob = getEdgeProbability(Src, Dst);
1718     Src->addSuccessor(Dst, Prob);
1719   }
1720 }
1721 
1722 static bool InBlock(const Value *V, const BasicBlock *BB) {
1723   if (const Instruction *I = dyn_cast<Instruction>(V))
1724     return I->getParent() == BB;
1725   return true;
1726 }
1727 
1728 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1729 /// This function emits a branch and is used at the leaves of an OR or an
1730 /// AND operator tree.
1731 void
1732 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1733                                                   MachineBasicBlock *TBB,
1734                                                   MachineBasicBlock *FBB,
1735                                                   MachineBasicBlock *CurBB,
1736                                                   MachineBasicBlock *SwitchBB,
1737                                                   BranchProbability TProb,
1738                                                   BranchProbability FProb,
1739                                                   bool InvertCond) {
1740   const BasicBlock *BB = CurBB->getBasicBlock();
1741 
1742   // If the leaf of the tree is a comparison, merge the condition into
1743   // the caseblock.
1744   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1745     // The operands of the cmp have to be in this block.  We don't know
1746     // how to export them from some other block.  If this is the first block
1747     // of the sequence, no exporting is needed.
1748     if (CurBB == SwitchBB ||
1749         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1750          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1751       ISD::CondCode Condition;
1752       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1753         ICmpInst::Predicate Pred =
1754             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1755         Condition = getICmpCondCode(Pred);
1756       } else {
1757         const FCmpInst *FC = cast<FCmpInst>(Cond);
1758         FCmpInst::Predicate Pred =
1759             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1760         Condition = getFCmpCondCode(Pred);
1761         if (TM.Options.NoNaNsFPMath)
1762           Condition = getFCmpCodeWithoutNaN(Condition);
1763       }
1764 
1765       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1766                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1767       SwitchCases.push_back(CB);
1768       return;
1769     }
1770   }
1771 
1772   // Create a CaseBlock record representing this branch.
1773   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1774   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1775                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1776   SwitchCases.push_back(CB);
1777 }
1778 
1779 /// FindMergedConditions - If Cond is an expression like
1780 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1781                                                MachineBasicBlock *TBB,
1782                                                MachineBasicBlock *FBB,
1783                                                MachineBasicBlock *CurBB,
1784                                                MachineBasicBlock *SwitchBB,
1785                                                Instruction::BinaryOps Opc,
1786                                                BranchProbability TProb,
1787                                                BranchProbability FProb,
1788                                                bool InvertCond) {
1789   // Skip over not part of the tree and remember to invert op and operands at
1790   // next level.
1791   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1792     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1793     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1794       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1795                            !InvertCond);
1796       return;
1797     }
1798   }
1799 
1800   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1801   // Compute the effective opcode for Cond, taking into account whether it needs
1802   // to be inverted, e.g.
1803   //   and (not (or A, B)), C
1804   // gets lowered as
1805   //   and (and (not A, not B), C)
1806   unsigned BOpc = 0;
1807   if (BOp) {
1808     BOpc = BOp->getOpcode();
1809     if (InvertCond) {
1810       if (BOpc == Instruction::And)
1811         BOpc = Instruction::Or;
1812       else if (BOpc == Instruction::Or)
1813         BOpc = Instruction::And;
1814     }
1815   }
1816 
1817   // If this node is not part of the or/and tree, emit it as a branch.
1818   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1819       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1820       BOp->getParent() != CurBB->getBasicBlock() ||
1821       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1822       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1823     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1824                                  TProb, FProb, InvertCond);
1825     return;
1826   }
1827 
1828   //  Create TmpBB after CurBB.
1829   MachineFunction::iterator BBI(CurBB);
1830   MachineFunction &MF = DAG.getMachineFunction();
1831   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1832   CurBB->getParent()->insert(++BBI, TmpBB);
1833 
1834   if (Opc == Instruction::Or) {
1835     // Codegen X | Y as:
1836     // BB1:
1837     //   jmp_if_X TBB
1838     //   jmp TmpBB
1839     // TmpBB:
1840     //   jmp_if_Y TBB
1841     //   jmp FBB
1842     //
1843 
1844     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1845     // The requirement is that
1846     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1847     //     = TrueProb for original BB.
1848     // Assuming the original probabilities are A and B, one choice is to set
1849     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1850     // A/(1+B) and 2B/(1+B). This choice assumes that
1851     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1852     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1853     // TmpBB, but the math is more complicated.
1854 
1855     auto NewTrueProb = TProb / 2;
1856     auto NewFalseProb = TProb / 2 + FProb;
1857     // Emit the LHS condition.
1858     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1859                          NewTrueProb, NewFalseProb, InvertCond);
1860 
1861     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1862     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1863     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1864     // Emit the RHS condition into TmpBB.
1865     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1866                          Probs[0], Probs[1], InvertCond);
1867   } else {
1868     assert(Opc == Instruction::And && "Unknown merge op!");
1869     // Codegen X & Y as:
1870     // BB1:
1871     //   jmp_if_X TmpBB
1872     //   jmp FBB
1873     // TmpBB:
1874     //   jmp_if_Y TBB
1875     //   jmp FBB
1876     //
1877     //  This requires creation of TmpBB after CurBB.
1878 
1879     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1880     // The requirement is that
1881     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1882     //     = FalseProb for original BB.
1883     // Assuming the original probabilities are A and B, one choice is to set
1884     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1885     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1886     // TrueProb for BB1 * FalseProb for TmpBB.
1887 
1888     auto NewTrueProb = TProb + FProb / 2;
1889     auto NewFalseProb = FProb / 2;
1890     // Emit the LHS condition.
1891     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1892                          NewTrueProb, NewFalseProb, InvertCond);
1893 
1894     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1895     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1896     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1897     // Emit the RHS condition into TmpBB.
1898     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1899                          Probs[0], Probs[1], InvertCond);
1900   }
1901 }
1902 
1903 /// If the set of cases should be emitted as a series of branches, return true.
1904 /// If we should emit this as a bunch of and/or'd together conditions, return
1905 /// false.
1906 bool
1907 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1908   if (Cases.size() != 2) return true;
1909 
1910   // If this is two comparisons of the same values or'd or and'd together, they
1911   // will get folded into a single comparison, so don't emit two blocks.
1912   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1913        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1914       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1915        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1916     return false;
1917   }
1918 
1919   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1920   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1921   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1922       Cases[0].CC == Cases[1].CC &&
1923       isa<Constant>(Cases[0].CmpRHS) &&
1924       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1925     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1926       return false;
1927     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1928       return false;
1929   }
1930 
1931   return true;
1932 }
1933 
1934 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1935   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1936 
1937   // Update machine-CFG edges.
1938   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1939 
1940   if (I.isUnconditional()) {
1941     // Update machine-CFG edges.
1942     BrMBB->addSuccessor(Succ0MBB);
1943 
1944     // If this is not a fall-through branch or optimizations are switched off,
1945     // emit the branch.
1946     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1947       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1948                               MVT::Other, getControlRoot(),
1949                               DAG.getBasicBlock(Succ0MBB)));
1950 
1951     return;
1952   }
1953 
1954   // If this condition is one of the special cases we handle, do special stuff
1955   // now.
1956   const Value *CondVal = I.getCondition();
1957   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1958 
1959   // If this is a series of conditions that are or'd or and'd together, emit
1960   // this as a sequence of branches instead of setcc's with and/or operations.
1961   // As long as jumps are not expensive, this should improve performance.
1962   // For example, instead of something like:
1963   //     cmp A, B
1964   //     C = seteq
1965   //     cmp D, E
1966   //     F = setle
1967   //     or C, F
1968   //     jnz foo
1969   // Emit:
1970   //     cmp A, B
1971   //     je foo
1972   //     cmp D, E
1973   //     jle foo
1974   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1975     Instruction::BinaryOps Opcode = BOp->getOpcode();
1976     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1977         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1978         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1979       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1980                            Opcode,
1981                            getEdgeProbability(BrMBB, Succ0MBB),
1982                            getEdgeProbability(BrMBB, Succ1MBB),
1983                            /*InvertCond=*/false);
1984       // If the compares in later blocks need to use values not currently
1985       // exported from this block, export them now.  This block should always
1986       // be the first entry.
1987       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1988 
1989       // Allow some cases to be rejected.
1990       if (ShouldEmitAsBranches(SwitchCases)) {
1991         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1992           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1993           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1994         }
1995 
1996         // Emit the branch for this block.
1997         visitSwitchCase(SwitchCases[0], BrMBB);
1998         SwitchCases.erase(SwitchCases.begin());
1999         return;
2000       }
2001 
2002       // Okay, we decided not to do this, remove any inserted MBB's and clear
2003       // SwitchCases.
2004       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2005         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2006 
2007       SwitchCases.clear();
2008     }
2009   }
2010 
2011   // Create a CaseBlock record representing this branch.
2012   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2013                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2014 
2015   // Use visitSwitchCase to actually insert the fast branch sequence for this
2016   // cond branch.
2017   visitSwitchCase(CB, BrMBB);
2018 }
2019 
2020 /// visitSwitchCase - Emits the necessary code to represent a single node in
2021 /// the binary search tree resulting from lowering a switch instruction.
2022 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2023                                           MachineBasicBlock *SwitchBB) {
2024   SDValue Cond;
2025   SDValue CondLHS = getValue(CB.CmpLHS);
2026   SDLoc dl = CB.DL;
2027 
2028   // Build the setcc now.
2029   if (!CB.CmpMHS) {
2030     // Fold "(X == true)" to X and "(X == false)" to !X to
2031     // handle common cases produced by branch lowering.
2032     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2033         CB.CC == ISD::SETEQ)
2034       Cond = CondLHS;
2035     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2036              CB.CC == ISD::SETEQ) {
2037       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2038       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2039     } else
2040       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2041   } else {
2042     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2043 
2044     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2045     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2046 
2047     SDValue CmpOp = getValue(CB.CmpMHS);
2048     EVT VT = CmpOp.getValueType();
2049 
2050     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2051       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2052                           ISD::SETLE);
2053     } else {
2054       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2055                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2056       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2057                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2058     }
2059   }
2060 
2061   // Update successor info
2062   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2063   // TrueBB and FalseBB are always different unless the incoming IR is
2064   // degenerate. This only happens when running llc on weird IR.
2065   if (CB.TrueBB != CB.FalseBB)
2066     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2067   SwitchBB->normalizeSuccProbs();
2068 
2069   // If the lhs block is the next block, invert the condition so that we can
2070   // fall through to the lhs instead of the rhs block.
2071   if (CB.TrueBB == NextBlock(SwitchBB)) {
2072     std::swap(CB.TrueBB, CB.FalseBB);
2073     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2074     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2075   }
2076 
2077   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2078                                MVT::Other, getControlRoot(), Cond,
2079                                DAG.getBasicBlock(CB.TrueBB));
2080 
2081   // Insert the false branch. Do this even if it's a fall through branch,
2082   // this makes it easier to do DAG optimizations which require inverting
2083   // the branch condition.
2084   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2085                        DAG.getBasicBlock(CB.FalseBB));
2086 
2087   DAG.setRoot(BrCond);
2088 }
2089 
2090 /// visitJumpTable - Emit JumpTable node in the current MBB
2091 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2092   // Emit the code for the jump table
2093   assert(JT.Reg != -1U && "Should lower JT Header first!");
2094   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2095   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2096                                      JT.Reg, PTy);
2097   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2098   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2099                                     MVT::Other, Index.getValue(1),
2100                                     Table, Index);
2101   DAG.setRoot(BrJumpTable);
2102 }
2103 
2104 /// visitJumpTableHeader - This function emits necessary code to produce index
2105 /// in the JumpTable from switch case.
2106 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2107                                                JumpTableHeader &JTH,
2108                                                MachineBasicBlock *SwitchBB) {
2109   SDLoc dl = getCurSDLoc();
2110 
2111   // Subtract the lowest switch case value from the value being switched on and
2112   // conditional branch to default mbb if the result is greater than the
2113   // difference between smallest and largest cases.
2114   SDValue SwitchOp = getValue(JTH.SValue);
2115   EVT VT = SwitchOp.getValueType();
2116   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2117                             DAG.getConstant(JTH.First, dl, VT));
2118 
2119   // The SDNode we just created, which holds the value being switched on minus
2120   // the smallest case value, needs to be copied to a virtual register so it
2121   // can be used as an index into the jump table in a subsequent basic block.
2122   // This value may be smaller or larger than the target's pointer type, and
2123   // therefore require extension or truncating.
2124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2125   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2126 
2127   unsigned JumpTableReg =
2128       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2129   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2130                                     JumpTableReg, SwitchOp);
2131   JT.Reg = JumpTableReg;
2132 
2133   // Emit the range check for the jump table, and branch to the default block
2134   // for the switch statement if the value being switched on exceeds the largest
2135   // case in the switch.
2136   SDValue CMP = DAG.getSetCC(
2137       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2138                                  Sub.getValueType()),
2139       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2140 
2141   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2142                                MVT::Other, CopyTo, CMP,
2143                                DAG.getBasicBlock(JT.Default));
2144 
2145   // Avoid emitting unnecessary branches to the next block.
2146   if (JT.MBB != NextBlock(SwitchBB))
2147     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2148                          DAG.getBasicBlock(JT.MBB));
2149 
2150   DAG.setRoot(BrCond);
2151 }
2152 
2153 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2154 /// variable if there exists one.
2155 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2156                                  SDValue &Chain) {
2157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2158   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2159   MachineFunction &MF = DAG.getMachineFunction();
2160   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2161   MachineSDNode *Node =
2162       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2163   if (Global) {
2164     MachinePointerInfo MPInfo(Global);
2165     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2166     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2167                  MachineMemOperand::MODereferenceable;
2168     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2169                                        DAG.getEVTAlignment(PtrTy));
2170     Node->setMemRefs(MemRefs, MemRefs + 1);
2171   }
2172   return SDValue(Node, 0);
2173 }
2174 
2175 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2176 /// tail spliced into a stack protector check success bb.
2177 ///
2178 /// For a high level explanation of how this fits into the stack protector
2179 /// generation see the comment on the declaration of class
2180 /// StackProtectorDescriptor.
2181 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2182                                                   MachineBasicBlock *ParentBB) {
2183 
2184   // First create the loads to the guard/stack slot for the comparison.
2185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2186   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2187 
2188   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2189   int FI = MFI.getStackProtectorIndex();
2190 
2191   SDValue Guard;
2192   SDLoc dl = getCurSDLoc();
2193   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2194   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2195   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2196 
2197   // Generate code to load the content of the guard slot.
2198   SDValue GuardVal = DAG.getLoad(
2199       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2200       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2201       MachineMemOperand::MOVolatile);
2202 
2203   if (TLI.useStackGuardXorFP())
2204     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2205 
2206   // Retrieve guard check function, nullptr if instrumentation is inlined.
2207   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2208     // The target provides a guard check function to validate the guard value.
2209     // Generate a call to that function with the content of the guard slot as
2210     // argument.
2211     auto *Fn = cast<Function>(GuardCheck);
2212     FunctionType *FnTy = Fn->getFunctionType();
2213     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2214 
2215     TargetLowering::ArgListTy Args;
2216     TargetLowering::ArgListEntry Entry;
2217     Entry.Node = GuardVal;
2218     Entry.Ty = FnTy->getParamType(0);
2219     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2220       Entry.IsInReg = true;
2221     Args.push_back(Entry);
2222 
2223     TargetLowering::CallLoweringInfo CLI(DAG);
2224     CLI.setDebugLoc(getCurSDLoc())
2225       .setChain(DAG.getEntryNode())
2226       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2227                  getValue(GuardCheck), std::move(Args));
2228 
2229     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2230     DAG.setRoot(Result.second);
2231     return;
2232   }
2233 
2234   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2235   // Otherwise, emit a volatile load to retrieve the stack guard value.
2236   SDValue Chain = DAG.getEntryNode();
2237   if (TLI.useLoadStackGuardNode()) {
2238     Guard = getLoadStackGuard(DAG, dl, Chain);
2239   } else {
2240     const Value *IRGuard = TLI.getSDagStackGuard(M);
2241     SDValue GuardPtr = getValue(IRGuard);
2242 
2243     Guard =
2244         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2245                     Align, MachineMemOperand::MOVolatile);
2246   }
2247 
2248   // Perform the comparison via a subtract/getsetcc.
2249   EVT VT = Guard.getValueType();
2250   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2251 
2252   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2253                                                         *DAG.getContext(),
2254                                                         Sub.getValueType()),
2255                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2256 
2257   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2258   // branch to failure MBB.
2259   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2260                                MVT::Other, GuardVal.getOperand(0),
2261                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2262   // Otherwise branch to success MBB.
2263   SDValue Br = DAG.getNode(ISD::BR, dl,
2264                            MVT::Other, BrCond,
2265                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2266 
2267   DAG.setRoot(Br);
2268 }
2269 
2270 /// Codegen the failure basic block for a stack protector check.
2271 ///
2272 /// A failure stack protector machine basic block consists simply of a call to
2273 /// __stack_chk_fail().
2274 ///
2275 /// For a high level explanation of how this fits into the stack protector
2276 /// generation see the comment on the declaration of class
2277 /// StackProtectorDescriptor.
2278 void
2279 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2281   SDValue Chain =
2282       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2283                       None, false, getCurSDLoc(), false, false).second;
2284   DAG.setRoot(Chain);
2285 }
2286 
2287 /// visitBitTestHeader - This function emits necessary code to produce value
2288 /// suitable for "bit tests"
2289 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2290                                              MachineBasicBlock *SwitchBB) {
2291   SDLoc dl = getCurSDLoc();
2292 
2293   // Subtract the minimum value
2294   SDValue SwitchOp = getValue(B.SValue);
2295   EVT VT = SwitchOp.getValueType();
2296   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2297                             DAG.getConstant(B.First, dl, VT));
2298 
2299   // Check range
2300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2301   SDValue RangeCmp = DAG.getSetCC(
2302       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2303                                  Sub.getValueType()),
2304       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2305 
2306   // Determine the type of the test operands.
2307   bool UsePtrType = false;
2308   if (!TLI.isTypeLegal(VT))
2309     UsePtrType = true;
2310   else {
2311     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2312       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2313         // Switch table case range are encoded into series of masks.
2314         // Just use pointer type, it's guaranteed to fit.
2315         UsePtrType = true;
2316         break;
2317       }
2318   }
2319   if (UsePtrType) {
2320     VT = TLI.getPointerTy(DAG.getDataLayout());
2321     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2322   }
2323 
2324   B.RegVT = VT.getSimpleVT();
2325   B.Reg = FuncInfo.CreateReg(B.RegVT);
2326   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2327 
2328   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2329 
2330   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2331   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2332   SwitchBB->normalizeSuccProbs();
2333 
2334   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2335                                 MVT::Other, CopyTo, RangeCmp,
2336                                 DAG.getBasicBlock(B.Default));
2337 
2338   // Avoid emitting unnecessary branches to the next block.
2339   if (MBB != NextBlock(SwitchBB))
2340     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2341                           DAG.getBasicBlock(MBB));
2342 
2343   DAG.setRoot(BrRange);
2344 }
2345 
2346 /// visitBitTestCase - this function produces one "bit test"
2347 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2348                                            MachineBasicBlock* NextMBB,
2349                                            BranchProbability BranchProbToNext,
2350                                            unsigned Reg,
2351                                            BitTestCase &B,
2352                                            MachineBasicBlock *SwitchBB) {
2353   SDLoc dl = getCurSDLoc();
2354   MVT VT = BB.RegVT;
2355   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2356   SDValue Cmp;
2357   unsigned PopCount = countPopulation(B.Mask);
2358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2359   if (PopCount == 1) {
2360     // Testing for a single bit; just compare the shift count with what it
2361     // would need to be to shift a 1 bit in that position.
2362     Cmp = DAG.getSetCC(
2363         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2364         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2365         ISD::SETEQ);
2366   } else if (PopCount == BB.Range) {
2367     // There is only one zero bit in the range, test for it directly.
2368     Cmp = DAG.getSetCC(
2369         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2370         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2371         ISD::SETNE);
2372   } else {
2373     // Make desired shift
2374     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2375                                     DAG.getConstant(1, dl, VT), ShiftOp);
2376 
2377     // Emit bit tests and jumps
2378     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2379                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2380     Cmp = DAG.getSetCC(
2381         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2382         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2383   }
2384 
2385   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2386   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2387   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2388   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2389   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2390   // one as they are relative probabilities (and thus work more like weights),
2391   // and hence we need to normalize them to let the sum of them become one.
2392   SwitchBB->normalizeSuccProbs();
2393 
2394   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2395                               MVT::Other, getControlRoot(),
2396                               Cmp, DAG.getBasicBlock(B.TargetBB));
2397 
2398   // Avoid emitting unnecessary branches to the next block.
2399   if (NextMBB != NextBlock(SwitchBB))
2400     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2401                         DAG.getBasicBlock(NextMBB));
2402 
2403   DAG.setRoot(BrAnd);
2404 }
2405 
2406 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2407   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2408 
2409   // Retrieve successors. Look through artificial IR level blocks like
2410   // catchswitch for successors.
2411   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2412   const BasicBlock *EHPadBB = I.getSuccessor(1);
2413 
2414   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2415   // have to do anything here to lower funclet bundles.
2416   assert(!I.hasOperandBundlesOtherThan(
2417              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2418          "Cannot lower invokes with arbitrary operand bundles yet!");
2419 
2420   const Value *Callee(I.getCalledValue());
2421   const Function *Fn = dyn_cast<Function>(Callee);
2422   if (isa<InlineAsm>(Callee))
2423     visitInlineAsm(&I);
2424   else if (Fn && Fn->isIntrinsic()) {
2425     switch (Fn->getIntrinsicID()) {
2426     default:
2427       llvm_unreachable("Cannot invoke this intrinsic");
2428     case Intrinsic::donothing:
2429       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2430       break;
2431     case Intrinsic::experimental_patchpoint_void:
2432     case Intrinsic::experimental_patchpoint_i64:
2433       visitPatchpoint(&I, EHPadBB);
2434       break;
2435     case Intrinsic::experimental_gc_statepoint:
2436       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2437       break;
2438     }
2439   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2440     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2441     // Eventually we will support lowering the @llvm.experimental.deoptimize
2442     // intrinsic, and right now there are no plans to support other intrinsics
2443     // with deopt state.
2444     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2445   } else {
2446     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2447   }
2448 
2449   // If the value of the invoke is used outside of its defining block, make it
2450   // available as a virtual register.
2451   // We already took care of the exported value for the statepoint instruction
2452   // during call to the LowerStatepoint.
2453   if (!isStatepoint(I)) {
2454     CopyToExportRegsIfNeeded(&I);
2455   }
2456 
2457   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2458   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2459   BranchProbability EHPadBBProb =
2460       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2461           : BranchProbability::getZero();
2462   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2463 
2464   // Update successor info.
2465   addSuccessorWithProb(InvokeMBB, Return);
2466   for (auto &UnwindDest : UnwindDests) {
2467     UnwindDest.first->setIsEHPad();
2468     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2469   }
2470   InvokeMBB->normalizeSuccProbs();
2471 
2472   // Drop into normal successor.
2473   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2474                           MVT::Other, getControlRoot(),
2475                           DAG.getBasicBlock(Return)));
2476 }
2477 
2478 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2479   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2480 }
2481 
2482 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2483   assert(FuncInfo.MBB->isEHPad() &&
2484          "Call to landingpad not in landing pad!");
2485 
2486   MachineBasicBlock *MBB = FuncInfo.MBB;
2487   addLandingPadInfo(LP, *MBB);
2488 
2489   // If there aren't registers to copy the values into (e.g., during SjLj
2490   // exceptions), then don't bother to create these DAG nodes.
2491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2492   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2493   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2494       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2495     return;
2496 
2497   // If landingpad's return type is token type, we don't create DAG nodes
2498   // for its exception pointer and selector value. The extraction of exception
2499   // pointer or selector value from token type landingpads is not currently
2500   // supported.
2501   if (LP.getType()->isTokenTy())
2502     return;
2503 
2504   SmallVector<EVT, 2> ValueVTs;
2505   SDLoc dl = getCurSDLoc();
2506   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2507   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2508 
2509   // Get the two live-in registers as SDValues. The physregs have already been
2510   // copied into virtual registers.
2511   SDValue Ops[2];
2512   if (FuncInfo.ExceptionPointerVirtReg) {
2513     Ops[0] = DAG.getZExtOrTrunc(
2514         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2515                            FuncInfo.ExceptionPointerVirtReg,
2516                            TLI.getPointerTy(DAG.getDataLayout())),
2517         dl, ValueVTs[0]);
2518   } else {
2519     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2520   }
2521   Ops[1] = DAG.getZExtOrTrunc(
2522       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2523                          FuncInfo.ExceptionSelectorVirtReg,
2524                          TLI.getPointerTy(DAG.getDataLayout())),
2525       dl, ValueVTs[1]);
2526 
2527   // Merge into one.
2528   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2529                             DAG.getVTList(ValueVTs), Ops);
2530   setValue(&LP, Res);
2531 }
2532 
2533 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2534 #ifndef NDEBUG
2535   for (const CaseCluster &CC : Clusters)
2536     assert(CC.Low == CC.High && "Input clusters must be single-case");
2537 #endif
2538 
2539   llvm::sort(Clusters.begin(), Clusters.end(),
2540              [](const CaseCluster &a, const CaseCluster &b) {
2541     return a.Low->getValue().slt(b.Low->getValue());
2542   });
2543 
2544   // Merge adjacent clusters with the same destination.
2545   const unsigned N = Clusters.size();
2546   unsigned DstIndex = 0;
2547   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2548     CaseCluster &CC = Clusters[SrcIndex];
2549     const ConstantInt *CaseVal = CC.Low;
2550     MachineBasicBlock *Succ = CC.MBB;
2551 
2552     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2553         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2554       // If this case has the same successor and is a neighbour, merge it into
2555       // the previous cluster.
2556       Clusters[DstIndex - 1].High = CaseVal;
2557       Clusters[DstIndex - 1].Prob += CC.Prob;
2558     } else {
2559       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2560                    sizeof(Clusters[SrcIndex]));
2561     }
2562   }
2563   Clusters.resize(DstIndex);
2564 }
2565 
2566 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2567                                            MachineBasicBlock *Last) {
2568   // Update JTCases.
2569   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2570     if (JTCases[i].first.HeaderBB == First)
2571       JTCases[i].first.HeaderBB = Last;
2572 
2573   // Update BitTestCases.
2574   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2575     if (BitTestCases[i].Parent == First)
2576       BitTestCases[i].Parent = Last;
2577 }
2578 
2579 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2580   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2581 
2582   // Update machine-CFG edges with unique successors.
2583   SmallSet<BasicBlock*, 32> Done;
2584   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2585     BasicBlock *BB = I.getSuccessor(i);
2586     bool Inserted = Done.insert(BB).second;
2587     if (!Inserted)
2588         continue;
2589 
2590     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2591     addSuccessorWithProb(IndirectBrMBB, Succ);
2592   }
2593   IndirectBrMBB->normalizeSuccProbs();
2594 
2595   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2596                           MVT::Other, getControlRoot(),
2597                           getValue(I.getAddress())));
2598 }
2599 
2600 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2601   if (DAG.getTarget().Options.TrapUnreachable)
2602     DAG.setRoot(
2603         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2604 }
2605 
2606 void SelectionDAGBuilder::visitFSub(const User &I) {
2607   // -0.0 - X --> fneg
2608   Type *Ty = I.getType();
2609   if (isa<Constant>(I.getOperand(0)) &&
2610       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2611     SDValue Op2 = getValue(I.getOperand(1));
2612     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2613                              Op2.getValueType(), Op2));
2614     return;
2615   }
2616 
2617   visitBinary(I, ISD::FSUB);
2618 }
2619 
2620 /// Checks if the given instruction performs a vector reduction, in which case
2621 /// we have the freedom to alter the elements in the result as long as the
2622 /// reduction of them stays unchanged.
2623 static bool isVectorReductionOp(const User *I) {
2624   const Instruction *Inst = dyn_cast<Instruction>(I);
2625   if (!Inst || !Inst->getType()->isVectorTy())
2626     return false;
2627 
2628   auto OpCode = Inst->getOpcode();
2629   switch (OpCode) {
2630   case Instruction::Add:
2631   case Instruction::Mul:
2632   case Instruction::And:
2633   case Instruction::Or:
2634   case Instruction::Xor:
2635     break;
2636   case Instruction::FAdd:
2637   case Instruction::FMul:
2638     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2639       if (FPOp->getFastMathFlags().isFast())
2640         break;
2641     LLVM_FALLTHROUGH;
2642   default:
2643     return false;
2644   }
2645 
2646   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2647   unsigned ElemNumToReduce = ElemNum;
2648 
2649   // Do DFS search on the def-use chain from the given instruction. We only
2650   // allow four kinds of operations during the search until we reach the
2651   // instruction that extracts the first element from the vector:
2652   //
2653   //   1. The reduction operation of the same opcode as the given instruction.
2654   //
2655   //   2. PHI node.
2656   //
2657   //   3. ShuffleVector instruction together with a reduction operation that
2658   //      does a partial reduction.
2659   //
2660   //   4. ExtractElement that extracts the first element from the vector, and we
2661   //      stop searching the def-use chain here.
2662   //
2663   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2664   // from 1-3 to the stack to continue the DFS. The given instruction is not
2665   // a reduction operation if we meet any other instructions other than those
2666   // listed above.
2667 
2668   SmallVector<const User *, 16> UsersToVisit{Inst};
2669   SmallPtrSet<const User *, 16> Visited;
2670   bool ReduxExtracted = false;
2671 
2672   while (!UsersToVisit.empty()) {
2673     auto User = UsersToVisit.back();
2674     UsersToVisit.pop_back();
2675     if (!Visited.insert(User).second)
2676       continue;
2677 
2678     for (const auto &U : User->users()) {
2679       auto Inst = dyn_cast<Instruction>(U);
2680       if (!Inst)
2681         return false;
2682 
2683       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2684         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2685           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2686             return false;
2687         UsersToVisit.push_back(U);
2688       } else if (const ShuffleVectorInst *ShufInst =
2689                      dyn_cast<ShuffleVectorInst>(U)) {
2690         // Detect the following pattern: A ShuffleVector instruction together
2691         // with a reduction that do partial reduction on the first and second
2692         // ElemNumToReduce / 2 elements, and store the result in
2693         // ElemNumToReduce / 2 elements in another vector.
2694 
2695         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2696         if (ResultElements < ElemNum)
2697           return false;
2698 
2699         if (ElemNumToReduce == 1)
2700           return false;
2701         if (!isa<UndefValue>(U->getOperand(1)))
2702           return false;
2703         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2704           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2705             return false;
2706         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2707           if (ShufInst->getMaskValue(i) != -1)
2708             return false;
2709 
2710         // There is only one user of this ShuffleVector instruction, which
2711         // must be a reduction operation.
2712         if (!U->hasOneUse())
2713           return false;
2714 
2715         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2716         if (!U2 || U2->getOpcode() != OpCode)
2717           return false;
2718 
2719         // Check operands of the reduction operation.
2720         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2721             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2722           UsersToVisit.push_back(U2);
2723           ElemNumToReduce /= 2;
2724         } else
2725           return false;
2726       } else if (isa<ExtractElementInst>(U)) {
2727         // At this moment we should have reduced all elements in the vector.
2728         if (ElemNumToReduce != 1)
2729           return false;
2730 
2731         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2732         if (!Val || Val->getZExtValue() != 0)
2733           return false;
2734 
2735         ReduxExtracted = true;
2736       } else
2737         return false;
2738     }
2739   }
2740   return ReduxExtracted;
2741 }
2742 
2743 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2744   SDValue Op1 = getValue(I.getOperand(0));
2745   SDValue Op2 = getValue(I.getOperand(1));
2746 
2747   bool nuw = false;
2748   bool nsw = false;
2749   bool exact = false;
2750   bool vec_redux = false;
2751   FastMathFlags FMF;
2752 
2753   if (const OverflowingBinaryOperator *OFBinOp =
2754           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2755     nuw = OFBinOp->hasNoUnsignedWrap();
2756     nsw = OFBinOp->hasNoSignedWrap();
2757   }
2758   if (const PossiblyExactOperator *ExactOp =
2759           dyn_cast<const PossiblyExactOperator>(&I))
2760     exact = ExactOp->isExact();
2761   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2762     FMF = FPOp->getFastMathFlags();
2763 
2764   if (isVectorReductionOp(&I)) {
2765     vec_redux = true;
2766     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2767   }
2768 
2769   SDNodeFlags Flags;
2770   Flags.setExact(exact);
2771   Flags.setNoSignedWrap(nsw);
2772   Flags.setNoUnsignedWrap(nuw);
2773   Flags.setVectorReduction(vec_redux);
2774   Flags.setAllowReciprocal(FMF.allowReciprocal());
2775   Flags.setAllowContract(FMF.allowContract());
2776   Flags.setNoInfs(FMF.noInfs());
2777   Flags.setNoNaNs(FMF.noNaNs());
2778   Flags.setNoSignedZeros(FMF.noSignedZeros());
2779   Flags.setApproximateFuncs(FMF.approxFunc());
2780   Flags.setAllowReassociation(FMF.allowReassoc());
2781 
2782   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2783                                      Op1, Op2, Flags);
2784   setValue(&I, BinNodeValue);
2785 }
2786 
2787 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2788   SDValue Op1 = getValue(I.getOperand(0));
2789   SDValue Op2 = getValue(I.getOperand(1));
2790 
2791   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2792       Op2.getValueType(), DAG.getDataLayout());
2793 
2794   // Coerce the shift amount to the right type if we can.
2795   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2796     unsigned ShiftSize = ShiftTy.getSizeInBits();
2797     unsigned Op2Size = Op2.getValueSizeInBits();
2798     SDLoc DL = getCurSDLoc();
2799 
2800     // If the operand is smaller than the shift count type, promote it.
2801     if (ShiftSize > Op2Size)
2802       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2803 
2804     // If the operand is larger than the shift count type but the shift
2805     // count type has enough bits to represent any shift value, truncate
2806     // it now. This is a common case and it exposes the truncate to
2807     // optimization early.
2808     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2809       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2810     // Otherwise we'll need to temporarily settle for some other convenient
2811     // type.  Type legalization will make adjustments once the shiftee is split.
2812     else
2813       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2814   }
2815 
2816   bool nuw = false;
2817   bool nsw = false;
2818   bool exact = false;
2819 
2820   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2821 
2822     if (const OverflowingBinaryOperator *OFBinOp =
2823             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2824       nuw = OFBinOp->hasNoUnsignedWrap();
2825       nsw = OFBinOp->hasNoSignedWrap();
2826     }
2827     if (const PossiblyExactOperator *ExactOp =
2828             dyn_cast<const PossiblyExactOperator>(&I))
2829       exact = ExactOp->isExact();
2830   }
2831   SDNodeFlags Flags;
2832   Flags.setExact(exact);
2833   Flags.setNoSignedWrap(nsw);
2834   Flags.setNoUnsignedWrap(nuw);
2835   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2836                             Flags);
2837   setValue(&I, Res);
2838 }
2839 
2840 void SelectionDAGBuilder::visitSDiv(const User &I) {
2841   SDValue Op1 = getValue(I.getOperand(0));
2842   SDValue Op2 = getValue(I.getOperand(1));
2843 
2844   SDNodeFlags Flags;
2845   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2846                  cast<PossiblyExactOperator>(&I)->isExact());
2847   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2848                            Op2, Flags));
2849 }
2850 
2851 void SelectionDAGBuilder::visitICmp(const User &I) {
2852   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2853   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2854     predicate = IC->getPredicate();
2855   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2856     predicate = ICmpInst::Predicate(IC->getPredicate());
2857   SDValue Op1 = getValue(I.getOperand(0));
2858   SDValue Op2 = getValue(I.getOperand(1));
2859   ISD::CondCode Opcode = getICmpCondCode(predicate);
2860 
2861   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2862                                                         I.getType());
2863   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2864 }
2865 
2866 void SelectionDAGBuilder::visitFCmp(const User &I) {
2867   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2868   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2869     predicate = FC->getPredicate();
2870   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2871     predicate = FCmpInst::Predicate(FC->getPredicate());
2872   SDValue Op1 = getValue(I.getOperand(0));
2873   SDValue Op2 = getValue(I.getOperand(1));
2874   ISD::CondCode Condition = getFCmpCondCode(predicate);
2875 
2876   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2877   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2878   // further optimization, but currently FMF is only applicable to binary nodes.
2879   if (TM.Options.NoNaNsFPMath)
2880     Condition = getFCmpCodeWithoutNaN(Condition);
2881   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2882                                                         I.getType());
2883   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2884 }
2885 
2886 // Check if the condition of the select has one use or two users that are both
2887 // selects with the same condition.
2888 static bool hasOnlySelectUsers(const Value *Cond) {
2889   return llvm::all_of(Cond->users(), [](const Value *V) {
2890     return isa<SelectInst>(V);
2891   });
2892 }
2893 
2894 void SelectionDAGBuilder::visitSelect(const User &I) {
2895   SmallVector<EVT, 4> ValueVTs;
2896   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2897                   ValueVTs);
2898   unsigned NumValues = ValueVTs.size();
2899   if (NumValues == 0) return;
2900 
2901   SmallVector<SDValue, 4> Values(NumValues);
2902   SDValue Cond     = getValue(I.getOperand(0));
2903   SDValue LHSVal   = getValue(I.getOperand(1));
2904   SDValue RHSVal   = getValue(I.getOperand(2));
2905   auto BaseOps = {Cond};
2906   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2907     ISD::VSELECT : ISD::SELECT;
2908 
2909   // Min/max matching is only viable if all output VTs are the same.
2910   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2911     EVT VT = ValueVTs[0];
2912     LLVMContext &Ctx = *DAG.getContext();
2913     auto &TLI = DAG.getTargetLoweringInfo();
2914 
2915     // We care about the legality of the operation after it has been type
2916     // legalized.
2917     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2918            VT != TLI.getTypeToTransformTo(Ctx, VT))
2919       VT = TLI.getTypeToTransformTo(Ctx, VT);
2920 
2921     // If the vselect is legal, assume we want to leave this as a vector setcc +
2922     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2923     // min/max is legal on the scalar type.
2924     bool UseScalarMinMax = VT.isVector() &&
2925       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2926 
2927     Value *LHS, *RHS;
2928     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2929     ISD::NodeType Opc = ISD::DELETED_NODE;
2930     switch (SPR.Flavor) {
2931     case SPF_UMAX:    Opc = ISD::UMAX; break;
2932     case SPF_UMIN:    Opc = ISD::UMIN; break;
2933     case SPF_SMAX:    Opc = ISD::SMAX; break;
2934     case SPF_SMIN:    Opc = ISD::SMIN; break;
2935     case SPF_FMINNUM:
2936       switch (SPR.NaNBehavior) {
2937       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2938       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2939       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2940       case SPNB_RETURNS_ANY: {
2941         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2942           Opc = ISD::FMINNUM;
2943         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2944           Opc = ISD::FMINNAN;
2945         else if (UseScalarMinMax)
2946           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2947             ISD::FMINNUM : ISD::FMINNAN;
2948         break;
2949       }
2950       }
2951       break;
2952     case SPF_FMAXNUM:
2953       switch (SPR.NaNBehavior) {
2954       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2955       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2956       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2957       case SPNB_RETURNS_ANY:
2958 
2959         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2960           Opc = ISD::FMAXNUM;
2961         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2962           Opc = ISD::FMAXNAN;
2963         else if (UseScalarMinMax)
2964           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2965             ISD::FMAXNUM : ISD::FMAXNAN;
2966         break;
2967       }
2968       break;
2969     default: break;
2970     }
2971 
2972     if (Opc != ISD::DELETED_NODE &&
2973         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2974          (UseScalarMinMax &&
2975           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2976         // If the underlying comparison instruction is used by any other
2977         // instruction, the consumed instructions won't be destroyed, so it is
2978         // not profitable to convert to a min/max.
2979         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2980       OpCode = Opc;
2981       LHSVal = getValue(LHS);
2982       RHSVal = getValue(RHS);
2983       BaseOps = {};
2984     }
2985   }
2986 
2987   for (unsigned i = 0; i != NumValues; ++i) {
2988     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2989     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2990     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2991     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2992                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2993                             Ops);
2994   }
2995 
2996   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2997                            DAG.getVTList(ValueVTs), Values));
2998 }
2999 
3000 void SelectionDAGBuilder::visitTrunc(const User &I) {
3001   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3002   SDValue N = getValue(I.getOperand(0));
3003   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3004                                                         I.getType());
3005   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3006 }
3007 
3008 void SelectionDAGBuilder::visitZExt(const User &I) {
3009   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3010   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3011   SDValue N = getValue(I.getOperand(0));
3012   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3013                                                         I.getType());
3014   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3015 }
3016 
3017 void SelectionDAGBuilder::visitSExt(const User &I) {
3018   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3019   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3020   SDValue N = getValue(I.getOperand(0));
3021   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3022                                                         I.getType());
3023   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3024 }
3025 
3026 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3027   // FPTrunc is never a no-op cast, no need to check
3028   SDValue N = getValue(I.getOperand(0));
3029   SDLoc dl = getCurSDLoc();
3030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3031   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3032   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3033                            DAG.getTargetConstant(
3034                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3035 }
3036 
3037 void SelectionDAGBuilder::visitFPExt(const User &I) {
3038   // FPExt is never a no-op cast, no need to check
3039   SDValue N = getValue(I.getOperand(0));
3040   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3041                                                         I.getType());
3042   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3043 }
3044 
3045 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3046   // FPToUI is never a no-op cast, no need to check
3047   SDValue N = getValue(I.getOperand(0));
3048   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3049                                                         I.getType());
3050   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3051 }
3052 
3053 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3054   // FPToSI is never a no-op cast, no need to check
3055   SDValue N = getValue(I.getOperand(0));
3056   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3057                                                         I.getType());
3058   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3059 }
3060 
3061 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3062   // UIToFP is never a no-op cast, no need to check
3063   SDValue N = getValue(I.getOperand(0));
3064   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3065                                                         I.getType());
3066   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3067 }
3068 
3069 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3070   // SIToFP is never a no-op cast, no need to check
3071   SDValue N = getValue(I.getOperand(0));
3072   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3073                                                         I.getType());
3074   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3075 }
3076 
3077 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3078   // What to do depends on the size of the integer and the size of the pointer.
3079   // We can either truncate, zero extend, or no-op, accordingly.
3080   SDValue N = getValue(I.getOperand(0));
3081   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3082                                                         I.getType());
3083   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3084 }
3085 
3086 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3087   // What to do depends on the size of the integer and the size of the pointer.
3088   // We can either truncate, zero extend, or no-op, accordingly.
3089   SDValue N = getValue(I.getOperand(0));
3090   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3091                                                         I.getType());
3092   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3093 }
3094 
3095 void SelectionDAGBuilder::visitBitCast(const User &I) {
3096   SDValue N = getValue(I.getOperand(0));
3097   SDLoc dl = getCurSDLoc();
3098   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3099                                                         I.getType());
3100 
3101   // BitCast assures us that source and destination are the same size so this is
3102   // either a BITCAST or a no-op.
3103   if (DestVT != N.getValueType())
3104     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3105                              DestVT, N)); // convert types.
3106   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3107   // might fold any kind of constant expression to an integer constant and that
3108   // is not what we are looking for. Only recognize a bitcast of a genuine
3109   // constant integer as an opaque constant.
3110   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3111     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3112                                  /*isOpaque*/true));
3113   else
3114     setValue(&I, N);            // noop cast.
3115 }
3116 
3117 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3119   const Value *SV = I.getOperand(0);
3120   SDValue N = getValue(SV);
3121   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3122 
3123   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3124   unsigned DestAS = I.getType()->getPointerAddressSpace();
3125 
3126   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3127     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3128 
3129   setValue(&I, N);
3130 }
3131 
3132 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3134   SDValue InVec = getValue(I.getOperand(0));
3135   SDValue InVal = getValue(I.getOperand(1));
3136   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3137                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3138   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3139                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3140                            InVec, InVal, InIdx));
3141 }
3142 
3143 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3145   SDValue InVec = getValue(I.getOperand(0));
3146   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3147                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3148   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3149                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3150                            InVec, InIdx));
3151 }
3152 
3153 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3154   SDValue Src1 = getValue(I.getOperand(0));
3155   SDValue Src2 = getValue(I.getOperand(1));
3156   SDLoc DL = getCurSDLoc();
3157 
3158   SmallVector<int, 8> Mask;
3159   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3160   unsigned MaskNumElts = Mask.size();
3161 
3162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3163   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3164   EVT SrcVT = Src1.getValueType();
3165   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3166 
3167   if (SrcNumElts == MaskNumElts) {
3168     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3169     return;
3170   }
3171 
3172   // Normalize the shuffle vector since mask and vector length don't match.
3173   if (SrcNumElts < MaskNumElts) {
3174     // Mask is longer than the source vectors. We can use concatenate vector to
3175     // make the mask and vectors lengths match.
3176 
3177     if (MaskNumElts % SrcNumElts == 0) {
3178       // Mask length is a multiple of the source vector length.
3179       // Check if the shuffle is some kind of concatenation of the input
3180       // vectors.
3181       unsigned NumConcat = MaskNumElts / SrcNumElts;
3182       bool IsConcat = true;
3183       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3184       for (unsigned i = 0; i != MaskNumElts; ++i) {
3185         int Idx = Mask[i];
3186         if (Idx < 0)
3187           continue;
3188         // Ensure the indices in each SrcVT sized piece are sequential and that
3189         // the same source is used for the whole piece.
3190         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3191             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3192              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3193           IsConcat = false;
3194           break;
3195         }
3196         // Remember which source this index came from.
3197         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3198       }
3199 
3200       // The shuffle is concatenating multiple vectors together. Just emit
3201       // a CONCAT_VECTORS operation.
3202       if (IsConcat) {
3203         SmallVector<SDValue, 8> ConcatOps;
3204         for (auto Src : ConcatSrcs) {
3205           if (Src < 0)
3206             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3207           else if (Src == 0)
3208             ConcatOps.push_back(Src1);
3209           else
3210             ConcatOps.push_back(Src2);
3211         }
3212         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3213         return;
3214       }
3215     }
3216 
3217     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3218     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3219     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3220                                     PaddedMaskNumElts);
3221 
3222     // Pad both vectors with undefs to make them the same length as the mask.
3223     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3224 
3225     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3226     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3227     MOps1[0] = Src1;
3228     MOps2[0] = Src2;
3229 
3230     Src1 = Src1.isUndef()
3231                ? DAG.getUNDEF(PaddedVT)
3232                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3233     Src2 = Src2.isUndef()
3234                ? DAG.getUNDEF(PaddedVT)
3235                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3236 
3237     // Readjust mask for new input vector length.
3238     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3239     for (unsigned i = 0; i != MaskNumElts; ++i) {
3240       int Idx = Mask[i];
3241       if (Idx >= (int)SrcNumElts)
3242         Idx -= SrcNumElts - PaddedMaskNumElts;
3243       MappedOps[i] = Idx;
3244     }
3245 
3246     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3247 
3248     // If the concatenated vector was padded, extract a subvector with the
3249     // correct number of elements.
3250     if (MaskNumElts != PaddedMaskNumElts)
3251       Result = DAG.getNode(
3252           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3253           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3254 
3255     setValue(&I, Result);
3256     return;
3257   }
3258 
3259   if (SrcNumElts > MaskNumElts) {
3260     // Analyze the access pattern of the vector to see if we can extract
3261     // two subvectors and do the shuffle.
3262     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3263     bool CanExtract = true;
3264     for (int Idx : Mask) {
3265       unsigned Input = 0;
3266       if (Idx < 0)
3267         continue;
3268 
3269       if (Idx >= (int)SrcNumElts) {
3270         Input = 1;
3271         Idx -= SrcNumElts;
3272       }
3273 
3274       // If all the indices come from the same MaskNumElts sized portion of
3275       // the sources we can use extract. Also make sure the extract wouldn't
3276       // extract past the end of the source.
3277       int NewStartIdx = alignDown(Idx, MaskNumElts);
3278       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3279           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3280         CanExtract = false;
3281       // Make sure we always update StartIdx as we use it to track if all
3282       // elements are undef.
3283       StartIdx[Input] = NewStartIdx;
3284     }
3285 
3286     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3287       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3288       return;
3289     }
3290     if (CanExtract) {
3291       // Extract appropriate subvector and generate a vector shuffle
3292       for (unsigned Input = 0; Input < 2; ++Input) {
3293         SDValue &Src = Input == 0 ? Src1 : Src2;
3294         if (StartIdx[Input] < 0)
3295           Src = DAG.getUNDEF(VT);
3296         else {
3297           Src = DAG.getNode(
3298               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3299               DAG.getConstant(StartIdx[Input], DL,
3300                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3301         }
3302       }
3303 
3304       // Calculate new mask.
3305       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3306       for (int &Idx : MappedOps) {
3307         if (Idx >= (int)SrcNumElts)
3308           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3309         else if (Idx >= 0)
3310           Idx -= StartIdx[0];
3311       }
3312 
3313       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3314       return;
3315     }
3316   }
3317 
3318   // We can't use either concat vectors or extract subvectors so fall back to
3319   // replacing the shuffle with extract and build vector.
3320   // to insert and build vector.
3321   EVT EltVT = VT.getVectorElementType();
3322   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3323   SmallVector<SDValue,8> Ops;
3324   for (int Idx : Mask) {
3325     SDValue Res;
3326 
3327     if (Idx < 0) {
3328       Res = DAG.getUNDEF(EltVT);
3329     } else {
3330       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3331       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3332 
3333       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3334                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3335     }
3336 
3337     Ops.push_back(Res);
3338   }
3339 
3340   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3341 }
3342 
3343 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3344   ArrayRef<unsigned> Indices;
3345   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3346     Indices = IV->getIndices();
3347   else
3348     Indices = cast<ConstantExpr>(&I)->getIndices();
3349 
3350   const Value *Op0 = I.getOperand(0);
3351   const Value *Op1 = I.getOperand(1);
3352   Type *AggTy = I.getType();
3353   Type *ValTy = Op1->getType();
3354   bool IntoUndef = isa<UndefValue>(Op0);
3355   bool FromUndef = isa<UndefValue>(Op1);
3356 
3357   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3358 
3359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3360   SmallVector<EVT, 4> AggValueVTs;
3361   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3362   SmallVector<EVT, 4> ValValueVTs;
3363   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3364 
3365   unsigned NumAggValues = AggValueVTs.size();
3366   unsigned NumValValues = ValValueVTs.size();
3367   SmallVector<SDValue, 4> Values(NumAggValues);
3368 
3369   // Ignore an insertvalue that produces an empty object
3370   if (!NumAggValues) {
3371     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3372     return;
3373   }
3374 
3375   SDValue Agg = getValue(Op0);
3376   unsigned i = 0;
3377   // Copy the beginning value(s) from the original aggregate.
3378   for (; i != LinearIndex; ++i)
3379     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3380                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3381   // Copy values from the inserted value(s).
3382   if (NumValValues) {
3383     SDValue Val = getValue(Op1);
3384     for (; i != LinearIndex + NumValValues; ++i)
3385       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3386                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3387   }
3388   // Copy remaining value(s) from the original aggregate.
3389   for (; i != NumAggValues; ++i)
3390     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3391                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3392 
3393   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3394                            DAG.getVTList(AggValueVTs), Values));
3395 }
3396 
3397 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3398   ArrayRef<unsigned> Indices;
3399   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3400     Indices = EV->getIndices();
3401   else
3402     Indices = cast<ConstantExpr>(&I)->getIndices();
3403 
3404   const Value *Op0 = I.getOperand(0);
3405   Type *AggTy = Op0->getType();
3406   Type *ValTy = I.getType();
3407   bool OutOfUndef = isa<UndefValue>(Op0);
3408 
3409   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3410 
3411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3412   SmallVector<EVT, 4> ValValueVTs;
3413   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3414 
3415   unsigned NumValValues = ValValueVTs.size();
3416 
3417   // Ignore a extractvalue that produces an empty object
3418   if (!NumValValues) {
3419     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3420     return;
3421   }
3422 
3423   SmallVector<SDValue, 4> Values(NumValValues);
3424 
3425   SDValue Agg = getValue(Op0);
3426   // Copy out the selected value(s).
3427   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3428     Values[i - LinearIndex] =
3429       OutOfUndef ?
3430         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3431         SDValue(Agg.getNode(), Agg.getResNo() + i);
3432 
3433   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3434                            DAG.getVTList(ValValueVTs), Values));
3435 }
3436 
3437 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3438   Value *Op0 = I.getOperand(0);
3439   // Note that the pointer operand may be a vector of pointers. Take the scalar
3440   // element which holds a pointer.
3441   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3442   SDValue N = getValue(Op0);
3443   SDLoc dl = getCurSDLoc();
3444 
3445   // Normalize Vector GEP - all scalar operands should be converted to the
3446   // splat vector.
3447   unsigned VectorWidth = I.getType()->isVectorTy() ?
3448     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3449 
3450   if (VectorWidth && !N.getValueType().isVector()) {
3451     LLVMContext &Context = *DAG.getContext();
3452     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3453     N = DAG.getSplatBuildVector(VT, dl, N);
3454   }
3455 
3456   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3457        GTI != E; ++GTI) {
3458     const Value *Idx = GTI.getOperand();
3459     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3460       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3461       if (Field) {
3462         // N = N + Offset
3463         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3464 
3465         // In an inbounds GEP with an offset that is nonnegative even when
3466         // interpreted as signed, assume there is no unsigned overflow.
3467         SDNodeFlags Flags;
3468         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3469           Flags.setNoUnsignedWrap(true);
3470 
3471         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3472                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3473       }
3474     } else {
3475       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3476       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3477       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3478 
3479       // If this is a scalar constant or a splat vector of constants,
3480       // handle it quickly.
3481       const auto *CI = dyn_cast<ConstantInt>(Idx);
3482       if (!CI && isa<ConstantDataVector>(Idx) &&
3483           cast<ConstantDataVector>(Idx)->getSplatValue())
3484         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3485 
3486       if (CI) {
3487         if (CI->isZero())
3488           continue;
3489         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3490         LLVMContext &Context = *DAG.getContext();
3491         SDValue OffsVal = VectorWidth ?
3492           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3493           DAG.getConstant(Offs, dl, IdxTy);
3494 
3495         // In an inbouds GEP with an offset that is nonnegative even when
3496         // interpreted as signed, assume there is no unsigned overflow.
3497         SDNodeFlags Flags;
3498         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3499           Flags.setNoUnsignedWrap(true);
3500 
3501         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3502         continue;
3503       }
3504 
3505       // N = N + Idx * ElementSize;
3506       SDValue IdxN = getValue(Idx);
3507 
3508       if (!IdxN.getValueType().isVector() && VectorWidth) {
3509         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3510         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3511       }
3512 
3513       // If the index is smaller or larger than intptr_t, truncate or extend
3514       // it.
3515       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3516 
3517       // If this is a multiply by a power of two, turn it into a shl
3518       // immediately.  This is a very common case.
3519       if (ElementSize != 1) {
3520         if (ElementSize.isPowerOf2()) {
3521           unsigned Amt = ElementSize.logBase2();
3522           IdxN = DAG.getNode(ISD::SHL, dl,
3523                              N.getValueType(), IdxN,
3524                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3525         } else {
3526           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3527           IdxN = DAG.getNode(ISD::MUL, dl,
3528                              N.getValueType(), IdxN, Scale);
3529         }
3530       }
3531 
3532       N = DAG.getNode(ISD::ADD, dl,
3533                       N.getValueType(), N, IdxN);
3534     }
3535   }
3536 
3537   setValue(&I, N);
3538 }
3539 
3540 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3541   // If this is a fixed sized alloca in the entry block of the function,
3542   // allocate it statically on the stack.
3543   if (FuncInfo.StaticAllocaMap.count(&I))
3544     return;   // getValue will auto-populate this.
3545 
3546   SDLoc dl = getCurSDLoc();
3547   Type *Ty = I.getAllocatedType();
3548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3549   auto &DL = DAG.getDataLayout();
3550   uint64_t TySize = DL.getTypeAllocSize(Ty);
3551   unsigned Align =
3552       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3553 
3554   SDValue AllocSize = getValue(I.getArraySize());
3555 
3556   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3557   if (AllocSize.getValueType() != IntPtr)
3558     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3559 
3560   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3561                           AllocSize,
3562                           DAG.getConstant(TySize, dl, IntPtr));
3563 
3564   // Handle alignment.  If the requested alignment is less than or equal to
3565   // the stack alignment, ignore it.  If the size is greater than or equal to
3566   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3567   unsigned StackAlign =
3568       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3569   if (Align <= StackAlign)
3570     Align = 0;
3571 
3572   // Round the size of the allocation up to the stack alignment size
3573   // by add SA-1 to the size. This doesn't overflow because we're computing
3574   // an address inside an alloca.
3575   SDNodeFlags Flags;
3576   Flags.setNoUnsignedWrap(true);
3577   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3578                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3579 
3580   // Mask out the low bits for alignment purposes.
3581   AllocSize =
3582       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3583                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3584 
3585   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3586   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3587   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3588   setValue(&I, DSA);
3589   DAG.setRoot(DSA.getValue(1));
3590 
3591   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3592 }
3593 
3594 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3595   if (I.isAtomic())
3596     return visitAtomicLoad(I);
3597 
3598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3599   const Value *SV = I.getOperand(0);
3600   if (TLI.supportSwiftError()) {
3601     // Swifterror values can come from either a function parameter with
3602     // swifterror attribute or an alloca with swifterror attribute.
3603     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3604       if (Arg->hasSwiftErrorAttr())
3605         return visitLoadFromSwiftError(I);
3606     }
3607 
3608     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3609       if (Alloca->isSwiftError())
3610         return visitLoadFromSwiftError(I);
3611     }
3612   }
3613 
3614   SDValue Ptr = getValue(SV);
3615 
3616   Type *Ty = I.getType();
3617 
3618   bool isVolatile = I.isVolatile();
3619   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3620   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3621   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3622   unsigned Alignment = I.getAlignment();
3623 
3624   AAMDNodes AAInfo;
3625   I.getAAMetadata(AAInfo);
3626   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3627 
3628   SmallVector<EVT, 4> ValueVTs;
3629   SmallVector<uint64_t, 4> Offsets;
3630   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3631   unsigned NumValues = ValueVTs.size();
3632   if (NumValues == 0)
3633     return;
3634 
3635   SDValue Root;
3636   bool ConstantMemory = false;
3637   if (isVolatile || NumValues > MaxParallelChains)
3638     // Serialize volatile loads with other side effects.
3639     Root = getRoot();
3640   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3641                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3642     // Do not serialize (non-volatile) loads of constant memory with anything.
3643     Root = DAG.getEntryNode();
3644     ConstantMemory = true;
3645   } else {
3646     // Do not serialize non-volatile loads against each other.
3647     Root = DAG.getRoot();
3648   }
3649 
3650   SDLoc dl = getCurSDLoc();
3651 
3652   if (isVolatile)
3653     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3654 
3655   // An aggregate load cannot wrap around the address space, so offsets to its
3656   // parts don't wrap either.
3657   SDNodeFlags Flags;
3658   Flags.setNoUnsignedWrap(true);
3659 
3660   SmallVector<SDValue, 4> Values(NumValues);
3661   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3662   EVT PtrVT = Ptr.getValueType();
3663   unsigned ChainI = 0;
3664   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3665     // Serializing loads here may result in excessive register pressure, and
3666     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3667     // could recover a bit by hoisting nodes upward in the chain by recognizing
3668     // they are side-effect free or do not alias. The optimizer should really
3669     // avoid this case by converting large object/array copies to llvm.memcpy
3670     // (MaxParallelChains should always remain as failsafe).
3671     if (ChainI == MaxParallelChains) {
3672       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3673       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3674                                   makeArrayRef(Chains.data(), ChainI));
3675       Root = Chain;
3676       ChainI = 0;
3677     }
3678     SDValue A = DAG.getNode(ISD::ADD, dl,
3679                             PtrVT, Ptr,
3680                             DAG.getConstant(Offsets[i], dl, PtrVT),
3681                             Flags);
3682     auto MMOFlags = MachineMemOperand::MONone;
3683     if (isVolatile)
3684       MMOFlags |= MachineMemOperand::MOVolatile;
3685     if (isNonTemporal)
3686       MMOFlags |= MachineMemOperand::MONonTemporal;
3687     if (isInvariant)
3688       MMOFlags |= MachineMemOperand::MOInvariant;
3689     if (isDereferenceable)
3690       MMOFlags |= MachineMemOperand::MODereferenceable;
3691     MMOFlags |= TLI.getMMOFlags(I);
3692 
3693     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3694                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3695                             MMOFlags, AAInfo, Ranges);
3696 
3697     Values[i] = L;
3698     Chains[ChainI] = L.getValue(1);
3699   }
3700 
3701   if (!ConstantMemory) {
3702     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3703                                 makeArrayRef(Chains.data(), ChainI));
3704     if (isVolatile)
3705       DAG.setRoot(Chain);
3706     else
3707       PendingLoads.push_back(Chain);
3708   }
3709 
3710   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3711                            DAG.getVTList(ValueVTs), Values));
3712 }
3713 
3714 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3715   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3716          "call visitStoreToSwiftError when backend supports swifterror");
3717 
3718   SmallVector<EVT, 4> ValueVTs;
3719   SmallVector<uint64_t, 4> Offsets;
3720   const Value *SrcV = I.getOperand(0);
3721   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3722                   SrcV->getType(), ValueVTs, &Offsets);
3723   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3724          "expect a single EVT for swifterror");
3725 
3726   SDValue Src = getValue(SrcV);
3727   // Create a virtual register, then update the virtual register.
3728   unsigned VReg; bool CreatedVReg;
3729   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3730   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3731   // Chain can be getRoot or getControlRoot.
3732   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3733                                       SDValue(Src.getNode(), Src.getResNo()));
3734   DAG.setRoot(CopyNode);
3735   if (CreatedVReg)
3736     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3737 }
3738 
3739 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3740   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3741          "call visitLoadFromSwiftError when backend supports swifterror");
3742 
3743   assert(!I.isVolatile() &&
3744          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3745          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3746          "Support volatile, non temporal, invariant for load_from_swift_error");
3747 
3748   const Value *SV = I.getOperand(0);
3749   Type *Ty = I.getType();
3750   AAMDNodes AAInfo;
3751   I.getAAMetadata(AAInfo);
3752   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3753              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3754          "load_from_swift_error should not be constant memory");
3755 
3756   SmallVector<EVT, 4> ValueVTs;
3757   SmallVector<uint64_t, 4> Offsets;
3758   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3759                   ValueVTs, &Offsets);
3760   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3761          "expect a single EVT for swifterror");
3762 
3763   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3764   SDValue L = DAG.getCopyFromReg(
3765       getRoot(), getCurSDLoc(),
3766       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3767       ValueVTs[0]);
3768 
3769   setValue(&I, L);
3770 }
3771 
3772 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3773   if (I.isAtomic())
3774     return visitAtomicStore(I);
3775 
3776   const Value *SrcV = I.getOperand(0);
3777   const Value *PtrV = I.getOperand(1);
3778 
3779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3780   if (TLI.supportSwiftError()) {
3781     // Swifterror values can come from either a function parameter with
3782     // swifterror attribute or an alloca with swifterror attribute.
3783     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3784       if (Arg->hasSwiftErrorAttr())
3785         return visitStoreToSwiftError(I);
3786     }
3787 
3788     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3789       if (Alloca->isSwiftError())
3790         return visitStoreToSwiftError(I);
3791     }
3792   }
3793 
3794   SmallVector<EVT, 4> ValueVTs;
3795   SmallVector<uint64_t, 4> Offsets;
3796   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3797                   SrcV->getType(), ValueVTs, &Offsets);
3798   unsigned NumValues = ValueVTs.size();
3799   if (NumValues == 0)
3800     return;
3801 
3802   // Get the lowered operands. Note that we do this after
3803   // checking if NumResults is zero, because with zero results
3804   // the operands won't have values in the map.
3805   SDValue Src = getValue(SrcV);
3806   SDValue Ptr = getValue(PtrV);
3807 
3808   SDValue Root = getRoot();
3809   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3810   SDLoc dl = getCurSDLoc();
3811   EVT PtrVT = Ptr.getValueType();
3812   unsigned Alignment = I.getAlignment();
3813   AAMDNodes AAInfo;
3814   I.getAAMetadata(AAInfo);
3815 
3816   auto MMOFlags = MachineMemOperand::MONone;
3817   if (I.isVolatile())
3818     MMOFlags |= MachineMemOperand::MOVolatile;
3819   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3820     MMOFlags |= MachineMemOperand::MONonTemporal;
3821   MMOFlags |= TLI.getMMOFlags(I);
3822 
3823   // An aggregate load cannot wrap around the address space, so offsets to its
3824   // parts don't wrap either.
3825   SDNodeFlags Flags;
3826   Flags.setNoUnsignedWrap(true);
3827 
3828   unsigned ChainI = 0;
3829   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3830     // See visitLoad comments.
3831     if (ChainI == MaxParallelChains) {
3832       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3833                                   makeArrayRef(Chains.data(), ChainI));
3834       Root = Chain;
3835       ChainI = 0;
3836     }
3837     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3838                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3839     SDValue St = DAG.getStore(
3840         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3841         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3842     Chains[ChainI] = St;
3843   }
3844 
3845   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3846                                   makeArrayRef(Chains.data(), ChainI));
3847   DAG.setRoot(StoreNode);
3848 }
3849 
3850 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3851                                            bool IsCompressing) {
3852   SDLoc sdl = getCurSDLoc();
3853 
3854   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3855                            unsigned& Alignment) {
3856     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3857     Src0 = I.getArgOperand(0);
3858     Ptr = I.getArgOperand(1);
3859     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3860     Mask = I.getArgOperand(3);
3861   };
3862   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3863                            unsigned& Alignment) {
3864     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3865     Src0 = I.getArgOperand(0);
3866     Ptr = I.getArgOperand(1);
3867     Mask = I.getArgOperand(2);
3868     Alignment = 0;
3869   };
3870 
3871   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3872   unsigned Alignment;
3873   if (IsCompressing)
3874     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3875   else
3876     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3877 
3878   SDValue Ptr = getValue(PtrOperand);
3879   SDValue Src0 = getValue(Src0Operand);
3880   SDValue Mask = getValue(MaskOperand);
3881 
3882   EVT VT = Src0.getValueType();
3883   if (!Alignment)
3884     Alignment = DAG.getEVTAlignment(VT);
3885 
3886   AAMDNodes AAInfo;
3887   I.getAAMetadata(AAInfo);
3888 
3889   MachineMemOperand *MMO =
3890     DAG.getMachineFunction().
3891     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3892                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3893                           Alignment, AAInfo);
3894   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3895                                          MMO, false /* Truncating */,
3896                                          IsCompressing);
3897   DAG.setRoot(StoreNode);
3898   setValue(&I, StoreNode);
3899 }
3900 
3901 // Get a uniform base for the Gather/Scatter intrinsic.
3902 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3903 // We try to represent it as a base pointer + vector of indices.
3904 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3905 // The first operand of the GEP may be a single pointer or a vector of pointers
3906 // Example:
3907 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3908 //  or
3909 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3910 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3911 //
3912 // When the first GEP operand is a single pointer - it is the uniform base we
3913 // are looking for. If first operand of the GEP is a splat vector - we
3914 // extract the splat value and use it as a uniform base.
3915 // In all other cases the function returns 'false'.
3916 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3917                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3918   SelectionDAG& DAG = SDB->DAG;
3919   LLVMContext &Context = *DAG.getContext();
3920 
3921   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3922   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3923   if (!GEP)
3924     return false;
3925 
3926   const Value *GEPPtr = GEP->getPointerOperand();
3927   if (!GEPPtr->getType()->isVectorTy())
3928     Ptr = GEPPtr;
3929   else if (!(Ptr = getSplatValue(GEPPtr)))
3930     return false;
3931 
3932   unsigned FinalIndex = GEP->getNumOperands() - 1;
3933   Value *IndexVal = GEP->getOperand(FinalIndex);
3934 
3935   // Ensure all the other indices are 0.
3936   for (unsigned i = 1; i < FinalIndex; ++i) {
3937     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3938     if (!C || !C->isZero())
3939       return false;
3940   }
3941 
3942   // The operands of the GEP may be defined in another basic block.
3943   // In this case we'll not find nodes for the operands.
3944   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3945     return false;
3946 
3947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3948   const DataLayout &DL = DAG.getDataLayout();
3949   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3950                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3951   Base = SDB->getValue(Ptr);
3952   Index = SDB->getValue(IndexVal);
3953 
3954   if (!Index.getValueType().isVector()) {
3955     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3956     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3957     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3958   }
3959   return true;
3960 }
3961 
3962 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3963   SDLoc sdl = getCurSDLoc();
3964 
3965   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3966   const Value *Ptr = I.getArgOperand(1);
3967   SDValue Src0 = getValue(I.getArgOperand(0));
3968   SDValue Mask = getValue(I.getArgOperand(3));
3969   EVT VT = Src0.getValueType();
3970   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3971   if (!Alignment)
3972     Alignment = DAG.getEVTAlignment(VT);
3973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3974 
3975   AAMDNodes AAInfo;
3976   I.getAAMetadata(AAInfo);
3977 
3978   SDValue Base;
3979   SDValue Index;
3980   SDValue Scale;
3981   const Value *BasePtr = Ptr;
3982   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
3983 
3984   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3985   MachineMemOperand *MMO = DAG.getMachineFunction().
3986     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3987                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3988                          Alignment, AAInfo);
3989   if (!UniformBase) {
3990     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3991     Index = getValue(Ptr);
3992     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3993   }
3994   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
3995   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3996                                          Ops, MMO);
3997   DAG.setRoot(Scatter);
3998   setValue(&I, Scatter);
3999 }
4000 
4001 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4002   SDLoc sdl = getCurSDLoc();
4003 
4004   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4005                            unsigned& Alignment) {
4006     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4007     Ptr = I.getArgOperand(0);
4008     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4009     Mask = I.getArgOperand(2);
4010     Src0 = I.getArgOperand(3);
4011   };
4012   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4013                            unsigned& Alignment) {
4014     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4015     Ptr = I.getArgOperand(0);
4016     Alignment = 0;
4017     Mask = I.getArgOperand(1);
4018     Src0 = I.getArgOperand(2);
4019   };
4020 
4021   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4022   unsigned Alignment;
4023   if (IsExpanding)
4024     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4025   else
4026     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4027 
4028   SDValue Ptr = getValue(PtrOperand);
4029   SDValue Src0 = getValue(Src0Operand);
4030   SDValue Mask = getValue(MaskOperand);
4031 
4032   EVT VT = Src0.getValueType();
4033   if (!Alignment)
4034     Alignment = DAG.getEVTAlignment(VT);
4035 
4036   AAMDNodes AAInfo;
4037   I.getAAMetadata(AAInfo);
4038   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4039 
4040   // Do not serialize masked loads of constant memory with anything.
4041   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4042       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4043   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4044 
4045   MachineMemOperand *MMO =
4046     DAG.getMachineFunction().
4047     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4048                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4049                           Alignment, AAInfo, Ranges);
4050 
4051   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4052                                    ISD::NON_EXTLOAD, IsExpanding);
4053   if (AddToChain) {
4054     SDValue OutChain = Load.getValue(1);
4055     DAG.setRoot(OutChain);
4056   }
4057   setValue(&I, Load);
4058 }
4059 
4060 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4061   SDLoc sdl = getCurSDLoc();
4062 
4063   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4064   const Value *Ptr = I.getArgOperand(0);
4065   SDValue Src0 = getValue(I.getArgOperand(3));
4066   SDValue Mask = getValue(I.getArgOperand(2));
4067 
4068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4069   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4070   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4071   if (!Alignment)
4072     Alignment = DAG.getEVTAlignment(VT);
4073 
4074   AAMDNodes AAInfo;
4075   I.getAAMetadata(AAInfo);
4076   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4077 
4078   SDValue Root = DAG.getRoot();
4079   SDValue Base;
4080   SDValue Index;
4081   SDValue Scale;
4082   const Value *BasePtr = Ptr;
4083   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4084   bool ConstantMemory = false;
4085   if (UniformBase &&
4086       AA && AA->pointsToConstantMemory(MemoryLocation(
4087           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4088           AAInfo))) {
4089     // Do not serialize (non-volatile) loads of constant memory with anything.
4090     Root = DAG.getEntryNode();
4091     ConstantMemory = true;
4092   }
4093 
4094   MachineMemOperand *MMO =
4095     DAG.getMachineFunction().
4096     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4097                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4098                          Alignment, AAInfo, Ranges);
4099 
4100   if (!UniformBase) {
4101     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4102     Index = getValue(Ptr);
4103     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4104   }
4105   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4106   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4107                                        Ops, MMO);
4108 
4109   SDValue OutChain = Gather.getValue(1);
4110   if (!ConstantMemory)
4111     PendingLoads.push_back(OutChain);
4112   setValue(&I, Gather);
4113 }
4114 
4115 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4116   SDLoc dl = getCurSDLoc();
4117   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4118   AtomicOrdering FailureOrder = I.getFailureOrdering();
4119   SyncScope::ID SSID = I.getSyncScopeID();
4120 
4121   SDValue InChain = getRoot();
4122 
4123   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4124   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4125   SDValue L = DAG.getAtomicCmpSwap(
4126       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4127       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4128       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4129       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4130 
4131   SDValue OutChain = L.getValue(2);
4132 
4133   setValue(&I, L);
4134   DAG.setRoot(OutChain);
4135 }
4136 
4137 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4138   SDLoc dl = getCurSDLoc();
4139   ISD::NodeType NT;
4140   switch (I.getOperation()) {
4141   default: llvm_unreachable("Unknown atomicrmw operation");
4142   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4143   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4144   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4145   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4146   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4147   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4148   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4149   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4150   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4151   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4152   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4153   }
4154   AtomicOrdering Order = I.getOrdering();
4155   SyncScope::ID SSID = I.getSyncScopeID();
4156 
4157   SDValue InChain = getRoot();
4158 
4159   SDValue L =
4160     DAG.getAtomic(NT, dl,
4161                   getValue(I.getValOperand()).getSimpleValueType(),
4162                   InChain,
4163                   getValue(I.getPointerOperand()),
4164                   getValue(I.getValOperand()),
4165                   I.getPointerOperand(),
4166                   /* Alignment=*/ 0, Order, SSID);
4167 
4168   SDValue OutChain = L.getValue(1);
4169 
4170   setValue(&I, L);
4171   DAG.setRoot(OutChain);
4172 }
4173 
4174 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4175   SDLoc dl = getCurSDLoc();
4176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4177   SDValue Ops[3];
4178   Ops[0] = getRoot();
4179   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4180                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4181   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4182                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4183   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4184 }
4185 
4186 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4187   SDLoc dl = getCurSDLoc();
4188   AtomicOrdering Order = I.getOrdering();
4189   SyncScope::ID SSID = I.getSyncScopeID();
4190 
4191   SDValue InChain = getRoot();
4192 
4193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4194   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4195 
4196   if (!TLI.supportsUnalignedAtomics() &&
4197       I.getAlignment() < VT.getStoreSize())
4198     report_fatal_error("Cannot generate unaligned atomic load");
4199 
4200   MachineMemOperand *MMO =
4201       DAG.getMachineFunction().
4202       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4203                            MachineMemOperand::MOVolatile |
4204                            MachineMemOperand::MOLoad,
4205                            VT.getStoreSize(),
4206                            I.getAlignment() ? I.getAlignment() :
4207                                               DAG.getEVTAlignment(VT),
4208                            AAMDNodes(), nullptr, SSID, Order);
4209 
4210   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4211   SDValue L =
4212       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4213                     getValue(I.getPointerOperand()), MMO);
4214 
4215   SDValue OutChain = L.getValue(1);
4216 
4217   setValue(&I, L);
4218   DAG.setRoot(OutChain);
4219 }
4220 
4221 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4222   SDLoc dl = getCurSDLoc();
4223 
4224   AtomicOrdering Order = I.getOrdering();
4225   SyncScope::ID SSID = I.getSyncScopeID();
4226 
4227   SDValue InChain = getRoot();
4228 
4229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4230   EVT VT =
4231       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4232 
4233   if (I.getAlignment() < VT.getStoreSize())
4234     report_fatal_error("Cannot generate unaligned atomic store");
4235 
4236   SDValue OutChain =
4237     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4238                   InChain,
4239                   getValue(I.getPointerOperand()),
4240                   getValue(I.getValueOperand()),
4241                   I.getPointerOperand(), I.getAlignment(),
4242                   Order, SSID);
4243 
4244   DAG.setRoot(OutChain);
4245 }
4246 
4247 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4248 /// node.
4249 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4250                                                unsigned Intrinsic) {
4251   // Ignore the callsite's attributes. A specific call site may be marked with
4252   // readnone, but the lowering code will expect the chain based on the
4253   // definition.
4254   const Function *F = I.getCalledFunction();
4255   bool HasChain = !F->doesNotAccessMemory();
4256   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4257 
4258   // Build the operand list.
4259   SmallVector<SDValue, 8> Ops;
4260   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4261     if (OnlyLoad) {
4262       // We don't need to serialize loads against other loads.
4263       Ops.push_back(DAG.getRoot());
4264     } else {
4265       Ops.push_back(getRoot());
4266     }
4267   }
4268 
4269   // Info is set by getTgtMemInstrinsic
4270   TargetLowering::IntrinsicInfo Info;
4271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4272   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4273                                                DAG.getMachineFunction(),
4274                                                Intrinsic);
4275 
4276   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4277   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4278       Info.opc == ISD::INTRINSIC_W_CHAIN)
4279     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4280                                         TLI.getPointerTy(DAG.getDataLayout())));
4281 
4282   // Add all operands of the call to the operand list.
4283   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4284     SDValue Op = getValue(I.getArgOperand(i));
4285     Ops.push_back(Op);
4286   }
4287 
4288   SmallVector<EVT, 4> ValueVTs;
4289   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4290 
4291   if (HasChain)
4292     ValueVTs.push_back(MVT::Other);
4293 
4294   SDVTList VTs = DAG.getVTList(ValueVTs);
4295 
4296   // Create the node.
4297   SDValue Result;
4298   if (IsTgtIntrinsic) {
4299     // This is target intrinsic that touches memory
4300     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4301       Ops, Info.memVT,
4302       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4303       Info.flags, Info.size);
4304   } else if (!HasChain) {
4305     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4306   } else if (!I.getType()->isVoidTy()) {
4307     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4308   } else {
4309     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4310   }
4311 
4312   if (HasChain) {
4313     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4314     if (OnlyLoad)
4315       PendingLoads.push_back(Chain);
4316     else
4317       DAG.setRoot(Chain);
4318   }
4319 
4320   if (!I.getType()->isVoidTy()) {
4321     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4322       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4323       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4324     } else
4325       Result = lowerRangeToAssertZExt(DAG, I, Result);
4326 
4327     setValue(&I, Result);
4328   }
4329 }
4330 
4331 /// GetSignificand - Get the significand and build it into a floating-point
4332 /// number with exponent of 1:
4333 ///
4334 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4335 ///
4336 /// where Op is the hexadecimal representation of floating point value.
4337 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4338   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4339                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4340   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4341                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4342   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4343 }
4344 
4345 /// GetExponent - Get the exponent:
4346 ///
4347 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4348 ///
4349 /// where Op is the hexadecimal representation of floating point value.
4350 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4351                            const TargetLowering &TLI, const SDLoc &dl) {
4352   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4353                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4354   SDValue t1 = DAG.getNode(
4355       ISD::SRL, dl, MVT::i32, t0,
4356       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4357   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4358                            DAG.getConstant(127, dl, MVT::i32));
4359   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4360 }
4361 
4362 /// getF32Constant - Get 32-bit floating point constant.
4363 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4364                               const SDLoc &dl) {
4365   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4366                            MVT::f32);
4367 }
4368 
4369 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4370                                        SelectionDAG &DAG) {
4371   // TODO: What fast-math-flags should be set on the floating-point nodes?
4372 
4373   //   IntegerPartOfX = ((int32_t)(t0);
4374   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4375 
4376   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4377   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4378   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4379 
4380   //   IntegerPartOfX <<= 23;
4381   IntegerPartOfX = DAG.getNode(
4382       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4383       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4384                                   DAG.getDataLayout())));
4385 
4386   SDValue TwoToFractionalPartOfX;
4387   if (LimitFloatPrecision <= 6) {
4388     // For floating-point precision of 6:
4389     //
4390     //   TwoToFractionalPartOfX =
4391     //     0.997535578f +
4392     //       (0.735607626f + 0.252464424f * x) * x;
4393     //
4394     // error 0.0144103317, which is 6 bits
4395     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4396                              getF32Constant(DAG, 0x3e814304, dl));
4397     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4398                              getF32Constant(DAG, 0x3f3c50c8, dl));
4399     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4400     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4401                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4402   } else if (LimitFloatPrecision <= 12) {
4403     // For floating-point precision of 12:
4404     //
4405     //   TwoToFractionalPartOfX =
4406     //     0.999892986f +
4407     //       (0.696457318f +
4408     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4409     //
4410     // error 0.000107046256, which is 13 to 14 bits
4411     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4412                              getF32Constant(DAG, 0x3da235e3, dl));
4413     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4414                              getF32Constant(DAG, 0x3e65b8f3, dl));
4415     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4416     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4417                              getF32Constant(DAG, 0x3f324b07, dl));
4418     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4419     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4420                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4421   } else { // LimitFloatPrecision <= 18
4422     // For floating-point precision of 18:
4423     //
4424     //   TwoToFractionalPartOfX =
4425     //     0.999999982f +
4426     //       (0.693148872f +
4427     //         (0.240227044f +
4428     //           (0.554906021e-1f +
4429     //             (0.961591928e-2f +
4430     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4431     // error 2.47208000*10^(-7), which is better than 18 bits
4432     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4433                              getF32Constant(DAG, 0x3924b03e, dl));
4434     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4435                              getF32Constant(DAG, 0x3ab24b87, dl));
4436     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4437     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4438                              getF32Constant(DAG, 0x3c1d8c17, dl));
4439     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4440     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4441                              getF32Constant(DAG, 0x3d634a1d, dl));
4442     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4443     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4444                              getF32Constant(DAG, 0x3e75fe14, dl));
4445     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4446     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4447                               getF32Constant(DAG, 0x3f317234, dl));
4448     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4449     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4450                                          getF32Constant(DAG, 0x3f800000, dl));
4451   }
4452 
4453   // Add the exponent into the result in integer domain.
4454   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4455   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4456                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4457 }
4458 
4459 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4460 /// limited-precision mode.
4461 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4462                          const TargetLowering &TLI) {
4463   if (Op.getValueType() == MVT::f32 &&
4464       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4465 
4466     // Put the exponent in the right bit position for later addition to the
4467     // final result:
4468     //
4469     //   #define LOG2OFe 1.4426950f
4470     //   t0 = Op * LOG2OFe
4471 
4472     // TODO: What fast-math-flags should be set here?
4473     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4474                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4475     return getLimitedPrecisionExp2(t0, dl, DAG);
4476   }
4477 
4478   // No special expansion.
4479   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4480 }
4481 
4482 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4483 /// limited-precision mode.
4484 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4485                          const TargetLowering &TLI) {
4486   // TODO: What fast-math-flags should be set on the floating-point nodes?
4487 
4488   if (Op.getValueType() == MVT::f32 &&
4489       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4490     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4491 
4492     // Scale the exponent by log(2) [0.69314718f].
4493     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4494     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4495                                         getF32Constant(DAG, 0x3f317218, dl));
4496 
4497     // Get the significand and build it into a floating-point number with
4498     // exponent of 1.
4499     SDValue X = GetSignificand(DAG, Op1, dl);
4500 
4501     SDValue LogOfMantissa;
4502     if (LimitFloatPrecision <= 6) {
4503       // For floating-point precision of 6:
4504       //
4505       //   LogofMantissa =
4506       //     -1.1609546f +
4507       //       (1.4034025f - 0.23903021f * x) * x;
4508       //
4509       // error 0.0034276066, which is better than 8 bits
4510       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4511                                getF32Constant(DAG, 0xbe74c456, dl));
4512       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4513                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4514       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4515       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4516                                   getF32Constant(DAG, 0x3f949a29, dl));
4517     } else if (LimitFloatPrecision <= 12) {
4518       // For floating-point precision of 12:
4519       //
4520       //   LogOfMantissa =
4521       //     -1.7417939f +
4522       //       (2.8212026f +
4523       //         (-1.4699568f +
4524       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4525       //
4526       // error 0.000061011436, which is 14 bits
4527       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4528                                getF32Constant(DAG, 0xbd67b6d6, dl));
4529       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4530                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4531       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4532       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4533                                getF32Constant(DAG, 0x3fbc278b, dl));
4534       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4535       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4536                                getF32Constant(DAG, 0x40348e95, dl));
4537       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4538       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4539                                   getF32Constant(DAG, 0x3fdef31a, dl));
4540     } else { // LimitFloatPrecision <= 18
4541       // For floating-point precision of 18:
4542       //
4543       //   LogOfMantissa =
4544       //     -2.1072184f +
4545       //       (4.2372794f +
4546       //         (-3.7029485f +
4547       //           (2.2781945f +
4548       //             (-0.87823314f +
4549       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4550       //
4551       // error 0.0000023660568, which is better than 18 bits
4552       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4553                                getF32Constant(DAG, 0xbc91e5ac, dl));
4554       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4555                                getF32Constant(DAG, 0x3e4350aa, dl));
4556       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4557       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4558                                getF32Constant(DAG, 0x3f60d3e3, dl));
4559       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4560       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4561                                getF32Constant(DAG, 0x4011cdf0, dl));
4562       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4563       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4564                                getF32Constant(DAG, 0x406cfd1c, dl));
4565       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4566       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4567                                getF32Constant(DAG, 0x408797cb, dl));
4568       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4569       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4570                                   getF32Constant(DAG, 0x4006dcab, dl));
4571     }
4572 
4573     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4574   }
4575 
4576   // No special expansion.
4577   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4578 }
4579 
4580 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4581 /// limited-precision mode.
4582 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4583                           const TargetLowering &TLI) {
4584   // TODO: What fast-math-flags should be set on the floating-point nodes?
4585 
4586   if (Op.getValueType() == MVT::f32 &&
4587       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4588     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4589 
4590     // Get the exponent.
4591     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4592 
4593     // Get the significand and build it into a floating-point number with
4594     // exponent of 1.
4595     SDValue X = GetSignificand(DAG, Op1, dl);
4596 
4597     // Different possible minimax approximations of significand in
4598     // floating-point for various degrees of accuracy over [1,2].
4599     SDValue Log2ofMantissa;
4600     if (LimitFloatPrecision <= 6) {
4601       // For floating-point precision of 6:
4602       //
4603       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4604       //
4605       // error 0.0049451742, which is more than 7 bits
4606       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4607                                getF32Constant(DAG, 0xbeb08fe0, dl));
4608       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4609                                getF32Constant(DAG, 0x40019463, dl));
4610       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4611       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4612                                    getF32Constant(DAG, 0x3fd6633d, dl));
4613     } else if (LimitFloatPrecision <= 12) {
4614       // For floating-point precision of 12:
4615       //
4616       //   Log2ofMantissa =
4617       //     -2.51285454f +
4618       //       (4.07009056f +
4619       //         (-2.12067489f +
4620       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4621       //
4622       // error 0.0000876136000, which is better than 13 bits
4623       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4624                                getF32Constant(DAG, 0xbda7262e, dl));
4625       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4626                                getF32Constant(DAG, 0x3f25280b, dl));
4627       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4628       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4629                                getF32Constant(DAG, 0x4007b923, dl));
4630       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4631       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4632                                getF32Constant(DAG, 0x40823e2f, dl));
4633       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4634       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4635                                    getF32Constant(DAG, 0x4020d29c, dl));
4636     } else { // LimitFloatPrecision <= 18
4637       // For floating-point precision of 18:
4638       //
4639       //   Log2ofMantissa =
4640       //     -3.0400495f +
4641       //       (6.1129976f +
4642       //         (-5.3420409f +
4643       //           (3.2865683f +
4644       //             (-1.2669343f +
4645       //               (0.27515199f -
4646       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4647       //
4648       // error 0.0000018516, which is better than 18 bits
4649       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4650                                getF32Constant(DAG, 0xbcd2769e, dl));
4651       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4652                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4653       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4654       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4655                                getF32Constant(DAG, 0x3fa22ae7, dl));
4656       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4657       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4658                                getF32Constant(DAG, 0x40525723, dl));
4659       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4660       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4661                                getF32Constant(DAG, 0x40aaf200, dl));
4662       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4663       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4664                                getF32Constant(DAG, 0x40c39dad, dl));
4665       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4666       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4667                                    getF32Constant(DAG, 0x4042902c, dl));
4668     }
4669 
4670     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4671   }
4672 
4673   // No special expansion.
4674   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4675 }
4676 
4677 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4678 /// limited-precision mode.
4679 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4680                            const TargetLowering &TLI) {
4681   // TODO: What fast-math-flags should be set on the floating-point nodes?
4682 
4683   if (Op.getValueType() == MVT::f32 &&
4684       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4685     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4686 
4687     // Scale the exponent by log10(2) [0.30102999f].
4688     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4689     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4690                                         getF32Constant(DAG, 0x3e9a209a, dl));
4691 
4692     // Get the significand and build it into a floating-point number with
4693     // exponent of 1.
4694     SDValue X = GetSignificand(DAG, Op1, dl);
4695 
4696     SDValue Log10ofMantissa;
4697     if (LimitFloatPrecision <= 6) {
4698       // For floating-point precision of 6:
4699       //
4700       //   Log10ofMantissa =
4701       //     -0.50419619f +
4702       //       (0.60948995f - 0.10380950f * x) * x;
4703       //
4704       // error 0.0014886165, which is 6 bits
4705       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4706                                getF32Constant(DAG, 0xbdd49a13, dl));
4707       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4708                                getF32Constant(DAG, 0x3f1c0789, dl));
4709       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4710       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4711                                     getF32Constant(DAG, 0x3f011300, dl));
4712     } else if (LimitFloatPrecision <= 12) {
4713       // For floating-point precision of 12:
4714       //
4715       //   Log10ofMantissa =
4716       //     -0.64831180f +
4717       //       (0.91751397f +
4718       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4719       //
4720       // error 0.00019228036, which is better than 12 bits
4721       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4722                                getF32Constant(DAG, 0x3d431f31, dl));
4723       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4724                                getF32Constant(DAG, 0x3ea21fb2, dl));
4725       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4726       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4727                                getF32Constant(DAG, 0x3f6ae232, dl));
4728       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4729       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4730                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4731     } else { // LimitFloatPrecision <= 18
4732       // For floating-point precision of 18:
4733       //
4734       //   Log10ofMantissa =
4735       //     -0.84299375f +
4736       //       (1.5327582f +
4737       //         (-1.0688956f +
4738       //           (0.49102474f +
4739       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4740       //
4741       // error 0.0000037995730, which is better than 18 bits
4742       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4743                                getF32Constant(DAG, 0x3c5d51ce, dl));
4744       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4745                                getF32Constant(DAG, 0x3e00685a, dl));
4746       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4747       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4748                                getF32Constant(DAG, 0x3efb6798, dl));
4749       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4750       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4751                                getF32Constant(DAG, 0x3f88d192, dl));
4752       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4753       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4754                                getF32Constant(DAG, 0x3fc4316c, dl));
4755       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4756       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4757                                     getF32Constant(DAG, 0x3f57ce70, dl));
4758     }
4759 
4760     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4761   }
4762 
4763   // No special expansion.
4764   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4765 }
4766 
4767 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4768 /// limited-precision mode.
4769 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4770                           const TargetLowering &TLI) {
4771   if (Op.getValueType() == MVT::f32 &&
4772       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4773     return getLimitedPrecisionExp2(Op, dl, DAG);
4774 
4775   // No special expansion.
4776   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4777 }
4778 
4779 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4780 /// limited-precision mode with x == 10.0f.
4781 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4782                          SelectionDAG &DAG, const TargetLowering &TLI) {
4783   bool IsExp10 = false;
4784   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4785       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4786     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4787       APFloat Ten(10.0f);
4788       IsExp10 = LHSC->isExactlyValue(Ten);
4789     }
4790   }
4791 
4792   // TODO: What fast-math-flags should be set on the FMUL node?
4793   if (IsExp10) {
4794     // Put the exponent in the right bit position for later addition to the
4795     // final result:
4796     //
4797     //   #define LOG2OF10 3.3219281f
4798     //   t0 = Op * LOG2OF10;
4799     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4800                              getF32Constant(DAG, 0x40549a78, dl));
4801     return getLimitedPrecisionExp2(t0, dl, DAG);
4802   }
4803 
4804   // No special expansion.
4805   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4806 }
4807 
4808 /// ExpandPowI - Expand a llvm.powi intrinsic.
4809 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4810                           SelectionDAG &DAG) {
4811   // If RHS is a constant, we can expand this out to a multiplication tree,
4812   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4813   // optimizing for size, we only want to do this if the expansion would produce
4814   // a small number of multiplies, otherwise we do the full expansion.
4815   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4816     // Get the exponent as a positive value.
4817     unsigned Val = RHSC->getSExtValue();
4818     if ((int)Val < 0) Val = -Val;
4819 
4820     // powi(x, 0) -> 1.0
4821     if (Val == 0)
4822       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4823 
4824     const Function &F = DAG.getMachineFunction().getFunction();
4825     if (!F.optForSize() ||
4826         // If optimizing for size, don't insert too many multiplies.
4827         // This inserts up to 5 multiplies.
4828         countPopulation(Val) + Log2_32(Val) < 7) {
4829       // We use the simple binary decomposition method to generate the multiply
4830       // sequence.  There are more optimal ways to do this (for example,
4831       // powi(x,15) generates one more multiply than it should), but this has
4832       // the benefit of being both really simple and much better than a libcall.
4833       SDValue Res;  // Logically starts equal to 1.0
4834       SDValue CurSquare = LHS;
4835       // TODO: Intrinsics should have fast-math-flags that propagate to these
4836       // nodes.
4837       while (Val) {
4838         if (Val & 1) {
4839           if (Res.getNode())
4840             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4841           else
4842             Res = CurSquare;  // 1.0*CurSquare.
4843         }
4844 
4845         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4846                                 CurSquare, CurSquare);
4847         Val >>= 1;
4848       }
4849 
4850       // If the original was negative, invert the result, producing 1/(x*x*x).
4851       if (RHSC->getSExtValue() < 0)
4852         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4853                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4854       return Res;
4855     }
4856   }
4857 
4858   // Otherwise, expand to a libcall.
4859   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4860 }
4861 
4862 // getUnderlyingArgReg - Find underlying register used for a truncated or
4863 // bitcasted argument.
4864 static unsigned getUnderlyingArgReg(const SDValue &N) {
4865   switch (N.getOpcode()) {
4866   case ISD::CopyFromReg:
4867     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4868   case ISD::BITCAST:
4869   case ISD::AssertZext:
4870   case ISD::AssertSext:
4871   case ISD::TRUNCATE:
4872     return getUnderlyingArgReg(N.getOperand(0));
4873   default:
4874     return 0;
4875   }
4876 }
4877 
4878 /// If the DbgValueInst is a dbg_value of a function argument, create the
4879 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4880 /// instruction selection, they will be inserted to the entry BB.
4881 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4882     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4883     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4884   const Argument *Arg = dyn_cast<Argument>(V);
4885   if (!Arg)
4886     return false;
4887 
4888   MachineFunction &MF = DAG.getMachineFunction();
4889   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4890 
4891   bool IsIndirect = false;
4892   Optional<MachineOperand> Op;
4893   // Some arguments' frame index is recorded during argument lowering.
4894   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4895   if (FI != std::numeric_limits<int>::max())
4896     Op = MachineOperand::CreateFI(FI);
4897 
4898   if (!Op && N.getNode()) {
4899     unsigned Reg = getUnderlyingArgReg(N);
4900     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4901       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4902       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4903       if (PR)
4904         Reg = PR;
4905     }
4906     if (Reg) {
4907       Op = MachineOperand::CreateReg(Reg, false);
4908       IsIndirect = IsDbgDeclare;
4909     }
4910   }
4911 
4912   if (!Op && N.getNode())
4913     // Check if frame index is available.
4914     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4915       if (FrameIndexSDNode *FINode =
4916           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4917         Op = MachineOperand::CreateFI(FINode->getIndex());
4918 
4919   if (!Op) {
4920     // Check if ValueMap has reg number.
4921     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4922     if (VMI != FuncInfo.ValueMap.end()) {
4923       const auto &TLI = DAG.getTargetLoweringInfo();
4924       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4925                        V->getType(), isABIRegCopy(V));
4926       if (RFV.occupiesMultipleRegs()) {
4927         unsigned Offset = 0;
4928         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4929           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4930           auto FragmentExpr = DIExpression::createFragmentExpression(
4931               Expr, Offset, RegAndSize.second);
4932           if (!FragmentExpr)
4933             continue;
4934           FuncInfo.ArgDbgValues.push_back(
4935               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4936                       Op->getReg(), Variable, *FragmentExpr));
4937           Offset += RegAndSize.second;
4938         }
4939         return true;
4940       }
4941       Op = MachineOperand::CreateReg(VMI->second, false);
4942       IsIndirect = IsDbgDeclare;
4943     }
4944   }
4945 
4946   if (!Op)
4947     return false;
4948 
4949   assert(Variable->isValidLocationForIntrinsic(DL) &&
4950          "Expected inlined-at fields to agree");
4951   if (Op->isReg())
4952     FuncInfo.ArgDbgValues.push_back(
4953         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4954                 Op->getReg(), Variable, Expr));
4955   else
4956     FuncInfo.ArgDbgValues.push_back(
4957         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4958             .add(*Op)
4959             .addImm(0)
4960             .addMetadata(Variable)
4961             .addMetadata(Expr));
4962 
4963   return true;
4964 }
4965 
4966 /// Return the appropriate SDDbgValue based on N.
4967 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4968                                              DILocalVariable *Variable,
4969                                              DIExpression *Expr,
4970                                              const DebugLoc &dl,
4971                                              unsigned DbgSDNodeOrder) {
4972   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4973     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4974     // stack slot locations as such instead of as indirectly addressed
4975     // locations.
4976     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
4977                                      DbgSDNodeOrder);
4978   }
4979   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4980                          DbgSDNodeOrder);
4981 }
4982 
4983 // VisualStudio defines setjmp as _setjmp
4984 #if defined(_MSC_VER) && defined(setjmp) && \
4985                          !defined(setjmp_undefined_for_msvc)
4986 #  pragma push_macro("setjmp")
4987 #  undef setjmp
4988 #  define setjmp_undefined_for_msvc
4989 #endif
4990 
4991 /// Lower the call to the specified intrinsic function. If we want to emit this
4992 /// as a call to a named external function, return the name. Otherwise, lower it
4993 /// and return null.
4994 const char *
4995 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4997   SDLoc sdl = getCurSDLoc();
4998   DebugLoc dl = getCurDebugLoc();
4999   SDValue Res;
5000 
5001   switch (Intrinsic) {
5002   default:
5003     // By default, turn this into a target intrinsic node.
5004     visitTargetIntrinsic(I, Intrinsic);
5005     return nullptr;
5006   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5007   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5008   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5009   case Intrinsic::returnaddress:
5010     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5011                              TLI.getPointerTy(DAG.getDataLayout()),
5012                              getValue(I.getArgOperand(0))));
5013     return nullptr;
5014   case Intrinsic::addressofreturnaddress:
5015     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5016                              TLI.getPointerTy(DAG.getDataLayout())));
5017     return nullptr;
5018   case Intrinsic::frameaddress:
5019     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5020                              TLI.getPointerTy(DAG.getDataLayout()),
5021                              getValue(I.getArgOperand(0))));
5022     return nullptr;
5023   case Intrinsic::read_register: {
5024     Value *Reg = I.getArgOperand(0);
5025     SDValue Chain = getRoot();
5026     SDValue RegName =
5027         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5028     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5029     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5030       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5031     setValue(&I, Res);
5032     DAG.setRoot(Res.getValue(1));
5033     return nullptr;
5034   }
5035   case Intrinsic::write_register: {
5036     Value *Reg = I.getArgOperand(0);
5037     Value *RegValue = I.getArgOperand(1);
5038     SDValue Chain = getRoot();
5039     SDValue RegName =
5040         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5041     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5042                             RegName, getValue(RegValue)));
5043     return nullptr;
5044   }
5045   case Intrinsic::setjmp:
5046     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5047   case Intrinsic::longjmp:
5048     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5049   case Intrinsic::memcpy: {
5050     const auto &MCI = cast<MemCpyInst>(I);
5051     SDValue Op1 = getValue(I.getArgOperand(0));
5052     SDValue Op2 = getValue(I.getArgOperand(1));
5053     SDValue Op3 = getValue(I.getArgOperand(2));
5054     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5055     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5056     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5057     unsigned Align = MinAlign(DstAlign, SrcAlign);
5058     bool isVol = MCI.isVolatile();
5059     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5060     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5061     // node.
5062     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5063                                false, isTC,
5064                                MachinePointerInfo(I.getArgOperand(0)),
5065                                MachinePointerInfo(I.getArgOperand(1)));
5066     updateDAGForMaybeTailCall(MC);
5067     return nullptr;
5068   }
5069   case Intrinsic::memset: {
5070     const auto &MSI = cast<MemSetInst>(I);
5071     SDValue Op1 = getValue(I.getArgOperand(0));
5072     SDValue Op2 = getValue(I.getArgOperand(1));
5073     SDValue Op3 = getValue(I.getArgOperand(2));
5074     // @llvm.memset defines 0 and 1 to both mean no alignment.
5075     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5076     bool isVol = MSI.isVolatile();
5077     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5078     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5079                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5080     updateDAGForMaybeTailCall(MS);
5081     return nullptr;
5082   }
5083   case Intrinsic::memmove: {
5084     const auto &MMI = cast<MemMoveInst>(I);
5085     SDValue Op1 = getValue(I.getArgOperand(0));
5086     SDValue Op2 = getValue(I.getArgOperand(1));
5087     SDValue Op3 = getValue(I.getArgOperand(2));
5088     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5089     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5090     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5091     unsigned Align = MinAlign(DstAlign, SrcAlign);
5092     bool isVol = MMI.isVolatile();
5093     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5094     // FIXME: Support passing different dest/src alignments to the memmove DAG
5095     // node.
5096     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5097                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5098                                 MachinePointerInfo(I.getArgOperand(1)));
5099     updateDAGForMaybeTailCall(MM);
5100     return nullptr;
5101   }
5102   case Intrinsic::memcpy_element_unordered_atomic: {
5103     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5104     SDValue Dst = getValue(MI.getRawDest());
5105     SDValue Src = getValue(MI.getRawSource());
5106     SDValue Length = getValue(MI.getLength());
5107 
5108     unsigned DstAlign = MI.getDestAlignment();
5109     unsigned SrcAlign = MI.getSourceAlignment();
5110     Type *LengthTy = MI.getLength()->getType();
5111     unsigned ElemSz = MI.getElementSizeInBytes();
5112     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5113     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5114                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5115                                      MachinePointerInfo(MI.getRawDest()),
5116                                      MachinePointerInfo(MI.getRawSource()));
5117     updateDAGForMaybeTailCall(MC);
5118     return nullptr;
5119   }
5120   case Intrinsic::memmove_element_unordered_atomic: {
5121     auto &MI = cast<AtomicMemMoveInst>(I);
5122     SDValue Dst = getValue(MI.getRawDest());
5123     SDValue Src = getValue(MI.getRawSource());
5124     SDValue Length = getValue(MI.getLength());
5125 
5126     unsigned DstAlign = MI.getDestAlignment();
5127     unsigned SrcAlign = MI.getSourceAlignment();
5128     Type *LengthTy = MI.getLength()->getType();
5129     unsigned ElemSz = MI.getElementSizeInBytes();
5130     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5131     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5132                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5133                                       MachinePointerInfo(MI.getRawDest()),
5134                                       MachinePointerInfo(MI.getRawSource()));
5135     updateDAGForMaybeTailCall(MC);
5136     return nullptr;
5137   }
5138   case Intrinsic::memset_element_unordered_atomic: {
5139     auto &MI = cast<AtomicMemSetInst>(I);
5140     SDValue Dst = getValue(MI.getRawDest());
5141     SDValue Val = getValue(MI.getValue());
5142     SDValue Length = getValue(MI.getLength());
5143 
5144     unsigned DstAlign = MI.getDestAlignment();
5145     Type *LengthTy = MI.getLength()->getType();
5146     unsigned ElemSz = MI.getElementSizeInBytes();
5147     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5148     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5149                                      LengthTy, ElemSz, isTC,
5150                                      MachinePointerInfo(MI.getRawDest()));
5151     updateDAGForMaybeTailCall(MC);
5152     return nullptr;
5153   }
5154   case Intrinsic::dbg_addr:
5155   case Intrinsic::dbg_declare: {
5156     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
5157     DILocalVariable *Variable = DI.getVariable();
5158     DIExpression *Expression = DI.getExpression();
5159     dropDanglingDebugInfo(Variable, Expression);
5160     assert(Variable && "Missing variable");
5161 
5162     // Check if address has undef value.
5163     const Value *Address = DI.getVariableLocation();
5164     if (!Address || isa<UndefValue>(Address) ||
5165         (Address->use_empty() && !isa<Argument>(Address))) {
5166       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5167       return nullptr;
5168     }
5169 
5170     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5171 
5172     // Check if this variable can be described by a frame index, typically
5173     // either as a static alloca or a byval parameter.
5174     int FI = std::numeric_limits<int>::max();
5175     if (const auto *AI =
5176             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5177       if (AI->isStaticAlloca()) {
5178         auto I = FuncInfo.StaticAllocaMap.find(AI);
5179         if (I != FuncInfo.StaticAllocaMap.end())
5180           FI = I->second;
5181       }
5182     } else if (const auto *Arg = dyn_cast<Argument>(
5183                    Address->stripInBoundsConstantOffsets())) {
5184       FI = FuncInfo.getArgumentFrameIndex(Arg);
5185     }
5186 
5187     // llvm.dbg.addr is control dependent and always generates indirect
5188     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5189     // the MachineFunction variable table.
5190     if (FI != std::numeric_limits<int>::max()) {
5191       if (Intrinsic == Intrinsic::dbg_addr) {
5192          SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5193                                                      FI, dl, SDNodeOrder);
5194          DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5195       }
5196       return nullptr;
5197     }
5198 
5199     SDValue &N = NodeMap[Address];
5200     if (!N.getNode() && isa<Argument>(Address))
5201       // Check unused arguments map.
5202       N = UnusedArgNodeMap[Address];
5203     SDDbgValue *SDV;
5204     if (N.getNode()) {
5205       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5206         Address = BCI->getOperand(0);
5207       // Parameters are handled specially.
5208       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5209       if (isParameter && FINode) {
5210         // Byval parameter. We have a frame index at this point.
5211         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5212                                         FINode->getIndex(), dl, SDNodeOrder);
5213       } else if (isa<Argument>(Address)) {
5214         // Address is an argument, so try to emit its dbg value using
5215         // virtual register info from the FuncInfo.ValueMap.
5216         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5217         return nullptr;
5218       } else {
5219         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5220                               true, dl, SDNodeOrder);
5221       }
5222       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5223     } else {
5224       // If Address is an argument then try to emit its dbg value using
5225       // virtual register info from the FuncInfo.ValueMap.
5226       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5227                                     N)) {
5228         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5229       }
5230     }
5231     return nullptr;
5232   }
5233   case Intrinsic::dbg_label: {
5234     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5235     DILabel *Label = DI.getLabel();
5236     assert(Label && "Missing label");
5237 
5238     SDDbgLabel *SDV;
5239     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5240     DAG.AddDbgLabel(SDV);
5241     return nullptr;
5242   }
5243   case Intrinsic::dbg_value: {
5244     const DbgValueInst &DI = cast<DbgValueInst>(I);
5245     assert(DI.getVariable() && "Missing variable");
5246 
5247     DILocalVariable *Variable = DI.getVariable();
5248     DIExpression *Expression = DI.getExpression();
5249     dropDanglingDebugInfo(Variable, Expression);
5250     const Value *V = DI.getValue();
5251     if (!V)
5252       return nullptr;
5253 
5254     SDDbgValue *SDV;
5255     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5256       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5257       DAG.AddDbgValue(SDV, nullptr, false);
5258       return nullptr;
5259     }
5260 
5261     // Do not use getValue() in here; we don't want to generate code at
5262     // this point if it hasn't been done yet.
5263     SDValue N = NodeMap[V];
5264     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5265       N = UnusedArgNodeMap[V];
5266     if (N.getNode()) {
5267       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5268         return nullptr;
5269       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5270       DAG.AddDbgValue(SDV, N.getNode(), false);
5271       return nullptr;
5272     }
5273 
5274     // PHI nodes have already been selected, so we should know which VReg that
5275     // is assigns to already.
5276     if (isa<PHINode>(V)) {
5277       auto VMI = FuncInfo.ValueMap.find(V);
5278       if (VMI != FuncInfo.ValueMap.end()) {
5279         unsigned Reg = VMI->second;
5280         // The PHI node may be split up into several MI PHI nodes (in
5281         // FunctionLoweringInfo::set).
5282         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5283                          V->getType(), false);
5284         if (RFV.occupiesMultipleRegs()) {
5285           unsigned Offset = 0;
5286           unsigned BitsToDescribe = 0;
5287           if (auto VarSize = Variable->getSizeInBits())
5288             BitsToDescribe = *VarSize;
5289           if (auto Fragment = Expression->getFragmentInfo())
5290             BitsToDescribe = Fragment->SizeInBits;
5291           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5292             unsigned RegisterSize = RegAndSize.second;
5293             // Bail out if all bits are described already.
5294             if (Offset >= BitsToDescribe)
5295               break;
5296             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5297                 ? BitsToDescribe - Offset
5298                 : RegisterSize;
5299             auto FragmentExpr = DIExpression::createFragmentExpression(
5300                 Expression, Offset, FragmentSize);
5301             if (!FragmentExpr)
5302                 continue;
5303             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5304                                       false, dl, SDNodeOrder);
5305             DAG.AddDbgValue(SDV, nullptr, false);
5306             Offset += RegisterSize;
5307           }
5308         } else {
5309           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5310                                     SDNodeOrder);
5311           DAG.AddDbgValue(SDV, nullptr, false);
5312         }
5313         return nullptr;
5314       }
5315     }
5316 
5317     // TODO: When we get here we will either drop the dbg.value completely, or
5318     // we try to move it forward by letting it dangle for awhile. So we should
5319     // probably add an extra DbgValue to the DAG here, with a reference to
5320     // "noreg", to indicate that we have lost the debug location for the
5321     // variable.
5322 
5323     if (!V->use_empty() ) {
5324       // Do not call getValue(V) yet, as we don't want to generate code.
5325       // Remember it for later.
5326       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5327       DanglingDebugInfoMap[V].push_back(DDI);
5328       return nullptr;
5329     }
5330 
5331     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5332     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5333     return nullptr;
5334   }
5335 
5336   case Intrinsic::eh_typeid_for: {
5337     // Find the type id for the given typeinfo.
5338     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5339     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5340     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5341     setValue(&I, Res);
5342     return nullptr;
5343   }
5344 
5345   case Intrinsic::eh_return_i32:
5346   case Intrinsic::eh_return_i64:
5347     DAG.getMachineFunction().setCallsEHReturn(true);
5348     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5349                             MVT::Other,
5350                             getControlRoot(),
5351                             getValue(I.getArgOperand(0)),
5352                             getValue(I.getArgOperand(1))));
5353     return nullptr;
5354   case Intrinsic::eh_unwind_init:
5355     DAG.getMachineFunction().setCallsUnwindInit(true);
5356     return nullptr;
5357   case Intrinsic::eh_dwarf_cfa:
5358     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5359                              TLI.getPointerTy(DAG.getDataLayout()),
5360                              getValue(I.getArgOperand(0))));
5361     return nullptr;
5362   case Intrinsic::eh_sjlj_callsite: {
5363     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5364     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5365     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5366     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5367 
5368     MMI.setCurrentCallSite(CI->getZExtValue());
5369     return nullptr;
5370   }
5371   case Intrinsic::eh_sjlj_functioncontext: {
5372     // Get and store the index of the function context.
5373     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5374     AllocaInst *FnCtx =
5375       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5376     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5377     MFI.setFunctionContextIndex(FI);
5378     return nullptr;
5379   }
5380   case Intrinsic::eh_sjlj_setjmp: {
5381     SDValue Ops[2];
5382     Ops[0] = getRoot();
5383     Ops[1] = getValue(I.getArgOperand(0));
5384     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5385                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5386     setValue(&I, Op.getValue(0));
5387     DAG.setRoot(Op.getValue(1));
5388     return nullptr;
5389   }
5390   case Intrinsic::eh_sjlj_longjmp:
5391     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5392                             getRoot(), getValue(I.getArgOperand(0))));
5393     return nullptr;
5394   case Intrinsic::eh_sjlj_setup_dispatch:
5395     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5396                             getRoot()));
5397     return nullptr;
5398   case Intrinsic::masked_gather:
5399     visitMaskedGather(I);
5400     return nullptr;
5401   case Intrinsic::masked_load:
5402     visitMaskedLoad(I);
5403     return nullptr;
5404   case Intrinsic::masked_scatter:
5405     visitMaskedScatter(I);
5406     return nullptr;
5407   case Intrinsic::masked_store:
5408     visitMaskedStore(I);
5409     return nullptr;
5410   case Intrinsic::masked_expandload:
5411     visitMaskedLoad(I, true /* IsExpanding */);
5412     return nullptr;
5413   case Intrinsic::masked_compressstore:
5414     visitMaskedStore(I, true /* IsCompressing */);
5415     return nullptr;
5416   case Intrinsic::x86_mmx_pslli_w:
5417   case Intrinsic::x86_mmx_pslli_d:
5418   case Intrinsic::x86_mmx_pslli_q:
5419   case Intrinsic::x86_mmx_psrli_w:
5420   case Intrinsic::x86_mmx_psrli_d:
5421   case Intrinsic::x86_mmx_psrli_q:
5422   case Intrinsic::x86_mmx_psrai_w:
5423   case Intrinsic::x86_mmx_psrai_d: {
5424     SDValue ShAmt = getValue(I.getArgOperand(1));
5425     if (isa<ConstantSDNode>(ShAmt)) {
5426       visitTargetIntrinsic(I, Intrinsic);
5427       return nullptr;
5428     }
5429     unsigned NewIntrinsic = 0;
5430     EVT ShAmtVT = MVT::v2i32;
5431     switch (Intrinsic) {
5432     case Intrinsic::x86_mmx_pslli_w:
5433       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5434       break;
5435     case Intrinsic::x86_mmx_pslli_d:
5436       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5437       break;
5438     case Intrinsic::x86_mmx_pslli_q:
5439       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5440       break;
5441     case Intrinsic::x86_mmx_psrli_w:
5442       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5443       break;
5444     case Intrinsic::x86_mmx_psrli_d:
5445       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5446       break;
5447     case Intrinsic::x86_mmx_psrli_q:
5448       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5449       break;
5450     case Intrinsic::x86_mmx_psrai_w:
5451       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5452       break;
5453     case Intrinsic::x86_mmx_psrai_d:
5454       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5455       break;
5456     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5457     }
5458 
5459     // The vector shift intrinsics with scalars uses 32b shift amounts but
5460     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5461     // to be zero.
5462     // We must do this early because v2i32 is not a legal type.
5463     SDValue ShOps[2];
5464     ShOps[0] = ShAmt;
5465     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5466     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5467     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5468     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5469     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5470                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5471                        getValue(I.getArgOperand(0)), ShAmt);
5472     setValue(&I, Res);
5473     return nullptr;
5474   }
5475   case Intrinsic::powi:
5476     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5477                             getValue(I.getArgOperand(1)), DAG));
5478     return nullptr;
5479   case Intrinsic::log:
5480     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5481     return nullptr;
5482   case Intrinsic::log2:
5483     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5484     return nullptr;
5485   case Intrinsic::log10:
5486     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5487     return nullptr;
5488   case Intrinsic::exp:
5489     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5490     return nullptr;
5491   case Intrinsic::exp2:
5492     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5493     return nullptr;
5494   case Intrinsic::pow:
5495     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5496                            getValue(I.getArgOperand(1)), DAG, TLI));
5497     return nullptr;
5498   case Intrinsic::sqrt:
5499   case Intrinsic::fabs:
5500   case Intrinsic::sin:
5501   case Intrinsic::cos:
5502   case Intrinsic::floor:
5503   case Intrinsic::ceil:
5504   case Intrinsic::trunc:
5505   case Intrinsic::rint:
5506   case Intrinsic::nearbyint:
5507   case Intrinsic::round:
5508   case Intrinsic::canonicalize: {
5509     unsigned Opcode;
5510     switch (Intrinsic) {
5511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5512     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5513     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5514     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5515     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5516     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5517     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5518     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5519     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5520     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5521     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5522     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5523     }
5524 
5525     setValue(&I, DAG.getNode(Opcode, sdl,
5526                              getValue(I.getArgOperand(0)).getValueType(),
5527                              getValue(I.getArgOperand(0))));
5528     return nullptr;
5529   }
5530   case Intrinsic::minnum: {
5531     auto VT = getValue(I.getArgOperand(0)).getValueType();
5532     unsigned Opc =
5533         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5534             ? ISD::FMINNAN
5535             : ISD::FMINNUM;
5536     setValue(&I, DAG.getNode(Opc, sdl, VT,
5537                              getValue(I.getArgOperand(0)),
5538                              getValue(I.getArgOperand(1))));
5539     return nullptr;
5540   }
5541   case Intrinsic::maxnum: {
5542     auto VT = getValue(I.getArgOperand(0)).getValueType();
5543     unsigned Opc =
5544         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5545             ? ISD::FMAXNAN
5546             : ISD::FMAXNUM;
5547     setValue(&I, DAG.getNode(Opc, sdl, VT,
5548                              getValue(I.getArgOperand(0)),
5549                              getValue(I.getArgOperand(1))));
5550     return nullptr;
5551   }
5552   case Intrinsic::copysign:
5553     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5554                              getValue(I.getArgOperand(0)).getValueType(),
5555                              getValue(I.getArgOperand(0)),
5556                              getValue(I.getArgOperand(1))));
5557     return nullptr;
5558   case Intrinsic::fma:
5559     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5560                              getValue(I.getArgOperand(0)).getValueType(),
5561                              getValue(I.getArgOperand(0)),
5562                              getValue(I.getArgOperand(1)),
5563                              getValue(I.getArgOperand(2))));
5564     return nullptr;
5565   case Intrinsic::experimental_constrained_fadd:
5566   case Intrinsic::experimental_constrained_fsub:
5567   case Intrinsic::experimental_constrained_fmul:
5568   case Intrinsic::experimental_constrained_fdiv:
5569   case Intrinsic::experimental_constrained_frem:
5570   case Intrinsic::experimental_constrained_fma:
5571   case Intrinsic::experimental_constrained_sqrt:
5572   case Intrinsic::experimental_constrained_pow:
5573   case Intrinsic::experimental_constrained_powi:
5574   case Intrinsic::experimental_constrained_sin:
5575   case Intrinsic::experimental_constrained_cos:
5576   case Intrinsic::experimental_constrained_exp:
5577   case Intrinsic::experimental_constrained_exp2:
5578   case Intrinsic::experimental_constrained_log:
5579   case Intrinsic::experimental_constrained_log10:
5580   case Intrinsic::experimental_constrained_log2:
5581   case Intrinsic::experimental_constrained_rint:
5582   case Intrinsic::experimental_constrained_nearbyint:
5583     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5584     return nullptr;
5585   case Intrinsic::fmuladd: {
5586     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5587     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5588         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5589       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5590                                getValue(I.getArgOperand(0)).getValueType(),
5591                                getValue(I.getArgOperand(0)),
5592                                getValue(I.getArgOperand(1)),
5593                                getValue(I.getArgOperand(2))));
5594     } else {
5595       // TODO: Intrinsic calls should have fast-math-flags.
5596       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5597                                 getValue(I.getArgOperand(0)).getValueType(),
5598                                 getValue(I.getArgOperand(0)),
5599                                 getValue(I.getArgOperand(1)));
5600       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5601                                 getValue(I.getArgOperand(0)).getValueType(),
5602                                 Mul,
5603                                 getValue(I.getArgOperand(2)));
5604       setValue(&I, Add);
5605     }
5606     return nullptr;
5607   }
5608   case Intrinsic::convert_to_fp16:
5609     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5610                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5611                                          getValue(I.getArgOperand(0)),
5612                                          DAG.getTargetConstant(0, sdl,
5613                                                                MVT::i32))));
5614     return nullptr;
5615   case Intrinsic::convert_from_fp16:
5616     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5617                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5618                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5619                                          getValue(I.getArgOperand(0)))));
5620     return nullptr;
5621   case Intrinsic::pcmarker: {
5622     SDValue Tmp = getValue(I.getArgOperand(0));
5623     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5624     return nullptr;
5625   }
5626   case Intrinsic::readcyclecounter: {
5627     SDValue Op = getRoot();
5628     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5629                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5630     setValue(&I, Res);
5631     DAG.setRoot(Res.getValue(1));
5632     return nullptr;
5633   }
5634   case Intrinsic::bitreverse:
5635     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5636                              getValue(I.getArgOperand(0)).getValueType(),
5637                              getValue(I.getArgOperand(0))));
5638     return nullptr;
5639   case Intrinsic::bswap:
5640     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5641                              getValue(I.getArgOperand(0)).getValueType(),
5642                              getValue(I.getArgOperand(0))));
5643     return nullptr;
5644   case Intrinsic::cttz: {
5645     SDValue Arg = getValue(I.getArgOperand(0));
5646     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5647     EVT Ty = Arg.getValueType();
5648     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5649                              sdl, Ty, Arg));
5650     return nullptr;
5651   }
5652   case Intrinsic::ctlz: {
5653     SDValue Arg = getValue(I.getArgOperand(0));
5654     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5655     EVT Ty = Arg.getValueType();
5656     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5657                              sdl, Ty, Arg));
5658     return nullptr;
5659   }
5660   case Intrinsic::ctpop: {
5661     SDValue Arg = getValue(I.getArgOperand(0));
5662     EVT Ty = Arg.getValueType();
5663     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5664     return nullptr;
5665   }
5666   case Intrinsic::stacksave: {
5667     SDValue Op = getRoot();
5668     Res = DAG.getNode(
5669         ISD::STACKSAVE, sdl,
5670         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5671     setValue(&I, Res);
5672     DAG.setRoot(Res.getValue(1));
5673     return nullptr;
5674   }
5675   case Intrinsic::stackrestore:
5676     Res = getValue(I.getArgOperand(0));
5677     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5678     return nullptr;
5679   case Intrinsic::get_dynamic_area_offset: {
5680     SDValue Op = getRoot();
5681     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5682     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5683     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5684     // target.
5685     if (PtrTy != ResTy)
5686       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5687                          " intrinsic!");
5688     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5689                       Op);
5690     DAG.setRoot(Op);
5691     setValue(&I, Res);
5692     return nullptr;
5693   }
5694   case Intrinsic::stackguard: {
5695     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5696     MachineFunction &MF = DAG.getMachineFunction();
5697     const Module &M = *MF.getFunction().getParent();
5698     SDValue Chain = getRoot();
5699     if (TLI.useLoadStackGuardNode()) {
5700       Res = getLoadStackGuard(DAG, sdl, Chain);
5701     } else {
5702       const Value *Global = TLI.getSDagStackGuard(M);
5703       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5704       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5705                         MachinePointerInfo(Global, 0), Align,
5706                         MachineMemOperand::MOVolatile);
5707     }
5708     if (TLI.useStackGuardXorFP())
5709       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5710     DAG.setRoot(Chain);
5711     setValue(&I, Res);
5712     return nullptr;
5713   }
5714   case Intrinsic::stackprotector: {
5715     // Emit code into the DAG to store the stack guard onto the stack.
5716     MachineFunction &MF = DAG.getMachineFunction();
5717     MachineFrameInfo &MFI = MF.getFrameInfo();
5718     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5719     SDValue Src, Chain = getRoot();
5720 
5721     if (TLI.useLoadStackGuardNode())
5722       Src = getLoadStackGuard(DAG, sdl, Chain);
5723     else
5724       Src = getValue(I.getArgOperand(0));   // The guard's value.
5725 
5726     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5727 
5728     int FI = FuncInfo.StaticAllocaMap[Slot];
5729     MFI.setStackProtectorIndex(FI);
5730 
5731     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5732 
5733     // Store the stack protector onto the stack.
5734     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5735                                                  DAG.getMachineFunction(), FI),
5736                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5737     setValue(&I, Res);
5738     DAG.setRoot(Res);
5739     return nullptr;
5740   }
5741   case Intrinsic::objectsize: {
5742     // If we don't know by now, we're never going to know.
5743     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5744 
5745     assert(CI && "Non-constant type in __builtin_object_size?");
5746 
5747     SDValue Arg = getValue(I.getCalledValue());
5748     EVT Ty = Arg.getValueType();
5749 
5750     if (CI->isZero())
5751       Res = DAG.getConstant(-1ULL, sdl, Ty);
5752     else
5753       Res = DAG.getConstant(0, sdl, Ty);
5754 
5755     setValue(&I, Res);
5756     return nullptr;
5757   }
5758   case Intrinsic::annotation:
5759   case Intrinsic::ptr_annotation:
5760   case Intrinsic::launder_invariant_group:
5761     // Drop the intrinsic, but forward the value
5762     setValue(&I, getValue(I.getOperand(0)));
5763     return nullptr;
5764   case Intrinsic::assume:
5765   case Intrinsic::var_annotation:
5766   case Intrinsic::sideeffect:
5767     // Discard annotate attributes, assumptions, and artificial side-effects.
5768     return nullptr;
5769 
5770   case Intrinsic::codeview_annotation: {
5771     // Emit a label associated with this metadata.
5772     MachineFunction &MF = DAG.getMachineFunction();
5773     MCSymbol *Label =
5774         MF.getMMI().getContext().createTempSymbol("annotation", true);
5775     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5776     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5777     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5778     DAG.setRoot(Res);
5779     return nullptr;
5780   }
5781 
5782   case Intrinsic::init_trampoline: {
5783     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5784 
5785     SDValue Ops[6];
5786     Ops[0] = getRoot();
5787     Ops[1] = getValue(I.getArgOperand(0));
5788     Ops[2] = getValue(I.getArgOperand(1));
5789     Ops[3] = getValue(I.getArgOperand(2));
5790     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5791     Ops[5] = DAG.getSrcValue(F);
5792 
5793     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5794 
5795     DAG.setRoot(Res);
5796     return nullptr;
5797   }
5798   case Intrinsic::adjust_trampoline:
5799     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5800                              TLI.getPointerTy(DAG.getDataLayout()),
5801                              getValue(I.getArgOperand(0))));
5802     return nullptr;
5803   case Intrinsic::gcroot: {
5804     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5805            "only valid in functions with gc specified, enforced by Verifier");
5806     assert(GFI && "implied by previous");
5807     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5808     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5809 
5810     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5811     GFI->addStackRoot(FI->getIndex(), TypeMap);
5812     return nullptr;
5813   }
5814   case Intrinsic::gcread:
5815   case Intrinsic::gcwrite:
5816     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5817   case Intrinsic::flt_rounds:
5818     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5819     return nullptr;
5820 
5821   case Intrinsic::expect:
5822     // Just replace __builtin_expect(exp, c) with EXP.
5823     setValue(&I, getValue(I.getArgOperand(0)));
5824     return nullptr;
5825 
5826   case Intrinsic::debugtrap:
5827   case Intrinsic::trap: {
5828     StringRef TrapFuncName =
5829         I.getAttributes()
5830             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5831             .getValueAsString();
5832     if (TrapFuncName.empty()) {
5833       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5834         ISD::TRAP : ISD::DEBUGTRAP;
5835       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5836       return nullptr;
5837     }
5838     TargetLowering::ArgListTy Args;
5839 
5840     TargetLowering::CallLoweringInfo CLI(DAG);
5841     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5842         CallingConv::C, I.getType(),
5843         DAG.getExternalSymbol(TrapFuncName.data(),
5844                               TLI.getPointerTy(DAG.getDataLayout())),
5845         std::move(Args));
5846 
5847     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5848     DAG.setRoot(Result.second);
5849     return nullptr;
5850   }
5851 
5852   case Intrinsic::uadd_with_overflow:
5853   case Intrinsic::sadd_with_overflow:
5854   case Intrinsic::usub_with_overflow:
5855   case Intrinsic::ssub_with_overflow:
5856   case Intrinsic::umul_with_overflow:
5857   case Intrinsic::smul_with_overflow: {
5858     ISD::NodeType Op;
5859     switch (Intrinsic) {
5860     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5861     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5862     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5863     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5864     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5865     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5866     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5867     }
5868     SDValue Op1 = getValue(I.getArgOperand(0));
5869     SDValue Op2 = getValue(I.getArgOperand(1));
5870 
5871     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5872     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5873     return nullptr;
5874   }
5875   case Intrinsic::prefetch: {
5876     SDValue Ops[5];
5877     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5878     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5879     Ops[0] = DAG.getRoot();
5880     Ops[1] = getValue(I.getArgOperand(0));
5881     Ops[2] = getValue(I.getArgOperand(1));
5882     Ops[3] = getValue(I.getArgOperand(2));
5883     Ops[4] = getValue(I.getArgOperand(3));
5884     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5885                                              DAG.getVTList(MVT::Other), Ops,
5886                                              EVT::getIntegerVT(*Context, 8),
5887                                              MachinePointerInfo(I.getArgOperand(0)),
5888                                              0, /* align */
5889                                              Flags);
5890 
5891     // Chain the prefetch in parallell with any pending loads, to stay out of
5892     // the way of later optimizations.
5893     PendingLoads.push_back(Result);
5894     Result = getRoot();
5895     DAG.setRoot(Result);
5896     return nullptr;
5897   }
5898   case Intrinsic::lifetime_start:
5899   case Intrinsic::lifetime_end: {
5900     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5901     // Stack coloring is not enabled in O0, discard region information.
5902     if (TM.getOptLevel() == CodeGenOpt::None)
5903       return nullptr;
5904 
5905     SmallVector<Value *, 4> Allocas;
5906     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5907 
5908     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5909            E = Allocas.end(); Object != E; ++Object) {
5910       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5911 
5912       // Could not find an Alloca.
5913       if (!LifetimeObject)
5914         continue;
5915 
5916       // First check that the Alloca is static, otherwise it won't have a
5917       // valid frame index.
5918       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5919       if (SI == FuncInfo.StaticAllocaMap.end())
5920         return nullptr;
5921 
5922       int FI = SI->second;
5923 
5924       SDValue Ops[2];
5925       Ops[0] = getRoot();
5926       Ops[1] =
5927           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5928       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5929 
5930       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5931       DAG.setRoot(Res);
5932     }
5933     return nullptr;
5934   }
5935   case Intrinsic::invariant_start:
5936     // Discard region information.
5937     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5938     return nullptr;
5939   case Intrinsic::invariant_end:
5940     // Discard region information.
5941     return nullptr;
5942   case Intrinsic::clear_cache:
5943     return TLI.getClearCacheBuiltinName();
5944   case Intrinsic::donothing:
5945     // ignore
5946     return nullptr;
5947   case Intrinsic::experimental_stackmap:
5948     visitStackmap(I);
5949     return nullptr;
5950   case Intrinsic::experimental_patchpoint_void:
5951   case Intrinsic::experimental_patchpoint_i64:
5952     visitPatchpoint(&I);
5953     return nullptr;
5954   case Intrinsic::experimental_gc_statepoint:
5955     LowerStatepoint(ImmutableStatepoint(&I));
5956     return nullptr;
5957   case Intrinsic::experimental_gc_result:
5958     visitGCResult(cast<GCResultInst>(I));
5959     return nullptr;
5960   case Intrinsic::experimental_gc_relocate:
5961     visitGCRelocate(cast<GCRelocateInst>(I));
5962     return nullptr;
5963   case Intrinsic::instrprof_increment:
5964     llvm_unreachable("instrprof failed to lower an increment");
5965   case Intrinsic::instrprof_value_profile:
5966     llvm_unreachable("instrprof failed to lower a value profiling call");
5967   case Intrinsic::localescape: {
5968     MachineFunction &MF = DAG.getMachineFunction();
5969     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5970 
5971     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5972     // is the same on all targets.
5973     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5974       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5975       if (isa<ConstantPointerNull>(Arg))
5976         continue; // Skip null pointers. They represent a hole in index space.
5977       AllocaInst *Slot = cast<AllocaInst>(Arg);
5978       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5979              "can only escape static allocas");
5980       int FI = FuncInfo.StaticAllocaMap[Slot];
5981       MCSymbol *FrameAllocSym =
5982           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5983               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5984       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5985               TII->get(TargetOpcode::LOCAL_ESCAPE))
5986           .addSym(FrameAllocSym)
5987           .addFrameIndex(FI);
5988     }
5989 
5990     return nullptr;
5991   }
5992 
5993   case Intrinsic::localrecover: {
5994     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5995     MachineFunction &MF = DAG.getMachineFunction();
5996     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5997 
5998     // Get the symbol that defines the frame offset.
5999     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6000     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6001     unsigned IdxVal =
6002         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6003     MCSymbol *FrameAllocSym =
6004         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6005             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6006 
6007     // Create a MCSymbol for the label to avoid any target lowering
6008     // that would make this PC relative.
6009     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6010     SDValue OffsetVal =
6011         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6012 
6013     // Add the offset to the FP.
6014     Value *FP = I.getArgOperand(1);
6015     SDValue FPVal = getValue(FP);
6016     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6017     setValue(&I, Add);
6018 
6019     return nullptr;
6020   }
6021 
6022   case Intrinsic::eh_exceptionpointer:
6023   case Intrinsic::eh_exceptioncode: {
6024     // Get the exception pointer vreg, copy from it, and resize it to fit.
6025     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6026     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6027     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6028     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6029     SDValue N =
6030         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6031     if (Intrinsic == Intrinsic::eh_exceptioncode)
6032       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6033     setValue(&I, N);
6034     return nullptr;
6035   }
6036   case Intrinsic::xray_customevent: {
6037     // Here we want to make sure that the intrinsic behaves as if it has a
6038     // specific calling convention, and only for x86_64.
6039     // FIXME: Support other platforms later.
6040     const auto &Triple = DAG.getTarget().getTargetTriple();
6041     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6042       return nullptr;
6043 
6044     SDLoc DL = getCurSDLoc();
6045     SmallVector<SDValue, 8> Ops;
6046 
6047     // We want to say that we always want the arguments in registers.
6048     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6049     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6050     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6051     SDValue Chain = getRoot();
6052     Ops.push_back(LogEntryVal);
6053     Ops.push_back(StrSizeVal);
6054     Ops.push_back(Chain);
6055 
6056     // We need to enforce the calling convention for the callsite, so that
6057     // argument ordering is enforced correctly, and that register allocation can
6058     // see that some registers may be assumed clobbered and have to preserve
6059     // them across calls to the intrinsic.
6060     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6061                                            DL, NodeTys, Ops);
6062     SDValue patchableNode = SDValue(MN, 0);
6063     DAG.setRoot(patchableNode);
6064     setValue(&I, patchableNode);
6065     return nullptr;
6066   }
6067   case Intrinsic::xray_typedevent: {
6068     // Here we want to make sure that the intrinsic behaves as if it has a
6069     // specific calling convention, and only for x86_64.
6070     // FIXME: Support other platforms later.
6071     const auto &Triple = DAG.getTarget().getTargetTriple();
6072     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6073       return nullptr;
6074 
6075     SDLoc DL = getCurSDLoc();
6076     SmallVector<SDValue, 8> Ops;
6077 
6078     // We want to say that we always want the arguments in registers.
6079     // It's unclear to me how manipulating the selection DAG here forces callers
6080     // to provide arguments in registers instead of on the stack.
6081     SDValue LogTypeId = getValue(I.getArgOperand(0));
6082     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6083     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6084     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6085     SDValue Chain = getRoot();
6086     Ops.push_back(LogTypeId);
6087     Ops.push_back(LogEntryVal);
6088     Ops.push_back(StrSizeVal);
6089     Ops.push_back(Chain);
6090 
6091     // We need to enforce the calling convention for the callsite, so that
6092     // argument ordering is enforced correctly, and that register allocation can
6093     // see that some registers may be assumed clobbered and have to preserve
6094     // them across calls to the intrinsic.
6095     MachineSDNode *MN = DAG.getMachineNode(
6096         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6097     SDValue patchableNode = SDValue(MN, 0);
6098     DAG.setRoot(patchableNode);
6099     setValue(&I, patchableNode);
6100     return nullptr;
6101   }
6102   case Intrinsic::experimental_deoptimize:
6103     LowerDeoptimizeCall(&I);
6104     return nullptr;
6105 
6106   case Intrinsic::experimental_vector_reduce_fadd:
6107   case Intrinsic::experimental_vector_reduce_fmul:
6108   case Intrinsic::experimental_vector_reduce_add:
6109   case Intrinsic::experimental_vector_reduce_mul:
6110   case Intrinsic::experimental_vector_reduce_and:
6111   case Intrinsic::experimental_vector_reduce_or:
6112   case Intrinsic::experimental_vector_reduce_xor:
6113   case Intrinsic::experimental_vector_reduce_smax:
6114   case Intrinsic::experimental_vector_reduce_smin:
6115   case Intrinsic::experimental_vector_reduce_umax:
6116   case Intrinsic::experimental_vector_reduce_umin:
6117   case Intrinsic::experimental_vector_reduce_fmax:
6118   case Intrinsic::experimental_vector_reduce_fmin:
6119     visitVectorReduce(I, Intrinsic);
6120     return nullptr;
6121 
6122   case Intrinsic::icall_branch_funnel: {
6123     SmallVector<SDValue, 16> Ops;
6124     Ops.push_back(DAG.getRoot());
6125     Ops.push_back(getValue(I.getArgOperand(0)));
6126 
6127     int64_t Offset;
6128     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6129         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6130     if (!Base)
6131       report_fatal_error(
6132           "llvm.icall.branch.funnel operand must be a GlobalValue");
6133     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6134 
6135     struct BranchFunnelTarget {
6136       int64_t Offset;
6137       SDValue Target;
6138     };
6139     SmallVector<BranchFunnelTarget, 8> Targets;
6140 
6141     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6142       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6143           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6144       if (ElemBase != Base)
6145         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6146                            "to the same GlobalValue");
6147 
6148       SDValue Val = getValue(I.getArgOperand(Op + 1));
6149       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6150       if (!GA)
6151         report_fatal_error(
6152             "llvm.icall.branch.funnel operand must be a GlobalValue");
6153       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6154                                      GA->getGlobal(), getCurSDLoc(),
6155                                      Val.getValueType(), GA->getOffset())});
6156     }
6157     llvm::sort(Targets.begin(), Targets.end(),
6158                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6159                  return T1.Offset < T2.Offset;
6160                });
6161 
6162     for (auto &T : Targets) {
6163       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6164       Ops.push_back(T.Target);
6165     }
6166 
6167     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6168                                  getCurSDLoc(), MVT::Other, Ops),
6169               0);
6170     DAG.setRoot(N);
6171     setValue(&I, N);
6172     HasTailCall = true;
6173     return nullptr;
6174   }
6175   }
6176 }
6177 
6178 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6179     const ConstrainedFPIntrinsic &FPI) {
6180   SDLoc sdl = getCurSDLoc();
6181   unsigned Opcode;
6182   switch (FPI.getIntrinsicID()) {
6183   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6184   case Intrinsic::experimental_constrained_fadd:
6185     Opcode = ISD::STRICT_FADD;
6186     break;
6187   case Intrinsic::experimental_constrained_fsub:
6188     Opcode = ISD::STRICT_FSUB;
6189     break;
6190   case Intrinsic::experimental_constrained_fmul:
6191     Opcode = ISD::STRICT_FMUL;
6192     break;
6193   case Intrinsic::experimental_constrained_fdiv:
6194     Opcode = ISD::STRICT_FDIV;
6195     break;
6196   case Intrinsic::experimental_constrained_frem:
6197     Opcode = ISD::STRICT_FREM;
6198     break;
6199   case Intrinsic::experimental_constrained_fma:
6200     Opcode = ISD::STRICT_FMA;
6201     break;
6202   case Intrinsic::experimental_constrained_sqrt:
6203     Opcode = ISD::STRICT_FSQRT;
6204     break;
6205   case Intrinsic::experimental_constrained_pow:
6206     Opcode = ISD::STRICT_FPOW;
6207     break;
6208   case Intrinsic::experimental_constrained_powi:
6209     Opcode = ISD::STRICT_FPOWI;
6210     break;
6211   case Intrinsic::experimental_constrained_sin:
6212     Opcode = ISD::STRICT_FSIN;
6213     break;
6214   case Intrinsic::experimental_constrained_cos:
6215     Opcode = ISD::STRICT_FCOS;
6216     break;
6217   case Intrinsic::experimental_constrained_exp:
6218     Opcode = ISD::STRICT_FEXP;
6219     break;
6220   case Intrinsic::experimental_constrained_exp2:
6221     Opcode = ISD::STRICT_FEXP2;
6222     break;
6223   case Intrinsic::experimental_constrained_log:
6224     Opcode = ISD::STRICT_FLOG;
6225     break;
6226   case Intrinsic::experimental_constrained_log10:
6227     Opcode = ISD::STRICT_FLOG10;
6228     break;
6229   case Intrinsic::experimental_constrained_log2:
6230     Opcode = ISD::STRICT_FLOG2;
6231     break;
6232   case Intrinsic::experimental_constrained_rint:
6233     Opcode = ISD::STRICT_FRINT;
6234     break;
6235   case Intrinsic::experimental_constrained_nearbyint:
6236     Opcode = ISD::STRICT_FNEARBYINT;
6237     break;
6238   }
6239   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6240   SDValue Chain = getRoot();
6241   SmallVector<EVT, 4> ValueVTs;
6242   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6243   ValueVTs.push_back(MVT::Other); // Out chain
6244 
6245   SDVTList VTs = DAG.getVTList(ValueVTs);
6246   SDValue Result;
6247   if (FPI.isUnaryOp())
6248     Result = DAG.getNode(Opcode, sdl, VTs,
6249                          { Chain, getValue(FPI.getArgOperand(0)) });
6250   else if (FPI.isTernaryOp())
6251     Result = DAG.getNode(Opcode, sdl, VTs,
6252                          { Chain, getValue(FPI.getArgOperand(0)),
6253                                   getValue(FPI.getArgOperand(1)),
6254                                   getValue(FPI.getArgOperand(2)) });
6255   else
6256     Result = DAG.getNode(Opcode, sdl, VTs,
6257                          { Chain, getValue(FPI.getArgOperand(0)),
6258                            getValue(FPI.getArgOperand(1))  });
6259 
6260   assert(Result.getNode()->getNumValues() == 2);
6261   SDValue OutChain = Result.getValue(1);
6262   DAG.setRoot(OutChain);
6263   SDValue FPResult = Result.getValue(0);
6264   setValue(&FPI, FPResult);
6265 }
6266 
6267 std::pair<SDValue, SDValue>
6268 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6269                                     const BasicBlock *EHPadBB) {
6270   MachineFunction &MF = DAG.getMachineFunction();
6271   MachineModuleInfo &MMI = MF.getMMI();
6272   MCSymbol *BeginLabel = nullptr;
6273 
6274   if (EHPadBB) {
6275     // Insert a label before the invoke call to mark the try range.  This can be
6276     // used to detect deletion of the invoke via the MachineModuleInfo.
6277     BeginLabel = MMI.getContext().createTempSymbol();
6278 
6279     // For SjLj, keep track of which landing pads go with which invokes
6280     // so as to maintain the ordering of pads in the LSDA.
6281     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6282     if (CallSiteIndex) {
6283       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6284       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6285 
6286       // Now that the call site is handled, stop tracking it.
6287       MMI.setCurrentCallSite(0);
6288     }
6289 
6290     // Both PendingLoads and PendingExports must be flushed here;
6291     // this call might not return.
6292     (void)getRoot();
6293     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6294 
6295     CLI.setChain(getRoot());
6296   }
6297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6298   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6299 
6300   assert((CLI.IsTailCall || Result.second.getNode()) &&
6301          "Non-null chain expected with non-tail call!");
6302   assert((Result.second.getNode() || !Result.first.getNode()) &&
6303          "Null value expected with tail call!");
6304 
6305   if (!Result.second.getNode()) {
6306     // As a special case, a null chain means that a tail call has been emitted
6307     // and the DAG root is already updated.
6308     HasTailCall = true;
6309 
6310     // Since there's no actual continuation from this block, nothing can be
6311     // relying on us setting vregs for them.
6312     PendingExports.clear();
6313   } else {
6314     DAG.setRoot(Result.second);
6315   }
6316 
6317   if (EHPadBB) {
6318     // Insert a label at the end of the invoke call to mark the try range.  This
6319     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6320     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6321     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6322 
6323     // Inform MachineModuleInfo of range.
6324     if (MF.hasEHFunclets()) {
6325       assert(CLI.CS);
6326       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6327       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6328                                 BeginLabel, EndLabel);
6329     } else {
6330       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6331     }
6332   }
6333 
6334   return Result;
6335 }
6336 
6337 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6338                                       bool isTailCall,
6339                                       const BasicBlock *EHPadBB) {
6340   auto &DL = DAG.getDataLayout();
6341   FunctionType *FTy = CS.getFunctionType();
6342   Type *RetTy = CS.getType();
6343 
6344   TargetLowering::ArgListTy Args;
6345   Args.reserve(CS.arg_size());
6346 
6347   const Value *SwiftErrorVal = nullptr;
6348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6349 
6350   // We can't tail call inside a function with a swifterror argument. Lowering
6351   // does not support this yet. It would have to move into the swifterror
6352   // register before the call.
6353   auto *Caller = CS.getInstruction()->getParent()->getParent();
6354   if (TLI.supportSwiftError() &&
6355       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6356     isTailCall = false;
6357 
6358   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6359        i != e; ++i) {
6360     TargetLowering::ArgListEntry Entry;
6361     const Value *V = *i;
6362 
6363     // Skip empty types
6364     if (V->getType()->isEmptyTy())
6365       continue;
6366 
6367     SDValue ArgNode = getValue(V);
6368     Entry.Node = ArgNode; Entry.Ty = V->getType();
6369 
6370     Entry.setAttributes(&CS, i - CS.arg_begin());
6371 
6372     // Use swifterror virtual register as input to the call.
6373     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6374       SwiftErrorVal = V;
6375       // We find the virtual register for the actual swifterror argument.
6376       // Instead of using the Value, we use the virtual register instead.
6377       Entry.Node = DAG.getRegister(FuncInfo
6378                                        .getOrCreateSwiftErrorVRegUseAt(
6379                                            CS.getInstruction(), FuncInfo.MBB, V)
6380                                        .first,
6381                                    EVT(TLI.getPointerTy(DL)));
6382     }
6383 
6384     Args.push_back(Entry);
6385 
6386     // If we have an explicit sret argument that is an Instruction, (i.e., it
6387     // might point to function-local memory), we can't meaningfully tail-call.
6388     if (Entry.IsSRet && isa<Instruction>(V))
6389       isTailCall = false;
6390   }
6391 
6392   // Check if target-independent constraints permit a tail call here.
6393   // Target-dependent constraints are checked within TLI->LowerCallTo.
6394   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6395     isTailCall = false;
6396 
6397   // Disable tail calls if there is an swifterror argument. Targets have not
6398   // been updated to support tail calls.
6399   if (TLI.supportSwiftError() && SwiftErrorVal)
6400     isTailCall = false;
6401 
6402   TargetLowering::CallLoweringInfo CLI(DAG);
6403   CLI.setDebugLoc(getCurSDLoc())
6404       .setChain(getRoot())
6405       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6406       .setTailCall(isTailCall)
6407       .setConvergent(CS.isConvergent());
6408   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6409 
6410   if (Result.first.getNode()) {
6411     const Instruction *Inst = CS.getInstruction();
6412     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6413     setValue(Inst, Result.first);
6414   }
6415 
6416   // The last element of CLI.InVals has the SDValue for swifterror return.
6417   // Here we copy it to a virtual register and update SwiftErrorMap for
6418   // book-keeping.
6419   if (SwiftErrorVal && TLI.supportSwiftError()) {
6420     // Get the last element of InVals.
6421     SDValue Src = CLI.InVals.back();
6422     unsigned VReg; bool CreatedVReg;
6423     std::tie(VReg, CreatedVReg) =
6424         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6425     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6426     // We update the virtual register for the actual swifterror argument.
6427     if (CreatedVReg)
6428       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6429     DAG.setRoot(CopyNode);
6430   }
6431 }
6432 
6433 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6434                              SelectionDAGBuilder &Builder) {
6435   // Check to see if this load can be trivially constant folded, e.g. if the
6436   // input is from a string literal.
6437   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6438     // Cast pointer to the type we really want to load.
6439     Type *LoadTy =
6440         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6441     if (LoadVT.isVector())
6442       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6443 
6444     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6445                                          PointerType::getUnqual(LoadTy));
6446 
6447     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6448             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6449       return Builder.getValue(LoadCst);
6450   }
6451 
6452   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6453   // still constant memory, the input chain can be the entry node.
6454   SDValue Root;
6455   bool ConstantMemory = false;
6456 
6457   // Do not serialize (non-volatile) loads of constant memory with anything.
6458   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6459     Root = Builder.DAG.getEntryNode();
6460     ConstantMemory = true;
6461   } else {
6462     // Do not serialize non-volatile loads against each other.
6463     Root = Builder.DAG.getRoot();
6464   }
6465 
6466   SDValue Ptr = Builder.getValue(PtrVal);
6467   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6468                                         Ptr, MachinePointerInfo(PtrVal),
6469                                         /* Alignment = */ 1);
6470 
6471   if (!ConstantMemory)
6472     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6473   return LoadVal;
6474 }
6475 
6476 /// Record the value for an instruction that produces an integer result,
6477 /// converting the type where necessary.
6478 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6479                                                   SDValue Value,
6480                                                   bool IsSigned) {
6481   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6482                                                     I.getType(), true);
6483   if (IsSigned)
6484     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6485   else
6486     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6487   setValue(&I, Value);
6488 }
6489 
6490 /// See if we can lower a memcmp call into an optimized form. If so, return
6491 /// true and lower it. Otherwise return false, and it will be lowered like a
6492 /// normal call.
6493 /// The caller already checked that \p I calls the appropriate LibFunc with a
6494 /// correct prototype.
6495 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6496   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6497   const Value *Size = I.getArgOperand(2);
6498   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6499   if (CSize && CSize->getZExtValue() == 0) {
6500     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6501                                                           I.getType(), true);
6502     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6503     return true;
6504   }
6505 
6506   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6507   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6508       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6509       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6510   if (Res.first.getNode()) {
6511     processIntegerCallValue(I, Res.first, true);
6512     PendingLoads.push_back(Res.second);
6513     return true;
6514   }
6515 
6516   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6517   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6518   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6519     return false;
6520 
6521   // If the target has a fast compare for the given size, it will return a
6522   // preferred load type for that size. Require that the load VT is legal and
6523   // that the target supports unaligned loads of that type. Otherwise, return
6524   // INVALID.
6525   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6526     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6527     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6528     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6529       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6530       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6531       // TODO: Check alignment of src and dest ptrs.
6532       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6533       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6534       if (!TLI.isTypeLegal(LVT) ||
6535           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6536           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6537         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6538     }
6539 
6540     return LVT;
6541   };
6542 
6543   // This turns into unaligned loads. We only do this if the target natively
6544   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6545   // we'll only produce a small number of byte loads.
6546   MVT LoadVT;
6547   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6548   switch (NumBitsToCompare) {
6549   default:
6550     return false;
6551   case 16:
6552     LoadVT = MVT::i16;
6553     break;
6554   case 32:
6555     LoadVT = MVT::i32;
6556     break;
6557   case 64:
6558   case 128:
6559   case 256:
6560     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6561     break;
6562   }
6563 
6564   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6565     return false;
6566 
6567   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6568   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6569 
6570   // Bitcast to a wide integer type if the loads are vectors.
6571   if (LoadVT.isVector()) {
6572     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6573     LoadL = DAG.getBitcast(CmpVT, LoadL);
6574     LoadR = DAG.getBitcast(CmpVT, LoadR);
6575   }
6576 
6577   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6578   processIntegerCallValue(I, Cmp, false);
6579   return true;
6580 }
6581 
6582 /// See if we can lower a memchr call into an optimized form. If so, return
6583 /// true and lower it. Otherwise return false, and it will be lowered like a
6584 /// normal call.
6585 /// The caller already checked that \p I calls the appropriate LibFunc with a
6586 /// correct prototype.
6587 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6588   const Value *Src = I.getArgOperand(0);
6589   const Value *Char = I.getArgOperand(1);
6590   const Value *Length = I.getArgOperand(2);
6591 
6592   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6593   std::pair<SDValue, SDValue> Res =
6594     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6595                                 getValue(Src), getValue(Char), getValue(Length),
6596                                 MachinePointerInfo(Src));
6597   if (Res.first.getNode()) {
6598     setValue(&I, Res.first);
6599     PendingLoads.push_back(Res.second);
6600     return true;
6601   }
6602 
6603   return false;
6604 }
6605 
6606 /// See if we can lower a mempcpy call into an optimized form. If so, return
6607 /// true and lower it. Otherwise return false, and it will be lowered like a
6608 /// normal call.
6609 /// The caller already checked that \p I calls the appropriate LibFunc with a
6610 /// correct prototype.
6611 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6612   SDValue Dst = getValue(I.getArgOperand(0));
6613   SDValue Src = getValue(I.getArgOperand(1));
6614   SDValue Size = getValue(I.getArgOperand(2));
6615 
6616   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6617   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6618   unsigned Align = std::min(DstAlign, SrcAlign);
6619   if (Align == 0) // Alignment of one or both could not be inferred.
6620     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6621 
6622   bool isVol = false;
6623   SDLoc sdl = getCurSDLoc();
6624 
6625   // In the mempcpy context we need to pass in a false value for isTailCall
6626   // because the return pointer needs to be adjusted by the size of
6627   // the copied memory.
6628   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6629                              false, /*isTailCall=*/false,
6630                              MachinePointerInfo(I.getArgOperand(0)),
6631                              MachinePointerInfo(I.getArgOperand(1)));
6632   assert(MC.getNode() != nullptr &&
6633          "** memcpy should not be lowered as TailCall in mempcpy context **");
6634   DAG.setRoot(MC);
6635 
6636   // Check if Size needs to be truncated or extended.
6637   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6638 
6639   // Adjust return pointer to point just past the last dst byte.
6640   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6641                                     Dst, Size);
6642   setValue(&I, DstPlusSize);
6643   return true;
6644 }
6645 
6646 /// See if we can lower a strcpy call into an optimized form.  If so, return
6647 /// true and lower it, otherwise return false and it will be lowered like a
6648 /// normal call.
6649 /// The caller already checked that \p I calls the appropriate LibFunc with a
6650 /// correct prototype.
6651 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6652   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6653 
6654   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6655   std::pair<SDValue, SDValue> Res =
6656     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6657                                 getValue(Arg0), getValue(Arg1),
6658                                 MachinePointerInfo(Arg0),
6659                                 MachinePointerInfo(Arg1), isStpcpy);
6660   if (Res.first.getNode()) {
6661     setValue(&I, Res.first);
6662     DAG.setRoot(Res.second);
6663     return true;
6664   }
6665 
6666   return false;
6667 }
6668 
6669 /// See if we can lower a strcmp call into an optimized form.  If so, return
6670 /// true and lower it, otherwise return false and it will be lowered like a
6671 /// normal call.
6672 /// The caller already checked that \p I calls the appropriate LibFunc with a
6673 /// correct prototype.
6674 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6675   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6676 
6677   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6678   std::pair<SDValue, SDValue> Res =
6679     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6680                                 getValue(Arg0), getValue(Arg1),
6681                                 MachinePointerInfo(Arg0),
6682                                 MachinePointerInfo(Arg1));
6683   if (Res.first.getNode()) {
6684     processIntegerCallValue(I, Res.first, true);
6685     PendingLoads.push_back(Res.second);
6686     return true;
6687   }
6688 
6689   return false;
6690 }
6691 
6692 /// See if we can lower a strlen call into an optimized form.  If so, return
6693 /// true and lower it, otherwise return false and it will be lowered like a
6694 /// normal call.
6695 /// The caller already checked that \p I calls the appropriate LibFunc with a
6696 /// correct prototype.
6697 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6698   const Value *Arg0 = I.getArgOperand(0);
6699 
6700   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6701   std::pair<SDValue, SDValue> Res =
6702     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6703                                 getValue(Arg0), MachinePointerInfo(Arg0));
6704   if (Res.first.getNode()) {
6705     processIntegerCallValue(I, Res.first, false);
6706     PendingLoads.push_back(Res.second);
6707     return true;
6708   }
6709 
6710   return false;
6711 }
6712 
6713 /// See if we can lower a strnlen call into an optimized form.  If so, return
6714 /// true and lower it, otherwise return false and it will be lowered like a
6715 /// normal call.
6716 /// The caller already checked that \p I calls the appropriate LibFunc with a
6717 /// correct prototype.
6718 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6719   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6720 
6721   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6722   std::pair<SDValue, SDValue> Res =
6723     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6724                                  getValue(Arg0), getValue(Arg1),
6725                                  MachinePointerInfo(Arg0));
6726   if (Res.first.getNode()) {
6727     processIntegerCallValue(I, Res.first, false);
6728     PendingLoads.push_back(Res.second);
6729     return true;
6730   }
6731 
6732   return false;
6733 }
6734 
6735 /// See if we can lower a unary floating-point operation into an SDNode with
6736 /// the specified Opcode.  If so, return true and lower it, otherwise return
6737 /// false and it will be lowered like a normal call.
6738 /// The caller already checked that \p I calls the appropriate LibFunc with a
6739 /// correct prototype.
6740 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6741                                               unsigned Opcode) {
6742   // We already checked this call's prototype; verify it doesn't modify errno.
6743   if (!I.onlyReadsMemory())
6744     return false;
6745 
6746   SDValue Tmp = getValue(I.getArgOperand(0));
6747   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6748   return true;
6749 }
6750 
6751 /// See if we can lower a binary floating-point operation into an SDNode with
6752 /// the specified Opcode. If so, return true and lower it. Otherwise return
6753 /// false, and it will be lowered like a normal call.
6754 /// The caller already checked that \p I calls the appropriate LibFunc with a
6755 /// correct prototype.
6756 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6757                                                unsigned Opcode) {
6758   // We already checked this call's prototype; verify it doesn't modify errno.
6759   if (!I.onlyReadsMemory())
6760     return false;
6761 
6762   SDValue Tmp0 = getValue(I.getArgOperand(0));
6763   SDValue Tmp1 = getValue(I.getArgOperand(1));
6764   EVT VT = Tmp0.getValueType();
6765   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6766   return true;
6767 }
6768 
6769 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6770   // Handle inline assembly differently.
6771   if (isa<InlineAsm>(I.getCalledValue())) {
6772     visitInlineAsm(&I);
6773     return;
6774   }
6775 
6776   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6777   computeUsesVAFloatArgument(I, MMI);
6778 
6779   const char *RenameFn = nullptr;
6780   if (Function *F = I.getCalledFunction()) {
6781     if (F->isDeclaration()) {
6782       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6783         if (unsigned IID = II->getIntrinsicID(F)) {
6784           RenameFn = visitIntrinsicCall(I, IID);
6785           if (!RenameFn)
6786             return;
6787         }
6788       }
6789       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6790         RenameFn = visitIntrinsicCall(I, IID);
6791         if (!RenameFn)
6792           return;
6793       }
6794     }
6795 
6796     // Check for well-known libc/libm calls.  If the function is internal, it
6797     // can't be a library call.  Don't do the check if marked as nobuiltin for
6798     // some reason or the call site requires strict floating point semantics.
6799     LibFunc Func;
6800     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6801         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6802         LibInfo->hasOptimizedCodeGen(Func)) {
6803       switch (Func) {
6804       default: break;
6805       case LibFunc_copysign:
6806       case LibFunc_copysignf:
6807       case LibFunc_copysignl:
6808         // We already checked this call's prototype; verify it doesn't modify
6809         // errno.
6810         if (I.onlyReadsMemory()) {
6811           SDValue LHS = getValue(I.getArgOperand(0));
6812           SDValue RHS = getValue(I.getArgOperand(1));
6813           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6814                                    LHS.getValueType(), LHS, RHS));
6815           return;
6816         }
6817         break;
6818       case LibFunc_fabs:
6819       case LibFunc_fabsf:
6820       case LibFunc_fabsl:
6821         if (visitUnaryFloatCall(I, ISD::FABS))
6822           return;
6823         break;
6824       case LibFunc_fmin:
6825       case LibFunc_fminf:
6826       case LibFunc_fminl:
6827         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6828           return;
6829         break;
6830       case LibFunc_fmax:
6831       case LibFunc_fmaxf:
6832       case LibFunc_fmaxl:
6833         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6834           return;
6835         break;
6836       case LibFunc_sin:
6837       case LibFunc_sinf:
6838       case LibFunc_sinl:
6839         if (visitUnaryFloatCall(I, ISD::FSIN))
6840           return;
6841         break;
6842       case LibFunc_cos:
6843       case LibFunc_cosf:
6844       case LibFunc_cosl:
6845         if (visitUnaryFloatCall(I, ISD::FCOS))
6846           return;
6847         break;
6848       case LibFunc_sqrt:
6849       case LibFunc_sqrtf:
6850       case LibFunc_sqrtl:
6851       case LibFunc_sqrt_finite:
6852       case LibFunc_sqrtf_finite:
6853       case LibFunc_sqrtl_finite:
6854         if (visitUnaryFloatCall(I, ISD::FSQRT))
6855           return;
6856         break;
6857       case LibFunc_floor:
6858       case LibFunc_floorf:
6859       case LibFunc_floorl:
6860         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6861           return;
6862         break;
6863       case LibFunc_nearbyint:
6864       case LibFunc_nearbyintf:
6865       case LibFunc_nearbyintl:
6866         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6867           return;
6868         break;
6869       case LibFunc_ceil:
6870       case LibFunc_ceilf:
6871       case LibFunc_ceill:
6872         if (visitUnaryFloatCall(I, ISD::FCEIL))
6873           return;
6874         break;
6875       case LibFunc_rint:
6876       case LibFunc_rintf:
6877       case LibFunc_rintl:
6878         if (visitUnaryFloatCall(I, ISD::FRINT))
6879           return;
6880         break;
6881       case LibFunc_round:
6882       case LibFunc_roundf:
6883       case LibFunc_roundl:
6884         if (visitUnaryFloatCall(I, ISD::FROUND))
6885           return;
6886         break;
6887       case LibFunc_trunc:
6888       case LibFunc_truncf:
6889       case LibFunc_truncl:
6890         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6891           return;
6892         break;
6893       case LibFunc_log2:
6894       case LibFunc_log2f:
6895       case LibFunc_log2l:
6896         if (visitUnaryFloatCall(I, ISD::FLOG2))
6897           return;
6898         break;
6899       case LibFunc_exp2:
6900       case LibFunc_exp2f:
6901       case LibFunc_exp2l:
6902         if (visitUnaryFloatCall(I, ISD::FEXP2))
6903           return;
6904         break;
6905       case LibFunc_memcmp:
6906         if (visitMemCmpCall(I))
6907           return;
6908         break;
6909       case LibFunc_mempcpy:
6910         if (visitMemPCpyCall(I))
6911           return;
6912         break;
6913       case LibFunc_memchr:
6914         if (visitMemChrCall(I))
6915           return;
6916         break;
6917       case LibFunc_strcpy:
6918         if (visitStrCpyCall(I, false))
6919           return;
6920         break;
6921       case LibFunc_stpcpy:
6922         if (visitStrCpyCall(I, true))
6923           return;
6924         break;
6925       case LibFunc_strcmp:
6926         if (visitStrCmpCall(I))
6927           return;
6928         break;
6929       case LibFunc_strlen:
6930         if (visitStrLenCall(I))
6931           return;
6932         break;
6933       case LibFunc_strnlen:
6934         if (visitStrNLenCall(I))
6935           return;
6936         break;
6937       }
6938     }
6939   }
6940 
6941   SDValue Callee;
6942   if (!RenameFn)
6943     Callee = getValue(I.getCalledValue());
6944   else
6945     Callee = DAG.getExternalSymbol(
6946         RenameFn,
6947         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6948 
6949   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6950   // have to do anything here to lower funclet bundles.
6951   assert(!I.hasOperandBundlesOtherThan(
6952              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6953          "Cannot lower calls with arbitrary operand bundles!");
6954 
6955   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6956     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6957   else
6958     // Check if we can potentially perform a tail call. More detailed checking
6959     // is be done within LowerCallTo, after more information about the call is
6960     // known.
6961     LowerCallTo(&I, Callee, I.isTailCall());
6962 }
6963 
6964 namespace {
6965 
6966 /// AsmOperandInfo - This contains information for each constraint that we are
6967 /// lowering.
6968 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6969 public:
6970   /// CallOperand - If this is the result output operand or a clobber
6971   /// this is null, otherwise it is the incoming operand to the CallInst.
6972   /// This gets modified as the asm is processed.
6973   SDValue CallOperand;
6974 
6975   /// AssignedRegs - If this is a register or register class operand, this
6976   /// contains the set of register corresponding to the operand.
6977   RegsForValue AssignedRegs;
6978 
6979   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6980     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
6981   }
6982 
6983   /// Whether or not this operand accesses memory
6984   bool hasMemory(const TargetLowering &TLI) const {
6985     // Indirect operand accesses access memory.
6986     if (isIndirect)
6987       return true;
6988 
6989     for (const auto &Code : Codes)
6990       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6991         return true;
6992 
6993     return false;
6994   }
6995 
6996   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6997   /// corresponds to.  If there is no Value* for this operand, it returns
6998   /// MVT::Other.
6999   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7000                            const DataLayout &DL) const {
7001     if (!CallOperandVal) return MVT::Other;
7002 
7003     if (isa<BasicBlock>(CallOperandVal))
7004       return TLI.getPointerTy(DL);
7005 
7006     llvm::Type *OpTy = CallOperandVal->getType();
7007 
7008     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7009     // If this is an indirect operand, the operand is a pointer to the
7010     // accessed type.
7011     if (isIndirect) {
7012       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7013       if (!PtrTy)
7014         report_fatal_error("Indirect operand for inline asm not a pointer!");
7015       OpTy = PtrTy->getElementType();
7016     }
7017 
7018     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7019     if (StructType *STy = dyn_cast<StructType>(OpTy))
7020       if (STy->getNumElements() == 1)
7021         OpTy = STy->getElementType(0);
7022 
7023     // If OpTy is not a single value, it may be a struct/union that we
7024     // can tile with integers.
7025     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7026       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7027       switch (BitSize) {
7028       default: break;
7029       case 1:
7030       case 8:
7031       case 16:
7032       case 32:
7033       case 64:
7034       case 128:
7035         OpTy = IntegerType::get(Context, BitSize);
7036         break;
7037       }
7038     }
7039 
7040     return TLI.getValueType(DL, OpTy, true);
7041   }
7042 };
7043 
7044 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7045 
7046 } // end anonymous namespace
7047 
7048 /// Make sure that the output operand \p OpInfo and its corresponding input
7049 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7050 /// out).
7051 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7052                                SDISelAsmOperandInfo &MatchingOpInfo,
7053                                SelectionDAG &DAG) {
7054   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7055     return;
7056 
7057   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7058   const auto &TLI = DAG.getTargetLoweringInfo();
7059 
7060   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7061       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7062                                        OpInfo.ConstraintVT);
7063   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7064       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7065                                        MatchingOpInfo.ConstraintVT);
7066   if ((OpInfo.ConstraintVT.isInteger() !=
7067        MatchingOpInfo.ConstraintVT.isInteger()) ||
7068       (MatchRC.second != InputRC.second)) {
7069     // FIXME: error out in a more elegant fashion
7070     report_fatal_error("Unsupported asm: input constraint"
7071                        " with a matching output constraint of"
7072                        " incompatible type!");
7073   }
7074   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7075 }
7076 
7077 /// Get a direct memory input to behave well as an indirect operand.
7078 /// This may introduce stores, hence the need for a \p Chain.
7079 /// \return The (possibly updated) chain.
7080 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7081                                         SDISelAsmOperandInfo &OpInfo,
7082                                         SelectionDAG &DAG) {
7083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7084 
7085   // If we don't have an indirect input, put it in the constpool if we can,
7086   // otherwise spill it to a stack slot.
7087   // TODO: This isn't quite right. We need to handle these according to
7088   // the addressing mode that the constraint wants. Also, this may take
7089   // an additional register for the computation and we don't want that
7090   // either.
7091 
7092   // If the operand is a float, integer, or vector constant, spill to a
7093   // constant pool entry to get its address.
7094   const Value *OpVal = OpInfo.CallOperandVal;
7095   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7096       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7097     OpInfo.CallOperand = DAG.getConstantPool(
7098         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7099     return Chain;
7100   }
7101 
7102   // Otherwise, create a stack slot and emit a store to it before the asm.
7103   Type *Ty = OpVal->getType();
7104   auto &DL = DAG.getDataLayout();
7105   uint64_t TySize = DL.getTypeAllocSize(Ty);
7106   unsigned Align = DL.getPrefTypeAlignment(Ty);
7107   MachineFunction &MF = DAG.getMachineFunction();
7108   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7109   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7110   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7111                        MachinePointerInfo::getFixedStack(MF, SSFI));
7112   OpInfo.CallOperand = StackSlot;
7113 
7114   return Chain;
7115 }
7116 
7117 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7118 /// specified operand.  We prefer to assign virtual registers, to allow the
7119 /// register allocator to handle the assignment process.  However, if the asm
7120 /// uses features that we can't model on machineinstrs, we have SDISel do the
7121 /// allocation.  This produces generally horrible, but correct, code.
7122 ///
7123 ///   OpInfo describes the operand.
7124 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7125                                  const SDLoc &DL,
7126                                  SDISelAsmOperandInfo &OpInfo) {
7127   LLVMContext &Context = *DAG.getContext();
7128 
7129   MachineFunction &MF = DAG.getMachineFunction();
7130   SmallVector<unsigned, 4> Regs;
7131   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7132 
7133   // If this is a constraint for a single physreg, or a constraint for a
7134   // register class, find it.
7135   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7136       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
7137                                        OpInfo.ConstraintVT);
7138 
7139   unsigned NumRegs = 1;
7140   if (OpInfo.ConstraintVT != MVT::Other) {
7141     // If this is a FP input in an integer register (or visa versa) insert a bit
7142     // cast of the input value.  More generally, handle any case where the input
7143     // value disagrees with the register class we plan to stick this in.
7144     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
7145         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7146       // Try to convert to the first EVT that the reg class contains.  If the
7147       // types are identical size, use a bitcast to convert (e.g. two differing
7148       // vector types).
7149       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7150       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
7151         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7152                                          RegVT, OpInfo.CallOperand);
7153         OpInfo.ConstraintVT = RegVT;
7154       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7155         // If the input is a FP value and we want it in FP registers, do a
7156         // bitcast to the corresponding integer type.  This turns an f64 value
7157         // into i64, which can be passed with two i32 values on a 32-bit
7158         // machine.
7159         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7160         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7161                                          RegVT, OpInfo.CallOperand);
7162         OpInfo.ConstraintVT = RegVT;
7163       }
7164     }
7165 
7166     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7167   }
7168 
7169   MVT RegVT;
7170   EVT ValueVT = OpInfo.ConstraintVT;
7171 
7172   // If this is a constraint for a specific physical register, like {r17},
7173   // assign it now.
7174   if (unsigned AssignedReg = PhysReg.first) {
7175     const TargetRegisterClass *RC = PhysReg.second;
7176     if (OpInfo.ConstraintVT == MVT::Other)
7177       ValueVT = *TRI.legalclasstypes_begin(*RC);
7178 
7179     // Get the actual register value type.  This is important, because the user
7180     // may have asked for (e.g.) the AX register in i32 type.  We need to
7181     // remember that AX is actually i16 to get the right extension.
7182     RegVT = *TRI.legalclasstypes_begin(*RC);
7183 
7184     // This is a explicit reference to a physical register.
7185     Regs.push_back(AssignedReg);
7186 
7187     // If this is an expanded reference, add the rest of the regs to Regs.
7188     if (NumRegs != 1) {
7189       TargetRegisterClass::iterator I = RC->begin();
7190       for (; *I != AssignedReg; ++I)
7191         assert(I != RC->end() && "Didn't find reg!");
7192 
7193       // Already added the first reg.
7194       --NumRegs; ++I;
7195       for (; NumRegs; --NumRegs, ++I) {
7196         assert(I != RC->end() && "Ran out of registers to allocate!");
7197         Regs.push_back(*I);
7198       }
7199     }
7200 
7201     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7202     return;
7203   }
7204 
7205   // Otherwise, if this was a reference to an LLVM register class, create vregs
7206   // for this reference.
7207   if (const TargetRegisterClass *RC = PhysReg.second) {
7208     RegVT = *TRI.legalclasstypes_begin(*RC);
7209     if (OpInfo.ConstraintVT == MVT::Other)
7210       ValueVT = RegVT;
7211 
7212     // Create the appropriate number of virtual registers.
7213     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7214     for (; NumRegs; --NumRegs)
7215       Regs.push_back(RegInfo.createVirtualRegister(RC));
7216 
7217     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7218     return;
7219   }
7220 
7221   // Otherwise, we couldn't allocate enough registers for this.
7222 }
7223 
7224 static unsigned
7225 findMatchingInlineAsmOperand(unsigned OperandNo,
7226                              const std::vector<SDValue> &AsmNodeOperands) {
7227   // Scan until we find the definition we already emitted of this operand.
7228   unsigned CurOp = InlineAsm::Op_FirstOperand;
7229   for (; OperandNo; --OperandNo) {
7230     // Advance to the next operand.
7231     unsigned OpFlag =
7232         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7233     assert((InlineAsm::isRegDefKind(OpFlag) ||
7234             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7235             InlineAsm::isMemKind(OpFlag)) &&
7236            "Skipped past definitions?");
7237     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7238   }
7239   return CurOp;
7240 }
7241 
7242 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7243 /// \return true if it has succeeded, false otherwise
7244 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7245                               MVT RegVT, SelectionDAG &DAG) {
7246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7247   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7248   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7249     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7250       Regs.push_back(RegInfo.createVirtualRegister(RC));
7251     else
7252       return false;
7253   }
7254   return true;
7255 }
7256 
7257 namespace {
7258 
7259 class ExtraFlags {
7260   unsigned Flags = 0;
7261 
7262 public:
7263   explicit ExtraFlags(ImmutableCallSite CS) {
7264     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7265     if (IA->hasSideEffects())
7266       Flags |= InlineAsm::Extra_HasSideEffects;
7267     if (IA->isAlignStack())
7268       Flags |= InlineAsm::Extra_IsAlignStack;
7269     if (CS.isConvergent())
7270       Flags |= InlineAsm::Extra_IsConvergent;
7271     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7272   }
7273 
7274   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7275     // Ideally, we would only check against memory constraints.  However, the
7276     // meaning of an Other constraint can be target-specific and we can't easily
7277     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7278     // for Other constraints as well.
7279     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7280         OpInfo.ConstraintType == TargetLowering::C_Other) {
7281       if (OpInfo.Type == InlineAsm::isInput)
7282         Flags |= InlineAsm::Extra_MayLoad;
7283       else if (OpInfo.Type == InlineAsm::isOutput)
7284         Flags |= InlineAsm::Extra_MayStore;
7285       else if (OpInfo.Type == InlineAsm::isClobber)
7286         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7287     }
7288   }
7289 
7290   unsigned get() const { return Flags; }
7291 };
7292 
7293 } // end anonymous namespace
7294 
7295 /// visitInlineAsm - Handle a call to an InlineAsm object.
7296 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7297   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7298 
7299   /// ConstraintOperands - Information about all of the constraints.
7300   SDISelAsmOperandInfoVector ConstraintOperands;
7301 
7302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7303   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7304       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7305 
7306   bool hasMemory = false;
7307 
7308   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7309   ExtraFlags ExtraInfo(CS);
7310 
7311   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7312   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7313   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7314     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7315     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7316 
7317     MVT OpVT = MVT::Other;
7318 
7319     // Compute the value type for each operand.
7320     if (OpInfo.Type == InlineAsm::isInput ||
7321         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7322       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7323 
7324       // Process the call argument. BasicBlocks are labels, currently appearing
7325       // only in asm's.
7326       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7327         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7328       } else {
7329         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7330       }
7331 
7332       OpVT =
7333           OpInfo
7334               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7335               .getSimpleVT();
7336     }
7337 
7338     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7339       // The return value of the call is this value.  As such, there is no
7340       // corresponding argument.
7341       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7342       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7343         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7344                                       STy->getElementType(ResNo));
7345       } else {
7346         assert(ResNo == 0 && "Asm only has one result!");
7347         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7348       }
7349       ++ResNo;
7350     }
7351 
7352     OpInfo.ConstraintVT = OpVT;
7353 
7354     if (!hasMemory)
7355       hasMemory = OpInfo.hasMemory(TLI);
7356 
7357     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7358     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7359     auto TargetConstraint = TargetConstraints[i];
7360 
7361     // Compute the constraint code and ConstraintType to use.
7362     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7363 
7364     ExtraInfo.update(TargetConstraint);
7365   }
7366 
7367   SDValue Chain, Flag;
7368 
7369   // We won't need to flush pending loads if this asm doesn't touch
7370   // memory and is nonvolatile.
7371   if (hasMemory || IA->hasSideEffects())
7372     Chain = getRoot();
7373   else
7374     Chain = DAG.getRoot();
7375 
7376   // Second pass over the constraints: compute which constraint option to use
7377   // and assign registers to constraints that want a specific physreg.
7378   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7379     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7380 
7381     // If this is an output operand with a matching input operand, look up the
7382     // matching input. If their types mismatch, e.g. one is an integer, the
7383     // other is floating point, or their sizes are different, flag it as an
7384     // error.
7385     if (OpInfo.hasMatchingInput()) {
7386       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7387       patchMatchingInput(OpInfo, Input, DAG);
7388     }
7389 
7390     // Compute the constraint code and ConstraintType to use.
7391     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7392 
7393     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7394         OpInfo.Type == InlineAsm::isClobber)
7395       continue;
7396 
7397     // If this is a memory input, and if the operand is not indirect, do what we
7398     // need to provide an address for the memory input.
7399     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7400         !OpInfo.isIndirect) {
7401       assert((OpInfo.isMultipleAlternative ||
7402               (OpInfo.Type == InlineAsm::isInput)) &&
7403              "Can only indirectify direct input operands!");
7404 
7405       // Memory operands really want the address of the value.
7406       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7407 
7408       // There is no longer a Value* corresponding to this operand.
7409       OpInfo.CallOperandVal = nullptr;
7410 
7411       // It is now an indirect operand.
7412       OpInfo.isIndirect = true;
7413     }
7414 
7415     // If this constraint is for a specific register, allocate it before
7416     // anything else.
7417     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7418       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7419   }
7420 
7421   // Third pass - Loop over all of the operands, assigning virtual or physregs
7422   // to register class operands.
7423   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7424     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7425 
7426     // C_Register operands have already been allocated, Other/Memory don't need
7427     // to be.
7428     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7429       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7430   }
7431 
7432   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7433   std::vector<SDValue> AsmNodeOperands;
7434   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7435   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7436       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7437 
7438   // If we have a !srcloc metadata node associated with it, we want to attach
7439   // this to the ultimately generated inline asm machineinstr.  To do this, we
7440   // pass in the third operand as this (potentially null) inline asm MDNode.
7441   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7442   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7443 
7444   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7445   // bits as operand 3.
7446   AsmNodeOperands.push_back(DAG.getTargetConstant(
7447       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7448 
7449   // Loop over all of the inputs, copying the operand values into the
7450   // appropriate registers and processing the output regs.
7451   RegsForValue RetValRegs;
7452 
7453   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7454   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7455 
7456   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7457     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7458 
7459     switch (OpInfo.Type) {
7460     case InlineAsm::isOutput:
7461       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7462           OpInfo.ConstraintType != TargetLowering::C_Register) {
7463         // Memory output, or 'other' output (e.g. 'X' constraint).
7464         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7465 
7466         unsigned ConstraintID =
7467             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7468         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7469                "Failed to convert memory constraint code to constraint id.");
7470 
7471         // Add information to the INLINEASM node to know about this output.
7472         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7473         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7474         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7475                                                         MVT::i32));
7476         AsmNodeOperands.push_back(OpInfo.CallOperand);
7477         break;
7478       }
7479 
7480       // Otherwise, this is a register or register class output.
7481 
7482       // Copy the output from the appropriate register.  Find a register that
7483       // we can use.
7484       if (OpInfo.AssignedRegs.Regs.empty()) {
7485         emitInlineAsmError(
7486             CS, "couldn't allocate output register for constraint '" +
7487                     Twine(OpInfo.ConstraintCode) + "'");
7488         return;
7489       }
7490 
7491       // If this is an indirect operand, store through the pointer after the
7492       // asm.
7493       if (OpInfo.isIndirect) {
7494         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7495                                                       OpInfo.CallOperandVal));
7496       } else {
7497         // This is the result value of the call.
7498         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7499         // Concatenate this output onto the outputs list.
7500         RetValRegs.append(OpInfo.AssignedRegs);
7501       }
7502 
7503       // Add information to the INLINEASM node to know that this register is
7504       // set.
7505       OpInfo.AssignedRegs
7506           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7507                                     ? InlineAsm::Kind_RegDefEarlyClobber
7508                                     : InlineAsm::Kind_RegDef,
7509                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7510       break;
7511 
7512     case InlineAsm::isInput: {
7513       SDValue InOperandVal = OpInfo.CallOperand;
7514 
7515       if (OpInfo.isMatchingInputConstraint()) {
7516         // If this is required to match an output register we have already set,
7517         // just use its register.
7518         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7519                                                   AsmNodeOperands);
7520         unsigned OpFlag =
7521           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7522         if (InlineAsm::isRegDefKind(OpFlag) ||
7523             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7524           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7525           if (OpInfo.isIndirect) {
7526             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7527             emitInlineAsmError(CS, "inline asm not supported yet:"
7528                                    " don't know how to handle tied "
7529                                    "indirect register inputs");
7530             return;
7531           }
7532 
7533           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7534           SmallVector<unsigned, 4> Regs;
7535 
7536           if (!createVirtualRegs(Regs,
7537                                  InlineAsm::getNumOperandRegisters(OpFlag),
7538                                  RegVT, DAG)) {
7539             emitInlineAsmError(CS, "inline asm error: This value type register "
7540                                    "class is not natively supported!");
7541             return;
7542           }
7543 
7544           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7545 
7546           SDLoc dl = getCurSDLoc();
7547           // Use the produced MatchedRegs object to
7548           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7549                                     CS.getInstruction());
7550           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7551                                            true, OpInfo.getMatchedOperand(), dl,
7552                                            DAG, AsmNodeOperands);
7553           break;
7554         }
7555 
7556         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7557         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7558                "Unexpected number of operands");
7559         // Add information to the INLINEASM node to know about this input.
7560         // See InlineAsm.h isUseOperandTiedToDef.
7561         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7562         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7563                                                     OpInfo.getMatchedOperand());
7564         AsmNodeOperands.push_back(DAG.getTargetConstant(
7565             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7566         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7567         break;
7568       }
7569 
7570       // Treat indirect 'X' constraint as memory.
7571       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7572           OpInfo.isIndirect)
7573         OpInfo.ConstraintType = TargetLowering::C_Memory;
7574 
7575       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7576         std::vector<SDValue> Ops;
7577         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7578                                           Ops, DAG);
7579         if (Ops.empty()) {
7580           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7581                                      Twine(OpInfo.ConstraintCode) + "'");
7582           return;
7583         }
7584 
7585         // Add information to the INLINEASM node to know about this input.
7586         unsigned ResOpType =
7587           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7588         AsmNodeOperands.push_back(DAG.getTargetConstant(
7589             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7590         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7591         break;
7592       }
7593 
7594       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7595         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7596         assert(InOperandVal.getValueType() ==
7597                    TLI.getPointerTy(DAG.getDataLayout()) &&
7598                "Memory operands expect pointer values");
7599 
7600         unsigned ConstraintID =
7601             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7602         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7603                "Failed to convert memory constraint code to constraint id.");
7604 
7605         // Add information to the INLINEASM node to know about this input.
7606         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7607         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7608         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7609                                                         getCurSDLoc(),
7610                                                         MVT::i32));
7611         AsmNodeOperands.push_back(InOperandVal);
7612         break;
7613       }
7614 
7615       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7616               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7617              "Unknown constraint type!");
7618 
7619       // TODO: Support this.
7620       if (OpInfo.isIndirect) {
7621         emitInlineAsmError(
7622             CS, "Don't know how to handle indirect register inputs yet "
7623                 "for constraint '" +
7624                     Twine(OpInfo.ConstraintCode) + "'");
7625         return;
7626       }
7627 
7628       // Copy the input into the appropriate registers.
7629       if (OpInfo.AssignedRegs.Regs.empty()) {
7630         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7631                                    Twine(OpInfo.ConstraintCode) + "'");
7632         return;
7633       }
7634 
7635       SDLoc dl = getCurSDLoc();
7636 
7637       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7638                                         Chain, &Flag, CS.getInstruction());
7639 
7640       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7641                                                dl, DAG, AsmNodeOperands);
7642       break;
7643     }
7644     case InlineAsm::isClobber:
7645       // Add the clobbered value to the operand list, so that the register
7646       // allocator is aware that the physreg got clobbered.
7647       if (!OpInfo.AssignedRegs.Regs.empty())
7648         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7649                                                  false, 0, getCurSDLoc(), DAG,
7650                                                  AsmNodeOperands);
7651       break;
7652     }
7653   }
7654 
7655   // Finish up input operands.  Set the input chain and add the flag last.
7656   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7657   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7658 
7659   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7660                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7661   Flag = Chain.getValue(1);
7662 
7663   // If this asm returns a register value, copy the result from that register
7664   // and set it as the value of the call.
7665   if (!RetValRegs.Regs.empty()) {
7666     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7667                                              Chain, &Flag, CS.getInstruction());
7668 
7669     // FIXME: Why don't we do this for inline asms with MRVs?
7670     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7671       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7672 
7673       // If any of the results of the inline asm is a vector, it may have the
7674       // wrong width/num elts.  This can happen for register classes that can
7675       // contain multiple different value types.  The preg or vreg allocated may
7676       // not have the same VT as was expected.  Convert it to the right type
7677       // with bit_convert.
7678       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7679         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7680                           ResultType, Val);
7681 
7682       } else if (ResultType != Val.getValueType() &&
7683                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7684         // If a result value was tied to an input value, the computed result may
7685         // have a wider width than the expected result.  Extract the relevant
7686         // portion.
7687         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7688       }
7689 
7690       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7691     }
7692 
7693     setValue(CS.getInstruction(), Val);
7694     // Don't need to use this as a chain in this case.
7695     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7696       return;
7697   }
7698 
7699   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7700 
7701   // Process indirect outputs, first output all of the flagged copies out of
7702   // physregs.
7703   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7704     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7705     const Value *Ptr = IndirectStoresToEmit[i].second;
7706     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7707                                              Chain, &Flag, IA);
7708     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7709   }
7710 
7711   // Emit the non-flagged stores from the physregs.
7712   SmallVector<SDValue, 8> OutChains;
7713   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7714     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7715                                getValue(StoresToEmit[i].second),
7716                                MachinePointerInfo(StoresToEmit[i].second));
7717     OutChains.push_back(Val);
7718   }
7719 
7720   if (!OutChains.empty())
7721     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7722 
7723   DAG.setRoot(Chain);
7724 }
7725 
7726 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7727                                              const Twine &Message) {
7728   LLVMContext &Ctx = *DAG.getContext();
7729   Ctx.emitError(CS.getInstruction(), Message);
7730 
7731   // Make sure we leave the DAG in a valid state
7732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7733   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7734   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7735 }
7736 
7737 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7738   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7739                           MVT::Other, getRoot(),
7740                           getValue(I.getArgOperand(0)),
7741                           DAG.getSrcValue(I.getArgOperand(0))));
7742 }
7743 
7744 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7746   const DataLayout &DL = DAG.getDataLayout();
7747   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7748                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7749                            DAG.getSrcValue(I.getOperand(0)),
7750                            DL.getABITypeAlignment(I.getType()));
7751   setValue(&I, V);
7752   DAG.setRoot(V.getValue(1));
7753 }
7754 
7755 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7756   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7757                           MVT::Other, getRoot(),
7758                           getValue(I.getArgOperand(0)),
7759                           DAG.getSrcValue(I.getArgOperand(0))));
7760 }
7761 
7762 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7763   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7764                           MVT::Other, getRoot(),
7765                           getValue(I.getArgOperand(0)),
7766                           getValue(I.getArgOperand(1)),
7767                           DAG.getSrcValue(I.getArgOperand(0)),
7768                           DAG.getSrcValue(I.getArgOperand(1))));
7769 }
7770 
7771 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7772                                                     const Instruction &I,
7773                                                     SDValue Op) {
7774   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7775   if (!Range)
7776     return Op;
7777 
7778   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7779   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7780     return Op;
7781 
7782   APInt Lo = CR.getUnsignedMin();
7783   if (!Lo.isMinValue())
7784     return Op;
7785 
7786   APInt Hi = CR.getUnsignedMax();
7787   unsigned Bits = Hi.getActiveBits();
7788 
7789   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7790 
7791   SDLoc SL = getCurSDLoc();
7792 
7793   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7794                              DAG.getValueType(SmallVT));
7795   unsigned NumVals = Op.getNode()->getNumValues();
7796   if (NumVals == 1)
7797     return ZExt;
7798 
7799   SmallVector<SDValue, 4> Ops;
7800 
7801   Ops.push_back(ZExt);
7802   for (unsigned I = 1; I != NumVals; ++I)
7803     Ops.push_back(Op.getValue(I));
7804 
7805   return DAG.getMergeValues(Ops, SL);
7806 }
7807 
7808 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
7809 /// the call being lowered.
7810 ///
7811 /// This is a helper for lowering intrinsics that follow a target calling
7812 /// convention or require stack pointer adjustment. Only a subset of the
7813 /// intrinsic's operands need to participate in the calling convention.
7814 void SelectionDAGBuilder::populateCallLoweringInfo(
7815     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7816     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7817     bool IsPatchPoint) {
7818   TargetLowering::ArgListTy Args;
7819   Args.reserve(NumArgs);
7820 
7821   // Populate the argument list.
7822   // Attributes for args start at offset 1, after the return attribute.
7823   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7824        ArgI != ArgE; ++ArgI) {
7825     const Value *V = CS->getOperand(ArgI);
7826 
7827     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7828 
7829     TargetLowering::ArgListEntry Entry;
7830     Entry.Node = getValue(V);
7831     Entry.Ty = V->getType();
7832     Entry.setAttributes(&CS, ArgI);
7833     Args.push_back(Entry);
7834   }
7835 
7836   CLI.setDebugLoc(getCurSDLoc())
7837       .setChain(getRoot())
7838       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7839       .setDiscardResult(CS->use_empty())
7840       .setIsPatchPoint(IsPatchPoint);
7841 }
7842 
7843 /// Add a stack map intrinsic call's live variable operands to a stackmap
7844 /// or patchpoint target node's operand list.
7845 ///
7846 /// Constants are converted to TargetConstants purely as an optimization to
7847 /// avoid constant materialization and register allocation.
7848 ///
7849 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7850 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7851 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7852 /// address materialization and register allocation, but may also be required
7853 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7854 /// alloca in the entry block, then the runtime may assume that the alloca's
7855 /// StackMap location can be read immediately after compilation and that the
7856 /// location is valid at any point during execution (this is similar to the
7857 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7858 /// only available in a register, then the runtime would need to trap when
7859 /// execution reaches the StackMap in order to read the alloca's location.
7860 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7861                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7862                                 SelectionDAGBuilder &Builder) {
7863   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7864     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7865     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7866       Ops.push_back(
7867         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7868       Ops.push_back(
7869         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7870     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7871       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7872       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7873           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7874     } else
7875       Ops.push_back(OpVal);
7876   }
7877 }
7878 
7879 /// Lower llvm.experimental.stackmap directly to its target opcode.
7880 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7881   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7882   //                                  [live variables...])
7883 
7884   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7885 
7886   SDValue Chain, InFlag, Callee, NullPtr;
7887   SmallVector<SDValue, 32> Ops;
7888 
7889   SDLoc DL = getCurSDLoc();
7890   Callee = getValue(CI.getCalledValue());
7891   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7892 
7893   // The stackmap intrinsic only records the live variables (the arguemnts
7894   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7895   // intrinsic, this won't be lowered to a function call. This means we don't
7896   // have to worry about calling conventions and target specific lowering code.
7897   // Instead we perform the call lowering right here.
7898   //
7899   // chain, flag = CALLSEQ_START(chain, 0, 0)
7900   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7901   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7902   //
7903   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7904   InFlag = Chain.getValue(1);
7905 
7906   // Add the <id> and <numBytes> constants.
7907   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7908   Ops.push_back(DAG.getTargetConstant(
7909                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7910   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7911   Ops.push_back(DAG.getTargetConstant(
7912                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7913                   MVT::i32));
7914 
7915   // Push live variables for the stack map.
7916   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7917 
7918   // We are not pushing any register mask info here on the operands list,
7919   // because the stackmap doesn't clobber anything.
7920 
7921   // Push the chain and the glue flag.
7922   Ops.push_back(Chain);
7923   Ops.push_back(InFlag);
7924 
7925   // Create the STACKMAP node.
7926   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7927   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7928   Chain = SDValue(SM, 0);
7929   InFlag = Chain.getValue(1);
7930 
7931   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7932 
7933   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7934 
7935   // Set the root to the target-lowered call chain.
7936   DAG.setRoot(Chain);
7937 
7938   // Inform the Frame Information that we have a stackmap in this function.
7939   FuncInfo.MF->getFrameInfo().setHasStackMap();
7940 }
7941 
7942 /// Lower llvm.experimental.patchpoint directly to its target opcode.
7943 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7944                                           const BasicBlock *EHPadBB) {
7945   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7946   //                                                 i32 <numBytes>,
7947   //                                                 i8* <target>,
7948   //                                                 i32 <numArgs>,
7949   //                                                 [Args...],
7950   //                                                 [live variables...])
7951 
7952   CallingConv::ID CC = CS.getCallingConv();
7953   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7954   bool HasDef = !CS->getType()->isVoidTy();
7955   SDLoc dl = getCurSDLoc();
7956   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7957 
7958   // Handle immediate and symbolic callees.
7959   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7960     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7961                                    /*isTarget=*/true);
7962   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7963     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7964                                          SDLoc(SymbolicCallee),
7965                                          SymbolicCallee->getValueType(0));
7966 
7967   // Get the real number of arguments participating in the call <numArgs>
7968   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7969   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7970 
7971   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7972   // Intrinsics include all meta-operands up to but not including CC.
7973   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7974   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7975          "Not enough arguments provided to the patchpoint intrinsic");
7976 
7977   // For AnyRegCC the arguments are lowered later on manually.
7978   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7979   Type *ReturnTy =
7980     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7981 
7982   TargetLowering::CallLoweringInfo CLI(DAG);
7983   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7984                            true);
7985   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7986 
7987   SDNode *CallEnd = Result.second.getNode();
7988   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7989     CallEnd = CallEnd->getOperand(0).getNode();
7990 
7991   /// Get a call instruction from the call sequence chain.
7992   /// Tail calls are not allowed.
7993   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7994          "Expected a callseq node.");
7995   SDNode *Call = CallEnd->getOperand(0).getNode();
7996   bool HasGlue = Call->getGluedNode();
7997 
7998   // Replace the target specific call node with the patchable intrinsic.
7999   SmallVector<SDValue, 8> Ops;
8000 
8001   // Add the <id> and <numBytes> constants.
8002   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8003   Ops.push_back(DAG.getTargetConstant(
8004                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8005   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8006   Ops.push_back(DAG.getTargetConstant(
8007                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8008                   MVT::i32));
8009 
8010   // Add the callee.
8011   Ops.push_back(Callee);
8012 
8013   // Adjust <numArgs> to account for any arguments that have been passed on the
8014   // stack instead.
8015   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8016   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8017   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8018   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8019 
8020   // Add the calling convention
8021   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8022 
8023   // Add the arguments we omitted previously. The register allocator should
8024   // place these in any free register.
8025   if (IsAnyRegCC)
8026     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8027       Ops.push_back(getValue(CS.getArgument(i)));
8028 
8029   // Push the arguments from the call instruction up to the register mask.
8030   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8031   Ops.append(Call->op_begin() + 2, e);
8032 
8033   // Push live variables for the stack map.
8034   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8035 
8036   // Push the register mask info.
8037   if (HasGlue)
8038     Ops.push_back(*(Call->op_end()-2));
8039   else
8040     Ops.push_back(*(Call->op_end()-1));
8041 
8042   // Push the chain (this is originally the first operand of the call, but
8043   // becomes now the last or second to last operand).
8044   Ops.push_back(*(Call->op_begin()));
8045 
8046   // Push the glue flag (last operand).
8047   if (HasGlue)
8048     Ops.push_back(*(Call->op_end()-1));
8049 
8050   SDVTList NodeTys;
8051   if (IsAnyRegCC && HasDef) {
8052     // Create the return types based on the intrinsic definition
8053     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8054     SmallVector<EVT, 3> ValueVTs;
8055     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8056     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8057 
8058     // There is always a chain and a glue type at the end
8059     ValueVTs.push_back(MVT::Other);
8060     ValueVTs.push_back(MVT::Glue);
8061     NodeTys = DAG.getVTList(ValueVTs);
8062   } else
8063     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8064 
8065   // Replace the target specific call node with a PATCHPOINT node.
8066   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8067                                          dl, NodeTys, Ops);
8068 
8069   // Update the NodeMap.
8070   if (HasDef) {
8071     if (IsAnyRegCC)
8072       setValue(CS.getInstruction(), SDValue(MN, 0));
8073     else
8074       setValue(CS.getInstruction(), Result.first);
8075   }
8076 
8077   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8078   // call sequence. Furthermore the location of the chain and glue can change
8079   // when the AnyReg calling convention is used and the intrinsic returns a
8080   // value.
8081   if (IsAnyRegCC && HasDef) {
8082     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8083     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8084     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8085   } else
8086     DAG.ReplaceAllUsesWith(Call, MN);
8087   DAG.DeleteNode(Call);
8088 
8089   // Inform the Frame Information that we have a patchpoint in this function.
8090   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8091 }
8092 
8093 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8094                                             unsigned Intrinsic) {
8095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8096   SDValue Op1 = getValue(I.getArgOperand(0));
8097   SDValue Op2;
8098   if (I.getNumArgOperands() > 1)
8099     Op2 = getValue(I.getArgOperand(1));
8100   SDLoc dl = getCurSDLoc();
8101   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8102   SDValue Res;
8103   FastMathFlags FMF;
8104   if (isa<FPMathOperator>(I))
8105     FMF = I.getFastMathFlags();
8106   SDNodeFlags SDFlags;
8107   SDFlags.setNoNaNs(FMF.noNaNs());
8108 
8109   switch (Intrinsic) {
8110   case Intrinsic::experimental_vector_reduce_fadd:
8111     if (FMF.isFast())
8112       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8113     else
8114       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8115     break;
8116   case Intrinsic::experimental_vector_reduce_fmul:
8117     if (FMF.isFast())
8118       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8119     else
8120       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8121     break;
8122   case Intrinsic::experimental_vector_reduce_add:
8123     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8124     break;
8125   case Intrinsic::experimental_vector_reduce_mul:
8126     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8127     break;
8128   case Intrinsic::experimental_vector_reduce_and:
8129     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8130     break;
8131   case Intrinsic::experimental_vector_reduce_or:
8132     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8133     break;
8134   case Intrinsic::experimental_vector_reduce_xor:
8135     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8136     break;
8137   case Intrinsic::experimental_vector_reduce_smax:
8138     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8139     break;
8140   case Intrinsic::experimental_vector_reduce_smin:
8141     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8142     break;
8143   case Intrinsic::experimental_vector_reduce_umax:
8144     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8145     break;
8146   case Intrinsic::experimental_vector_reduce_umin:
8147     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8148     break;
8149   case Intrinsic::experimental_vector_reduce_fmax:
8150     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
8151     break;
8152   case Intrinsic::experimental_vector_reduce_fmin:
8153     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
8154     break;
8155   default:
8156     llvm_unreachable("Unhandled vector reduce intrinsic");
8157   }
8158   setValue(&I, Res);
8159 }
8160 
8161 /// Returns an AttributeList representing the attributes applied to the return
8162 /// value of the given call.
8163 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8164   SmallVector<Attribute::AttrKind, 2> Attrs;
8165   if (CLI.RetSExt)
8166     Attrs.push_back(Attribute::SExt);
8167   if (CLI.RetZExt)
8168     Attrs.push_back(Attribute::ZExt);
8169   if (CLI.IsInReg)
8170     Attrs.push_back(Attribute::InReg);
8171 
8172   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8173                             Attrs);
8174 }
8175 
8176 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8177 /// implementation, which just calls LowerCall.
8178 /// FIXME: When all targets are
8179 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8180 std::pair<SDValue, SDValue>
8181 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8182   // Handle the incoming return values from the call.
8183   CLI.Ins.clear();
8184   Type *OrigRetTy = CLI.RetTy;
8185   SmallVector<EVT, 4> RetTys;
8186   SmallVector<uint64_t, 4> Offsets;
8187   auto &DL = CLI.DAG.getDataLayout();
8188   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8189 
8190   if (CLI.IsPostTypeLegalization) {
8191     // If we are lowering a libcall after legalization, split the return type.
8192     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8193     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8194     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8195       EVT RetVT = OldRetTys[i];
8196       uint64_t Offset = OldOffsets[i];
8197       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8198       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8199       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8200       RetTys.append(NumRegs, RegisterVT);
8201       for (unsigned j = 0; j != NumRegs; ++j)
8202         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8203     }
8204   }
8205 
8206   SmallVector<ISD::OutputArg, 4> Outs;
8207   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8208 
8209   bool CanLowerReturn =
8210       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8211                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8212 
8213   SDValue DemoteStackSlot;
8214   int DemoteStackIdx = -100;
8215   if (!CanLowerReturn) {
8216     // FIXME: equivalent assert?
8217     // assert(!CS.hasInAllocaArgument() &&
8218     //        "sret demotion is incompatible with inalloca");
8219     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8220     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8221     MachineFunction &MF = CLI.DAG.getMachineFunction();
8222     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8223     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
8224 
8225     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8226     ArgListEntry Entry;
8227     Entry.Node = DemoteStackSlot;
8228     Entry.Ty = StackSlotPtrType;
8229     Entry.IsSExt = false;
8230     Entry.IsZExt = false;
8231     Entry.IsInReg = false;
8232     Entry.IsSRet = true;
8233     Entry.IsNest = false;
8234     Entry.IsByVal = false;
8235     Entry.IsReturned = false;
8236     Entry.IsSwiftSelf = false;
8237     Entry.IsSwiftError = false;
8238     Entry.Alignment = Align;
8239     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8240     CLI.NumFixedArgs += 1;
8241     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8242 
8243     // sret demotion isn't compatible with tail-calls, since the sret argument
8244     // points into the callers stack frame.
8245     CLI.IsTailCall = false;
8246   } else {
8247     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8248       EVT VT = RetTys[I];
8249       MVT RegisterVT =
8250           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8251       unsigned NumRegs =
8252           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8253       for (unsigned i = 0; i != NumRegs; ++i) {
8254         ISD::InputArg MyFlags;
8255         MyFlags.VT = RegisterVT;
8256         MyFlags.ArgVT = VT;
8257         MyFlags.Used = CLI.IsReturnValueUsed;
8258         if (CLI.RetSExt)
8259           MyFlags.Flags.setSExt();
8260         if (CLI.RetZExt)
8261           MyFlags.Flags.setZExt();
8262         if (CLI.IsInReg)
8263           MyFlags.Flags.setInReg();
8264         CLI.Ins.push_back(MyFlags);
8265       }
8266     }
8267   }
8268 
8269   // We push in swifterror return as the last element of CLI.Ins.
8270   ArgListTy &Args = CLI.getArgs();
8271   if (supportSwiftError()) {
8272     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8273       if (Args[i].IsSwiftError) {
8274         ISD::InputArg MyFlags;
8275         MyFlags.VT = getPointerTy(DL);
8276         MyFlags.ArgVT = EVT(getPointerTy(DL));
8277         MyFlags.Flags.setSwiftError();
8278         CLI.Ins.push_back(MyFlags);
8279       }
8280     }
8281   }
8282 
8283   // Handle all of the outgoing arguments.
8284   CLI.Outs.clear();
8285   CLI.OutVals.clear();
8286   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8287     SmallVector<EVT, 4> ValueVTs;
8288     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8289     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8290     Type *FinalType = Args[i].Ty;
8291     if (Args[i].IsByVal)
8292       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8293     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8294         FinalType, CLI.CallConv, CLI.IsVarArg);
8295     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8296          ++Value) {
8297       EVT VT = ValueVTs[Value];
8298       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8299       SDValue Op = SDValue(Args[i].Node.getNode(),
8300                            Args[i].Node.getResNo() + Value);
8301       ISD::ArgFlagsTy Flags;
8302 
8303       // Certain targets (such as MIPS), may have a different ABI alignment
8304       // for a type depending on the context. Give the target a chance to
8305       // specify the alignment it wants.
8306       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8307 
8308       if (Args[i].IsZExt)
8309         Flags.setZExt();
8310       if (Args[i].IsSExt)
8311         Flags.setSExt();
8312       if (Args[i].IsInReg) {
8313         // If we are using vectorcall calling convention, a structure that is
8314         // passed InReg - is surely an HVA
8315         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8316             isa<StructType>(FinalType)) {
8317           // The first value of a structure is marked
8318           if (0 == Value)
8319             Flags.setHvaStart();
8320           Flags.setHva();
8321         }
8322         // Set InReg Flag
8323         Flags.setInReg();
8324       }
8325       if (Args[i].IsSRet)
8326         Flags.setSRet();
8327       if (Args[i].IsSwiftSelf)
8328         Flags.setSwiftSelf();
8329       if (Args[i].IsSwiftError)
8330         Flags.setSwiftError();
8331       if (Args[i].IsByVal)
8332         Flags.setByVal();
8333       if (Args[i].IsInAlloca) {
8334         Flags.setInAlloca();
8335         // Set the byval flag for CCAssignFn callbacks that don't know about
8336         // inalloca.  This way we can know how many bytes we should've allocated
8337         // and how many bytes a callee cleanup function will pop.  If we port
8338         // inalloca to more targets, we'll have to add custom inalloca handling
8339         // in the various CC lowering callbacks.
8340         Flags.setByVal();
8341       }
8342       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8343         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8344         Type *ElementTy = Ty->getElementType();
8345         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8346         // For ByVal, alignment should come from FE.  BE will guess if this
8347         // info is not there but there are cases it cannot get right.
8348         unsigned FrameAlign;
8349         if (Args[i].Alignment)
8350           FrameAlign = Args[i].Alignment;
8351         else
8352           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8353         Flags.setByValAlign(FrameAlign);
8354       }
8355       if (Args[i].IsNest)
8356         Flags.setNest();
8357       if (NeedsRegBlock)
8358         Flags.setInConsecutiveRegs();
8359       Flags.setOrigAlign(OriginalAlignment);
8360 
8361       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8362       unsigned NumParts =
8363           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8364       SmallVector<SDValue, 4> Parts(NumParts);
8365       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8366 
8367       if (Args[i].IsSExt)
8368         ExtendKind = ISD::SIGN_EXTEND;
8369       else if (Args[i].IsZExt)
8370         ExtendKind = ISD::ZERO_EXTEND;
8371 
8372       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8373       // for now.
8374       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8375           CanLowerReturn) {
8376         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8377                "unexpected use of 'returned'");
8378         // Before passing 'returned' to the target lowering code, ensure that
8379         // either the register MVT and the actual EVT are the same size or that
8380         // the return value and argument are extended in the same way; in these
8381         // cases it's safe to pass the argument register value unchanged as the
8382         // return register value (although it's at the target's option whether
8383         // to do so)
8384         // TODO: allow code generation to take advantage of partially preserved
8385         // registers rather than clobbering the entire register when the
8386         // parameter extension method is not compatible with the return
8387         // extension method
8388         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8389             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8390              CLI.RetZExt == Args[i].IsZExt))
8391           Flags.setReturned();
8392       }
8393 
8394       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8395                      CLI.CS.getInstruction(), ExtendKind, true);
8396 
8397       for (unsigned j = 0; j != NumParts; ++j) {
8398         // if it isn't first piece, alignment must be 1
8399         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8400                                i < CLI.NumFixedArgs,
8401                                i, j*Parts[j].getValueType().getStoreSize());
8402         if (NumParts > 1 && j == 0)
8403           MyFlags.Flags.setSplit();
8404         else if (j != 0) {
8405           MyFlags.Flags.setOrigAlign(1);
8406           if (j == NumParts - 1)
8407             MyFlags.Flags.setSplitEnd();
8408         }
8409 
8410         CLI.Outs.push_back(MyFlags);
8411         CLI.OutVals.push_back(Parts[j]);
8412       }
8413 
8414       if (NeedsRegBlock && Value == NumValues - 1)
8415         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8416     }
8417   }
8418 
8419   SmallVector<SDValue, 4> InVals;
8420   CLI.Chain = LowerCall(CLI, InVals);
8421 
8422   // Update CLI.InVals to use outside of this function.
8423   CLI.InVals = InVals;
8424 
8425   // Verify that the target's LowerCall behaved as expected.
8426   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8427          "LowerCall didn't return a valid chain!");
8428   assert((!CLI.IsTailCall || InVals.empty()) &&
8429          "LowerCall emitted a return value for a tail call!");
8430   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8431          "LowerCall didn't emit the correct number of values!");
8432 
8433   // For a tail call, the return value is merely live-out and there aren't
8434   // any nodes in the DAG representing it. Return a special value to
8435   // indicate that a tail call has been emitted and no more Instructions
8436   // should be processed in the current block.
8437   if (CLI.IsTailCall) {
8438     CLI.DAG.setRoot(CLI.Chain);
8439     return std::make_pair(SDValue(), SDValue());
8440   }
8441 
8442 #ifndef NDEBUG
8443   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8444     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8445     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8446            "LowerCall emitted a value with the wrong type!");
8447   }
8448 #endif
8449 
8450   SmallVector<SDValue, 4> ReturnValues;
8451   if (!CanLowerReturn) {
8452     // The instruction result is the result of loading from the
8453     // hidden sret parameter.
8454     SmallVector<EVT, 1> PVTs;
8455     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8456 
8457     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8458     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8459     EVT PtrVT = PVTs[0];
8460 
8461     unsigned NumValues = RetTys.size();
8462     ReturnValues.resize(NumValues);
8463     SmallVector<SDValue, 4> Chains(NumValues);
8464 
8465     // An aggregate return value cannot wrap around the address space, so
8466     // offsets to its parts don't wrap either.
8467     SDNodeFlags Flags;
8468     Flags.setNoUnsignedWrap(true);
8469 
8470     for (unsigned i = 0; i < NumValues; ++i) {
8471       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8472                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8473                                                         PtrVT), Flags);
8474       SDValue L = CLI.DAG.getLoad(
8475           RetTys[i], CLI.DL, CLI.Chain, Add,
8476           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8477                                             DemoteStackIdx, Offsets[i]),
8478           /* Alignment = */ 1);
8479       ReturnValues[i] = L;
8480       Chains[i] = L.getValue(1);
8481     }
8482 
8483     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8484   } else {
8485     // Collect the legal value parts into potentially illegal values
8486     // that correspond to the original function's return values.
8487     Optional<ISD::NodeType> AssertOp;
8488     if (CLI.RetSExt)
8489       AssertOp = ISD::AssertSext;
8490     else if (CLI.RetZExt)
8491       AssertOp = ISD::AssertZext;
8492     unsigned CurReg = 0;
8493     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8494       EVT VT = RetTys[I];
8495       MVT RegisterVT =
8496           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8497       unsigned NumRegs =
8498           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8499 
8500       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8501                                               NumRegs, RegisterVT, VT, nullptr,
8502                                               AssertOp, true));
8503       CurReg += NumRegs;
8504     }
8505 
8506     // For a function returning void, there is no return value. We can't create
8507     // such a node, so we just return a null return value in that case. In
8508     // that case, nothing will actually look at the value.
8509     if (ReturnValues.empty())
8510       return std::make_pair(SDValue(), CLI.Chain);
8511   }
8512 
8513   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8514                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8515   return std::make_pair(Res, CLI.Chain);
8516 }
8517 
8518 void TargetLowering::LowerOperationWrapper(SDNode *N,
8519                                            SmallVectorImpl<SDValue> &Results,
8520                                            SelectionDAG &DAG) const {
8521   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8522     Results.push_back(Res);
8523 }
8524 
8525 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8526   llvm_unreachable("LowerOperation not implemented for this target!");
8527 }
8528 
8529 void
8530 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8531   SDValue Op = getNonRegisterValue(V);
8532   assert((Op.getOpcode() != ISD::CopyFromReg ||
8533           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8534          "Copy from a reg to the same reg!");
8535   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8536 
8537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8538   // If this is an InlineAsm we have to match the registers required, not the
8539   // notional registers required by the type.
8540 
8541   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8542                    V->getType(), isABIRegCopy(V));
8543   SDValue Chain = DAG.getEntryNode();
8544 
8545   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8546                               FuncInfo.PreferredExtendType.end())
8547                                  ? ISD::ANY_EXTEND
8548                                  : FuncInfo.PreferredExtendType[V];
8549   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8550   PendingExports.push_back(Chain);
8551 }
8552 
8553 #include "llvm/CodeGen/SelectionDAGISel.h"
8554 
8555 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8556 /// entry block, return true.  This includes arguments used by switches, since
8557 /// the switch may expand into multiple basic blocks.
8558 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8559   // With FastISel active, we may be splitting blocks, so force creation
8560   // of virtual registers for all non-dead arguments.
8561   if (FastISel)
8562     return A->use_empty();
8563 
8564   const BasicBlock &Entry = A->getParent()->front();
8565   for (const User *U : A->users())
8566     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8567       return false;  // Use not in entry block.
8568 
8569   return true;
8570 }
8571 
8572 using ArgCopyElisionMapTy =
8573     DenseMap<const Argument *,
8574              std::pair<const AllocaInst *, const StoreInst *>>;
8575 
8576 /// Scan the entry block of the function in FuncInfo for arguments that look
8577 /// like copies into a local alloca. Record any copied arguments in
8578 /// ArgCopyElisionCandidates.
8579 static void
8580 findArgumentCopyElisionCandidates(const DataLayout &DL,
8581                                   FunctionLoweringInfo *FuncInfo,
8582                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8583   // Record the state of every static alloca used in the entry block. Argument
8584   // allocas are all used in the entry block, so we need approximately as many
8585   // entries as we have arguments.
8586   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8587   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8588   unsigned NumArgs = FuncInfo->Fn->arg_size();
8589   StaticAllocas.reserve(NumArgs * 2);
8590 
8591   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8592     if (!V)
8593       return nullptr;
8594     V = V->stripPointerCasts();
8595     const auto *AI = dyn_cast<AllocaInst>(V);
8596     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8597       return nullptr;
8598     auto Iter = StaticAllocas.insert({AI, Unknown});
8599     return &Iter.first->second;
8600   };
8601 
8602   // Look for stores of arguments to static allocas. Look through bitcasts and
8603   // GEPs to handle type coercions, as long as the alloca is fully initialized
8604   // by the store. Any non-store use of an alloca escapes it and any subsequent
8605   // unanalyzed store might write it.
8606   // FIXME: Handle structs initialized with multiple stores.
8607   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8608     // Look for stores, and handle non-store uses conservatively.
8609     const auto *SI = dyn_cast<StoreInst>(&I);
8610     if (!SI) {
8611       // We will look through cast uses, so ignore them completely.
8612       if (I.isCast())
8613         continue;
8614       // Ignore debug info intrinsics, they don't escape or store to allocas.
8615       if (isa<DbgInfoIntrinsic>(I))
8616         continue;
8617       // This is an unknown instruction. Assume it escapes or writes to all
8618       // static alloca operands.
8619       for (const Use &U : I.operands()) {
8620         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8621           *Info = StaticAllocaInfo::Clobbered;
8622       }
8623       continue;
8624     }
8625 
8626     // If the stored value is a static alloca, mark it as escaped.
8627     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8628       *Info = StaticAllocaInfo::Clobbered;
8629 
8630     // Check if the destination is a static alloca.
8631     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8632     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8633     if (!Info)
8634       continue;
8635     const AllocaInst *AI = cast<AllocaInst>(Dst);
8636 
8637     // Skip allocas that have been initialized or clobbered.
8638     if (*Info != StaticAllocaInfo::Unknown)
8639       continue;
8640 
8641     // Check if the stored value is an argument, and that this store fully
8642     // initializes the alloca. Don't elide copies from the same argument twice.
8643     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8644     const auto *Arg = dyn_cast<Argument>(Val);
8645     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8646         Arg->getType()->isEmptyTy() ||
8647         DL.getTypeStoreSize(Arg->getType()) !=
8648             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8649         ArgCopyElisionCandidates.count(Arg)) {
8650       *Info = StaticAllocaInfo::Clobbered;
8651       continue;
8652     }
8653 
8654     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8655 
8656     // Mark this alloca and store for argument copy elision.
8657     *Info = StaticAllocaInfo::Elidable;
8658     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8659 
8660     // Stop scanning if we've seen all arguments. This will happen early in -O0
8661     // builds, which is useful, because -O0 builds have large entry blocks and
8662     // many allocas.
8663     if (ArgCopyElisionCandidates.size() == NumArgs)
8664       break;
8665   }
8666 }
8667 
8668 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8669 /// ArgVal is a load from a suitable fixed stack object.
8670 static void tryToElideArgumentCopy(
8671     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8672     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8673     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8674     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8675     SDValue ArgVal, bool &ArgHasUses) {
8676   // Check if this is a load from a fixed stack object.
8677   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8678   if (!LNode)
8679     return;
8680   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8681   if (!FINode)
8682     return;
8683 
8684   // Check that the fixed stack object is the right size and alignment.
8685   // Look at the alignment that the user wrote on the alloca instead of looking
8686   // at the stack object.
8687   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8688   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8689   const AllocaInst *AI = ArgCopyIter->second.first;
8690   int FixedIndex = FINode->getIndex();
8691   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8692   int OldIndex = AllocaIndex;
8693   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8694   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8695     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8696                     "object size\n");
8697     return;
8698   }
8699   unsigned RequiredAlignment = AI->getAlignment();
8700   if (!RequiredAlignment) {
8701     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8702         AI->getAllocatedType());
8703   }
8704   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8705     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8706                     "greater than stack argument alignment ("
8707                  << RequiredAlignment << " vs "
8708                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8709     return;
8710   }
8711 
8712   // Perform the elision. Delete the old stack object and replace its only use
8713   // in the variable info map. Mark the stack object as mutable.
8714   DEBUG({
8715     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8716            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8717            << '\n';
8718   });
8719   MFI.RemoveStackObject(OldIndex);
8720   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8721   AllocaIndex = FixedIndex;
8722   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8723   Chains.push_back(ArgVal.getValue(1));
8724 
8725   // Avoid emitting code for the store implementing the copy.
8726   const StoreInst *SI = ArgCopyIter->second.second;
8727   ElidedArgCopyInstrs.insert(SI);
8728 
8729   // Check for uses of the argument again so that we can avoid exporting ArgVal
8730   // if it is't used by anything other than the store.
8731   for (const Value *U : Arg.users()) {
8732     if (U != SI) {
8733       ArgHasUses = true;
8734       break;
8735     }
8736   }
8737 }
8738 
8739 void SelectionDAGISel::LowerArguments(const Function &F) {
8740   SelectionDAG &DAG = SDB->DAG;
8741   SDLoc dl = SDB->getCurSDLoc();
8742   const DataLayout &DL = DAG.getDataLayout();
8743   SmallVector<ISD::InputArg, 16> Ins;
8744 
8745   if (!FuncInfo->CanLowerReturn) {
8746     // Put in an sret pointer parameter before all the other parameters.
8747     SmallVector<EVT, 1> ValueVTs;
8748     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8749                     F.getReturnType()->getPointerTo(
8750                         DAG.getDataLayout().getAllocaAddrSpace()),
8751                     ValueVTs);
8752 
8753     // NOTE: Assuming that a pointer will never break down to more than one VT
8754     // or one register.
8755     ISD::ArgFlagsTy Flags;
8756     Flags.setSRet();
8757     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8758     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8759                          ISD::InputArg::NoArgIndex, 0);
8760     Ins.push_back(RetArg);
8761   }
8762 
8763   // Look for stores of arguments to static allocas. Mark such arguments with a
8764   // flag to ask the target to give us the memory location of that argument if
8765   // available.
8766   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8767   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8768 
8769   // Set up the incoming argument description vector.
8770   for (const Argument &Arg : F.args()) {
8771     unsigned ArgNo = Arg.getArgNo();
8772     SmallVector<EVT, 4> ValueVTs;
8773     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8774     bool isArgValueUsed = !Arg.use_empty();
8775     unsigned PartBase = 0;
8776     Type *FinalType = Arg.getType();
8777     if (Arg.hasAttribute(Attribute::ByVal))
8778       FinalType = cast<PointerType>(FinalType)->getElementType();
8779     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8780         FinalType, F.getCallingConv(), F.isVarArg());
8781     for (unsigned Value = 0, NumValues = ValueVTs.size();
8782          Value != NumValues; ++Value) {
8783       EVT VT = ValueVTs[Value];
8784       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8785       ISD::ArgFlagsTy Flags;
8786 
8787       // Certain targets (such as MIPS), may have a different ABI alignment
8788       // for a type depending on the context. Give the target a chance to
8789       // specify the alignment it wants.
8790       unsigned OriginalAlignment =
8791           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8792 
8793       if (Arg.hasAttribute(Attribute::ZExt))
8794         Flags.setZExt();
8795       if (Arg.hasAttribute(Attribute::SExt))
8796         Flags.setSExt();
8797       if (Arg.hasAttribute(Attribute::InReg)) {
8798         // If we are using vectorcall calling convention, a structure that is
8799         // passed InReg - is surely an HVA
8800         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8801             isa<StructType>(Arg.getType())) {
8802           // The first value of a structure is marked
8803           if (0 == Value)
8804             Flags.setHvaStart();
8805           Flags.setHva();
8806         }
8807         // Set InReg Flag
8808         Flags.setInReg();
8809       }
8810       if (Arg.hasAttribute(Attribute::StructRet))
8811         Flags.setSRet();
8812       if (Arg.hasAttribute(Attribute::SwiftSelf))
8813         Flags.setSwiftSelf();
8814       if (Arg.hasAttribute(Attribute::SwiftError))
8815         Flags.setSwiftError();
8816       if (Arg.hasAttribute(Attribute::ByVal))
8817         Flags.setByVal();
8818       if (Arg.hasAttribute(Attribute::InAlloca)) {
8819         Flags.setInAlloca();
8820         // Set the byval flag for CCAssignFn callbacks that don't know about
8821         // inalloca.  This way we can know how many bytes we should've allocated
8822         // and how many bytes a callee cleanup function will pop.  If we port
8823         // inalloca to more targets, we'll have to add custom inalloca handling
8824         // in the various CC lowering callbacks.
8825         Flags.setByVal();
8826       }
8827       if (F.getCallingConv() == CallingConv::X86_INTR) {
8828         // IA Interrupt passes frame (1st parameter) by value in the stack.
8829         if (ArgNo == 0)
8830           Flags.setByVal();
8831       }
8832       if (Flags.isByVal() || Flags.isInAlloca()) {
8833         PointerType *Ty = cast<PointerType>(Arg.getType());
8834         Type *ElementTy = Ty->getElementType();
8835         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8836         // For ByVal, alignment should be passed from FE.  BE will guess if
8837         // this info is not there but there are cases it cannot get right.
8838         unsigned FrameAlign;
8839         if (Arg.getParamAlignment())
8840           FrameAlign = Arg.getParamAlignment();
8841         else
8842           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8843         Flags.setByValAlign(FrameAlign);
8844       }
8845       if (Arg.hasAttribute(Attribute::Nest))
8846         Flags.setNest();
8847       if (NeedsRegBlock)
8848         Flags.setInConsecutiveRegs();
8849       Flags.setOrigAlign(OriginalAlignment);
8850       if (ArgCopyElisionCandidates.count(&Arg))
8851         Flags.setCopyElisionCandidate();
8852 
8853       MVT RegisterVT =
8854           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8855       unsigned NumRegs =
8856           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8857       for (unsigned i = 0; i != NumRegs; ++i) {
8858         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8859                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8860         if (NumRegs > 1 && i == 0)
8861           MyFlags.Flags.setSplit();
8862         // if it isn't first piece, alignment must be 1
8863         else if (i > 0) {
8864           MyFlags.Flags.setOrigAlign(1);
8865           if (i == NumRegs - 1)
8866             MyFlags.Flags.setSplitEnd();
8867         }
8868         Ins.push_back(MyFlags);
8869       }
8870       if (NeedsRegBlock && Value == NumValues - 1)
8871         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8872       PartBase += VT.getStoreSize();
8873     }
8874   }
8875 
8876   // Call the target to set up the argument values.
8877   SmallVector<SDValue, 8> InVals;
8878   SDValue NewRoot = TLI->LowerFormalArguments(
8879       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8880 
8881   // Verify that the target's LowerFormalArguments behaved as expected.
8882   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8883          "LowerFormalArguments didn't return a valid chain!");
8884   assert(InVals.size() == Ins.size() &&
8885          "LowerFormalArguments didn't emit the correct number of values!");
8886   DEBUG({
8887       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8888         assert(InVals[i].getNode() &&
8889                "LowerFormalArguments emitted a null value!");
8890         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8891                "LowerFormalArguments emitted a value with the wrong type!");
8892       }
8893     });
8894 
8895   // Update the DAG with the new chain value resulting from argument lowering.
8896   DAG.setRoot(NewRoot);
8897 
8898   // Set up the argument values.
8899   unsigned i = 0;
8900   if (!FuncInfo->CanLowerReturn) {
8901     // Create a virtual register for the sret pointer, and put in a copy
8902     // from the sret argument into it.
8903     SmallVector<EVT, 1> ValueVTs;
8904     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8905                     F.getReturnType()->getPointerTo(
8906                         DAG.getDataLayout().getAllocaAddrSpace()),
8907                     ValueVTs);
8908     MVT VT = ValueVTs[0].getSimpleVT();
8909     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8910     Optional<ISD::NodeType> AssertOp = None;
8911     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8912                                         RegVT, VT, nullptr, AssertOp);
8913 
8914     MachineFunction& MF = SDB->DAG.getMachineFunction();
8915     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8916     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8917     FuncInfo->DemoteRegister = SRetReg;
8918     NewRoot =
8919         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8920     DAG.setRoot(NewRoot);
8921 
8922     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8923     ++i;
8924   }
8925 
8926   SmallVector<SDValue, 4> Chains;
8927   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8928   for (const Argument &Arg : F.args()) {
8929     SmallVector<SDValue, 4> ArgValues;
8930     SmallVector<EVT, 4> ValueVTs;
8931     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8932     unsigned NumValues = ValueVTs.size();
8933     if (NumValues == 0)
8934       continue;
8935 
8936     bool ArgHasUses = !Arg.use_empty();
8937 
8938     // Elide the copying store if the target loaded this argument from a
8939     // suitable fixed stack object.
8940     if (Ins[i].Flags.isCopyElisionCandidate()) {
8941       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8942                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8943                              InVals[i], ArgHasUses);
8944     }
8945 
8946     // If this argument is unused then remember its value. It is used to generate
8947     // debugging information.
8948     bool isSwiftErrorArg =
8949         TLI->supportSwiftError() &&
8950         Arg.hasAttribute(Attribute::SwiftError);
8951     if (!ArgHasUses && !isSwiftErrorArg) {
8952       SDB->setUnusedArgValue(&Arg, InVals[i]);
8953 
8954       // Also remember any frame index for use in FastISel.
8955       if (FrameIndexSDNode *FI =
8956           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8957         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8958     }
8959 
8960     for (unsigned Val = 0; Val != NumValues; ++Val) {
8961       EVT VT = ValueVTs[Val];
8962       MVT PartVT =
8963           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8964       unsigned NumParts =
8965           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8966 
8967       // Even an apparant 'unused' swifterror argument needs to be returned. So
8968       // we do generate a copy for it that can be used on return from the
8969       // function.
8970       if (ArgHasUses || isSwiftErrorArg) {
8971         Optional<ISD::NodeType> AssertOp;
8972         if (Arg.hasAttribute(Attribute::SExt))
8973           AssertOp = ISD::AssertSext;
8974         else if (Arg.hasAttribute(Attribute::ZExt))
8975           AssertOp = ISD::AssertZext;
8976 
8977         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8978                                              PartVT, VT, nullptr, AssertOp,
8979                                              true));
8980       }
8981 
8982       i += NumParts;
8983     }
8984 
8985     // We don't need to do anything else for unused arguments.
8986     if (ArgValues.empty())
8987       continue;
8988 
8989     // Note down frame index.
8990     if (FrameIndexSDNode *FI =
8991         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8992       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8993 
8994     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8995                                      SDB->getCurSDLoc());
8996 
8997     SDB->setValue(&Arg, Res);
8998     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8999       // We want to associate the argument with the frame index, among
9000       // involved operands, that correspond to the lowest address. The
9001       // getCopyFromParts function, called earlier, is swapping the order of
9002       // the operands to BUILD_PAIR depending on endianness. The result of
9003       // that swapping is that the least significant bits of the argument will
9004       // be in the first operand of the BUILD_PAIR node, and the most
9005       // significant bits will be in the second operand.
9006       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9007       if (LoadSDNode *LNode =
9008           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9009         if (FrameIndexSDNode *FI =
9010             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9011           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9012     }
9013 
9014     // Update the SwiftErrorVRegDefMap.
9015     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9016       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9017       if (TargetRegisterInfo::isVirtualRegister(Reg))
9018         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9019                                            FuncInfo->SwiftErrorArg, Reg);
9020     }
9021 
9022     // If this argument is live outside of the entry block, insert a copy from
9023     // wherever we got it to the vreg that other BB's will reference it as.
9024     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9025       // If we can, though, try to skip creating an unnecessary vreg.
9026       // FIXME: This isn't very clean... it would be nice to make this more
9027       // general.  It's also subtly incompatible with the hacks FastISel
9028       // uses with vregs.
9029       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9030       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9031         FuncInfo->ValueMap[&Arg] = Reg;
9032         continue;
9033       }
9034     }
9035     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9036       FuncInfo->InitializeRegForValue(&Arg);
9037       SDB->CopyToExportRegsIfNeeded(&Arg);
9038     }
9039   }
9040 
9041   if (!Chains.empty()) {
9042     Chains.push_back(NewRoot);
9043     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9044   }
9045 
9046   DAG.setRoot(NewRoot);
9047 
9048   assert(i == InVals.size() && "Argument register count mismatch!");
9049 
9050   // If any argument copy elisions occurred and we have debug info, update the
9051   // stale frame indices used in the dbg.declare variable info table.
9052   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9053   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9054     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9055       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9056       if (I != ArgCopyElisionFrameIndexMap.end())
9057         VI.Slot = I->second;
9058     }
9059   }
9060 
9061   // Finally, if the target has anything special to do, allow it to do so.
9062   EmitFunctionEntryCode();
9063 }
9064 
9065 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9066 /// ensure constants are generated when needed.  Remember the virtual registers
9067 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9068 /// directly add them, because expansion might result in multiple MBB's for one
9069 /// BB.  As such, the start of the BB might correspond to a different MBB than
9070 /// the end.
9071 void
9072 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9073   const TerminatorInst *TI = LLVMBB->getTerminator();
9074 
9075   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9076 
9077   // Check PHI nodes in successors that expect a value to be available from this
9078   // block.
9079   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9080     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9081     if (!isa<PHINode>(SuccBB->begin())) continue;
9082     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9083 
9084     // If this terminator has multiple identical successors (common for
9085     // switches), only handle each succ once.
9086     if (!SuccsHandled.insert(SuccMBB).second)
9087       continue;
9088 
9089     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9090 
9091     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9092     // nodes and Machine PHI nodes, but the incoming operands have not been
9093     // emitted yet.
9094     for (const PHINode &PN : SuccBB->phis()) {
9095       // Ignore dead phi's.
9096       if (PN.use_empty())
9097         continue;
9098 
9099       // Skip empty types
9100       if (PN.getType()->isEmptyTy())
9101         continue;
9102 
9103       unsigned Reg;
9104       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9105 
9106       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9107         unsigned &RegOut = ConstantsOut[C];
9108         if (RegOut == 0) {
9109           RegOut = FuncInfo.CreateRegs(C->getType());
9110           CopyValueToVirtualRegister(C, RegOut);
9111         }
9112         Reg = RegOut;
9113       } else {
9114         DenseMap<const Value *, unsigned>::iterator I =
9115           FuncInfo.ValueMap.find(PHIOp);
9116         if (I != FuncInfo.ValueMap.end())
9117           Reg = I->second;
9118         else {
9119           assert(isa<AllocaInst>(PHIOp) &&
9120                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9121                  "Didn't codegen value into a register!??");
9122           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9123           CopyValueToVirtualRegister(PHIOp, Reg);
9124         }
9125       }
9126 
9127       // Remember that this register needs to added to the machine PHI node as
9128       // the input for this MBB.
9129       SmallVector<EVT, 4> ValueVTs;
9130       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9131       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9132       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9133         EVT VT = ValueVTs[vti];
9134         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9135         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9136           FuncInfo.PHINodesToUpdate.push_back(
9137               std::make_pair(&*MBBI++, Reg + i));
9138         Reg += NumRegisters;
9139       }
9140     }
9141   }
9142 
9143   ConstantsOut.clear();
9144 }
9145 
9146 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9147 /// is 0.
9148 MachineBasicBlock *
9149 SelectionDAGBuilder::StackProtectorDescriptor::
9150 AddSuccessorMBB(const BasicBlock *BB,
9151                 MachineBasicBlock *ParentMBB,
9152                 bool IsLikely,
9153                 MachineBasicBlock *SuccMBB) {
9154   // If SuccBB has not been created yet, create it.
9155   if (!SuccMBB) {
9156     MachineFunction *MF = ParentMBB->getParent();
9157     MachineFunction::iterator BBI(ParentMBB);
9158     SuccMBB = MF->CreateMachineBasicBlock(BB);
9159     MF->insert(++BBI, SuccMBB);
9160   }
9161   // Add it as a successor of ParentMBB.
9162   ParentMBB->addSuccessor(
9163       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9164   return SuccMBB;
9165 }
9166 
9167 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9168   MachineFunction::iterator I(MBB);
9169   if (++I == FuncInfo.MF->end())
9170     return nullptr;
9171   return &*I;
9172 }
9173 
9174 /// During lowering new call nodes can be created (such as memset, etc.).
9175 /// Those will become new roots of the current DAG, but complications arise
9176 /// when they are tail calls. In such cases, the call lowering will update
9177 /// the root, but the builder still needs to know that a tail call has been
9178 /// lowered in order to avoid generating an additional return.
9179 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9180   // If the node is null, we do have a tail call.
9181   if (MaybeTC.getNode() != nullptr)
9182     DAG.setRoot(MaybeTC);
9183   else
9184     HasTailCall = true;
9185 }
9186 
9187 uint64_t
9188 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9189                                        unsigned First, unsigned Last) const {
9190   assert(Last >= First);
9191   const APInt &LowCase = Clusters[First].Low->getValue();
9192   const APInt &HighCase = Clusters[Last].High->getValue();
9193   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9194 
9195   // FIXME: A range of consecutive cases has 100% density, but only requires one
9196   // comparison to lower. We should discriminate against such consecutive ranges
9197   // in jump tables.
9198 
9199   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9200 }
9201 
9202 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9203     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9204     unsigned Last) const {
9205   assert(Last >= First);
9206   assert(TotalCases[Last] >= TotalCases[First]);
9207   uint64_t NumCases =
9208       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9209   return NumCases;
9210 }
9211 
9212 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9213                                          unsigned First, unsigned Last,
9214                                          const SwitchInst *SI,
9215                                          MachineBasicBlock *DefaultMBB,
9216                                          CaseCluster &JTCluster) {
9217   assert(First <= Last);
9218 
9219   auto Prob = BranchProbability::getZero();
9220   unsigned NumCmps = 0;
9221   std::vector<MachineBasicBlock*> Table;
9222   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9223 
9224   // Initialize probabilities in JTProbs.
9225   for (unsigned I = First; I <= Last; ++I)
9226     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9227 
9228   for (unsigned I = First; I <= Last; ++I) {
9229     assert(Clusters[I].Kind == CC_Range);
9230     Prob += Clusters[I].Prob;
9231     const APInt &Low = Clusters[I].Low->getValue();
9232     const APInt &High = Clusters[I].High->getValue();
9233     NumCmps += (Low == High) ? 1 : 2;
9234     if (I != First) {
9235       // Fill the gap between this and the previous cluster.
9236       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9237       assert(PreviousHigh.slt(Low));
9238       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9239       for (uint64_t J = 0; J < Gap; J++)
9240         Table.push_back(DefaultMBB);
9241     }
9242     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9243     for (uint64_t J = 0; J < ClusterSize; ++J)
9244       Table.push_back(Clusters[I].MBB);
9245     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9246   }
9247 
9248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9249   unsigned NumDests = JTProbs.size();
9250   if (TLI.isSuitableForBitTests(
9251           NumDests, NumCmps, Clusters[First].Low->getValue(),
9252           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9253     // Clusters[First..Last] should be lowered as bit tests instead.
9254     return false;
9255   }
9256 
9257   // Create the MBB that will load from and jump through the table.
9258   // Note: We create it here, but it's not inserted into the function yet.
9259   MachineFunction *CurMF = FuncInfo.MF;
9260   MachineBasicBlock *JumpTableMBB =
9261       CurMF->CreateMachineBasicBlock(SI->getParent());
9262 
9263   // Add successors. Note: use table order for determinism.
9264   SmallPtrSet<MachineBasicBlock *, 8> Done;
9265   for (MachineBasicBlock *Succ : Table) {
9266     if (Done.count(Succ))
9267       continue;
9268     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9269     Done.insert(Succ);
9270   }
9271   JumpTableMBB->normalizeSuccProbs();
9272 
9273   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9274                      ->createJumpTableIndex(Table);
9275 
9276   // Set up the jump table info.
9277   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9278   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9279                       Clusters[Last].High->getValue(), SI->getCondition(),
9280                       nullptr, false);
9281   JTCases.emplace_back(std::move(JTH), std::move(JT));
9282 
9283   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9284                                      JTCases.size() - 1, Prob);
9285   return true;
9286 }
9287 
9288 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9289                                          const SwitchInst *SI,
9290                                          MachineBasicBlock *DefaultMBB) {
9291 #ifndef NDEBUG
9292   // Clusters must be non-empty, sorted, and only contain Range clusters.
9293   assert(!Clusters.empty());
9294   for (CaseCluster &C : Clusters)
9295     assert(C.Kind == CC_Range);
9296   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9297     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9298 #endif
9299 
9300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9301   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9302     return;
9303 
9304   const int64_t N = Clusters.size();
9305   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9306   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9307 
9308   if (N < 2 || N < MinJumpTableEntries)
9309     return;
9310 
9311   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9312   SmallVector<unsigned, 8> TotalCases(N);
9313   for (unsigned i = 0; i < N; ++i) {
9314     const APInt &Hi = Clusters[i].High->getValue();
9315     const APInt &Lo = Clusters[i].Low->getValue();
9316     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9317     if (i != 0)
9318       TotalCases[i] += TotalCases[i - 1];
9319   }
9320 
9321   // Cheap case: the whole range may be suitable for jump table.
9322   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9323   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9324   assert(NumCases < UINT64_MAX / 100);
9325   assert(Range >= NumCases);
9326   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9327     CaseCluster JTCluster;
9328     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9329       Clusters[0] = JTCluster;
9330       Clusters.resize(1);
9331       return;
9332     }
9333   }
9334 
9335   // The algorithm below is not suitable for -O0.
9336   if (TM.getOptLevel() == CodeGenOpt::None)
9337     return;
9338 
9339   // Split Clusters into minimum number of dense partitions. The algorithm uses
9340   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9341   // for the Case Statement'" (1994), but builds the MinPartitions array in
9342   // reverse order to make it easier to reconstruct the partitions in ascending
9343   // order. In the choice between two optimal partitionings, it picks the one
9344   // which yields more jump tables.
9345 
9346   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9347   SmallVector<unsigned, 8> MinPartitions(N);
9348   // LastElement[i] is the last element of the partition starting at i.
9349   SmallVector<unsigned, 8> LastElement(N);
9350   // PartitionsScore[i] is used to break ties when choosing between two
9351   // partitionings resulting in the same number of partitions.
9352   SmallVector<unsigned, 8> PartitionsScore(N);
9353   // For PartitionsScore, a small number of comparisons is considered as good as
9354   // a jump table and a single comparison is considered better than a jump
9355   // table.
9356   enum PartitionScores : unsigned {
9357     NoTable = 0,
9358     Table = 1,
9359     FewCases = 1,
9360     SingleCase = 2
9361   };
9362 
9363   // Base case: There is only one way to partition Clusters[N-1].
9364   MinPartitions[N - 1] = 1;
9365   LastElement[N - 1] = N - 1;
9366   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9367 
9368   // Note: loop indexes are signed to avoid underflow.
9369   for (int64_t i = N - 2; i >= 0; i--) {
9370     // Find optimal partitioning of Clusters[i..N-1].
9371     // Baseline: Put Clusters[i] into a partition on its own.
9372     MinPartitions[i] = MinPartitions[i + 1] + 1;
9373     LastElement[i] = i;
9374     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9375 
9376     // Search for a solution that results in fewer partitions.
9377     for (int64_t j = N - 1; j > i; j--) {
9378       // Try building a partition from Clusters[i..j].
9379       uint64_t Range = getJumpTableRange(Clusters, i, j);
9380       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9381       assert(NumCases < UINT64_MAX / 100);
9382       assert(Range >= NumCases);
9383       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9384         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9385         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9386         int64_t NumEntries = j - i + 1;
9387 
9388         if (NumEntries == 1)
9389           Score += PartitionScores::SingleCase;
9390         else if (NumEntries <= SmallNumberOfEntries)
9391           Score += PartitionScores::FewCases;
9392         else if (NumEntries >= MinJumpTableEntries)
9393           Score += PartitionScores::Table;
9394 
9395         // If this leads to fewer partitions, or to the same number of
9396         // partitions with better score, it is a better partitioning.
9397         if (NumPartitions < MinPartitions[i] ||
9398             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9399           MinPartitions[i] = NumPartitions;
9400           LastElement[i] = j;
9401           PartitionsScore[i] = Score;
9402         }
9403       }
9404     }
9405   }
9406 
9407   // Iterate over the partitions, replacing some with jump tables in-place.
9408   unsigned DstIndex = 0;
9409   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9410     Last = LastElement[First];
9411     assert(Last >= First);
9412     assert(DstIndex <= First);
9413     unsigned NumClusters = Last - First + 1;
9414 
9415     CaseCluster JTCluster;
9416     if (NumClusters >= MinJumpTableEntries &&
9417         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9418       Clusters[DstIndex++] = JTCluster;
9419     } else {
9420       for (unsigned I = First; I <= Last; ++I)
9421         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9422     }
9423   }
9424   Clusters.resize(DstIndex);
9425 }
9426 
9427 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9428                                         unsigned First, unsigned Last,
9429                                         const SwitchInst *SI,
9430                                         CaseCluster &BTCluster) {
9431   assert(First <= Last);
9432   if (First == Last)
9433     return false;
9434 
9435   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9436   unsigned NumCmps = 0;
9437   for (int64_t I = First; I <= Last; ++I) {
9438     assert(Clusters[I].Kind == CC_Range);
9439     Dests.set(Clusters[I].MBB->getNumber());
9440     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9441   }
9442   unsigned NumDests = Dests.count();
9443 
9444   APInt Low = Clusters[First].Low->getValue();
9445   APInt High = Clusters[Last].High->getValue();
9446   assert(Low.slt(High));
9447 
9448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9449   const DataLayout &DL = DAG.getDataLayout();
9450   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9451     return false;
9452 
9453   APInt LowBound;
9454   APInt CmpRange;
9455 
9456   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9457   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9458          "Case range must fit in bit mask!");
9459 
9460   // Check if the clusters cover a contiguous range such that no value in the
9461   // range will jump to the default statement.
9462   bool ContiguousRange = true;
9463   for (int64_t I = First + 1; I <= Last; ++I) {
9464     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9465       ContiguousRange = false;
9466       break;
9467     }
9468   }
9469 
9470   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9471     // Optimize the case where all the case values fit in a word without having
9472     // to subtract minValue. In this case, we can optimize away the subtraction.
9473     LowBound = APInt::getNullValue(Low.getBitWidth());
9474     CmpRange = High;
9475     ContiguousRange = false;
9476   } else {
9477     LowBound = Low;
9478     CmpRange = High - Low;
9479   }
9480 
9481   CaseBitsVector CBV;
9482   auto TotalProb = BranchProbability::getZero();
9483   for (unsigned i = First; i <= Last; ++i) {
9484     // Find the CaseBits for this destination.
9485     unsigned j;
9486     for (j = 0; j < CBV.size(); ++j)
9487       if (CBV[j].BB == Clusters[i].MBB)
9488         break;
9489     if (j == CBV.size())
9490       CBV.push_back(
9491           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9492     CaseBits *CB = &CBV[j];
9493 
9494     // Update Mask, Bits and ExtraProb.
9495     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9496     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9497     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9498     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9499     CB->Bits += Hi - Lo + 1;
9500     CB->ExtraProb += Clusters[i].Prob;
9501     TotalProb += Clusters[i].Prob;
9502   }
9503 
9504   BitTestInfo BTI;
9505   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9506     // Sort by probability first, number of bits second, bit mask third.
9507     if (a.ExtraProb != b.ExtraProb)
9508       return a.ExtraProb > b.ExtraProb;
9509     if (a.Bits != b.Bits)
9510       return a.Bits > b.Bits;
9511     return a.Mask < b.Mask;
9512   });
9513 
9514   for (auto &CB : CBV) {
9515     MachineBasicBlock *BitTestBB =
9516         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9517     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9518   }
9519   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9520                             SI->getCondition(), -1U, MVT::Other, false,
9521                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9522                             TotalProb);
9523 
9524   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9525                                     BitTestCases.size() - 1, TotalProb);
9526   return true;
9527 }
9528 
9529 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9530                                               const SwitchInst *SI) {
9531 // Partition Clusters into as few subsets as possible, where each subset has a
9532 // range that fits in a machine word and has <= 3 unique destinations.
9533 
9534 #ifndef NDEBUG
9535   // Clusters must be sorted and contain Range or JumpTable clusters.
9536   assert(!Clusters.empty());
9537   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9538   for (const CaseCluster &C : Clusters)
9539     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9540   for (unsigned i = 1; i < Clusters.size(); ++i)
9541     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9542 #endif
9543 
9544   // The algorithm below is not suitable for -O0.
9545   if (TM.getOptLevel() == CodeGenOpt::None)
9546     return;
9547 
9548   // If target does not have legal shift left, do not emit bit tests at all.
9549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9550   const DataLayout &DL = DAG.getDataLayout();
9551 
9552   EVT PTy = TLI.getPointerTy(DL);
9553   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9554     return;
9555 
9556   int BitWidth = PTy.getSizeInBits();
9557   const int64_t N = Clusters.size();
9558 
9559   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9560   SmallVector<unsigned, 8> MinPartitions(N);
9561   // LastElement[i] is the last element of the partition starting at i.
9562   SmallVector<unsigned, 8> LastElement(N);
9563 
9564   // FIXME: This might not be the best algorithm for finding bit test clusters.
9565 
9566   // Base case: There is only one way to partition Clusters[N-1].
9567   MinPartitions[N - 1] = 1;
9568   LastElement[N - 1] = N - 1;
9569 
9570   // Note: loop indexes are signed to avoid underflow.
9571   for (int64_t i = N - 2; i >= 0; --i) {
9572     // Find optimal partitioning of Clusters[i..N-1].
9573     // Baseline: Put Clusters[i] into a partition on its own.
9574     MinPartitions[i] = MinPartitions[i + 1] + 1;
9575     LastElement[i] = i;
9576 
9577     // Search for a solution that results in fewer partitions.
9578     // Note: the search is limited by BitWidth, reducing time complexity.
9579     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9580       // Try building a partition from Clusters[i..j].
9581 
9582       // Check the range.
9583       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9584                                Clusters[j].High->getValue(), DL))
9585         continue;
9586 
9587       // Check nbr of destinations and cluster types.
9588       // FIXME: This works, but doesn't seem very efficient.
9589       bool RangesOnly = true;
9590       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9591       for (int64_t k = i; k <= j; k++) {
9592         if (Clusters[k].Kind != CC_Range) {
9593           RangesOnly = false;
9594           break;
9595         }
9596         Dests.set(Clusters[k].MBB->getNumber());
9597       }
9598       if (!RangesOnly || Dests.count() > 3)
9599         break;
9600 
9601       // Check if it's a better partition.
9602       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9603       if (NumPartitions < MinPartitions[i]) {
9604         // Found a better partition.
9605         MinPartitions[i] = NumPartitions;
9606         LastElement[i] = j;
9607       }
9608     }
9609   }
9610 
9611   // Iterate over the partitions, replacing with bit-test clusters in-place.
9612   unsigned DstIndex = 0;
9613   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9614     Last = LastElement[First];
9615     assert(First <= Last);
9616     assert(DstIndex <= First);
9617 
9618     CaseCluster BitTestCluster;
9619     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9620       Clusters[DstIndex++] = BitTestCluster;
9621     } else {
9622       size_t NumClusters = Last - First + 1;
9623       std::memmove(&Clusters[DstIndex], &Clusters[First],
9624                    sizeof(Clusters[0]) * NumClusters);
9625       DstIndex += NumClusters;
9626     }
9627   }
9628   Clusters.resize(DstIndex);
9629 }
9630 
9631 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9632                                         MachineBasicBlock *SwitchMBB,
9633                                         MachineBasicBlock *DefaultMBB) {
9634   MachineFunction *CurMF = FuncInfo.MF;
9635   MachineBasicBlock *NextMBB = nullptr;
9636   MachineFunction::iterator BBI(W.MBB);
9637   if (++BBI != FuncInfo.MF->end())
9638     NextMBB = &*BBI;
9639 
9640   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9641 
9642   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9643 
9644   if (Size == 2 && W.MBB == SwitchMBB) {
9645     // If any two of the cases has the same destination, and if one value
9646     // is the same as the other, but has one bit unset that the other has set,
9647     // use bit manipulation to do two compares at once.  For example:
9648     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9649     // TODO: This could be extended to merge any 2 cases in switches with 3
9650     // cases.
9651     // TODO: Handle cases where W.CaseBB != SwitchBB.
9652     CaseCluster &Small = *W.FirstCluster;
9653     CaseCluster &Big = *W.LastCluster;
9654 
9655     if (Small.Low == Small.High && Big.Low == Big.High &&
9656         Small.MBB == Big.MBB) {
9657       const APInt &SmallValue = Small.Low->getValue();
9658       const APInt &BigValue = Big.Low->getValue();
9659 
9660       // Check that there is only one bit different.
9661       APInt CommonBit = BigValue ^ SmallValue;
9662       if (CommonBit.isPowerOf2()) {
9663         SDValue CondLHS = getValue(Cond);
9664         EVT VT = CondLHS.getValueType();
9665         SDLoc DL = getCurSDLoc();
9666 
9667         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9668                                  DAG.getConstant(CommonBit, DL, VT));
9669         SDValue Cond = DAG.getSetCC(
9670             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9671             ISD::SETEQ);
9672 
9673         // Update successor info.
9674         // Both Small and Big will jump to Small.BB, so we sum up the
9675         // probabilities.
9676         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9677         if (BPI)
9678           addSuccessorWithProb(
9679               SwitchMBB, DefaultMBB,
9680               // The default destination is the first successor in IR.
9681               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9682         else
9683           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9684 
9685         // Insert the true branch.
9686         SDValue BrCond =
9687             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9688                         DAG.getBasicBlock(Small.MBB));
9689         // Insert the false branch.
9690         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9691                              DAG.getBasicBlock(DefaultMBB));
9692 
9693         DAG.setRoot(BrCond);
9694         return;
9695       }
9696     }
9697   }
9698 
9699   if (TM.getOptLevel() != CodeGenOpt::None) {
9700     // Here, we order cases by probability so the most likely case will be
9701     // checked first. However, two clusters can have the same probability in
9702     // which case their relative ordering is non-deterministic. So we use Low
9703     // as a tie-breaker as clusters are guaranteed to never overlap.
9704     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9705                [](const CaseCluster &a, const CaseCluster &b) {
9706       return a.Prob != b.Prob ?
9707              a.Prob > b.Prob :
9708              a.Low->getValue().slt(b.Low->getValue());
9709     });
9710 
9711     // Rearrange the case blocks so that the last one falls through if possible
9712     // without changing the order of probabilities.
9713     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9714       --I;
9715       if (I->Prob > W.LastCluster->Prob)
9716         break;
9717       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9718         std::swap(*I, *W.LastCluster);
9719         break;
9720       }
9721     }
9722   }
9723 
9724   // Compute total probability.
9725   BranchProbability DefaultProb = W.DefaultProb;
9726   BranchProbability UnhandledProbs = DefaultProb;
9727   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9728     UnhandledProbs += I->Prob;
9729 
9730   MachineBasicBlock *CurMBB = W.MBB;
9731   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9732     MachineBasicBlock *Fallthrough;
9733     if (I == W.LastCluster) {
9734       // For the last cluster, fall through to the default destination.
9735       Fallthrough = DefaultMBB;
9736     } else {
9737       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9738       CurMF->insert(BBI, Fallthrough);
9739       // Put Cond in a virtual register to make it available from the new blocks.
9740       ExportFromCurrentBlock(Cond);
9741     }
9742     UnhandledProbs -= I->Prob;
9743 
9744     switch (I->Kind) {
9745       case CC_JumpTable: {
9746         // FIXME: Optimize away range check based on pivot comparisons.
9747         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9748         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9749 
9750         // The jump block hasn't been inserted yet; insert it here.
9751         MachineBasicBlock *JumpMBB = JT->MBB;
9752         CurMF->insert(BBI, JumpMBB);
9753 
9754         auto JumpProb = I->Prob;
9755         auto FallthroughProb = UnhandledProbs;
9756 
9757         // If the default statement is a target of the jump table, we evenly
9758         // distribute the default probability to successors of CurMBB. Also
9759         // update the probability on the edge from JumpMBB to Fallthrough.
9760         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9761                                               SE = JumpMBB->succ_end();
9762              SI != SE; ++SI) {
9763           if (*SI == DefaultMBB) {
9764             JumpProb += DefaultProb / 2;
9765             FallthroughProb -= DefaultProb / 2;
9766             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9767             JumpMBB->normalizeSuccProbs();
9768             break;
9769           }
9770         }
9771 
9772         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9773         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9774         CurMBB->normalizeSuccProbs();
9775 
9776         // The jump table header will be inserted in our current block, do the
9777         // range check, and fall through to our fallthrough block.
9778         JTH->HeaderBB = CurMBB;
9779         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9780 
9781         // If we're in the right place, emit the jump table header right now.
9782         if (CurMBB == SwitchMBB) {
9783           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9784           JTH->Emitted = true;
9785         }
9786         break;
9787       }
9788       case CC_BitTests: {
9789         // FIXME: Optimize away range check based on pivot comparisons.
9790         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9791 
9792         // The bit test blocks haven't been inserted yet; insert them here.
9793         for (BitTestCase &BTC : BTB->Cases)
9794           CurMF->insert(BBI, BTC.ThisBB);
9795 
9796         // Fill in fields of the BitTestBlock.
9797         BTB->Parent = CurMBB;
9798         BTB->Default = Fallthrough;
9799 
9800         BTB->DefaultProb = UnhandledProbs;
9801         // If the cases in bit test don't form a contiguous range, we evenly
9802         // distribute the probability on the edge to Fallthrough to two
9803         // successors of CurMBB.
9804         if (!BTB->ContiguousRange) {
9805           BTB->Prob += DefaultProb / 2;
9806           BTB->DefaultProb -= DefaultProb / 2;
9807         }
9808 
9809         // If we're in the right place, emit the bit test header right now.
9810         if (CurMBB == SwitchMBB) {
9811           visitBitTestHeader(*BTB, SwitchMBB);
9812           BTB->Emitted = true;
9813         }
9814         break;
9815       }
9816       case CC_Range: {
9817         const Value *RHS, *LHS, *MHS;
9818         ISD::CondCode CC;
9819         if (I->Low == I->High) {
9820           // Check Cond == I->Low.
9821           CC = ISD::SETEQ;
9822           LHS = Cond;
9823           RHS=I->Low;
9824           MHS = nullptr;
9825         } else {
9826           // Check I->Low <= Cond <= I->High.
9827           CC = ISD::SETLE;
9828           LHS = I->Low;
9829           MHS = Cond;
9830           RHS = I->High;
9831         }
9832 
9833         // The false probability is the sum of all unhandled cases.
9834         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9835                      getCurSDLoc(), I->Prob, UnhandledProbs);
9836 
9837         if (CurMBB == SwitchMBB)
9838           visitSwitchCase(CB, SwitchMBB);
9839         else
9840           SwitchCases.push_back(CB);
9841 
9842         break;
9843       }
9844     }
9845     CurMBB = Fallthrough;
9846   }
9847 }
9848 
9849 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9850                                               CaseClusterIt First,
9851                                               CaseClusterIt Last) {
9852   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9853     if (X.Prob != CC.Prob)
9854       return X.Prob > CC.Prob;
9855 
9856     // Ties are broken by comparing the case value.
9857     return X.Low->getValue().slt(CC.Low->getValue());
9858   });
9859 }
9860 
9861 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9862                                         const SwitchWorkListItem &W,
9863                                         Value *Cond,
9864                                         MachineBasicBlock *SwitchMBB) {
9865   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9866          "Clusters not sorted?");
9867 
9868   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9869 
9870   // Balance the tree based on branch probabilities to create a near-optimal (in
9871   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9872   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9873   CaseClusterIt LastLeft = W.FirstCluster;
9874   CaseClusterIt FirstRight = W.LastCluster;
9875   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9876   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9877 
9878   // Move LastLeft and FirstRight towards each other from opposite directions to
9879   // find a partitioning of the clusters which balances the probability on both
9880   // sides. If LeftProb and RightProb are equal, alternate which side is
9881   // taken to ensure 0-probability nodes are distributed evenly.
9882   unsigned I = 0;
9883   while (LastLeft + 1 < FirstRight) {
9884     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9885       LeftProb += (++LastLeft)->Prob;
9886     else
9887       RightProb += (--FirstRight)->Prob;
9888     I++;
9889   }
9890 
9891   while (true) {
9892     // Our binary search tree differs from a typical BST in that ours can have up
9893     // to three values in each leaf. The pivot selection above doesn't take that
9894     // into account, which means the tree might require more nodes and be less
9895     // efficient. We compensate for this here.
9896 
9897     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9898     unsigned NumRight = W.LastCluster - FirstRight + 1;
9899 
9900     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9901       // If one side has less than 3 clusters, and the other has more than 3,
9902       // consider taking a cluster from the other side.
9903 
9904       if (NumLeft < NumRight) {
9905         // Consider moving the first cluster on the right to the left side.
9906         CaseCluster &CC = *FirstRight;
9907         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9908         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9909         if (LeftSideRank <= RightSideRank) {
9910           // Moving the cluster to the left does not demote it.
9911           ++LastLeft;
9912           ++FirstRight;
9913           continue;
9914         }
9915       } else {
9916         assert(NumRight < NumLeft);
9917         // Consider moving the last element on the left to the right side.
9918         CaseCluster &CC = *LastLeft;
9919         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9920         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9921         if (RightSideRank <= LeftSideRank) {
9922           // Moving the cluster to the right does not demot it.
9923           --LastLeft;
9924           --FirstRight;
9925           continue;
9926         }
9927       }
9928     }
9929     break;
9930   }
9931 
9932   assert(LastLeft + 1 == FirstRight);
9933   assert(LastLeft >= W.FirstCluster);
9934   assert(FirstRight <= W.LastCluster);
9935 
9936   // Use the first element on the right as pivot since we will make less-than
9937   // comparisons against it.
9938   CaseClusterIt PivotCluster = FirstRight;
9939   assert(PivotCluster > W.FirstCluster);
9940   assert(PivotCluster <= W.LastCluster);
9941 
9942   CaseClusterIt FirstLeft = W.FirstCluster;
9943   CaseClusterIt LastRight = W.LastCluster;
9944 
9945   const ConstantInt *Pivot = PivotCluster->Low;
9946 
9947   // New blocks will be inserted immediately after the current one.
9948   MachineFunction::iterator BBI(W.MBB);
9949   ++BBI;
9950 
9951   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9952   // we can branch to its destination directly if it's squeezed exactly in
9953   // between the known lower bound and Pivot - 1.
9954   MachineBasicBlock *LeftMBB;
9955   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9956       FirstLeft->Low == W.GE &&
9957       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9958     LeftMBB = FirstLeft->MBB;
9959   } else {
9960     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9961     FuncInfo.MF->insert(BBI, LeftMBB);
9962     WorkList.push_back(
9963         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9964     // Put Cond in a virtual register to make it available from the new blocks.
9965     ExportFromCurrentBlock(Cond);
9966   }
9967 
9968   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9969   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9970   // directly if RHS.High equals the current upper bound.
9971   MachineBasicBlock *RightMBB;
9972   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9973       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9974     RightMBB = FirstRight->MBB;
9975   } else {
9976     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9977     FuncInfo.MF->insert(BBI, RightMBB);
9978     WorkList.push_back(
9979         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9980     // Put Cond in a virtual register to make it available from the new blocks.
9981     ExportFromCurrentBlock(Cond);
9982   }
9983 
9984   // Create the CaseBlock record that will be used to lower the branch.
9985   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9986                getCurSDLoc(), LeftProb, RightProb);
9987 
9988   if (W.MBB == SwitchMBB)
9989     visitSwitchCase(CB, SwitchMBB);
9990   else
9991     SwitchCases.push_back(CB);
9992 }
9993 
9994 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
9995 // from the swith statement.
9996 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
9997                                             BranchProbability PeeledCaseProb) {
9998   if (PeeledCaseProb == BranchProbability::getOne())
9999     return BranchProbability::getZero();
10000   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10001 
10002   uint32_t Numerator = CaseProb.getNumerator();
10003   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10004   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10005 }
10006 
10007 // Try to peel the top probability case if it exceeds the threshold.
10008 // Return current MachineBasicBlock for the switch statement if the peeling
10009 // does not occur.
10010 // If the peeling is performed, return the newly created MachineBasicBlock
10011 // for the peeled switch statement. Also update Clusters to remove the peeled
10012 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10013 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10014     const SwitchInst &SI, CaseClusterVector &Clusters,
10015     BranchProbability &PeeledCaseProb) {
10016   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10017   // Don't perform if there is only one cluster or optimizing for size.
10018   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10019       TM.getOptLevel() == CodeGenOpt::None ||
10020       SwitchMBB->getParent()->getFunction().optForMinSize())
10021     return SwitchMBB;
10022 
10023   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10024   unsigned PeeledCaseIndex = 0;
10025   bool SwitchPeeled = false;
10026   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10027     CaseCluster &CC = Clusters[Index];
10028     if (CC.Prob < TopCaseProb)
10029       continue;
10030     TopCaseProb = CC.Prob;
10031     PeeledCaseIndex = Index;
10032     SwitchPeeled = true;
10033   }
10034   if (!SwitchPeeled)
10035     return SwitchMBB;
10036 
10037   DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
10038                << "\n");
10039 
10040   // Record the MBB for the peeled switch statement.
10041   MachineFunction::iterator BBI(SwitchMBB);
10042   ++BBI;
10043   MachineBasicBlock *PeeledSwitchMBB =
10044       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10045   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10046 
10047   ExportFromCurrentBlock(SI.getCondition());
10048   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10049   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10050                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10051   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10052 
10053   Clusters.erase(PeeledCaseIt);
10054   for (CaseCluster &CC : Clusters) {
10055     DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
10056                  << CC.Prob << "\n");
10057     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10058     DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10059   }
10060   PeeledCaseProb = TopCaseProb;
10061   return PeeledSwitchMBB;
10062 }
10063 
10064 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10065   // Extract cases from the switch.
10066   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10067   CaseClusterVector Clusters;
10068   Clusters.reserve(SI.getNumCases());
10069   for (auto I : SI.cases()) {
10070     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10071     const ConstantInt *CaseVal = I.getCaseValue();
10072     BranchProbability Prob =
10073         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10074             : BranchProbability(1, SI.getNumCases() + 1);
10075     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10076   }
10077 
10078   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10079 
10080   // Cluster adjacent cases with the same destination. We do this at all
10081   // optimization levels because it's cheap to do and will make codegen faster
10082   // if there are many clusters.
10083   sortAndRangeify(Clusters);
10084 
10085   if (TM.getOptLevel() != CodeGenOpt::None) {
10086     // Replace an unreachable default with the most popular destination.
10087     // FIXME: Exploit unreachable default more aggressively.
10088     bool UnreachableDefault =
10089         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10090     if (UnreachableDefault && !Clusters.empty()) {
10091       DenseMap<const BasicBlock *, unsigned> Popularity;
10092       unsigned MaxPop = 0;
10093       const BasicBlock *MaxBB = nullptr;
10094       for (auto I : SI.cases()) {
10095         const BasicBlock *BB = I.getCaseSuccessor();
10096         if (++Popularity[BB] > MaxPop) {
10097           MaxPop = Popularity[BB];
10098           MaxBB = BB;
10099         }
10100       }
10101       // Set new default.
10102       assert(MaxPop > 0 && MaxBB);
10103       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10104 
10105       // Remove cases that were pointing to the destination that is now the
10106       // default.
10107       CaseClusterVector New;
10108       New.reserve(Clusters.size());
10109       for (CaseCluster &CC : Clusters) {
10110         if (CC.MBB != DefaultMBB)
10111           New.push_back(CC);
10112       }
10113       Clusters = std::move(New);
10114     }
10115   }
10116 
10117   // The branch probablity of the peeled case.
10118   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10119   MachineBasicBlock *PeeledSwitchMBB =
10120       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10121 
10122   // If there is only the default destination, jump there directly.
10123   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10124   if (Clusters.empty()) {
10125     assert(PeeledSwitchMBB == SwitchMBB);
10126     SwitchMBB->addSuccessor(DefaultMBB);
10127     if (DefaultMBB != NextBlock(SwitchMBB)) {
10128       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10129                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10130     }
10131     return;
10132   }
10133 
10134   findJumpTables(Clusters, &SI, DefaultMBB);
10135   findBitTestClusters(Clusters, &SI);
10136 
10137   DEBUG({
10138     dbgs() << "Case clusters: ";
10139     for (const CaseCluster &C : Clusters) {
10140       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
10141       if (C.Kind == CC_BitTests) dbgs() << "BT:";
10142 
10143       C.Low->getValue().print(dbgs(), true);
10144       if (C.Low != C.High) {
10145         dbgs() << '-';
10146         C.High->getValue().print(dbgs(), true);
10147       }
10148       dbgs() << ' ';
10149     }
10150     dbgs() << '\n';
10151   });
10152 
10153   assert(!Clusters.empty());
10154   SwitchWorkList WorkList;
10155   CaseClusterIt First = Clusters.begin();
10156   CaseClusterIt Last = Clusters.end() - 1;
10157   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10158   // Scale the branchprobability for DefaultMBB if the peel occurs and
10159   // DefaultMBB is not replaced.
10160   if (PeeledCaseProb != BranchProbability::getZero() &&
10161       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10162     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10163   WorkList.push_back(
10164       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10165 
10166   while (!WorkList.empty()) {
10167     SwitchWorkListItem W = WorkList.back();
10168     WorkList.pop_back();
10169     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10170 
10171     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10172         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10173       // For optimized builds, lower large range as a balanced binary tree.
10174       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10175       continue;
10176     }
10177 
10178     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10179   }
10180 }
10181