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