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