xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision fb0ccff6e56bde6c42b2ff941861564e24a7a805)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.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/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(
442           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
443           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
444     }
445 
446     // Vector/Vector bitcast.
447     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
448       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
449 
450     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
451       "Cannot handle this kind of promotion");
452     // Promoted vector extract
453     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
454 
455   }
456 
457   // Trivial bitcast if the types are the same size and the destination
458   // vector type is legal.
459   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
460       TLI.isTypeLegal(ValueVT))
461     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462 
463   if (ValueVT.getVectorNumElements() != 1) {
464      // Certain ABIs require that vectors are passed as integers. For vectors
465      // are the same size, this is an obvious bitcast.
466      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
467        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
468      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
469        // Bitcast Val back the original type and extract the corresponding
470        // vector we want.
471        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
472        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
473                                            ValueVT.getVectorElementType(), Elts);
474        Val = DAG.getBitcast(WiderVecType, Val);
475        return DAG.getNode(
476            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
478      }
479 
480      diagnosePossiblyInvalidConstraint(
481          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482      return DAG.getUNDEF(ValueVT);
483   }
484 
485   // Handle cases such as i8 -> <1 x i1>
486   EVT ValueSVT = ValueVT.getVectorElementType();
487   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
488     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  Optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
503                            SDValue *Parts, unsigned NumParts, MVT PartVT,
504                            const Value *V,
505                            Optional<CallingConv::ID> CallConv = None,
506                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   EVT ValueVT = Val.getValueType();
508 
509   // Handle the vector case separately.
510   if (ValueVT.isVector())
511     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
512                                 CallConv);
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   unsigned OrigNumParts = NumParts;
516   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
517          "Copying to an illegal type!");
518 
519   if (NumParts == 0)
520     return;
521 
522   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
523   EVT PartEVT = PartVT;
524   if (PartEVT == ValueVT) {
525     assert(NumParts == 1 && "No-op copy with multiple parts!");
526     Parts[0] = Val;
527     return;
528   }
529 
530   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
531     // If the parts cover more bits than the value has, promote the value.
532     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
533       assert(NumParts == 1 && "Do not know what to promote to!");
534       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
535     } else {
536       if (ValueVT.isFloatingPoint()) {
537         // FP values need to be bitcast, then extended if they are being put
538         // into a larger container.
539         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
540         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
541       }
542       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543              ValueVT.isInteger() &&
544              "Unknown mismatch!");
545       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
547       if (PartVT == MVT::x86mmx)
548         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549     }
550   } else if (PartBits == ValueVT.getSizeInBits()) {
551     // Different types of the same size.
552     assert(NumParts == 1 && PartEVT != ValueVT);
553     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555     // If the parts cover less bits than value has, truncate the value.
556     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
557            ValueVT.isInteger() &&
558            "Unknown mismatch!");
559     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
561     if (PartVT == MVT::x86mmx)
562       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   }
564 
565   // The value may have changed - recompute ValueVT.
566   ValueVT = Val.getValueType();
567   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568          "Failed to tile the value with PartVT!");
569 
570   if (NumParts == 1) {
571     if (PartEVT != ValueVT) {
572       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
573                                         "scalar-to-vector conversion failed");
574       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575     }
576 
577     Parts[0] = Val;
578     return;
579   }
580 
581   // Expand the value into multiple parts.
582   if (NumParts & (NumParts - 1)) {
583     // The number of parts is not a power of 2.  Split off and copy the tail.
584     assert(PartVT.isInteger() && ValueVT.isInteger() &&
585            "Do not know what to expand to!");
586     unsigned RoundParts = 1 << Log2_32(NumParts);
587     unsigned RoundBits = RoundParts * PartBits;
588     unsigned OddParts = NumParts - RoundParts;
589     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
590       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
591 
592     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
593                    CallConv);
594 
595     if (DAG.getDataLayout().isBigEndian())
596       // The odd parts were reversed by getCopyToParts - unreverse them.
597       std::reverse(Parts + RoundParts, Parts + NumParts);
598 
599     NumParts = RoundParts;
600     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
601     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
602   }
603 
604   // The number of parts is a power of 2.  Repeatedly bisect the value using
605   // EXTRACT_ELEMENT.
606   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
607                          EVT::getIntegerVT(*DAG.getContext(),
608                                            ValueVT.getSizeInBits()),
609                          Val);
610 
611   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
612     for (unsigned i = 0; i < NumParts; i += StepSize) {
613       unsigned ThisBits = StepSize * PartBits / 2;
614       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
615       SDValue &Part0 = Parts[i];
616       SDValue &Part1 = Parts[i+StepSize/2];
617 
618       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
620       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
621                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
622 
623       if (ThisBits == PartBits && ThisVT != PartVT) {
624         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
625         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626       }
627     }
628   }
629 
630   if (DAG.getDataLayout().isBigEndian())
631     std::reverse(Parts, Parts + OrigNumParts);
632 }
633 
634 static SDValue widenVectorToPartType(SelectionDAG &DAG,
635                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
636   if (!PartVT.isVector())
637     return SDValue();
638 
639   EVT ValueVT = Val.getValueType();
640   unsigned PartNumElts = PartVT.getVectorNumElements();
641   unsigned ValueNumElts = ValueVT.getVectorNumElements();
642   if (PartNumElts > ValueNumElts &&
643       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
644     EVT ElementVT = PartVT.getVectorElementType();
645     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
646     // undef elements.
647     SmallVector<SDValue, 16> Ops;
648     DAG.ExtractVectorElements(Val, Ops);
649     SDValue EltUndef = DAG.getUNDEF(ElementVT);
650     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
651       Ops.push_back(EltUndef);
652 
653     // FIXME: Use CONCAT for 2x -> 4x.
654     return DAG.getBuildVector(PartVT, DL, Ops);
655   }
656 
657   return SDValue();
658 }
659 
660 /// getCopyToPartsVector - Create a series of nodes that contain the specified
661 /// value split into legal parts.
662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
663                                  SDValue Val, SDValue *Parts, unsigned NumParts,
664                                  MVT PartVT, const Value *V,
665                                  Optional<CallingConv::ID> CallConv) {
666   EVT ValueVT = Val.getValueType();
667   assert(ValueVT.isVector() && "Not a vector");
668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
669   const bool IsABIRegCopy = CallConv.hasValue();
670 
671   if (NumParts == 1) {
672     EVT PartEVT = PartVT;
673     if (PartEVT == ValueVT) {
674       // Nothing to do.
675     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
676       // Bitconvert vector->vector case.
677       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
678     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
679       Val = Widened;
680     } else if (PartVT.isVector() &&
681                PartEVT.getVectorElementType().bitsGE(
682                  ValueVT.getVectorElementType()) &&
683                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
684 
685       // Promoted vector extract
686       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorNumElements() == 1) {
689         Val = DAG.getNode(
690             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
691             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
692       } else {
693         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType =
696             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
697         Val = DAG.getBitcast(IntermediateType, Val);
698         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
699       }
700     }
701 
702     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703     Parts[0] = Val;
704     return;
705   }
706 
707   // Handle a multi-element vector.
708   EVT IntermediateVT;
709   MVT RegisterVT;
710   unsigned NumIntermediates;
711   unsigned NumRegs;
712   if (IsABIRegCopy) {
713     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
714         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
715         NumIntermediates, RegisterVT);
716   } else {
717     NumRegs =
718         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
719                                    NumIntermediates, RegisterVT);
720   }
721 
722   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
723   NumParts = NumRegs; // Silence a compiler warning.
724   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
725 
726   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
727     IntermediateVT.getVectorNumElements() : 1;
728 
729   // Convert the vector to the appropriate type if necessary.
730   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
731 
732   EVT BuiltVectorTy = EVT::getVectorVT(
733       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
734   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
735   if (ValueVT != BuiltVectorTy) {
736     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
737       Val = Widened;
738 
739     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
740   }
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
747                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
748     } else {
749       Ops[i] = DAG.getNode(
750           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
751           DAG.getConstant(i, DL, IdxVT));
752     }
753   }
754 
755   // Split the intermediate operands into legal parts.
756   if (NumParts == NumIntermediates) {
757     // If the register was not expanded, promote or copy the value,
758     // as appropriate.
759     for (unsigned i = 0; i != NumParts; ++i)
760       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
761   } else if (NumParts > 0) {
762     // If the intermediate type was expanded, split each the value into
763     // legal parts.
764     assert(NumIntermediates != 0 && "division by zero");
765     assert(NumParts % NumIntermediates == 0 &&
766            "Must expand into a divisible number of parts!");
767     unsigned Factor = NumParts / NumIntermediates;
768     for (unsigned i = 0; i != NumIntermediates; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770                      CallConv);
771   }
772 }
773 
774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
775                            EVT valuevt, Optional<CallingConv::ID> CC)
776     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
777       RegCount(1, regs.size()), CallConv(CC) {}
778 
779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
780                            const DataLayout &DL, unsigned Reg, Type *Ty,
781                            Optional<CallingConv::ID> CC) {
782   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
783 
784   CallConv = CC;
785 
786   for (EVT ValueVT : ValueVTs) {
787     unsigned NumRegs =
788         isABIMangled()
789             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getNumRegisters(Context, ValueVT);
791     MVT RegisterVT =
792         isABIMangled()
793             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getRegisterType(Context, ValueVT);
795     for (unsigned i = 0; i != NumRegs; ++i)
796       Regs.push_back(Reg + i);
797     RegVTs.push_back(RegisterVT);
798     RegCount.push_back(NumRegs);
799     Reg += NumRegs;
800   }
801 }
802 
803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
804                                       FunctionLoweringInfo &FuncInfo,
805                                       const SDLoc &dl, SDValue &Chain,
806                                       SDValue *Flag, const Value *V) const {
807   // A Value with type {} or [0 x %t] needs no registers.
808   if (ValueVTs.empty())
809     return SDValue();
810 
811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
812 
813   // Assemble the legal parts into the final values.
814   SmallVector<SDValue, 4> Values(ValueVTs.size());
815   SmallVector<SDValue, 8> Parts;
816   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
817     // Copy the legal parts from the registers.
818     EVT ValueVT = ValueVTs[Value];
819     unsigned NumRegs = RegCount[Value];
820     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
821                                           *DAG.getContext(),
822                                           CallConv.getValue(), RegVTs[Value])
823                                     : RegVTs[Value];
824 
825     Parts.resize(NumRegs);
826     for (unsigned i = 0; i != NumRegs; ++i) {
827       SDValue P;
828       if (!Flag) {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
830       } else {
831         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
832         *Flag = P.getValue(2);
833       }
834 
835       Chain = P.getValue(1);
836       Parts[i] = P;
837 
838       // If the source register was virtual and if we know something about it,
839       // add an assert node.
840       if (!Register::isVirtualRegister(Regs[Part + i]) ||
841           !RegisterVT.isInteger())
842         continue;
843 
844       const FunctionLoweringInfo::LiveOutInfo *LOI =
845         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
846       if (!LOI)
847         continue;
848 
849       unsigned RegSize = RegisterVT.getScalarSizeInBits();
850       unsigned NumSignBits = LOI->NumSignBits;
851       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
852 
853       if (NumZeroBits == RegSize) {
854         // The current value is a zero.
855         // Explicitly express that as it would be easier for
856         // optimizations to kick in.
857         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
858         continue;
859       }
860 
861       // FIXME: We capture more information than the dag can represent.  For
862       // now, just use the tightest assertzext/assertsext possible.
863       bool isSExt;
864       EVT FromVT(MVT::Other);
865       if (NumZeroBits) {
866         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
867         isSExt = false;
868       } else if (NumSignBits > 1) {
869         FromVT =
870             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871         isSExt = true;
872       } else {
873         continue;
874       }
875       // Add an assertion node.
876       assert(FromVT != MVT::Other);
877       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
878                              RegisterVT, P, DAG.getValueType(FromVT));
879     }
880 
881     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
882                                      RegisterVT, ValueVT, V, CallConv);
883     Part += NumRegs;
884     Parts.clear();
885   }
886 
887   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
888 }
889 
890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
891                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
892                                  const Value *V,
893                                  ISD::NodeType PreferredExtendType) const {
894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
895   ISD::NodeType ExtendKind = PreferredExtendType;
896 
897   // Get the list of the values's legal parts.
898   unsigned NumRegs = Regs.size();
899   SmallVector<SDValue, 8> Parts(NumRegs);
900   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
901     unsigned NumParts = RegCount[Value];
902 
903     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
904                                           *DAG.getContext(),
905                                           CallConv.getValue(), RegVTs[Value])
906                                     : RegVTs[Value];
907 
908     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
909       ExtendKind = ISD::ZERO_EXTEND;
910 
911     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
912                    NumParts, RegisterVT, V, CallConv, ExtendKind);
913     Part += NumParts;
914   }
915 
916   // Copy the parts into the registers.
917   SmallVector<SDValue, 8> Chains(NumRegs);
918   for (unsigned i = 0; i != NumRegs; ++i) {
919     SDValue Part;
920     if (!Flag) {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
922     } else {
923       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
924       *Flag = Part.getValue(1);
925     }
926 
927     Chains[i] = Part.getValue(0);
928   }
929 
930   if (NumRegs == 1 || Flag)
931     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
932     // flagged to it. That is the CopyToReg nodes and the user are considered
933     // a single scheduling unit. If we create a TokenFactor and return it as
934     // chain, then the TokenFactor is both a predecessor (operand) of the
935     // user as well as a successor (the TF operands are flagged to the user).
936     // c1, f1 = CopyToReg
937     // c2, f2 = CopyToReg
938     // c3     = TokenFactor c1, c2
939     // ...
940     //        = op c3, ..., f2
941     Chain = Chains[NumRegs-1];
942   else
943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
944 }
945 
946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
947                                         unsigned MatchingIdx, const SDLoc &dl,
948                                         SelectionDAG &DAG,
949                                         std::vector<SDValue> &Ops) const {
950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
951 
952   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
953   if (HasMatching)
954     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
955   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
956     // Put the register class of the virtual registers in the flag word.  That
957     // way, later passes can recompute register class constraints for inline
958     // assembly as well as normal instructions.
959     // Don't do this for tied operands that can use the regclass information
960     // from the def.
961     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
962     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
963     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
964   }
965 
966   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
967   Ops.push_back(Res);
968 
969   if (Code == InlineAsm::Kind_Clobber) {
970     // Clobbers should always have a 1:1 mapping with registers, and may
971     // reference registers that have illegal (e.g. vector) types. Hence, we
972     // shouldn't try to apply any sort of splitting logic to them.
973     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
974            "No 1:1 mapping from clobbers to regs?");
975     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
976     (void)SP;
977     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
978       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
979       assert(
980           (Regs[I] != SP ||
981            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
982           "If we clobbered the stack pointer, MFI should know about it.");
983     }
984     return;
985   }
986 
987   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
988     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
989     MVT RegisterVT = RegVTs[Value];
990     for (unsigned i = 0; i != NumRegs; ++i) {
991       assert(Reg < Regs.size() && "Mismatch in # registers expected");
992       unsigned TheReg = Regs[Reg++];
993       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994     }
995   }
996 }
997 
998 SmallVector<std::pair<unsigned, unsigned>, 4>
999 RegsForValue::getRegsAndSizes() const {
1000   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1001   unsigned I = 0;
1002   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1003     unsigned RegCount = std::get<0>(CountAndVT);
1004     MVT RegisterVT = std::get<1>(CountAndVT);
1005     unsigned RegisterSize = RegisterVT.getSizeInBits();
1006     for (unsigned E = I + RegCount; I != E; ++I)
1007       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1008   }
1009   return OutVec;
1010 }
1011 
1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1013                                const TargetLibraryInfo *li) {
1014   AA = aa;
1015   GFI = gfi;
1016   LibInfo = li;
1017   DL = &DAG.getDataLayout();
1018   Context = DAG.getContext();
1019   LPadToCallSiteMap.clear();
1020   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1021 }
1022 
1023 void SelectionDAGBuilder::clear() {
1024   NodeMap.clear();
1025   UnusedArgNodeMap.clear();
1026   PendingLoads.clear();
1027   PendingExports.clear();
1028   CurInst = nullptr;
1029   HasTailCall = false;
1030   SDNodeOrder = LowestSDNodeOrder;
1031   StatepointLowering.clear();
1032 }
1033 
1034 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1035   DanglingDebugInfoMap.clear();
1036 }
1037 
1038 SDValue SelectionDAGBuilder::getRoot() {
1039   if (PendingLoads.empty())
1040     return DAG.getRoot();
1041 
1042   if (PendingLoads.size() == 1) {
1043     SDValue Root = PendingLoads[0];
1044     DAG.setRoot(Root);
1045     PendingLoads.clear();
1046     return Root;
1047   }
1048 
1049   // Otherwise, we have to make a token factor node.
1050   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1051   PendingLoads.clear();
1052   DAG.setRoot(Root);
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getControlRoot() {
1057   SDValue Root = DAG.getRoot();
1058 
1059   if (PendingExports.empty())
1060     return Root;
1061 
1062   // Turn all of the CopyToReg chains into one factored node.
1063   if (Root.getOpcode() != ISD::EntryToken) {
1064     unsigned i = 0, e = PendingExports.size();
1065     for (; i != e; ++i) {
1066       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1067       if (PendingExports[i].getNode()->getOperand(0) == Root)
1068         break;  // Don't add the root if we already indirectly depend on it.
1069     }
1070 
1071     if (i == e)
1072       PendingExports.push_back(Root);
1073   }
1074 
1075   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1076                      PendingExports);
1077   PendingExports.clear();
1078   DAG.setRoot(Root);
1079   return Root;
1080 }
1081 
1082 void SelectionDAGBuilder::visit(const Instruction &I) {
1083   // Set up outgoing PHI node register values before emitting the terminator.
1084   if (I.isTerminator()) {
1085     HandlePHINodesInSuccessorBlocks(I.getParent());
1086   }
1087 
1088   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1089   if (!isa<DbgInfoIntrinsic>(I))
1090     ++SDNodeOrder;
1091 
1092   CurInst = &I;
1093 
1094   visit(I.getOpcode(), I);
1095 
1096   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1097     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1098     // maps to this instruction.
1099     // TODO: We could handle all flags (nsw, etc) here.
1100     // TODO: If an IR instruction maps to >1 node, only the final node will have
1101     //       flags set.
1102     if (SDNode *Node = getNodeForIRValue(&I)) {
1103       SDNodeFlags IncomingFlags;
1104       IncomingFlags.copyFMF(*FPMO);
1105       if (!Node->getFlags().isDefined())
1106         Node->setFlags(IncomingFlags);
1107       else
1108         Node->intersectFlagsWith(IncomingFlags);
1109     }
1110   }
1111 
1112   if (!I.isTerminator() && !HasTailCall &&
1113       !isStatepoint(&I)) // statepoints handle their exports internally
1114     CopyToExportRegsIfNeeded(&I);
1115 
1116   CurInst = nullptr;
1117 }
1118 
1119 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1120   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1121 }
1122 
1123 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1124   // Note: this doesn't use InstVisitor, because it has to work with
1125   // ConstantExpr's in addition to instructions.
1126   switch (Opcode) {
1127   default: llvm_unreachable("Unknown instruction type encountered!");
1128     // Build the switch statement using the Instruction.def file.
1129 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1130     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1131 #include "llvm/IR/Instruction.def"
1132   }
1133 }
1134 
1135 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1136                                                 const DIExpression *Expr) {
1137   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1138     const DbgValueInst *DI = DDI.getDI();
1139     DIVariable *DanglingVariable = DI->getVariable();
1140     DIExpression *DanglingExpr = DI->getExpression();
1141     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1142       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1143       return true;
1144     }
1145     return false;
1146   };
1147 
1148   for (auto &DDIMI : DanglingDebugInfoMap) {
1149     DanglingDebugInfoVector &DDIV = DDIMI.second;
1150 
1151     // If debug info is to be dropped, run it through final checks to see
1152     // whether it can be salvaged.
1153     for (auto &DDI : DDIV)
1154       if (isMatchingDbgValue(DDI))
1155         salvageUnresolvedDbgValue(DDI);
1156 
1157     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1158   }
1159 }
1160 
1161 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1162 // generate the debug data structures now that we've seen its definition.
1163 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1164                                                    SDValue Val) {
1165   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1166   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1167     return;
1168 
1169   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1170   for (auto &DDI : DDIV) {
1171     const DbgValueInst *DI = DDI.getDI();
1172     assert(DI && "Ill-formed DanglingDebugInfo");
1173     DebugLoc dl = DDI.getdl();
1174     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1175     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1176     DILocalVariable *Variable = DI->getVariable();
1177     DIExpression *Expr = DI->getExpression();
1178     assert(Variable->isValidLocationForIntrinsic(dl) &&
1179            "Expected inlined-at fields to agree");
1180     SDDbgValue *SDV;
1181     if (Val.getNode()) {
1182       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1183       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1184       // we couldn't resolve it directly when examining the DbgValue intrinsic
1185       // in the first place we should not be more successful here). Unless we
1186       // have some test case that prove this to be correct we should avoid
1187       // calling EmitFuncArgumentDbgValue here.
1188       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1189         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1190                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1191         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1192         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1193         // inserted after the definition of Val when emitting the instructions
1194         // after ISel. An alternative could be to teach
1195         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1196         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1197                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1198                    << ValSDNodeOrder << "\n");
1199         SDV = getDbgValue(Val, Variable, Expr, dl,
1200                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1201         DAG.AddDbgValue(SDV, Val.getNode(), false);
1202       } else
1203         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1204                           << "in EmitFuncArgumentDbgValue\n");
1205     } else {
1206       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1207       auto Undef =
1208           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1209       auto SDV =
1210           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1211       DAG.AddDbgValue(SDV, nullptr, false);
1212     }
1213   }
1214   DDIV.clear();
1215 }
1216 
1217 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1218   Value *V = DDI.getDI()->getValue();
1219   DILocalVariable *Var = DDI.getDI()->getVariable();
1220   DIExpression *Expr = DDI.getDI()->getExpression();
1221   DebugLoc DL = DDI.getdl();
1222   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1223   unsigned SDOrder = DDI.getSDNodeOrder();
1224 
1225   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1226   // that DW_OP_stack_value is desired.
1227   assert(isa<DbgValueInst>(DDI.getDI()));
1228   bool StackValue = true;
1229 
1230   // Can this Value can be encoded without any further work?
1231   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1232     return;
1233 
1234   // Attempt to salvage back through as many instructions as possible. Bail if
1235   // a non-instruction is seen, such as a constant expression or global
1236   // variable. FIXME: Further work could recover those too.
1237   while (isa<Instruction>(V)) {
1238     Instruction &VAsInst = *cast<Instruction>(V);
1239     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1240 
1241     // If we cannot salvage any further, and haven't yet found a suitable debug
1242     // expression, bail out.
1243     if (!NewExpr)
1244       break;
1245 
1246     // New value and expr now represent this debuginfo.
1247     V = VAsInst.getOperand(0);
1248     Expr = NewExpr;
1249 
1250     // Some kind of simplification occurred: check whether the operand of the
1251     // salvaged debug expression can be encoded in this DAG.
1252     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1253       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1254                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1255       return;
1256     }
1257   }
1258 
1259   // This was the final opportunity to salvage this debug information, and it
1260   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1261   // any earlier variable location.
1262   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1263   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1264   DAG.AddDbgValue(SDV, nullptr, false);
1265 
1266   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1267                     << "\n");
1268   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1269                     << "\n");
1270 }
1271 
1272 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1273                                            DIExpression *Expr, DebugLoc dl,
1274                                            DebugLoc InstDL, unsigned Order) {
1275   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1276   SDDbgValue *SDV;
1277   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1278       isa<ConstantPointerNull>(V)) {
1279     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1280     DAG.AddDbgValue(SDV, nullptr, false);
1281     return true;
1282   }
1283 
1284   // If the Value is a frame index, we can create a FrameIndex debug value
1285   // without relying on the DAG at all.
1286   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1287     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1288     if (SI != FuncInfo.StaticAllocaMap.end()) {
1289       auto SDV =
1290           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1291                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1292       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1293       // is still available even if the SDNode gets optimized out.
1294       DAG.AddDbgValue(SDV, nullptr, false);
1295       return true;
1296     }
1297   }
1298 
1299   // Do not use getValue() in here; we don't want to generate code at
1300   // this point if it hasn't been done yet.
1301   SDValue N = NodeMap[V];
1302   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1303     N = UnusedArgNodeMap[V];
1304   if (N.getNode()) {
1305     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1306       return true;
1307     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1308     DAG.AddDbgValue(SDV, N.getNode(), false);
1309     return true;
1310   }
1311 
1312   // Special rules apply for the first dbg.values of parameter variables in a
1313   // function. Identify them by the fact they reference Argument Values, that
1314   // they're parameters, and they are parameters of the current function. We
1315   // need to let them dangle until they get an SDNode.
1316   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1317                        !InstDL.getInlinedAt();
1318   if (!IsParamOfFunc) {
1319     // The value is not used in this block yet (or it would have an SDNode).
1320     // We still want the value to appear for the user if possible -- if it has
1321     // an associated VReg, we can refer to that instead.
1322     auto VMI = FuncInfo.ValueMap.find(V);
1323     if (VMI != FuncInfo.ValueMap.end()) {
1324       unsigned Reg = VMI->second;
1325       // If this is a PHI node, it may be split up into several MI PHI nodes
1326       // (in FunctionLoweringInfo::set).
1327       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1328                        V->getType(), None);
1329       if (RFV.occupiesMultipleRegs()) {
1330         unsigned Offset = 0;
1331         unsigned BitsToDescribe = 0;
1332         if (auto VarSize = Var->getSizeInBits())
1333           BitsToDescribe = *VarSize;
1334         if (auto Fragment = Expr->getFragmentInfo())
1335           BitsToDescribe = Fragment->SizeInBits;
1336         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1337           unsigned RegisterSize = RegAndSize.second;
1338           // Bail out if all bits are described already.
1339           if (Offset >= BitsToDescribe)
1340             break;
1341           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1342               ? BitsToDescribe - Offset
1343               : RegisterSize;
1344           auto FragmentExpr = DIExpression::createFragmentExpression(
1345               Expr, Offset, FragmentSize);
1346           if (!FragmentExpr)
1347               continue;
1348           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1349                                     false, dl, SDNodeOrder);
1350           DAG.AddDbgValue(SDV, nullptr, false);
1351           Offset += RegisterSize;
1352         }
1353       } else {
1354         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1355         DAG.AddDbgValue(SDV, nullptr, false);
1356       }
1357       return true;
1358     }
1359   }
1360 
1361   return false;
1362 }
1363 
1364 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1365   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1366   for (auto &Pair : DanglingDebugInfoMap)
1367     for (auto &DDI : Pair.second)
1368       salvageUnresolvedDbgValue(DDI);
1369   clearDanglingDebugInfo();
1370 }
1371 
1372 /// getCopyFromRegs - If there was virtual register allocated for the value V
1373 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1374 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1375   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1376   SDValue Result;
1377 
1378   if (It != FuncInfo.ValueMap.end()) {
1379     unsigned InReg = It->second;
1380 
1381     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1382                      DAG.getDataLayout(), InReg, Ty,
1383                      None); // This is not an ABI copy.
1384     SDValue Chain = DAG.getEntryNode();
1385     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1386                                  V);
1387     resolveDanglingDebugInfo(V, Result);
1388   }
1389 
1390   return Result;
1391 }
1392 
1393 /// getValue - Return an SDValue for the given Value.
1394 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1395   // If we already have an SDValue for this value, use it. It's important
1396   // to do this first, so that we don't create a CopyFromReg if we already
1397   // have a regular SDValue.
1398   SDValue &N = NodeMap[V];
1399   if (N.getNode()) return N;
1400 
1401   // If there's a virtual register allocated and initialized for this
1402   // value, use it.
1403   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1404     return copyFromReg;
1405 
1406   // Otherwise create a new SDValue and remember it.
1407   SDValue Val = getValueImpl(V);
1408   NodeMap[V] = Val;
1409   resolveDanglingDebugInfo(V, Val);
1410   return Val;
1411 }
1412 
1413 // Return true if SDValue exists for the given Value
1414 bool SelectionDAGBuilder::findValue(const Value *V) const {
1415   return (NodeMap.find(V) != NodeMap.end()) ||
1416     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1417 }
1418 
1419 /// getNonRegisterValue - Return an SDValue for the given Value, but
1420 /// don't look in FuncInfo.ValueMap for a virtual register.
1421 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1422   // If we already have an SDValue for this value, use it.
1423   SDValue &N = NodeMap[V];
1424   if (N.getNode()) {
1425     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1426       // Remove the debug location from the node as the node is about to be used
1427       // in a location which may differ from the original debug location.  This
1428       // is relevant to Constant and ConstantFP nodes because they can appear
1429       // as constant expressions inside PHI nodes.
1430       N->setDebugLoc(DebugLoc());
1431     }
1432     return N;
1433   }
1434 
1435   // Otherwise create a new SDValue and remember it.
1436   SDValue Val = getValueImpl(V);
1437   NodeMap[V] = Val;
1438   resolveDanglingDebugInfo(V, Val);
1439   return Val;
1440 }
1441 
1442 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1443 /// Create an SDValue for the given value.
1444 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1446 
1447   if (const Constant *C = dyn_cast<Constant>(V)) {
1448     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1449 
1450     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1451       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1452 
1453     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1454       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1455 
1456     if (isa<ConstantPointerNull>(C)) {
1457       unsigned AS = V->getType()->getPointerAddressSpace();
1458       return DAG.getConstant(0, getCurSDLoc(),
1459                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1460     }
1461 
1462     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1463       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1464 
1465     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1466       return DAG.getUNDEF(VT);
1467 
1468     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1469       visit(CE->getOpcode(), *CE);
1470       SDValue N1 = NodeMap[V];
1471       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1472       return N1;
1473     }
1474 
1475     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1476       SmallVector<SDValue, 4> Constants;
1477       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1478            OI != OE; ++OI) {
1479         SDNode *Val = getValue(*OI).getNode();
1480         // If the operand is an empty aggregate, there are no values.
1481         if (!Val) continue;
1482         // Add each leaf value from the operand to the Constants list
1483         // to form a flattened list of all the values.
1484         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1485           Constants.push_back(SDValue(Val, i));
1486       }
1487 
1488       return DAG.getMergeValues(Constants, getCurSDLoc());
1489     }
1490 
1491     if (const ConstantDataSequential *CDS =
1492           dyn_cast<ConstantDataSequential>(C)) {
1493       SmallVector<SDValue, 4> Ops;
1494       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1495         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1496         // Add each leaf value from the operand to the Constants list
1497         // to form a flattened list of all the values.
1498         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1499           Ops.push_back(SDValue(Val, i));
1500       }
1501 
1502       if (isa<ArrayType>(CDS->getType()))
1503         return DAG.getMergeValues(Ops, getCurSDLoc());
1504       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1505     }
1506 
1507     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1508       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1509              "Unknown struct or array constant!");
1510 
1511       SmallVector<EVT, 4> ValueVTs;
1512       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1513       unsigned NumElts = ValueVTs.size();
1514       if (NumElts == 0)
1515         return SDValue(); // empty struct
1516       SmallVector<SDValue, 4> Constants(NumElts);
1517       for (unsigned i = 0; i != NumElts; ++i) {
1518         EVT EltVT = ValueVTs[i];
1519         if (isa<UndefValue>(C))
1520           Constants[i] = DAG.getUNDEF(EltVT);
1521         else if (EltVT.isFloatingPoint())
1522           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1523         else
1524           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1525       }
1526 
1527       return DAG.getMergeValues(Constants, getCurSDLoc());
1528     }
1529 
1530     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1531       return DAG.getBlockAddress(BA, VT);
1532 
1533     VectorType *VecTy = cast<VectorType>(V->getType());
1534     unsigned NumElements = VecTy->getNumElements();
1535 
1536     // Now that we know the number and type of the elements, get that number of
1537     // elements into the Ops array based on what kind of constant it is.
1538     SmallVector<SDValue, 16> Ops;
1539     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1540       for (unsigned i = 0; i != NumElements; ++i)
1541         Ops.push_back(getValue(CV->getOperand(i)));
1542     } else {
1543       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1544       EVT EltVT =
1545           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1546 
1547       SDValue Op;
1548       if (EltVT.isFloatingPoint())
1549         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1550       else
1551         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1552       Ops.assign(NumElements, Op);
1553     }
1554 
1555     // Create a BUILD_VECTOR node.
1556     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1557   }
1558 
1559   // If this is a static alloca, generate it as the frameindex instead of
1560   // computation.
1561   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1562     DenseMap<const AllocaInst*, int>::iterator SI =
1563       FuncInfo.StaticAllocaMap.find(AI);
1564     if (SI != FuncInfo.StaticAllocaMap.end())
1565       return DAG.getFrameIndex(SI->second,
1566                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1567   }
1568 
1569   // If this is an instruction which fast-isel has deferred, select it now.
1570   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1571     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1572 
1573     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1574                      Inst->getType(), getABIRegCopyCC(V));
1575     SDValue Chain = DAG.getEntryNode();
1576     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1577   }
1578 
1579   llvm_unreachable("Can't get register for value!");
1580 }
1581 
1582 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1583   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1584   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1585   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1586   bool IsSEH = isAsynchronousEHPersonality(Pers);
1587   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1588   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1589   if (!IsSEH)
1590     CatchPadMBB->setIsEHScopeEntry();
1591   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1592   if (IsMSVCCXX || IsCoreCLR)
1593     CatchPadMBB->setIsEHFuncletEntry();
1594   // Wasm does not need catchpads anymore
1595   if (!IsWasmCXX)
1596     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1597                             getControlRoot()));
1598 }
1599 
1600 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1601   // Update machine-CFG edge.
1602   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1603   FuncInfo.MBB->addSuccessor(TargetMBB);
1604 
1605   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1606   bool IsSEH = isAsynchronousEHPersonality(Pers);
1607   if (IsSEH) {
1608     // If this is not a fall-through branch or optimizations are switched off,
1609     // emit the branch.
1610     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1611         TM.getOptLevel() == CodeGenOpt::None)
1612       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1613                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1614     return;
1615   }
1616 
1617   // Figure out the funclet membership for the catchret's successor.
1618   // This will be used by the FuncletLayout pass to determine how to order the
1619   // BB's.
1620   // A 'catchret' returns to the outer scope's color.
1621   Value *ParentPad = I.getCatchSwitchParentPad();
1622   const BasicBlock *SuccessorColor;
1623   if (isa<ConstantTokenNone>(ParentPad))
1624     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1625   else
1626     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1627   assert(SuccessorColor && "No parent funclet for catchret!");
1628   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1629   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1630 
1631   // Create the terminator node.
1632   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1633                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1634                             DAG.getBasicBlock(SuccessorColorMBB));
1635   DAG.setRoot(Ret);
1636 }
1637 
1638 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1639   // Don't emit any special code for the cleanuppad instruction. It just marks
1640   // the start of an EH scope/funclet.
1641   FuncInfo.MBB->setIsEHScopeEntry();
1642   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1643   if (Pers != EHPersonality::Wasm_CXX) {
1644     FuncInfo.MBB->setIsEHFuncletEntry();
1645     FuncInfo.MBB->setIsCleanupFuncletEntry();
1646   }
1647 }
1648 
1649 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1650 // the control flow always stops at the single catch pad, as it does for a
1651 // cleanup pad. In case the exception caught is not of the types the catch pad
1652 // catches, it will be rethrown by a rethrow.
1653 static void findWasmUnwindDestinations(
1654     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1655     BranchProbability Prob,
1656     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1657         &UnwindDests) {
1658   while (EHPadBB) {
1659     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1660     if (isa<CleanupPadInst>(Pad)) {
1661       // Stop on cleanup pads.
1662       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1663       UnwindDests.back().first->setIsEHScopeEntry();
1664       break;
1665     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1666       // Add the catchpad handlers to the possible destinations. We don't
1667       // continue to the unwind destination of the catchswitch for wasm.
1668       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1669         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1670         UnwindDests.back().first->setIsEHScopeEntry();
1671       }
1672       break;
1673     } else {
1674       continue;
1675     }
1676   }
1677 }
1678 
1679 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1680 /// many places it could ultimately go. In the IR, we have a single unwind
1681 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1682 /// This function skips over imaginary basic blocks that hold catchswitch
1683 /// instructions, and finds all the "real" machine
1684 /// basic block destinations. As those destinations may not be successors of
1685 /// EHPadBB, here we also calculate the edge probability to those destinations.
1686 /// The passed-in Prob is the edge probability to EHPadBB.
1687 static void findUnwindDestinations(
1688     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1689     BranchProbability Prob,
1690     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1691         &UnwindDests) {
1692   EHPersonality Personality =
1693     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1694   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1695   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1696   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1697   bool IsSEH = isAsynchronousEHPersonality(Personality);
1698 
1699   if (IsWasmCXX) {
1700     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1701     assert(UnwindDests.size() <= 1 &&
1702            "There should be at most one unwind destination for wasm");
1703     return;
1704   }
1705 
1706   while (EHPadBB) {
1707     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1708     BasicBlock *NewEHPadBB = nullptr;
1709     if (isa<LandingPadInst>(Pad)) {
1710       // Stop on landingpads. They are not funclets.
1711       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1712       break;
1713     } else if (isa<CleanupPadInst>(Pad)) {
1714       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1715       // personalities.
1716       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1717       UnwindDests.back().first->setIsEHScopeEntry();
1718       UnwindDests.back().first->setIsEHFuncletEntry();
1719       break;
1720     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1721       // Add the catchpad handlers to the possible destinations.
1722       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1723         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1724         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1725         if (IsMSVCCXX || IsCoreCLR)
1726           UnwindDests.back().first->setIsEHFuncletEntry();
1727         if (!IsSEH)
1728           UnwindDests.back().first->setIsEHScopeEntry();
1729       }
1730       NewEHPadBB = CatchSwitch->getUnwindDest();
1731     } else {
1732       continue;
1733     }
1734 
1735     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1736     if (BPI && NewEHPadBB)
1737       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1738     EHPadBB = NewEHPadBB;
1739   }
1740 }
1741 
1742 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1743   // Update successor info.
1744   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1745   auto UnwindDest = I.getUnwindDest();
1746   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1747   BranchProbability UnwindDestProb =
1748       (BPI && UnwindDest)
1749           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1750           : BranchProbability::getZero();
1751   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1752   for (auto &UnwindDest : UnwindDests) {
1753     UnwindDest.first->setIsEHPad();
1754     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1755   }
1756   FuncInfo.MBB->normalizeSuccProbs();
1757 
1758   // Create the terminator node.
1759   SDValue Ret =
1760       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1761   DAG.setRoot(Ret);
1762 }
1763 
1764 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1765   report_fatal_error("visitCatchSwitch not yet implemented!");
1766 }
1767 
1768 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1770   auto &DL = DAG.getDataLayout();
1771   SDValue Chain = getControlRoot();
1772   SmallVector<ISD::OutputArg, 8> Outs;
1773   SmallVector<SDValue, 8> OutVals;
1774 
1775   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1776   // lower
1777   //
1778   //   %val = call <ty> @llvm.experimental.deoptimize()
1779   //   ret <ty> %val
1780   //
1781   // differently.
1782   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1783     LowerDeoptimizingReturn();
1784     return;
1785   }
1786 
1787   if (!FuncInfo.CanLowerReturn) {
1788     unsigned DemoteReg = FuncInfo.DemoteRegister;
1789     const Function *F = I.getParent()->getParent();
1790 
1791     // Emit a store of the return value through the virtual register.
1792     // Leave Outs empty so that LowerReturn won't try to load return
1793     // registers the usual way.
1794     SmallVector<EVT, 1> PtrValueVTs;
1795     ComputeValueVTs(TLI, DL,
1796                     F->getReturnType()->getPointerTo(
1797                         DAG.getDataLayout().getAllocaAddrSpace()),
1798                     PtrValueVTs);
1799 
1800     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1801                                         DemoteReg, PtrValueVTs[0]);
1802     SDValue RetOp = getValue(I.getOperand(0));
1803 
1804     SmallVector<EVT, 4> ValueVTs, MemVTs;
1805     SmallVector<uint64_t, 4> Offsets;
1806     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1807                     &Offsets);
1808     unsigned NumValues = ValueVTs.size();
1809 
1810     SmallVector<SDValue, 4> Chains(NumValues);
1811     for (unsigned i = 0; i != NumValues; ++i) {
1812       // An aggregate return value cannot wrap around the address space, so
1813       // offsets to its parts don't wrap either.
1814       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1815 
1816       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1817       if (MemVTs[i] != ValueVTs[i])
1818         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1819       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1820           // FIXME: better loc info would be nice.
1821           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1822     }
1823 
1824     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1825                         MVT::Other, Chains);
1826   } else if (I.getNumOperands() != 0) {
1827     SmallVector<EVT, 4> ValueVTs;
1828     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1829     unsigned NumValues = ValueVTs.size();
1830     if (NumValues) {
1831       SDValue RetOp = getValue(I.getOperand(0));
1832 
1833       const Function *F = I.getParent()->getParent();
1834 
1835       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1836           I.getOperand(0)->getType(), F->getCallingConv(),
1837           /*IsVarArg*/ false);
1838 
1839       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1840       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1841                                           Attribute::SExt))
1842         ExtendKind = ISD::SIGN_EXTEND;
1843       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1844                                                Attribute::ZExt))
1845         ExtendKind = ISD::ZERO_EXTEND;
1846 
1847       LLVMContext &Context = F->getContext();
1848       bool RetInReg = F->getAttributes().hasAttribute(
1849           AttributeList::ReturnIndex, Attribute::InReg);
1850 
1851       for (unsigned j = 0; j != NumValues; ++j) {
1852         EVT VT = ValueVTs[j];
1853 
1854         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1855           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1856 
1857         CallingConv::ID CC = F->getCallingConv();
1858 
1859         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1860         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1861         SmallVector<SDValue, 4> Parts(NumParts);
1862         getCopyToParts(DAG, getCurSDLoc(),
1863                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1864                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1865 
1866         // 'inreg' on function refers to return value
1867         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1868         if (RetInReg)
1869           Flags.setInReg();
1870 
1871         if (I.getOperand(0)->getType()->isPointerTy()) {
1872           Flags.setPointer();
1873           Flags.setPointerAddrSpace(
1874               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1875         }
1876 
1877         if (NeedsRegBlock) {
1878           Flags.setInConsecutiveRegs();
1879           if (j == NumValues - 1)
1880             Flags.setInConsecutiveRegsLast();
1881         }
1882 
1883         // Propagate extension type if any
1884         if (ExtendKind == ISD::SIGN_EXTEND)
1885           Flags.setSExt();
1886         else if (ExtendKind == ISD::ZERO_EXTEND)
1887           Flags.setZExt();
1888 
1889         for (unsigned i = 0; i < NumParts; ++i) {
1890           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1891                                         VT, /*isfixed=*/true, 0, 0));
1892           OutVals.push_back(Parts[i]);
1893         }
1894       }
1895     }
1896   }
1897 
1898   // Push in swifterror virtual register as the last element of Outs. This makes
1899   // sure swifterror virtual register will be returned in the swifterror
1900   // physical register.
1901   const Function *F = I.getParent()->getParent();
1902   if (TLI.supportSwiftError() &&
1903       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1904     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1905     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1906     Flags.setSwiftError();
1907     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1908                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1909                                   true /*isfixed*/, 1 /*origidx*/,
1910                                   0 /*partOffs*/));
1911     // Create SDNode for the swifterror virtual register.
1912     OutVals.push_back(
1913         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1914                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1915                         EVT(TLI.getPointerTy(DL))));
1916   }
1917 
1918   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1919   CallingConv::ID CallConv =
1920     DAG.getMachineFunction().getFunction().getCallingConv();
1921   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1922       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1923 
1924   // Verify that the target's LowerReturn behaved as expected.
1925   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1926          "LowerReturn didn't return a valid chain!");
1927 
1928   // Update the DAG with the new chain value resulting from return lowering.
1929   DAG.setRoot(Chain);
1930 }
1931 
1932 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1933 /// created for it, emit nodes to copy the value into the virtual
1934 /// registers.
1935 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1936   // Skip empty types
1937   if (V->getType()->isEmptyTy())
1938     return;
1939 
1940   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1941   if (VMI != FuncInfo.ValueMap.end()) {
1942     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1943     CopyValueToVirtualRegister(V, VMI->second);
1944   }
1945 }
1946 
1947 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1948 /// the current basic block, add it to ValueMap now so that we'll get a
1949 /// CopyTo/FromReg.
1950 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1951   // No need to export constants.
1952   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1953 
1954   // Already exported?
1955   if (FuncInfo.isExportedInst(V)) return;
1956 
1957   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1958   CopyValueToVirtualRegister(V, Reg);
1959 }
1960 
1961 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1962                                                      const BasicBlock *FromBB) {
1963   // The operands of the setcc have to be in this block.  We don't know
1964   // how to export them from some other block.
1965   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1966     // Can export from current BB.
1967     if (VI->getParent() == FromBB)
1968       return true;
1969 
1970     // Is already exported, noop.
1971     return FuncInfo.isExportedInst(V);
1972   }
1973 
1974   // If this is an argument, we can export it if the BB is the entry block or
1975   // if it is already exported.
1976   if (isa<Argument>(V)) {
1977     if (FromBB == &FromBB->getParent()->getEntryBlock())
1978       return true;
1979 
1980     // Otherwise, can only export this if it is already exported.
1981     return FuncInfo.isExportedInst(V);
1982   }
1983 
1984   // Otherwise, constants can always be exported.
1985   return true;
1986 }
1987 
1988 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1989 BranchProbability
1990 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1991                                         const MachineBasicBlock *Dst) const {
1992   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1993   const BasicBlock *SrcBB = Src->getBasicBlock();
1994   const BasicBlock *DstBB = Dst->getBasicBlock();
1995   if (!BPI) {
1996     // If BPI is not available, set the default probability as 1 / N, where N is
1997     // the number of successors.
1998     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1999     return BranchProbability(1, SuccSize);
2000   }
2001   return BPI->getEdgeProbability(SrcBB, DstBB);
2002 }
2003 
2004 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2005                                                MachineBasicBlock *Dst,
2006                                                BranchProbability Prob) {
2007   if (!FuncInfo.BPI)
2008     Src->addSuccessorWithoutProb(Dst);
2009   else {
2010     if (Prob.isUnknown())
2011       Prob = getEdgeProbability(Src, Dst);
2012     Src->addSuccessor(Dst, Prob);
2013   }
2014 }
2015 
2016 static bool InBlock(const Value *V, const BasicBlock *BB) {
2017   if (const Instruction *I = dyn_cast<Instruction>(V))
2018     return I->getParent() == BB;
2019   return true;
2020 }
2021 
2022 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2023 /// This function emits a branch and is used at the leaves of an OR or an
2024 /// AND operator tree.
2025 void
2026 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2027                                                   MachineBasicBlock *TBB,
2028                                                   MachineBasicBlock *FBB,
2029                                                   MachineBasicBlock *CurBB,
2030                                                   MachineBasicBlock *SwitchBB,
2031                                                   BranchProbability TProb,
2032                                                   BranchProbability FProb,
2033                                                   bool InvertCond) {
2034   const BasicBlock *BB = CurBB->getBasicBlock();
2035 
2036   // If the leaf of the tree is a comparison, merge the condition into
2037   // the caseblock.
2038   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2039     // The operands of the cmp have to be in this block.  We don't know
2040     // how to export them from some other block.  If this is the first block
2041     // of the sequence, no exporting is needed.
2042     if (CurBB == SwitchBB ||
2043         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2044          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2045       ISD::CondCode Condition;
2046       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2047         ICmpInst::Predicate Pred =
2048             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2049         Condition = getICmpCondCode(Pred);
2050       } else {
2051         const FCmpInst *FC = cast<FCmpInst>(Cond);
2052         FCmpInst::Predicate Pred =
2053             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2054         Condition = getFCmpCondCode(Pred);
2055         if (TM.Options.NoNaNsFPMath)
2056           Condition = getFCmpCodeWithoutNaN(Condition);
2057       }
2058 
2059       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2060                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2061       SL->SwitchCases.push_back(CB);
2062       return;
2063     }
2064   }
2065 
2066   // Create a CaseBlock record representing this branch.
2067   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2068   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2069                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2070   SL->SwitchCases.push_back(CB);
2071 }
2072 
2073 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2074                                                MachineBasicBlock *TBB,
2075                                                MachineBasicBlock *FBB,
2076                                                MachineBasicBlock *CurBB,
2077                                                MachineBasicBlock *SwitchBB,
2078                                                Instruction::BinaryOps Opc,
2079                                                BranchProbability TProb,
2080                                                BranchProbability FProb,
2081                                                bool InvertCond) {
2082   // Skip over not part of the tree and remember to invert op and operands at
2083   // next level.
2084   Value *NotCond;
2085   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2086       InBlock(NotCond, CurBB->getBasicBlock())) {
2087     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2088                          !InvertCond);
2089     return;
2090   }
2091 
2092   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2093   // Compute the effective opcode for Cond, taking into account whether it needs
2094   // to be inverted, e.g.
2095   //   and (not (or A, B)), C
2096   // gets lowered as
2097   //   and (and (not A, not B), C)
2098   unsigned BOpc = 0;
2099   if (BOp) {
2100     BOpc = BOp->getOpcode();
2101     if (InvertCond) {
2102       if (BOpc == Instruction::And)
2103         BOpc = Instruction::Or;
2104       else if (BOpc == Instruction::Or)
2105         BOpc = Instruction::And;
2106     }
2107   }
2108 
2109   // If this node is not part of the or/and tree, emit it as a branch.
2110   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2111       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2112       BOp->getParent() != CurBB->getBasicBlock() ||
2113       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2114       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2115     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2116                                  TProb, FProb, InvertCond);
2117     return;
2118   }
2119 
2120   //  Create TmpBB after CurBB.
2121   MachineFunction::iterator BBI(CurBB);
2122   MachineFunction &MF = DAG.getMachineFunction();
2123   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2124   CurBB->getParent()->insert(++BBI, TmpBB);
2125 
2126   if (Opc == Instruction::Or) {
2127     // Codegen X | Y as:
2128     // BB1:
2129     //   jmp_if_X TBB
2130     //   jmp TmpBB
2131     // TmpBB:
2132     //   jmp_if_Y TBB
2133     //   jmp FBB
2134     //
2135 
2136     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2137     // The requirement is that
2138     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2139     //     = TrueProb for original BB.
2140     // Assuming the original probabilities are A and B, one choice is to set
2141     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2142     // A/(1+B) and 2B/(1+B). This choice assumes that
2143     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2144     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2145     // TmpBB, but the math is more complicated.
2146 
2147     auto NewTrueProb = TProb / 2;
2148     auto NewFalseProb = TProb / 2 + FProb;
2149     // Emit the LHS condition.
2150     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2151                          NewTrueProb, NewFalseProb, InvertCond);
2152 
2153     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2154     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2155     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2156     // Emit the RHS condition into TmpBB.
2157     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2158                          Probs[0], Probs[1], InvertCond);
2159   } else {
2160     assert(Opc == Instruction::And && "Unknown merge op!");
2161     // Codegen X & Y as:
2162     // BB1:
2163     //   jmp_if_X TmpBB
2164     //   jmp FBB
2165     // TmpBB:
2166     //   jmp_if_Y TBB
2167     //   jmp FBB
2168     //
2169     //  This requires creation of TmpBB after CurBB.
2170 
2171     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2172     // The requirement is that
2173     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2174     //     = FalseProb for original BB.
2175     // Assuming the original probabilities are A and B, one choice is to set
2176     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2177     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2178     // TrueProb for BB1 * FalseProb for TmpBB.
2179 
2180     auto NewTrueProb = TProb + FProb / 2;
2181     auto NewFalseProb = FProb / 2;
2182     // Emit the LHS condition.
2183     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2184                          NewTrueProb, NewFalseProb, InvertCond);
2185 
2186     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2187     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2188     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2189     // Emit the RHS condition into TmpBB.
2190     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2191                          Probs[0], Probs[1], InvertCond);
2192   }
2193 }
2194 
2195 /// If the set of cases should be emitted as a series of branches, return true.
2196 /// If we should emit this as a bunch of and/or'd together conditions, return
2197 /// false.
2198 bool
2199 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2200   if (Cases.size() != 2) return true;
2201 
2202   // If this is two comparisons of the same values or'd or and'd together, they
2203   // will get folded into a single comparison, so don't emit two blocks.
2204   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2205        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2206       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2207        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2208     return false;
2209   }
2210 
2211   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2212   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2213   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2214       Cases[0].CC == Cases[1].CC &&
2215       isa<Constant>(Cases[0].CmpRHS) &&
2216       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2217     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2218       return false;
2219     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2220       return false;
2221   }
2222 
2223   return true;
2224 }
2225 
2226 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2227   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2228 
2229   // Update machine-CFG edges.
2230   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2231 
2232   if (I.isUnconditional()) {
2233     // Update machine-CFG edges.
2234     BrMBB->addSuccessor(Succ0MBB);
2235 
2236     // If this is not a fall-through branch or optimizations are switched off,
2237     // emit the branch.
2238     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2239       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2240                               MVT::Other, getControlRoot(),
2241                               DAG.getBasicBlock(Succ0MBB)));
2242 
2243     return;
2244   }
2245 
2246   // If this condition is one of the special cases we handle, do special stuff
2247   // now.
2248   const Value *CondVal = I.getCondition();
2249   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2250 
2251   // If this is a series of conditions that are or'd or and'd together, emit
2252   // this as a sequence of branches instead of setcc's with and/or operations.
2253   // As long as jumps are not expensive, this should improve performance.
2254   // For example, instead of something like:
2255   //     cmp A, B
2256   //     C = seteq
2257   //     cmp D, E
2258   //     F = setle
2259   //     or C, F
2260   //     jnz foo
2261   // Emit:
2262   //     cmp A, B
2263   //     je foo
2264   //     cmp D, E
2265   //     jle foo
2266   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2267     Instruction::BinaryOps Opcode = BOp->getOpcode();
2268     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2269         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2270         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2271       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2272                            Opcode,
2273                            getEdgeProbability(BrMBB, Succ0MBB),
2274                            getEdgeProbability(BrMBB, Succ1MBB),
2275                            /*InvertCond=*/false);
2276       // If the compares in later blocks need to use values not currently
2277       // exported from this block, export them now.  This block should always
2278       // be the first entry.
2279       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2280 
2281       // Allow some cases to be rejected.
2282       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2283         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2284           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2285           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2286         }
2287 
2288         // Emit the branch for this block.
2289         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2290         SL->SwitchCases.erase(SL->SwitchCases.begin());
2291         return;
2292       }
2293 
2294       // Okay, we decided not to do this, remove any inserted MBB's and clear
2295       // SwitchCases.
2296       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2297         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2298 
2299       SL->SwitchCases.clear();
2300     }
2301   }
2302 
2303   // Create a CaseBlock record representing this branch.
2304   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2305                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2306 
2307   // Use visitSwitchCase to actually insert the fast branch sequence for this
2308   // cond branch.
2309   visitSwitchCase(CB, BrMBB);
2310 }
2311 
2312 /// visitSwitchCase - Emits the necessary code to represent a single node in
2313 /// the binary search tree resulting from lowering a switch instruction.
2314 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2315                                           MachineBasicBlock *SwitchBB) {
2316   SDValue Cond;
2317   SDValue CondLHS = getValue(CB.CmpLHS);
2318   SDLoc dl = CB.DL;
2319 
2320   if (CB.CC == ISD::SETTRUE) {
2321     // Branch or fall through to TrueBB.
2322     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2323     SwitchBB->normalizeSuccProbs();
2324     if (CB.TrueBB != NextBlock(SwitchBB)) {
2325       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2326                               DAG.getBasicBlock(CB.TrueBB)));
2327     }
2328     return;
2329   }
2330 
2331   auto &TLI = DAG.getTargetLoweringInfo();
2332   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2333 
2334   // Build the setcc now.
2335   if (!CB.CmpMHS) {
2336     // Fold "(X == true)" to X and "(X == false)" to !X to
2337     // handle common cases produced by branch lowering.
2338     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2339         CB.CC == ISD::SETEQ)
2340       Cond = CondLHS;
2341     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2342              CB.CC == ISD::SETEQ) {
2343       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2344       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2345     } else {
2346       SDValue CondRHS = getValue(CB.CmpRHS);
2347 
2348       // If a pointer's DAG type is larger than its memory type then the DAG
2349       // values are zero-extended. This breaks signed comparisons so truncate
2350       // back to the underlying type before doing the compare.
2351       if (CondLHS.getValueType() != MemVT) {
2352         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2353         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2354       }
2355       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2356     }
2357   } else {
2358     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2359 
2360     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2361     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2362 
2363     SDValue CmpOp = getValue(CB.CmpMHS);
2364     EVT VT = CmpOp.getValueType();
2365 
2366     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2367       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2368                           ISD::SETLE);
2369     } else {
2370       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2371                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2372       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2373                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2374     }
2375   }
2376 
2377   // Update successor info
2378   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2379   // TrueBB and FalseBB are always different unless the incoming IR is
2380   // degenerate. This only happens when running llc on weird IR.
2381   if (CB.TrueBB != CB.FalseBB)
2382     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2383   SwitchBB->normalizeSuccProbs();
2384 
2385   // If the lhs block is the next block, invert the condition so that we can
2386   // fall through to the lhs instead of the rhs block.
2387   if (CB.TrueBB == NextBlock(SwitchBB)) {
2388     std::swap(CB.TrueBB, CB.FalseBB);
2389     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2390     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2391   }
2392 
2393   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2394                                MVT::Other, getControlRoot(), Cond,
2395                                DAG.getBasicBlock(CB.TrueBB));
2396 
2397   // Insert the false branch. Do this even if it's a fall through branch,
2398   // this makes it easier to do DAG optimizations which require inverting
2399   // the branch condition.
2400   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2401                        DAG.getBasicBlock(CB.FalseBB));
2402 
2403   DAG.setRoot(BrCond);
2404 }
2405 
2406 /// visitJumpTable - Emit JumpTable node in the current MBB
2407 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2408   // Emit the code for the jump table
2409   assert(JT.Reg != -1U && "Should lower JT Header first!");
2410   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2411   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2412                                      JT.Reg, PTy);
2413   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2414   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2415                                     MVT::Other, Index.getValue(1),
2416                                     Table, Index);
2417   DAG.setRoot(BrJumpTable);
2418 }
2419 
2420 /// visitJumpTableHeader - This function emits necessary code to produce index
2421 /// in the JumpTable from switch case.
2422 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2423                                                JumpTableHeader &JTH,
2424                                                MachineBasicBlock *SwitchBB) {
2425   SDLoc dl = getCurSDLoc();
2426 
2427   // Subtract the lowest switch case value from the value being switched on.
2428   SDValue SwitchOp = getValue(JTH.SValue);
2429   EVT VT = SwitchOp.getValueType();
2430   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2431                             DAG.getConstant(JTH.First, dl, VT));
2432 
2433   // The SDNode we just created, which holds the value being switched on minus
2434   // the smallest case value, needs to be copied to a virtual register so it
2435   // can be used as an index into the jump table in a subsequent basic block.
2436   // This value may be smaller or larger than the target's pointer type, and
2437   // therefore require extension or truncating.
2438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2439   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2440 
2441   unsigned JumpTableReg =
2442       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2443   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2444                                     JumpTableReg, SwitchOp);
2445   JT.Reg = JumpTableReg;
2446 
2447   if (!JTH.OmitRangeCheck) {
2448     // Emit the range check for the jump table, and branch to the default block
2449     // for the switch statement if the value being switched on exceeds the
2450     // largest case in the switch.
2451     SDValue CMP = DAG.getSetCC(
2452         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2453                                    Sub.getValueType()),
2454         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2455 
2456     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2457                                  MVT::Other, CopyTo, CMP,
2458                                  DAG.getBasicBlock(JT.Default));
2459 
2460     // Avoid emitting unnecessary branches to the next block.
2461     if (JT.MBB != NextBlock(SwitchBB))
2462       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2463                            DAG.getBasicBlock(JT.MBB));
2464 
2465     DAG.setRoot(BrCond);
2466   } else {
2467     // Avoid emitting unnecessary branches to the next block.
2468     if (JT.MBB != NextBlock(SwitchBB))
2469       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2470                               DAG.getBasicBlock(JT.MBB)));
2471     else
2472       DAG.setRoot(CopyTo);
2473   }
2474 }
2475 
2476 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2477 /// variable if there exists one.
2478 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2479                                  SDValue &Chain) {
2480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2481   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2482   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2485   MachineSDNode *Node =
2486       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2487   if (Global) {
2488     MachinePointerInfo MPInfo(Global);
2489     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2490                  MachineMemOperand::MODereferenceable;
2491     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2492         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2493     DAG.setNodeMemRefs(Node, {MemRef});
2494   }
2495   if (PtrTy != PtrMemTy)
2496     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2497   return SDValue(Node, 0);
2498 }
2499 
2500 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2501 /// tail spliced into a stack protector check success bb.
2502 ///
2503 /// For a high level explanation of how this fits into the stack protector
2504 /// generation see the comment on the declaration of class
2505 /// StackProtectorDescriptor.
2506 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2507                                                   MachineBasicBlock *ParentBB) {
2508 
2509   // First create the loads to the guard/stack slot for the comparison.
2510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2511   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2512   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2513 
2514   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2515   int FI = MFI.getStackProtectorIndex();
2516 
2517   SDValue Guard;
2518   SDLoc dl = getCurSDLoc();
2519   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2520   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2521   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2522 
2523   // Generate code to load the content of the guard slot.
2524   SDValue GuardVal = DAG.getLoad(
2525       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2526       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2527       MachineMemOperand::MOVolatile);
2528 
2529   if (TLI.useStackGuardXorFP())
2530     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2531 
2532   // Retrieve guard check function, nullptr if instrumentation is inlined.
2533   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2534     // The target provides a guard check function to validate the guard value.
2535     // Generate a call to that function with the content of the guard slot as
2536     // argument.
2537     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2538     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2539 
2540     TargetLowering::ArgListTy Args;
2541     TargetLowering::ArgListEntry Entry;
2542     Entry.Node = GuardVal;
2543     Entry.Ty = FnTy->getParamType(0);
2544     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2545       Entry.IsInReg = true;
2546     Args.push_back(Entry);
2547 
2548     TargetLowering::CallLoweringInfo CLI(DAG);
2549     CLI.setDebugLoc(getCurSDLoc())
2550         .setChain(DAG.getEntryNode())
2551         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2552                    getValue(GuardCheckFn), std::move(Args));
2553 
2554     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2555     DAG.setRoot(Result.second);
2556     return;
2557   }
2558 
2559   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2560   // Otherwise, emit a volatile load to retrieve the stack guard value.
2561   SDValue Chain = DAG.getEntryNode();
2562   if (TLI.useLoadStackGuardNode()) {
2563     Guard = getLoadStackGuard(DAG, dl, Chain);
2564   } else {
2565     const Value *IRGuard = TLI.getSDagStackGuard(M);
2566     SDValue GuardPtr = getValue(IRGuard);
2567 
2568     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2569                         MachinePointerInfo(IRGuard, 0), Align,
2570                         MachineMemOperand::MOVolatile);
2571   }
2572 
2573   // Perform the comparison via a subtract/getsetcc.
2574   EVT VT = Guard.getValueType();
2575   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2576 
2577   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2578                                                         *DAG.getContext(),
2579                                                         Sub.getValueType()),
2580                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2581 
2582   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2583   // branch to failure MBB.
2584   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2585                                MVT::Other, GuardVal.getOperand(0),
2586                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2587   // Otherwise branch to success MBB.
2588   SDValue Br = DAG.getNode(ISD::BR, dl,
2589                            MVT::Other, BrCond,
2590                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2591 
2592   DAG.setRoot(Br);
2593 }
2594 
2595 /// Codegen the failure basic block for a stack protector check.
2596 ///
2597 /// A failure stack protector machine basic block consists simply of a call to
2598 /// __stack_chk_fail().
2599 ///
2600 /// For a high level explanation of how this fits into the stack protector
2601 /// generation see the comment on the declaration of class
2602 /// StackProtectorDescriptor.
2603 void
2604 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2606   TargetLowering::MakeLibCallOptions CallOptions;
2607   CallOptions.setDiscardResult(true);
2608   SDValue Chain =
2609       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2610                       None, CallOptions, getCurSDLoc()).second;
2611   // On PS4, the "return address" must still be within the calling function,
2612   // even if it's at the very end, so emit an explicit TRAP here.
2613   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2614   if (TM.getTargetTriple().isPS4CPU())
2615     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2616 
2617   DAG.setRoot(Chain);
2618 }
2619 
2620 /// visitBitTestHeader - This function emits necessary code to produce value
2621 /// suitable for "bit tests"
2622 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2623                                              MachineBasicBlock *SwitchBB) {
2624   SDLoc dl = getCurSDLoc();
2625 
2626   // Subtract the minimum value.
2627   SDValue SwitchOp = getValue(B.SValue);
2628   EVT VT = SwitchOp.getValueType();
2629   SDValue RangeSub =
2630       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2631 
2632   // Determine the type of the test operands.
2633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2634   bool UsePtrType = false;
2635   if (!TLI.isTypeLegal(VT)) {
2636     UsePtrType = true;
2637   } else {
2638     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2639       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2640         // Switch table case range are encoded into series of masks.
2641         // Just use pointer type, it's guaranteed to fit.
2642         UsePtrType = true;
2643         break;
2644       }
2645   }
2646   SDValue Sub = RangeSub;
2647   if (UsePtrType) {
2648     VT = TLI.getPointerTy(DAG.getDataLayout());
2649     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2650   }
2651 
2652   B.RegVT = VT.getSimpleVT();
2653   B.Reg = FuncInfo.CreateReg(B.RegVT);
2654   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2655 
2656   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2657 
2658   if (!B.OmitRangeCheck)
2659     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2660   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2661   SwitchBB->normalizeSuccProbs();
2662 
2663   SDValue Root = CopyTo;
2664   if (!B.OmitRangeCheck) {
2665     // Conditional branch to the default block.
2666     SDValue RangeCmp = DAG.getSetCC(dl,
2667         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2668                                RangeSub.getValueType()),
2669         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2670         ISD::SETUGT);
2671 
2672     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2673                        DAG.getBasicBlock(B.Default));
2674   }
2675 
2676   // Avoid emitting unnecessary branches to the next block.
2677   if (MBB != NextBlock(SwitchBB))
2678     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2679 
2680   DAG.setRoot(Root);
2681 }
2682 
2683 /// visitBitTestCase - this function produces one "bit test"
2684 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2685                                            MachineBasicBlock* NextMBB,
2686                                            BranchProbability BranchProbToNext,
2687                                            unsigned Reg,
2688                                            BitTestCase &B,
2689                                            MachineBasicBlock *SwitchBB) {
2690   SDLoc dl = getCurSDLoc();
2691   MVT VT = BB.RegVT;
2692   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2693   SDValue Cmp;
2694   unsigned PopCount = countPopulation(B.Mask);
2695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2696   if (PopCount == 1) {
2697     // Testing for a single bit; just compare the shift count with what it
2698     // would need to be to shift a 1 bit in that position.
2699     Cmp = DAG.getSetCC(
2700         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2701         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2702         ISD::SETEQ);
2703   } else if (PopCount == BB.Range) {
2704     // There is only one zero bit in the range, test for it directly.
2705     Cmp = DAG.getSetCC(
2706         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2707         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2708         ISD::SETNE);
2709   } else {
2710     // Make desired shift
2711     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2712                                     DAG.getConstant(1, dl, VT), ShiftOp);
2713 
2714     // Emit bit tests and jumps
2715     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2716                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2717     Cmp = DAG.getSetCC(
2718         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2719         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2720   }
2721 
2722   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2723   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2724   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2725   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2726   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2727   // one as they are relative probabilities (and thus work more like weights),
2728   // and hence we need to normalize them to let the sum of them become one.
2729   SwitchBB->normalizeSuccProbs();
2730 
2731   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2732                               MVT::Other, getControlRoot(),
2733                               Cmp, DAG.getBasicBlock(B.TargetBB));
2734 
2735   // Avoid emitting unnecessary branches to the next block.
2736   if (NextMBB != NextBlock(SwitchBB))
2737     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2738                         DAG.getBasicBlock(NextMBB));
2739 
2740   DAG.setRoot(BrAnd);
2741 }
2742 
2743 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2744   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2745 
2746   // Retrieve successors. Look through artificial IR level blocks like
2747   // catchswitch for successors.
2748   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2749   const BasicBlock *EHPadBB = I.getSuccessor(1);
2750 
2751   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2752   // have to do anything here to lower funclet bundles.
2753   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2754                                         LLVMContext::OB_funclet,
2755                                         LLVMContext::OB_cfguardtarget}) &&
2756          "Cannot lower invokes with arbitrary operand bundles yet!");
2757 
2758   const Value *Callee(I.getCalledValue());
2759   const Function *Fn = dyn_cast<Function>(Callee);
2760   if (isa<InlineAsm>(Callee))
2761     visitInlineAsm(&I);
2762   else if (Fn && Fn->isIntrinsic()) {
2763     switch (Fn->getIntrinsicID()) {
2764     default:
2765       llvm_unreachable("Cannot invoke this intrinsic");
2766     case Intrinsic::donothing:
2767       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2768       break;
2769     case Intrinsic::experimental_patchpoint_void:
2770     case Intrinsic::experimental_patchpoint_i64:
2771       visitPatchpoint(&I, EHPadBB);
2772       break;
2773     case Intrinsic::experimental_gc_statepoint:
2774       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2775       break;
2776     case Intrinsic::wasm_rethrow_in_catch: {
2777       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2778       // special because it can be invoked, so we manually lower it to a DAG
2779       // node here.
2780       SmallVector<SDValue, 8> Ops;
2781       Ops.push_back(getRoot()); // inchain
2782       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2783       Ops.push_back(
2784           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2785                                 TLI.getPointerTy(DAG.getDataLayout())));
2786       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2787       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2788       break;
2789     }
2790     }
2791   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2792     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2793     // Eventually we will support lowering the @llvm.experimental.deoptimize
2794     // intrinsic, and right now there are no plans to support other intrinsics
2795     // with deopt state.
2796     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2797   } else {
2798     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2799   }
2800 
2801   // If the value of the invoke is used outside of its defining block, make it
2802   // available as a virtual register.
2803   // We already took care of the exported value for the statepoint instruction
2804   // during call to the LowerStatepoint.
2805   if (!isStatepoint(I)) {
2806     CopyToExportRegsIfNeeded(&I);
2807   }
2808 
2809   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2810   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2811   BranchProbability EHPadBBProb =
2812       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2813           : BranchProbability::getZero();
2814   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2815 
2816   // Update successor info.
2817   addSuccessorWithProb(InvokeMBB, Return);
2818   for (auto &UnwindDest : UnwindDests) {
2819     UnwindDest.first->setIsEHPad();
2820     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2821   }
2822   InvokeMBB->normalizeSuccProbs();
2823 
2824   // Drop into normal successor.
2825   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2826                           DAG.getBasicBlock(Return)));
2827 }
2828 
2829 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2830   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2831 
2832   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2833   // have to do anything here to lower funclet bundles.
2834   assert(!I.hasOperandBundlesOtherThan(
2835              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2836          "Cannot lower callbrs with arbitrary operand bundles yet!");
2837 
2838   assert(isa<InlineAsm>(I.getCalledValue()) &&
2839          "Only know how to handle inlineasm callbr");
2840   visitInlineAsm(&I);
2841 
2842   // Retrieve successors.
2843   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2844 
2845   // Update successor info.
2846   addSuccessorWithProb(CallBrMBB, Return);
2847   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2848     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2849     addSuccessorWithProb(CallBrMBB, Target);
2850   }
2851   CallBrMBB->normalizeSuccProbs();
2852 
2853   // Drop into default successor.
2854   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2855                           MVT::Other, getControlRoot(),
2856                           DAG.getBasicBlock(Return)));
2857 }
2858 
2859 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2860   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2861 }
2862 
2863 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2864   assert(FuncInfo.MBB->isEHPad() &&
2865          "Call to landingpad not in landing pad!");
2866 
2867   // If there aren't registers to copy the values into (e.g., during SjLj
2868   // exceptions), then don't bother to create these DAG nodes.
2869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2870   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2871   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2872       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2873     return;
2874 
2875   // If landingpad's return type is token type, we don't create DAG nodes
2876   // for its exception pointer and selector value. The extraction of exception
2877   // pointer or selector value from token type landingpads is not currently
2878   // supported.
2879   if (LP.getType()->isTokenTy())
2880     return;
2881 
2882   SmallVector<EVT, 2> ValueVTs;
2883   SDLoc dl = getCurSDLoc();
2884   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2885   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2886 
2887   // Get the two live-in registers as SDValues. The physregs have already been
2888   // copied into virtual registers.
2889   SDValue Ops[2];
2890   if (FuncInfo.ExceptionPointerVirtReg) {
2891     Ops[0] = DAG.getZExtOrTrunc(
2892         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2893                            FuncInfo.ExceptionPointerVirtReg,
2894                            TLI.getPointerTy(DAG.getDataLayout())),
2895         dl, ValueVTs[0]);
2896   } else {
2897     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2898   }
2899   Ops[1] = DAG.getZExtOrTrunc(
2900       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2901                          FuncInfo.ExceptionSelectorVirtReg,
2902                          TLI.getPointerTy(DAG.getDataLayout())),
2903       dl, ValueVTs[1]);
2904 
2905   // Merge into one.
2906   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2907                             DAG.getVTList(ValueVTs), Ops);
2908   setValue(&LP, Res);
2909 }
2910 
2911 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2912                                            MachineBasicBlock *Last) {
2913   // Update JTCases.
2914   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2915     if (SL->JTCases[i].first.HeaderBB == First)
2916       SL->JTCases[i].first.HeaderBB = Last;
2917 
2918   // Update BitTestCases.
2919   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2920     if (SL->BitTestCases[i].Parent == First)
2921       SL->BitTestCases[i].Parent = Last;
2922 }
2923 
2924 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2925   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2926 
2927   // Update machine-CFG edges with unique successors.
2928   SmallSet<BasicBlock*, 32> Done;
2929   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2930     BasicBlock *BB = I.getSuccessor(i);
2931     bool Inserted = Done.insert(BB).second;
2932     if (!Inserted)
2933         continue;
2934 
2935     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2936     addSuccessorWithProb(IndirectBrMBB, Succ);
2937   }
2938   IndirectBrMBB->normalizeSuccProbs();
2939 
2940   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2941                           MVT::Other, getControlRoot(),
2942                           getValue(I.getAddress())));
2943 }
2944 
2945 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2946   if (!DAG.getTarget().Options.TrapUnreachable)
2947     return;
2948 
2949   // We may be able to ignore unreachable behind a noreturn call.
2950   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2951     const BasicBlock &BB = *I.getParent();
2952     if (&I != &BB.front()) {
2953       BasicBlock::const_iterator PredI =
2954         std::prev(BasicBlock::const_iterator(&I));
2955       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2956         if (Call->doesNotReturn())
2957           return;
2958       }
2959     }
2960   }
2961 
2962   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2963 }
2964 
2965 void SelectionDAGBuilder::visitFSub(const User &I) {
2966   // -0.0 - X --> fneg
2967   Type *Ty = I.getType();
2968   if (isa<Constant>(I.getOperand(0)) &&
2969       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2970     SDValue Op2 = getValue(I.getOperand(1));
2971     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2972                              Op2.getValueType(), Op2));
2973     return;
2974   }
2975 
2976   visitBinary(I, ISD::FSUB);
2977 }
2978 
2979 /// Checks if the given instruction performs a vector reduction, in which case
2980 /// we have the freedom to alter the elements in the result as long as the
2981 /// reduction of them stays unchanged.
2982 static bool isVectorReductionOp(const User *I) {
2983   const Instruction *Inst = dyn_cast<Instruction>(I);
2984   if (!Inst || !Inst->getType()->isVectorTy())
2985     return false;
2986 
2987   auto OpCode = Inst->getOpcode();
2988   switch (OpCode) {
2989   case Instruction::Add:
2990   case Instruction::Mul:
2991   case Instruction::And:
2992   case Instruction::Or:
2993   case Instruction::Xor:
2994     break;
2995   case Instruction::FAdd:
2996   case Instruction::FMul:
2997     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2998       if (FPOp->getFastMathFlags().isFast())
2999         break;
3000     LLVM_FALLTHROUGH;
3001   default:
3002     return false;
3003   }
3004 
3005   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3006   // Ensure the reduction size is a power of 2.
3007   if (!isPowerOf2_32(ElemNum))
3008     return false;
3009 
3010   unsigned ElemNumToReduce = ElemNum;
3011 
3012   // Do DFS search on the def-use chain from the given instruction. We only
3013   // allow four kinds of operations during the search until we reach the
3014   // instruction that extracts the first element from the vector:
3015   //
3016   //   1. The reduction operation of the same opcode as the given instruction.
3017   //
3018   //   2. PHI node.
3019   //
3020   //   3. ShuffleVector instruction together with a reduction operation that
3021   //      does a partial reduction.
3022   //
3023   //   4. ExtractElement that extracts the first element from the vector, and we
3024   //      stop searching the def-use chain here.
3025   //
3026   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3027   // from 1-3 to the stack to continue the DFS. The given instruction is not
3028   // a reduction operation if we meet any other instructions other than those
3029   // listed above.
3030 
3031   SmallVector<const User *, 16> UsersToVisit{Inst};
3032   SmallPtrSet<const User *, 16> Visited;
3033   bool ReduxExtracted = false;
3034 
3035   while (!UsersToVisit.empty()) {
3036     auto User = UsersToVisit.back();
3037     UsersToVisit.pop_back();
3038     if (!Visited.insert(User).second)
3039       continue;
3040 
3041     for (const auto &U : User->users()) {
3042       auto Inst = dyn_cast<Instruction>(U);
3043       if (!Inst)
3044         return false;
3045 
3046       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3047         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3048           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3049             return false;
3050         UsersToVisit.push_back(U);
3051       } else if (const ShuffleVectorInst *ShufInst =
3052                      dyn_cast<ShuffleVectorInst>(U)) {
3053         // Detect the following pattern: A ShuffleVector instruction together
3054         // with a reduction that do partial reduction on the first and second
3055         // ElemNumToReduce / 2 elements, and store the result in
3056         // ElemNumToReduce / 2 elements in another vector.
3057 
3058         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3059         if (ResultElements < ElemNum)
3060           return false;
3061 
3062         if (ElemNumToReduce == 1)
3063           return false;
3064         if (!isa<UndefValue>(U->getOperand(1)))
3065           return false;
3066         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3067           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3068             return false;
3069         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3070           if (ShufInst->getMaskValue(i) != -1)
3071             return false;
3072 
3073         // There is only one user of this ShuffleVector instruction, which
3074         // must be a reduction operation.
3075         if (!U->hasOneUse())
3076           return false;
3077 
3078         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3079         if (!U2 || U2->getOpcode() != OpCode)
3080           return false;
3081 
3082         // Check operands of the reduction operation.
3083         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3084             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3085           UsersToVisit.push_back(U2);
3086           ElemNumToReduce /= 2;
3087         } else
3088           return false;
3089       } else if (isa<ExtractElementInst>(U)) {
3090         // At this moment we should have reduced all elements in the vector.
3091         if (ElemNumToReduce != 1)
3092           return false;
3093 
3094         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3095         if (!Val || !Val->isZero())
3096           return false;
3097 
3098         ReduxExtracted = true;
3099       } else
3100         return false;
3101     }
3102   }
3103   return ReduxExtracted;
3104 }
3105 
3106 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3107   SDNodeFlags Flags;
3108 
3109   SDValue Op = getValue(I.getOperand(0));
3110   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3111                                     Op, Flags);
3112   setValue(&I, UnNodeValue);
3113 }
3114 
3115 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3116   SDNodeFlags Flags;
3117   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3118     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3119     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3120   }
3121   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3122     Flags.setExact(ExactOp->isExact());
3123   }
3124   if (isVectorReductionOp(&I)) {
3125     Flags.setVectorReduction(true);
3126     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3127 
3128     // If no flags are set we will propagate the incoming flags, if any flags
3129     // are set, we will intersect them with the incoming flag and so we need to
3130     // copy the FMF flags here.
3131     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3132       Flags.copyFMF(*FPOp);
3133     }
3134   }
3135 
3136   SDValue Op1 = getValue(I.getOperand(0));
3137   SDValue Op2 = getValue(I.getOperand(1));
3138   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3139                                      Op1, Op2, Flags);
3140   setValue(&I, BinNodeValue);
3141 }
3142 
3143 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3144   SDValue Op1 = getValue(I.getOperand(0));
3145   SDValue Op2 = getValue(I.getOperand(1));
3146 
3147   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3148       Op1.getValueType(), DAG.getDataLayout());
3149 
3150   // Coerce the shift amount to the right type if we can.
3151   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3152     unsigned ShiftSize = ShiftTy.getSizeInBits();
3153     unsigned Op2Size = Op2.getValueSizeInBits();
3154     SDLoc DL = getCurSDLoc();
3155 
3156     // If the operand is smaller than the shift count type, promote it.
3157     if (ShiftSize > Op2Size)
3158       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3159 
3160     // If the operand is larger than the shift count type but the shift
3161     // count type has enough bits to represent any shift value, truncate
3162     // it now. This is a common case and it exposes the truncate to
3163     // optimization early.
3164     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3165       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3166     // Otherwise we'll need to temporarily settle for some other convenient
3167     // type.  Type legalization will make adjustments once the shiftee is split.
3168     else
3169       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3170   }
3171 
3172   bool nuw = false;
3173   bool nsw = false;
3174   bool exact = false;
3175 
3176   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3177 
3178     if (const OverflowingBinaryOperator *OFBinOp =
3179             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3180       nuw = OFBinOp->hasNoUnsignedWrap();
3181       nsw = OFBinOp->hasNoSignedWrap();
3182     }
3183     if (const PossiblyExactOperator *ExactOp =
3184             dyn_cast<const PossiblyExactOperator>(&I))
3185       exact = ExactOp->isExact();
3186   }
3187   SDNodeFlags Flags;
3188   Flags.setExact(exact);
3189   Flags.setNoSignedWrap(nsw);
3190   Flags.setNoUnsignedWrap(nuw);
3191   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3192                             Flags);
3193   setValue(&I, Res);
3194 }
3195 
3196 void SelectionDAGBuilder::visitSDiv(const User &I) {
3197   SDValue Op1 = getValue(I.getOperand(0));
3198   SDValue Op2 = getValue(I.getOperand(1));
3199 
3200   SDNodeFlags Flags;
3201   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3202                  cast<PossiblyExactOperator>(&I)->isExact());
3203   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3204                            Op2, Flags));
3205 }
3206 
3207 void SelectionDAGBuilder::visitICmp(const User &I) {
3208   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3209   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3210     predicate = IC->getPredicate();
3211   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3212     predicate = ICmpInst::Predicate(IC->getPredicate());
3213   SDValue Op1 = getValue(I.getOperand(0));
3214   SDValue Op2 = getValue(I.getOperand(1));
3215   ISD::CondCode Opcode = getICmpCondCode(predicate);
3216 
3217   auto &TLI = DAG.getTargetLoweringInfo();
3218   EVT MemVT =
3219       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3220 
3221   // If a pointer's DAG type is larger than its memory type then the DAG values
3222   // are zero-extended. This breaks signed comparisons so truncate back to the
3223   // underlying type before doing the compare.
3224   if (Op1.getValueType() != MemVT) {
3225     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3226     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3227   }
3228 
3229   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3230                                                         I.getType());
3231   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3232 }
3233 
3234 void SelectionDAGBuilder::visitFCmp(const User &I) {
3235   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3236   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3237     predicate = FC->getPredicate();
3238   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3239     predicate = FCmpInst::Predicate(FC->getPredicate());
3240   SDValue Op1 = getValue(I.getOperand(0));
3241   SDValue Op2 = getValue(I.getOperand(1));
3242 
3243   ISD::CondCode Condition = getFCmpCondCode(predicate);
3244   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3245   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3246     Condition = getFCmpCodeWithoutNaN(Condition);
3247 
3248   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3249                                                         I.getType());
3250   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3251 }
3252 
3253 // Check if the condition of the select has one use or two users that are both
3254 // selects with the same condition.
3255 static bool hasOnlySelectUsers(const Value *Cond) {
3256   return llvm::all_of(Cond->users(), [](const Value *V) {
3257     return isa<SelectInst>(V);
3258   });
3259 }
3260 
3261 void SelectionDAGBuilder::visitSelect(const User &I) {
3262   SmallVector<EVT, 4> ValueVTs;
3263   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3264                   ValueVTs);
3265   unsigned NumValues = ValueVTs.size();
3266   if (NumValues == 0) return;
3267 
3268   SmallVector<SDValue, 4> Values(NumValues);
3269   SDValue Cond     = getValue(I.getOperand(0));
3270   SDValue LHSVal   = getValue(I.getOperand(1));
3271   SDValue RHSVal   = getValue(I.getOperand(2));
3272   auto BaseOps = {Cond};
3273   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3274     ISD::VSELECT : ISD::SELECT;
3275 
3276   bool IsUnaryAbs = false;
3277 
3278   // Min/max matching is only viable if all output VTs are the same.
3279   if (is_splat(ValueVTs)) {
3280     EVT VT = ValueVTs[0];
3281     LLVMContext &Ctx = *DAG.getContext();
3282     auto &TLI = DAG.getTargetLoweringInfo();
3283 
3284     // We care about the legality of the operation after it has been type
3285     // legalized.
3286     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3287       VT = TLI.getTypeToTransformTo(Ctx, VT);
3288 
3289     // If the vselect is legal, assume we want to leave this as a vector setcc +
3290     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3291     // min/max is legal on the scalar type.
3292     bool UseScalarMinMax = VT.isVector() &&
3293       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3294 
3295     Value *LHS, *RHS;
3296     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3297     ISD::NodeType Opc = ISD::DELETED_NODE;
3298     switch (SPR.Flavor) {
3299     case SPF_UMAX:    Opc = ISD::UMAX; break;
3300     case SPF_UMIN:    Opc = ISD::UMIN; break;
3301     case SPF_SMAX:    Opc = ISD::SMAX; break;
3302     case SPF_SMIN:    Opc = ISD::SMIN; break;
3303     case SPF_FMINNUM:
3304       switch (SPR.NaNBehavior) {
3305       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3306       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3307       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3308       case SPNB_RETURNS_ANY: {
3309         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3310           Opc = ISD::FMINNUM;
3311         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3312           Opc = ISD::FMINIMUM;
3313         else if (UseScalarMinMax)
3314           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3315             ISD::FMINNUM : ISD::FMINIMUM;
3316         break;
3317       }
3318       }
3319       break;
3320     case SPF_FMAXNUM:
3321       switch (SPR.NaNBehavior) {
3322       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3323       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3324       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3325       case SPNB_RETURNS_ANY:
3326 
3327         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3328           Opc = ISD::FMAXNUM;
3329         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3330           Opc = ISD::FMAXIMUM;
3331         else if (UseScalarMinMax)
3332           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3333             ISD::FMAXNUM : ISD::FMAXIMUM;
3334         break;
3335       }
3336       break;
3337     case SPF_ABS:
3338       IsUnaryAbs = true;
3339       Opc = ISD::ABS;
3340       break;
3341     case SPF_NABS:
3342       // TODO: we need to produce sub(0, abs(X)).
3343     default: break;
3344     }
3345 
3346     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3347         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3348          (UseScalarMinMax &&
3349           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3350         // If the underlying comparison instruction is used by any other
3351         // instruction, the consumed instructions won't be destroyed, so it is
3352         // not profitable to convert to a min/max.
3353         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3354       OpCode = Opc;
3355       LHSVal = getValue(LHS);
3356       RHSVal = getValue(RHS);
3357       BaseOps = {};
3358     }
3359 
3360     if (IsUnaryAbs) {
3361       OpCode = Opc;
3362       LHSVal = getValue(LHS);
3363       BaseOps = {};
3364     }
3365   }
3366 
3367   if (IsUnaryAbs) {
3368     for (unsigned i = 0; i != NumValues; ++i) {
3369       Values[i] =
3370           DAG.getNode(OpCode, getCurSDLoc(),
3371                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3372                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3373     }
3374   } else {
3375     for (unsigned i = 0; i != NumValues; ++i) {
3376       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3377       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3378       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3379       Values[i] = DAG.getNode(
3380           OpCode, getCurSDLoc(),
3381           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3382     }
3383   }
3384 
3385   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3386                            DAG.getVTList(ValueVTs), Values));
3387 }
3388 
3389 void SelectionDAGBuilder::visitTrunc(const User &I) {
3390   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3391   SDValue N = getValue(I.getOperand(0));
3392   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3393                                                         I.getType());
3394   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3395 }
3396 
3397 void SelectionDAGBuilder::visitZExt(const User &I) {
3398   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3399   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3400   SDValue N = getValue(I.getOperand(0));
3401   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3402                                                         I.getType());
3403   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3404 }
3405 
3406 void SelectionDAGBuilder::visitSExt(const User &I) {
3407   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3408   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3409   SDValue N = getValue(I.getOperand(0));
3410   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3411                                                         I.getType());
3412   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3413 }
3414 
3415 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3416   // FPTrunc is never a no-op cast, no need to check
3417   SDValue N = getValue(I.getOperand(0));
3418   SDLoc dl = getCurSDLoc();
3419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3420   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3421   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3422                            DAG.getTargetConstant(
3423                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3424 }
3425 
3426 void SelectionDAGBuilder::visitFPExt(const User &I) {
3427   // FPExt is never a no-op cast, no need to check
3428   SDValue N = getValue(I.getOperand(0));
3429   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3430                                                         I.getType());
3431   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3432 }
3433 
3434 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3435   // FPToUI is never a no-op cast, no need to check
3436   SDValue N = getValue(I.getOperand(0));
3437   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3438                                                         I.getType());
3439   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3440 }
3441 
3442 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3443   // FPToSI is never a no-op cast, no need to check
3444   SDValue N = getValue(I.getOperand(0));
3445   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3446                                                         I.getType());
3447   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3448 }
3449 
3450 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3451   // UIToFP is never a no-op cast, no need to check
3452   SDValue N = getValue(I.getOperand(0));
3453   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3454                                                         I.getType());
3455   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3459   // SIToFP is never a no-op cast, no need to check
3460   SDValue N = getValue(I.getOperand(0));
3461   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3462                                                         I.getType());
3463   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3464 }
3465 
3466 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3467   // What to do depends on the size of the integer and the size of the pointer.
3468   // We can either truncate, zero extend, or no-op, accordingly.
3469   SDValue N = getValue(I.getOperand(0));
3470   auto &TLI = DAG.getTargetLoweringInfo();
3471   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3472                                                         I.getType());
3473   EVT PtrMemVT =
3474       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3475   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3476   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3477   setValue(&I, N);
3478 }
3479 
3480 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3481   // What to do depends on the size of the integer and the size of the pointer.
3482   // We can either truncate, zero extend, or no-op, accordingly.
3483   SDValue N = getValue(I.getOperand(0));
3484   auto &TLI = DAG.getTargetLoweringInfo();
3485   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3486   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3487   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3488   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3489   setValue(&I, N);
3490 }
3491 
3492 void SelectionDAGBuilder::visitBitCast(const User &I) {
3493   SDValue N = getValue(I.getOperand(0));
3494   SDLoc dl = getCurSDLoc();
3495   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3496                                                         I.getType());
3497 
3498   // BitCast assures us that source and destination are the same size so this is
3499   // either a BITCAST or a no-op.
3500   if (DestVT != N.getValueType())
3501     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3502                              DestVT, N)); // convert types.
3503   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3504   // might fold any kind of constant expression to an integer constant and that
3505   // is not what we are looking for. Only recognize a bitcast of a genuine
3506   // constant integer as an opaque constant.
3507   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3508     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3509                                  /*isOpaque*/true));
3510   else
3511     setValue(&I, N);            // noop cast.
3512 }
3513 
3514 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3516   const Value *SV = I.getOperand(0);
3517   SDValue N = getValue(SV);
3518   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3519 
3520   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3521   unsigned DestAS = I.getType()->getPointerAddressSpace();
3522 
3523   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3524     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3525 
3526   setValue(&I, N);
3527 }
3528 
3529 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3531   SDValue InVec = getValue(I.getOperand(0));
3532   SDValue InVal = getValue(I.getOperand(1));
3533   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3534                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3535   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3536                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3537                            InVec, InVal, InIdx));
3538 }
3539 
3540 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3542   SDValue InVec = getValue(I.getOperand(0));
3543   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3544                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3545   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3546                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3547                            InVec, InIdx));
3548 }
3549 
3550 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3551   SDValue Src1 = getValue(I.getOperand(0));
3552   SDValue Src2 = getValue(I.getOperand(1));
3553   Constant *MaskV = cast<Constant>(I.getOperand(2));
3554   SDLoc DL = getCurSDLoc();
3555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3556   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3557   EVT SrcVT = Src1.getValueType();
3558   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3559 
3560   if (MaskV->isNullValue() && VT.isScalableVector()) {
3561     // Canonical splat form of first element of first input vector.
3562     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3563                                    SrcVT.getScalarType(), Src1,
3564                                    DAG.getConstant(0, DL,
3565                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3566     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3567     return;
3568   }
3569 
3570   // For now, we only handle splats for scalable vectors.
3571   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3572   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3573   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3574 
3575   SmallVector<int, 8> Mask;
3576   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3577   unsigned MaskNumElts = Mask.size();
3578 
3579   if (SrcNumElts == MaskNumElts) {
3580     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3581     return;
3582   }
3583 
3584   // Normalize the shuffle vector since mask and vector length don't match.
3585   if (SrcNumElts < MaskNumElts) {
3586     // Mask is longer than the source vectors. We can use concatenate vector to
3587     // make the mask and vectors lengths match.
3588 
3589     if (MaskNumElts % SrcNumElts == 0) {
3590       // Mask length is a multiple of the source vector length.
3591       // Check if the shuffle is some kind of concatenation of the input
3592       // vectors.
3593       unsigned NumConcat = MaskNumElts / SrcNumElts;
3594       bool IsConcat = true;
3595       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3596       for (unsigned i = 0; i != MaskNumElts; ++i) {
3597         int Idx = Mask[i];
3598         if (Idx < 0)
3599           continue;
3600         // Ensure the indices in each SrcVT sized piece are sequential and that
3601         // the same source is used for the whole piece.
3602         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3603             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3604              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3605           IsConcat = false;
3606           break;
3607         }
3608         // Remember which source this index came from.
3609         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3610       }
3611 
3612       // The shuffle is concatenating multiple vectors together. Just emit
3613       // a CONCAT_VECTORS operation.
3614       if (IsConcat) {
3615         SmallVector<SDValue, 8> ConcatOps;
3616         for (auto Src : ConcatSrcs) {
3617           if (Src < 0)
3618             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3619           else if (Src == 0)
3620             ConcatOps.push_back(Src1);
3621           else
3622             ConcatOps.push_back(Src2);
3623         }
3624         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3625         return;
3626       }
3627     }
3628 
3629     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3630     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3631     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3632                                     PaddedMaskNumElts);
3633 
3634     // Pad both vectors with undefs to make them the same length as the mask.
3635     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3636 
3637     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3638     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3639     MOps1[0] = Src1;
3640     MOps2[0] = Src2;
3641 
3642     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3643     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3644 
3645     // Readjust mask for new input vector length.
3646     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3647     for (unsigned i = 0; i != MaskNumElts; ++i) {
3648       int Idx = Mask[i];
3649       if (Idx >= (int)SrcNumElts)
3650         Idx -= SrcNumElts - PaddedMaskNumElts;
3651       MappedOps[i] = Idx;
3652     }
3653 
3654     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3655 
3656     // If the concatenated vector was padded, extract a subvector with the
3657     // correct number of elements.
3658     if (MaskNumElts != PaddedMaskNumElts)
3659       Result = DAG.getNode(
3660           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3661           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3662 
3663     setValue(&I, Result);
3664     return;
3665   }
3666 
3667   if (SrcNumElts > MaskNumElts) {
3668     // Analyze the access pattern of the vector to see if we can extract
3669     // two subvectors and do the shuffle.
3670     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3671     bool CanExtract = true;
3672     for (int Idx : Mask) {
3673       unsigned Input = 0;
3674       if (Idx < 0)
3675         continue;
3676 
3677       if (Idx >= (int)SrcNumElts) {
3678         Input = 1;
3679         Idx -= SrcNumElts;
3680       }
3681 
3682       // If all the indices come from the same MaskNumElts sized portion of
3683       // the sources we can use extract. Also make sure the extract wouldn't
3684       // extract past the end of the source.
3685       int NewStartIdx = alignDown(Idx, MaskNumElts);
3686       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3687           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3688         CanExtract = false;
3689       // Make sure we always update StartIdx as we use it to track if all
3690       // elements are undef.
3691       StartIdx[Input] = NewStartIdx;
3692     }
3693 
3694     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3695       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3696       return;
3697     }
3698     if (CanExtract) {
3699       // Extract appropriate subvector and generate a vector shuffle
3700       for (unsigned Input = 0; Input < 2; ++Input) {
3701         SDValue &Src = Input == 0 ? Src1 : Src2;
3702         if (StartIdx[Input] < 0)
3703           Src = DAG.getUNDEF(VT);
3704         else {
3705           Src = DAG.getNode(
3706               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3707               DAG.getConstant(StartIdx[Input], DL,
3708                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3709         }
3710       }
3711 
3712       // Calculate new mask.
3713       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3714       for (int &Idx : MappedOps) {
3715         if (Idx >= (int)SrcNumElts)
3716           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3717         else if (Idx >= 0)
3718           Idx -= StartIdx[0];
3719       }
3720 
3721       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3722       return;
3723     }
3724   }
3725 
3726   // We can't use either concat vectors or extract subvectors so fall back to
3727   // replacing the shuffle with extract and build vector.
3728   // to insert and build vector.
3729   EVT EltVT = VT.getVectorElementType();
3730   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3731   SmallVector<SDValue,8> Ops;
3732   for (int Idx : Mask) {
3733     SDValue Res;
3734 
3735     if (Idx < 0) {
3736       Res = DAG.getUNDEF(EltVT);
3737     } else {
3738       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3739       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3740 
3741       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3742                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3743     }
3744 
3745     Ops.push_back(Res);
3746   }
3747 
3748   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3749 }
3750 
3751 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3752   ArrayRef<unsigned> Indices;
3753   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3754     Indices = IV->getIndices();
3755   else
3756     Indices = cast<ConstantExpr>(&I)->getIndices();
3757 
3758   const Value *Op0 = I.getOperand(0);
3759   const Value *Op1 = I.getOperand(1);
3760   Type *AggTy = I.getType();
3761   Type *ValTy = Op1->getType();
3762   bool IntoUndef = isa<UndefValue>(Op0);
3763   bool FromUndef = isa<UndefValue>(Op1);
3764 
3765   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3766 
3767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3768   SmallVector<EVT, 4> AggValueVTs;
3769   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3770   SmallVector<EVT, 4> ValValueVTs;
3771   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3772 
3773   unsigned NumAggValues = AggValueVTs.size();
3774   unsigned NumValValues = ValValueVTs.size();
3775   SmallVector<SDValue, 4> Values(NumAggValues);
3776 
3777   // Ignore an insertvalue that produces an empty object
3778   if (!NumAggValues) {
3779     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3780     return;
3781   }
3782 
3783   SDValue Agg = getValue(Op0);
3784   unsigned i = 0;
3785   // Copy the beginning value(s) from the original aggregate.
3786   for (; i != LinearIndex; ++i)
3787     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3788                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3789   // Copy values from the inserted value(s).
3790   if (NumValValues) {
3791     SDValue Val = getValue(Op1);
3792     for (; i != LinearIndex + NumValValues; ++i)
3793       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3794                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3795   }
3796   // Copy remaining value(s) from the original aggregate.
3797   for (; i != NumAggValues; ++i)
3798     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3799                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3800 
3801   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3802                            DAG.getVTList(AggValueVTs), Values));
3803 }
3804 
3805 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3806   ArrayRef<unsigned> Indices;
3807   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3808     Indices = EV->getIndices();
3809   else
3810     Indices = cast<ConstantExpr>(&I)->getIndices();
3811 
3812   const Value *Op0 = I.getOperand(0);
3813   Type *AggTy = Op0->getType();
3814   Type *ValTy = I.getType();
3815   bool OutOfUndef = isa<UndefValue>(Op0);
3816 
3817   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3818 
3819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3820   SmallVector<EVT, 4> ValValueVTs;
3821   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3822 
3823   unsigned NumValValues = ValValueVTs.size();
3824 
3825   // Ignore a extractvalue that produces an empty object
3826   if (!NumValValues) {
3827     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3828     return;
3829   }
3830 
3831   SmallVector<SDValue, 4> Values(NumValValues);
3832 
3833   SDValue Agg = getValue(Op0);
3834   // Copy out the selected value(s).
3835   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3836     Values[i - LinearIndex] =
3837       OutOfUndef ?
3838         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3839         SDValue(Agg.getNode(), Agg.getResNo() + i);
3840 
3841   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3842                            DAG.getVTList(ValValueVTs), Values));
3843 }
3844 
3845 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3846   Value *Op0 = I.getOperand(0);
3847   // Note that the pointer operand may be a vector of pointers. Take the scalar
3848   // element which holds a pointer.
3849   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3850   SDValue N = getValue(Op0);
3851   SDLoc dl = getCurSDLoc();
3852   auto &TLI = DAG.getTargetLoweringInfo();
3853   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3854   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3855 
3856   // Normalize Vector GEP - all scalar operands should be converted to the
3857   // splat vector.
3858   unsigned VectorWidth = I.getType()->isVectorTy() ?
3859     I.getType()->getVectorNumElements() : 0;
3860 
3861   if (VectorWidth && !N.getValueType().isVector()) {
3862     LLVMContext &Context = *DAG.getContext();
3863     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3864     N = DAG.getSplatBuildVector(VT, dl, N);
3865   }
3866 
3867   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3868        GTI != E; ++GTI) {
3869     const Value *Idx = GTI.getOperand();
3870     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3871       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3872       if (Field) {
3873         // N = N + Offset
3874         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3875 
3876         // In an inbounds GEP with an offset that is nonnegative even when
3877         // interpreted as signed, assume there is no unsigned overflow.
3878         SDNodeFlags Flags;
3879         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3880           Flags.setNoUnsignedWrap(true);
3881 
3882         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3883                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3884       }
3885     } else {
3886       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3887       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3888       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3889 
3890       // If this is a scalar constant or a splat vector of constants,
3891       // handle it quickly.
3892       const auto *C = dyn_cast<Constant>(Idx);
3893       if (C && isa<VectorType>(C->getType()))
3894         C = C->getSplatValue();
3895 
3896       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3897         if (CI->isZero())
3898           continue;
3899         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3900         LLVMContext &Context = *DAG.getContext();
3901         SDValue OffsVal = VectorWidth ?
3902           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3903           DAG.getConstant(Offs, dl, IdxTy);
3904 
3905         // In an inbounds GEP with an offset that is nonnegative even when
3906         // interpreted as signed, assume there is no unsigned overflow.
3907         SDNodeFlags Flags;
3908         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3909           Flags.setNoUnsignedWrap(true);
3910 
3911         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3912 
3913         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3914         continue;
3915       }
3916 
3917       // N = N + Idx * ElementSize;
3918       SDValue IdxN = getValue(Idx);
3919 
3920       if (!IdxN.getValueType().isVector() && VectorWidth) {
3921         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3922         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3923       }
3924 
3925       // If the index is smaller or larger than intptr_t, truncate or extend
3926       // it.
3927       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3928 
3929       // If this is a multiply by a power of two, turn it into a shl
3930       // immediately.  This is a very common case.
3931       if (ElementSize != 1) {
3932         if (ElementSize.isPowerOf2()) {
3933           unsigned Amt = ElementSize.logBase2();
3934           IdxN = DAG.getNode(ISD::SHL, dl,
3935                              N.getValueType(), IdxN,
3936                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3937         } else {
3938           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3939                                           IdxN.getValueType());
3940           IdxN = DAG.getNode(ISD::MUL, dl,
3941                              N.getValueType(), IdxN, Scale);
3942         }
3943       }
3944 
3945       N = DAG.getNode(ISD::ADD, dl,
3946                       N.getValueType(), N, IdxN);
3947     }
3948   }
3949 
3950   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3951     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3952 
3953   setValue(&I, N);
3954 }
3955 
3956 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3957   // If this is a fixed sized alloca in the entry block of the function,
3958   // allocate it statically on the stack.
3959   if (FuncInfo.StaticAllocaMap.count(&I))
3960     return;   // getValue will auto-populate this.
3961 
3962   SDLoc dl = getCurSDLoc();
3963   Type *Ty = I.getAllocatedType();
3964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3965   auto &DL = DAG.getDataLayout();
3966   uint64_t TySize = DL.getTypeAllocSize(Ty);
3967   unsigned Align =
3968       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3969 
3970   SDValue AllocSize = getValue(I.getArraySize());
3971 
3972   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3973   if (AllocSize.getValueType() != IntPtr)
3974     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3975 
3976   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3977                           AllocSize,
3978                           DAG.getConstant(TySize, dl, IntPtr));
3979 
3980   // Handle alignment.  If the requested alignment is less than or equal to
3981   // the stack alignment, ignore it.  If the size is greater than or equal to
3982   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3983   unsigned StackAlign =
3984       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3985   if (Align <= StackAlign)
3986     Align = 0;
3987 
3988   // Round the size of the allocation up to the stack alignment size
3989   // by add SA-1 to the size. This doesn't overflow because we're computing
3990   // an address inside an alloca.
3991   SDNodeFlags Flags;
3992   Flags.setNoUnsignedWrap(true);
3993   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3994                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3995 
3996   // Mask out the low bits for alignment purposes.
3997   AllocSize =
3998       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3999                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4000 
4001   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4002   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4003   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4004   setValue(&I, DSA);
4005   DAG.setRoot(DSA.getValue(1));
4006 
4007   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4008 }
4009 
4010 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4011   if (I.isAtomic())
4012     return visitAtomicLoad(I);
4013 
4014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4015   const Value *SV = I.getOperand(0);
4016   if (TLI.supportSwiftError()) {
4017     // Swifterror values can come from either a function parameter with
4018     // swifterror attribute or an alloca with swifterror attribute.
4019     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4020       if (Arg->hasSwiftErrorAttr())
4021         return visitLoadFromSwiftError(I);
4022     }
4023 
4024     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4025       if (Alloca->isSwiftError())
4026         return visitLoadFromSwiftError(I);
4027     }
4028   }
4029 
4030   SDValue Ptr = getValue(SV);
4031 
4032   Type *Ty = I.getType();
4033 
4034   bool isVolatile = I.isVolatile();
4035   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4036   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4037   bool isDereferenceable =
4038       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4039   unsigned Alignment = I.getAlignment();
4040 
4041   AAMDNodes AAInfo;
4042   I.getAAMetadata(AAInfo);
4043   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4044 
4045   SmallVector<EVT, 4> ValueVTs, MemVTs;
4046   SmallVector<uint64_t, 4> Offsets;
4047   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4048   unsigned NumValues = ValueVTs.size();
4049   if (NumValues == 0)
4050     return;
4051 
4052   SDValue Root;
4053   bool ConstantMemory = false;
4054   if (isVolatile || NumValues > MaxParallelChains)
4055     // Serialize volatile loads with other side effects.
4056     Root = getRoot();
4057   else if (AA &&
4058            AA->pointsToConstantMemory(MemoryLocation(
4059                SV,
4060                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4061                AAInfo))) {
4062     // Do not serialize (non-volatile) loads of constant memory with anything.
4063     Root = DAG.getEntryNode();
4064     ConstantMemory = true;
4065   } else {
4066     // Do not serialize non-volatile loads against each other.
4067     Root = DAG.getRoot();
4068   }
4069 
4070   SDLoc dl = getCurSDLoc();
4071 
4072   if (isVolatile)
4073     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4074 
4075   // An aggregate load cannot wrap around the address space, so offsets to its
4076   // parts don't wrap either.
4077   SDNodeFlags Flags;
4078   Flags.setNoUnsignedWrap(true);
4079 
4080   SmallVector<SDValue, 4> Values(NumValues);
4081   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4082   EVT PtrVT = Ptr.getValueType();
4083   unsigned ChainI = 0;
4084   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4085     // Serializing loads here may result in excessive register pressure, and
4086     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4087     // could recover a bit by hoisting nodes upward in the chain by recognizing
4088     // they are side-effect free or do not alias. The optimizer should really
4089     // avoid this case by converting large object/array copies to llvm.memcpy
4090     // (MaxParallelChains should always remain as failsafe).
4091     if (ChainI == MaxParallelChains) {
4092       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4093       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4094                                   makeArrayRef(Chains.data(), ChainI));
4095       Root = Chain;
4096       ChainI = 0;
4097     }
4098     SDValue A = DAG.getNode(ISD::ADD, dl,
4099                             PtrVT, Ptr,
4100                             DAG.getConstant(Offsets[i], dl, PtrVT),
4101                             Flags);
4102     auto MMOFlags = MachineMemOperand::MONone;
4103     if (isVolatile)
4104       MMOFlags |= MachineMemOperand::MOVolatile;
4105     if (isNonTemporal)
4106       MMOFlags |= MachineMemOperand::MONonTemporal;
4107     if (isInvariant)
4108       MMOFlags |= MachineMemOperand::MOInvariant;
4109     if (isDereferenceable)
4110       MMOFlags |= MachineMemOperand::MODereferenceable;
4111     MMOFlags |= TLI.getMMOFlags(I);
4112 
4113     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4114                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4115                             MMOFlags, AAInfo, Ranges);
4116     Chains[ChainI] = L.getValue(1);
4117 
4118     if (MemVTs[i] != ValueVTs[i])
4119       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4120 
4121     Values[i] = L;
4122   }
4123 
4124   if (!ConstantMemory) {
4125     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4126                                 makeArrayRef(Chains.data(), ChainI));
4127     if (isVolatile)
4128       DAG.setRoot(Chain);
4129     else
4130       PendingLoads.push_back(Chain);
4131   }
4132 
4133   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4134                            DAG.getVTList(ValueVTs), Values));
4135 }
4136 
4137 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4138   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4139          "call visitStoreToSwiftError when backend supports swifterror");
4140 
4141   SmallVector<EVT, 4> ValueVTs;
4142   SmallVector<uint64_t, 4> Offsets;
4143   const Value *SrcV = I.getOperand(0);
4144   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4145                   SrcV->getType(), ValueVTs, &Offsets);
4146   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4147          "expect a single EVT for swifterror");
4148 
4149   SDValue Src = getValue(SrcV);
4150   // Create a virtual register, then update the virtual register.
4151   Register VReg =
4152       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4153   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4154   // Chain can be getRoot or getControlRoot.
4155   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4156                                       SDValue(Src.getNode(), Src.getResNo()));
4157   DAG.setRoot(CopyNode);
4158 }
4159 
4160 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4161   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4162          "call visitLoadFromSwiftError when backend supports swifterror");
4163 
4164   assert(!I.isVolatile() &&
4165          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4166          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4167          "Support volatile, non temporal, invariant for load_from_swift_error");
4168 
4169   const Value *SV = I.getOperand(0);
4170   Type *Ty = I.getType();
4171   AAMDNodes AAInfo;
4172   I.getAAMetadata(AAInfo);
4173   assert(
4174       (!AA ||
4175        !AA->pointsToConstantMemory(MemoryLocation(
4176            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4177            AAInfo))) &&
4178       "load_from_swift_error should not be constant memory");
4179 
4180   SmallVector<EVT, 4> ValueVTs;
4181   SmallVector<uint64_t, 4> Offsets;
4182   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4183                   ValueVTs, &Offsets);
4184   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4185          "expect a single EVT for swifterror");
4186 
4187   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4188   SDValue L = DAG.getCopyFromReg(
4189       getRoot(), getCurSDLoc(),
4190       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4191 
4192   setValue(&I, L);
4193 }
4194 
4195 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4196   if (I.isAtomic())
4197     return visitAtomicStore(I);
4198 
4199   const Value *SrcV = I.getOperand(0);
4200   const Value *PtrV = I.getOperand(1);
4201 
4202   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4203   if (TLI.supportSwiftError()) {
4204     // Swifterror values can come from either a function parameter with
4205     // swifterror attribute or an alloca with swifterror attribute.
4206     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4207       if (Arg->hasSwiftErrorAttr())
4208         return visitStoreToSwiftError(I);
4209     }
4210 
4211     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4212       if (Alloca->isSwiftError())
4213         return visitStoreToSwiftError(I);
4214     }
4215   }
4216 
4217   SmallVector<EVT, 4> ValueVTs, MemVTs;
4218   SmallVector<uint64_t, 4> Offsets;
4219   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4220                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4221   unsigned NumValues = ValueVTs.size();
4222   if (NumValues == 0)
4223     return;
4224 
4225   // Get the lowered operands. Note that we do this after
4226   // checking if NumResults is zero, because with zero results
4227   // the operands won't have values in the map.
4228   SDValue Src = getValue(SrcV);
4229   SDValue Ptr = getValue(PtrV);
4230 
4231   SDValue Root = getRoot();
4232   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4233   SDLoc dl = getCurSDLoc();
4234   unsigned Alignment = I.getAlignment();
4235   AAMDNodes AAInfo;
4236   I.getAAMetadata(AAInfo);
4237 
4238   auto MMOFlags = MachineMemOperand::MONone;
4239   if (I.isVolatile())
4240     MMOFlags |= MachineMemOperand::MOVolatile;
4241   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4242     MMOFlags |= MachineMemOperand::MONonTemporal;
4243   MMOFlags |= TLI.getMMOFlags(I);
4244 
4245   // An aggregate load cannot wrap around the address space, so offsets to its
4246   // parts don't wrap either.
4247   SDNodeFlags Flags;
4248   Flags.setNoUnsignedWrap(true);
4249 
4250   unsigned ChainI = 0;
4251   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4252     // See visitLoad comments.
4253     if (ChainI == MaxParallelChains) {
4254       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4255                                   makeArrayRef(Chains.data(), ChainI));
4256       Root = Chain;
4257       ChainI = 0;
4258     }
4259     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4260     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4261     if (MemVTs[i] != ValueVTs[i])
4262       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4263     SDValue St =
4264         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4265                      Alignment, MMOFlags, AAInfo);
4266     Chains[ChainI] = St;
4267   }
4268 
4269   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4270                                   makeArrayRef(Chains.data(), ChainI));
4271   DAG.setRoot(StoreNode);
4272 }
4273 
4274 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4275                                            bool IsCompressing) {
4276   SDLoc sdl = getCurSDLoc();
4277 
4278   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4279                            unsigned& Alignment) {
4280     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4281     Src0 = I.getArgOperand(0);
4282     Ptr = I.getArgOperand(1);
4283     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4284     Mask = I.getArgOperand(3);
4285   };
4286   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4287                            unsigned& Alignment) {
4288     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4289     Src0 = I.getArgOperand(0);
4290     Ptr = I.getArgOperand(1);
4291     Mask = I.getArgOperand(2);
4292     Alignment = 0;
4293   };
4294 
4295   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4296   unsigned Alignment;
4297   if (IsCompressing)
4298     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4299   else
4300     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4301 
4302   SDValue Ptr = getValue(PtrOperand);
4303   SDValue Src0 = getValue(Src0Operand);
4304   SDValue Mask = getValue(MaskOperand);
4305   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4306 
4307   EVT VT = Src0.getValueType();
4308   if (!Alignment)
4309     Alignment = DAG.getEVTAlignment(VT);
4310 
4311   AAMDNodes AAInfo;
4312   I.getAAMetadata(AAInfo);
4313 
4314   MachineMemOperand *MMO =
4315     DAG.getMachineFunction().
4316     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4317                           MachineMemOperand::MOStore,
4318                           // TODO: Make MachineMemOperands aware of scalable
4319                           // vectors.
4320                           VT.getStoreSize().getKnownMinSize(),
4321                           Alignment, AAInfo);
4322   SDValue StoreNode =
4323       DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4324                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4325   DAG.setRoot(StoreNode);
4326   setValue(&I, StoreNode);
4327 }
4328 
4329 // Get a uniform base for the Gather/Scatter intrinsic.
4330 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4331 // We try to represent it as a base pointer + vector of indices.
4332 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4333 // The first operand of the GEP may be a single pointer or a vector of pointers
4334 // Example:
4335 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4336 //  or
4337 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4338 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4339 //
4340 // When the first GEP operand is a single pointer - it is the uniform base we
4341 // are looking for. If first operand of the GEP is a splat vector - we
4342 // extract the splat value and use it as a uniform base.
4343 // In all other cases the function returns 'false'.
4344 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4345                            ISD::MemIndexType &IndexType, SDValue &Scale,
4346                            SelectionDAGBuilder *SDB) {
4347   SelectionDAG& DAG = SDB->DAG;
4348   LLVMContext &Context = *DAG.getContext();
4349 
4350   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4351   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4352   if (!GEP)
4353     return false;
4354 
4355   const Value *GEPPtr = GEP->getPointerOperand();
4356   if (!GEPPtr->getType()->isVectorTy())
4357     Ptr = GEPPtr;
4358   else if (!(Ptr = getSplatValue(GEPPtr)))
4359     return false;
4360 
4361   unsigned FinalIndex = GEP->getNumOperands() - 1;
4362   Value *IndexVal = GEP->getOperand(FinalIndex);
4363   gep_type_iterator GTI = gep_type_begin(*GEP);
4364 
4365   // Ensure all the other indices are 0.
4366   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4367     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4368     if (!C)
4369       return false;
4370     if (isa<VectorType>(C->getType()))
4371       C = C->getSplatValue();
4372     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4373     if (!CI || !CI->isZero())
4374       return false;
4375   }
4376 
4377   // The operands of the GEP may be defined in another basic block.
4378   // In this case we'll not find nodes for the operands.
4379   if (!SDB->findValue(Ptr))
4380     return false;
4381   Constant *C = dyn_cast<Constant>(IndexVal);
4382   if (!C && !SDB->findValue(IndexVal))
4383     return false;
4384 
4385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4386   const DataLayout &DL = DAG.getDataLayout();
4387   StructType *STy = GTI.getStructTypeOrNull();
4388 
4389   if (STy) {
4390     const StructLayout *SL = DL.getStructLayout(STy);
4391     if (isa<VectorType>(C->getType())) {
4392       C = C->getSplatValue();
4393       // FIXME: If getSplatValue may return nullptr for a structure?
4394       // If not, the following check can be removed.
4395       if (!C)
4396         return false;
4397     }
4398     auto *CI = cast<ConstantInt>(C);
4399     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4400     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4401                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4402   } else {
4403     Scale = DAG.getTargetConstant(
4404                 DL.getTypeAllocSize(GEP->getResultElementType()),
4405                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4406     Index = SDB->getValue(IndexVal);
4407   }
4408   Base = SDB->getValue(Ptr);
4409   IndexType = ISD::SIGNED_SCALED;
4410 
4411   if (STy || !Index.getValueType().isVector()) {
4412     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4413     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4414     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4415   }
4416   return true;
4417 }
4418 
4419 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4420   SDLoc sdl = getCurSDLoc();
4421 
4422   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4423   const Value *Ptr = I.getArgOperand(1);
4424   SDValue Src0 = getValue(I.getArgOperand(0));
4425   SDValue Mask = getValue(I.getArgOperand(3));
4426   EVT VT = Src0.getValueType();
4427   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4428   if (!Alignment)
4429     Alignment = DAG.getEVTAlignment(VT);
4430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4431 
4432   AAMDNodes AAInfo;
4433   I.getAAMetadata(AAInfo);
4434 
4435   SDValue Base;
4436   SDValue Index;
4437   ISD::MemIndexType IndexType;
4438   SDValue Scale;
4439   const Value *BasePtr = Ptr;
4440   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4441                                     this);
4442 
4443   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4444   MachineMemOperand *MMO = DAG.getMachineFunction().
4445     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4446                          MachineMemOperand::MOStore,
4447                          // TODO: Make MachineMemOperands aware of scalable
4448                          // vectors.
4449                          VT.getStoreSize().getKnownMinSize(),
4450                          Alignment, AAInfo);
4451   if (!UniformBase) {
4452     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4453     Index = getValue(Ptr);
4454     IndexType = ISD::SIGNED_SCALED;
4455     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4456   }
4457   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4458   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4459                                          Ops, MMO, IndexType);
4460   DAG.setRoot(Scatter);
4461   setValue(&I, Scatter);
4462 }
4463 
4464 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4465   SDLoc sdl = getCurSDLoc();
4466 
4467   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4468                            unsigned& Alignment) {
4469     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4470     Ptr = I.getArgOperand(0);
4471     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4472     Mask = I.getArgOperand(2);
4473     Src0 = I.getArgOperand(3);
4474   };
4475   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4476                            unsigned& Alignment) {
4477     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4478     Ptr = I.getArgOperand(0);
4479     Alignment = 0;
4480     Mask = I.getArgOperand(1);
4481     Src0 = I.getArgOperand(2);
4482   };
4483 
4484   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4485   unsigned Alignment;
4486   if (IsExpanding)
4487     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4488   else
4489     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4490 
4491   SDValue Ptr = getValue(PtrOperand);
4492   SDValue Src0 = getValue(Src0Operand);
4493   SDValue Mask = getValue(MaskOperand);
4494   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4495 
4496   EVT VT = Src0.getValueType();
4497   if (!Alignment)
4498     Alignment = DAG.getEVTAlignment(VT);
4499 
4500   AAMDNodes AAInfo;
4501   I.getAAMetadata(AAInfo);
4502   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4503 
4504   // Do not serialize masked loads of constant memory with anything.
4505   MemoryLocation ML;
4506   if (VT.isScalableVector())
4507     ML = MemoryLocation(PtrOperand);
4508   else
4509     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4510                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4511                            AAInfo);
4512   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4513 
4514   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4515 
4516   MachineMemOperand *MMO =
4517     DAG.getMachineFunction().
4518     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4519                           MachineMemOperand::MOLoad,
4520                           // TODO: Make MachineMemOperands aware of scalable
4521                           // vectors.
4522                           VT.getStoreSize().getKnownMinSize(),
4523                           Alignment, AAInfo, Ranges);
4524 
4525   SDValue Load =
4526       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4527                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4528   if (AddToChain)
4529     PendingLoads.push_back(Load.getValue(1));
4530   setValue(&I, Load);
4531 }
4532 
4533 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4534   SDLoc sdl = getCurSDLoc();
4535 
4536   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4537   const Value *Ptr = I.getArgOperand(0);
4538   SDValue Src0 = getValue(I.getArgOperand(3));
4539   SDValue Mask = getValue(I.getArgOperand(2));
4540 
4541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4542   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4543   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4544   if (!Alignment)
4545     Alignment = DAG.getEVTAlignment(VT);
4546 
4547   AAMDNodes AAInfo;
4548   I.getAAMetadata(AAInfo);
4549   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4550 
4551   SDValue Root = DAG.getRoot();
4552   SDValue Base;
4553   SDValue Index;
4554   ISD::MemIndexType IndexType;
4555   SDValue Scale;
4556   const Value *BasePtr = Ptr;
4557   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4558                                     this);
4559   bool ConstantMemory = false;
4560   if (UniformBase && AA &&
4561       AA->pointsToConstantMemory(
4562           MemoryLocation(BasePtr,
4563                          LocationSize::precise(
4564                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4565                          AAInfo))) {
4566     // Do not serialize (non-volatile) loads of constant memory with anything.
4567     Root = DAG.getEntryNode();
4568     ConstantMemory = true;
4569   }
4570 
4571   MachineMemOperand *MMO =
4572     DAG.getMachineFunction().
4573     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4574                          MachineMemOperand::MOLoad,
4575                          // TODO: Make MachineMemOperands aware of scalable
4576                          // vectors.
4577                          VT.getStoreSize().getKnownMinSize(),
4578                          Alignment, AAInfo, Ranges);
4579 
4580   if (!UniformBase) {
4581     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4582     Index = getValue(Ptr);
4583     IndexType = ISD::SIGNED_SCALED;
4584     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4585   }
4586   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4587   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4588                                        Ops, MMO, IndexType);
4589 
4590   SDValue OutChain = Gather.getValue(1);
4591   if (!ConstantMemory)
4592     PendingLoads.push_back(OutChain);
4593   setValue(&I, Gather);
4594 }
4595 
4596 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4597   SDLoc dl = getCurSDLoc();
4598   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4599   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4600   SyncScope::ID SSID = I.getSyncScopeID();
4601 
4602   SDValue InChain = getRoot();
4603 
4604   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4605   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4606 
4607   auto Alignment = DAG.getEVTAlignment(MemVT);
4608 
4609   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4610   if (I.isVolatile())
4611     Flags |= MachineMemOperand::MOVolatile;
4612   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4613 
4614   MachineFunction &MF = DAG.getMachineFunction();
4615   MachineMemOperand *MMO =
4616     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4617                             Flags, MemVT.getStoreSize(), Alignment,
4618                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4619                             FailureOrdering);
4620 
4621   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4622                                    dl, MemVT, VTs, InChain,
4623                                    getValue(I.getPointerOperand()),
4624                                    getValue(I.getCompareOperand()),
4625                                    getValue(I.getNewValOperand()), MMO);
4626 
4627   SDValue OutChain = L.getValue(2);
4628 
4629   setValue(&I, L);
4630   DAG.setRoot(OutChain);
4631 }
4632 
4633 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4634   SDLoc dl = getCurSDLoc();
4635   ISD::NodeType NT;
4636   switch (I.getOperation()) {
4637   default: llvm_unreachable("Unknown atomicrmw operation");
4638   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4639   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4640   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4641   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4642   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4643   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4644   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4645   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4646   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4647   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4648   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4649   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4650   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4651   }
4652   AtomicOrdering Ordering = I.getOrdering();
4653   SyncScope::ID SSID = I.getSyncScopeID();
4654 
4655   SDValue InChain = getRoot();
4656 
4657   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4658   auto Alignment = DAG.getEVTAlignment(MemVT);
4659 
4660   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4661   if (I.isVolatile())
4662     Flags |= MachineMemOperand::MOVolatile;
4663   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4664 
4665   MachineFunction &MF = DAG.getMachineFunction();
4666   MachineMemOperand *MMO =
4667     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4668                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4669                             nullptr, SSID, Ordering);
4670 
4671   SDValue L =
4672     DAG.getAtomic(NT, dl, MemVT, InChain,
4673                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4674                   MMO);
4675 
4676   SDValue OutChain = L.getValue(1);
4677 
4678   setValue(&I, L);
4679   DAG.setRoot(OutChain);
4680 }
4681 
4682 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4683   SDLoc dl = getCurSDLoc();
4684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4685   SDValue Ops[3];
4686   Ops[0] = getRoot();
4687   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4688                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4689   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4690                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4691   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4692 }
4693 
4694 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4695   SDLoc dl = getCurSDLoc();
4696   AtomicOrdering Order = I.getOrdering();
4697   SyncScope::ID SSID = I.getSyncScopeID();
4698 
4699   SDValue InChain = getRoot();
4700 
4701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4702   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4703   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4704 
4705   if (!TLI.supportsUnalignedAtomics() &&
4706       I.getAlignment() < MemVT.getSizeInBits() / 8)
4707     report_fatal_error("Cannot generate unaligned atomic load");
4708 
4709   auto Flags = MachineMemOperand::MOLoad;
4710   if (I.isVolatile())
4711     Flags |= MachineMemOperand::MOVolatile;
4712   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4713     Flags |= MachineMemOperand::MOInvariant;
4714   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4715                                DAG.getDataLayout()))
4716     Flags |= MachineMemOperand::MODereferenceable;
4717 
4718   Flags |= TLI.getMMOFlags(I);
4719 
4720   MachineMemOperand *MMO =
4721       DAG.getMachineFunction().
4722       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4723                            Flags, MemVT.getStoreSize(),
4724                            I.getAlignment() ? I.getAlignment() :
4725                                               DAG.getEVTAlignment(MemVT),
4726                            AAMDNodes(), nullptr, SSID, Order);
4727 
4728   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4729 
4730   SDValue Ptr = getValue(I.getPointerOperand());
4731 
4732   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4733     // TODO: Once this is better exercised by tests, it should be merged with
4734     // the normal path for loads to prevent future divergence.
4735     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4736     if (MemVT != VT)
4737       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4738 
4739     setValue(&I, L);
4740     SDValue OutChain = L.getValue(1);
4741     if (!I.isUnordered())
4742       DAG.setRoot(OutChain);
4743     else
4744       PendingLoads.push_back(OutChain);
4745     return;
4746   }
4747 
4748   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4749                             Ptr, MMO);
4750 
4751   SDValue OutChain = L.getValue(1);
4752   if (MemVT != VT)
4753     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4754 
4755   setValue(&I, L);
4756   DAG.setRoot(OutChain);
4757 }
4758 
4759 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4760   SDLoc dl = getCurSDLoc();
4761 
4762   AtomicOrdering Ordering = I.getOrdering();
4763   SyncScope::ID SSID = I.getSyncScopeID();
4764 
4765   SDValue InChain = getRoot();
4766 
4767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4768   EVT MemVT =
4769       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4770 
4771   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4772     report_fatal_error("Cannot generate unaligned atomic store");
4773 
4774   auto Flags = MachineMemOperand::MOStore;
4775   if (I.isVolatile())
4776     Flags |= MachineMemOperand::MOVolatile;
4777   Flags |= TLI.getMMOFlags(I);
4778 
4779   MachineFunction &MF = DAG.getMachineFunction();
4780   MachineMemOperand *MMO =
4781     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4782                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4783                             nullptr, SSID, Ordering);
4784 
4785   SDValue Val = getValue(I.getValueOperand());
4786   if (Val.getValueType() != MemVT)
4787     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4788   SDValue Ptr = getValue(I.getPointerOperand());
4789 
4790   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4791     // TODO: Once this is better exercised by tests, it should be merged with
4792     // the normal path for stores to prevent future divergence.
4793     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4794     DAG.setRoot(S);
4795     return;
4796   }
4797   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4798                                    Ptr, Val, MMO);
4799 
4800 
4801   DAG.setRoot(OutChain);
4802 }
4803 
4804 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4805 /// node.
4806 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4807                                                unsigned Intrinsic) {
4808   // Ignore the callsite's attributes. A specific call site may be marked with
4809   // readnone, but the lowering code will expect the chain based on the
4810   // definition.
4811   const Function *F = I.getCalledFunction();
4812   bool HasChain = !F->doesNotAccessMemory();
4813   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4814 
4815   // Build the operand list.
4816   SmallVector<SDValue, 8> Ops;
4817   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4818     if (OnlyLoad) {
4819       // We don't need to serialize loads against other loads.
4820       Ops.push_back(DAG.getRoot());
4821     } else {
4822       Ops.push_back(getRoot());
4823     }
4824   }
4825 
4826   // Info is set by getTgtMemInstrinsic
4827   TargetLowering::IntrinsicInfo Info;
4828   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4829   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4830                                                DAG.getMachineFunction(),
4831                                                Intrinsic);
4832 
4833   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4834   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4835       Info.opc == ISD::INTRINSIC_W_CHAIN)
4836     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4837                                         TLI.getPointerTy(DAG.getDataLayout())));
4838 
4839   // Add all operands of the call to the operand list.
4840   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4841     const Value *Arg = I.getArgOperand(i);
4842     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4843       Ops.push_back(getValue(Arg));
4844       continue;
4845     }
4846 
4847     // Use TargetConstant instead of a regular constant for immarg.
4848     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4849     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4850       assert(CI->getBitWidth() <= 64 &&
4851              "large intrinsic immediates not handled");
4852       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4853     } else {
4854       Ops.push_back(
4855           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4856     }
4857   }
4858 
4859   SmallVector<EVT, 4> ValueVTs;
4860   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4861 
4862   if (HasChain)
4863     ValueVTs.push_back(MVT::Other);
4864 
4865   SDVTList VTs = DAG.getVTList(ValueVTs);
4866 
4867   // Create the node.
4868   SDValue Result;
4869   if (IsTgtIntrinsic) {
4870     // This is target intrinsic that touches memory
4871     AAMDNodes AAInfo;
4872     I.getAAMetadata(AAInfo);
4873     Result = DAG.getMemIntrinsicNode(
4874         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4875         MachinePointerInfo(Info.ptrVal, Info.offset),
4876         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4877   } else if (!HasChain) {
4878     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4879   } else if (!I.getType()->isVoidTy()) {
4880     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4881   } else {
4882     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4883   }
4884 
4885   if (HasChain) {
4886     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4887     if (OnlyLoad)
4888       PendingLoads.push_back(Chain);
4889     else
4890       DAG.setRoot(Chain);
4891   }
4892 
4893   if (!I.getType()->isVoidTy()) {
4894     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4895       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4896       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4897     } else
4898       Result = lowerRangeToAssertZExt(DAG, I, Result);
4899 
4900     setValue(&I, Result);
4901   }
4902 }
4903 
4904 /// GetSignificand - Get the significand and build it into a floating-point
4905 /// number with exponent of 1:
4906 ///
4907 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4908 ///
4909 /// where Op is the hexadecimal representation of floating point value.
4910 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4911   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4912                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4913   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4914                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4915   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4916 }
4917 
4918 /// GetExponent - Get the exponent:
4919 ///
4920 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4921 ///
4922 /// where Op is the hexadecimal representation of floating point value.
4923 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4924                            const TargetLowering &TLI, const SDLoc &dl) {
4925   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4926                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4927   SDValue t1 = DAG.getNode(
4928       ISD::SRL, dl, MVT::i32, t0,
4929       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4930   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4931                            DAG.getConstant(127, dl, MVT::i32));
4932   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4933 }
4934 
4935 /// getF32Constant - Get 32-bit floating point constant.
4936 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4937                               const SDLoc &dl) {
4938   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4939                            MVT::f32);
4940 }
4941 
4942 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4943                                        SelectionDAG &DAG) {
4944   // TODO: What fast-math-flags should be set on the floating-point nodes?
4945 
4946   //   IntegerPartOfX = ((int32_t)(t0);
4947   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4948 
4949   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4950   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4951   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4952 
4953   //   IntegerPartOfX <<= 23;
4954   IntegerPartOfX = DAG.getNode(
4955       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4956       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4957                                   DAG.getDataLayout())));
4958 
4959   SDValue TwoToFractionalPartOfX;
4960   if (LimitFloatPrecision <= 6) {
4961     // For floating-point precision of 6:
4962     //
4963     //   TwoToFractionalPartOfX =
4964     //     0.997535578f +
4965     //       (0.735607626f + 0.252464424f * x) * x;
4966     //
4967     // error 0.0144103317, which is 6 bits
4968     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4969                              getF32Constant(DAG, 0x3e814304, dl));
4970     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4971                              getF32Constant(DAG, 0x3f3c50c8, dl));
4972     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4973     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4974                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4975   } else if (LimitFloatPrecision <= 12) {
4976     // For floating-point precision of 12:
4977     //
4978     //   TwoToFractionalPartOfX =
4979     //     0.999892986f +
4980     //       (0.696457318f +
4981     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4982     //
4983     // error 0.000107046256, which is 13 to 14 bits
4984     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4985                              getF32Constant(DAG, 0x3da235e3, dl));
4986     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4987                              getF32Constant(DAG, 0x3e65b8f3, dl));
4988     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4989     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4990                              getF32Constant(DAG, 0x3f324b07, dl));
4991     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4992     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4993                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4994   } else { // LimitFloatPrecision <= 18
4995     // For floating-point precision of 18:
4996     //
4997     //   TwoToFractionalPartOfX =
4998     //     0.999999982f +
4999     //       (0.693148872f +
5000     //         (0.240227044f +
5001     //           (0.554906021e-1f +
5002     //             (0.961591928e-2f +
5003     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5004     // error 2.47208000*10^(-7), which is better than 18 bits
5005     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5006                              getF32Constant(DAG, 0x3924b03e, dl));
5007     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5008                              getF32Constant(DAG, 0x3ab24b87, dl));
5009     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5010     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5011                              getF32Constant(DAG, 0x3c1d8c17, dl));
5012     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5013     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5014                              getF32Constant(DAG, 0x3d634a1d, dl));
5015     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5016     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5017                              getF32Constant(DAG, 0x3e75fe14, dl));
5018     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5019     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5020                               getF32Constant(DAG, 0x3f317234, dl));
5021     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5022     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5023                                          getF32Constant(DAG, 0x3f800000, dl));
5024   }
5025 
5026   // Add the exponent into the result in integer domain.
5027   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5028   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5029                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5030 }
5031 
5032 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5033 /// limited-precision mode.
5034 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5035                          const TargetLowering &TLI) {
5036   if (Op.getValueType() == MVT::f32 &&
5037       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5038 
5039     // Put the exponent in the right bit position for later addition to the
5040     // final result:
5041     //
5042     // t0 = Op * log2(e)
5043 
5044     // TODO: What fast-math-flags should be set here?
5045     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5046                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5047     return getLimitedPrecisionExp2(t0, dl, DAG);
5048   }
5049 
5050   // No special expansion.
5051   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5052 }
5053 
5054 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5055 /// limited-precision mode.
5056 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5057                          const TargetLowering &TLI) {
5058   // TODO: What fast-math-flags should be set on the floating-point nodes?
5059 
5060   if (Op.getValueType() == MVT::f32 &&
5061       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5062     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5063 
5064     // Scale the exponent by log(2).
5065     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5066     SDValue LogOfExponent =
5067         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5068                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5069 
5070     // Get the significand and build it into a floating-point number with
5071     // exponent of 1.
5072     SDValue X = GetSignificand(DAG, Op1, dl);
5073 
5074     SDValue LogOfMantissa;
5075     if (LimitFloatPrecision <= 6) {
5076       // For floating-point precision of 6:
5077       //
5078       //   LogofMantissa =
5079       //     -1.1609546f +
5080       //       (1.4034025f - 0.23903021f * x) * x;
5081       //
5082       // error 0.0034276066, which is better than 8 bits
5083       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5084                                getF32Constant(DAG, 0xbe74c456, dl));
5085       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5086                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5087       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5088       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5089                                   getF32Constant(DAG, 0x3f949a29, dl));
5090     } else if (LimitFloatPrecision <= 12) {
5091       // For floating-point precision of 12:
5092       //
5093       //   LogOfMantissa =
5094       //     -1.7417939f +
5095       //       (2.8212026f +
5096       //         (-1.4699568f +
5097       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5098       //
5099       // error 0.000061011436, which is 14 bits
5100       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5101                                getF32Constant(DAG, 0xbd67b6d6, dl));
5102       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5103                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5104       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5105       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5106                                getF32Constant(DAG, 0x3fbc278b, dl));
5107       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5108       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5109                                getF32Constant(DAG, 0x40348e95, dl));
5110       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5111       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5112                                   getF32Constant(DAG, 0x3fdef31a, dl));
5113     } else { // LimitFloatPrecision <= 18
5114       // For floating-point precision of 18:
5115       //
5116       //   LogOfMantissa =
5117       //     -2.1072184f +
5118       //       (4.2372794f +
5119       //         (-3.7029485f +
5120       //           (2.2781945f +
5121       //             (-0.87823314f +
5122       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5123       //
5124       // error 0.0000023660568, which is better than 18 bits
5125       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5126                                getF32Constant(DAG, 0xbc91e5ac, dl));
5127       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5128                                getF32Constant(DAG, 0x3e4350aa, dl));
5129       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5130       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5131                                getF32Constant(DAG, 0x3f60d3e3, dl));
5132       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5133       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5134                                getF32Constant(DAG, 0x4011cdf0, dl));
5135       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5136       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5137                                getF32Constant(DAG, 0x406cfd1c, dl));
5138       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5139       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5140                                getF32Constant(DAG, 0x408797cb, dl));
5141       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5142       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5143                                   getF32Constant(DAG, 0x4006dcab, dl));
5144     }
5145 
5146     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5147   }
5148 
5149   // No special expansion.
5150   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5151 }
5152 
5153 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5154 /// limited-precision mode.
5155 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5156                           const TargetLowering &TLI) {
5157   // TODO: What fast-math-flags should be set on the floating-point nodes?
5158 
5159   if (Op.getValueType() == MVT::f32 &&
5160       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5161     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5162 
5163     // Get the exponent.
5164     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5165 
5166     // Get the significand and build it into a floating-point number with
5167     // exponent of 1.
5168     SDValue X = GetSignificand(DAG, Op1, dl);
5169 
5170     // Different possible minimax approximations of significand in
5171     // floating-point for various degrees of accuracy over [1,2].
5172     SDValue Log2ofMantissa;
5173     if (LimitFloatPrecision <= 6) {
5174       // For floating-point precision of 6:
5175       //
5176       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5177       //
5178       // error 0.0049451742, which is more than 7 bits
5179       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5180                                getF32Constant(DAG, 0xbeb08fe0, dl));
5181       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5182                                getF32Constant(DAG, 0x40019463, dl));
5183       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5184       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5185                                    getF32Constant(DAG, 0x3fd6633d, dl));
5186     } else if (LimitFloatPrecision <= 12) {
5187       // For floating-point precision of 12:
5188       //
5189       //   Log2ofMantissa =
5190       //     -2.51285454f +
5191       //       (4.07009056f +
5192       //         (-2.12067489f +
5193       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5194       //
5195       // error 0.0000876136000, which is better than 13 bits
5196       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5197                                getF32Constant(DAG, 0xbda7262e, dl));
5198       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5199                                getF32Constant(DAG, 0x3f25280b, dl));
5200       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5201       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5202                                getF32Constant(DAG, 0x4007b923, dl));
5203       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5204       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5205                                getF32Constant(DAG, 0x40823e2f, dl));
5206       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5207       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5208                                    getF32Constant(DAG, 0x4020d29c, dl));
5209     } else { // LimitFloatPrecision <= 18
5210       // For floating-point precision of 18:
5211       //
5212       //   Log2ofMantissa =
5213       //     -3.0400495f +
5214       //       (6.1129976f +
5215       //         (-5.3420409f +
5216       //           (3.2865683f +
5217       //             (-1.2669343f +
5218       //               (0.27515199f -
5219       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5220       //
5221       // error 0.0000018516, which is better than 18 bits
5222       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5223                                getF32Constant(DAG, 0xbcd2769e, dl));
5224       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5225                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5226       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5227       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5228                                getF32Constant(DAG, 0x3fa22ae7, dl));
5229       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5230       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5231                                getF32Constant(DAG, 0x40525723, dl));
5232       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5233       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5234                                getF32Constant(DAG, 0x40aaf200, dl));
5235       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5236       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5237                                getF32Constant(DAG, 0x40c39dad, dl));
5238       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5239       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5240                                    getF32Constant(DAG, 0x4042902c, dl));
5241     }
5242 
5243     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5244   }
5245 
5246   // No special expansion.
5247   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5248 }
5249 
5250 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5251 /// limited-precision mode.
5252 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5253                            const TargetLowering &TLI) {
5254   // TODO: What fast-math-flags should be set on the floating-point nodes?
5255 
5256   if (Op.getValueType() == MVT::f32 &&
5257       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5258     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5259 
5260     // Scale the exponent by log10(2) [0.30102999f].
5261     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5262     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5263                                         getF32Constant(DAG, 0x3e9a209a, dl));
5264 
5265     // Get the significand and build it into a floating-point number with
5266     // exponent of 1.
5267     SDValue X = GetSignificand(DAG, Op1, dl);
5268 
5269     SDValue Log10ofMantissa;
5270     if (LimitFloatPrecision <= 6) {
5271       // For floating-point precision of 6:
5272       //
5273       //   Log10ofMantissa =
5274       //     -0.50419619f +
5275       //       (0.60948995f - 0.10380950f * x) * x;
5276       //
5277       // error 0.0014886165, which is 6 bits
5278       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5279                                getF32Constant(DAG, 0xbdd49a13, dl));
5280       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5281                                getF32Constant(DAG, 0x3f1c0789, dl));
5282       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5283       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5284                                     getF32Constant(DAG, 0x3f011300, dl));
5285     } else if (LimitFloatPrecision <= 12) {
5286       // For floating-point precision of 12:
5287       //
5288       //   Log10ofMantissa =
5289       //     -0.64831180f +
5290       //       (0.91751397f +
5291       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5292       //
5293       // error 0.00019228036, which is better than 12 bits
5294       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5295                                getF32Constant(DAG, 0x3d431f31, dl));
5296       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5297                                getF32Constant(DAG, 0x3ea21fb2, dl));
5298       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5299       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5300                                getF32Constant(DAG, 0x3f6ae232, dl));
5301       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5302       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5303                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5304     } else { // LimitFloatPrecision <= 18
5305       // For floating-point precision of 18:
5306       //
5307       //   Log10ofMantissa =
5308       //     -0.84299375f +
5309       //       (1.5327582f +
5310       //         (-1.0688956f +
5311       //           (0.49102474f +
5312       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5313       //
5314       // error 0.0000037995730, which is better than 18 bits
5315       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5316                                getF32Constant(DAG, 0x3c5d51ce, dl));
5317       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5318                                getF32Constant(DAG, 0x3e00685a, dl));
5319       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5320       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5321                                getF32Constant(DAG, 0x3efb6798, dl));
5322       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5323       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5324                                getF32Constant(DAG, 0x3f88d192, dl));
5325       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5326       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5327                                getF32Constant(DAG, 0x3fc4316c, dl));
5328       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5329       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5330                                     getF32Constant(DAG, 0x3f57ce70, dl));
5331     }
5332 
5333     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5334   }
5335 
5336   // No special expansion.
5337   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5338 }
5339 
5340 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5341 /// limited-precision mode.
5342 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5343                           const TargetLowering &TLI) {
5344   if (Op.getValueType() == MVT::f32 &&
5345       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5346     return getLimitedPrecisionExp2(Op, dl, DAG);
5347 
5348   // No special expansion.
5349   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5350 }
5351 
5352 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5353 /// limited-precision mode with x == 10.0f.
5354 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5355                          SelectionDAG &DAG, const TargetLowering &TLI) {
5356   bool IsExp10 = false;
5357   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5358       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5359     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5360       APFloat Ten(10.0f);
5361       IsExp10 = LHSC->isExactlyValue(Ten);
5362     }
5363   }
5364 
5365   // TODO: What fast-math-flags should be set on the FMUL node?
5366   if (IsExp10) {
5367     // Put the exponent in the right bit position for later addition to the
5368     // final result:
5369     //
5370     //   #define LOG2OF10 3.3219281f
5371     //   t0 = Op * LOG2OF10;
5372     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5373                              getF32Constant(DAG, 0x40549a78, dl));
5374     return getLimitedPrecisionExp2(t0, dl, DAG);
5375   }
5376 
5377   // No special expansion.
5378   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5379 }
5380 
5381 /// ExpandPowI - Expand a llvm.powi intrinsic.
5382 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5383                           SelectionDAG &DAG) {
5384   // If RHS is a constant, we can expand this out to a multiplication tree,
5385   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5386   // optimizing for size, we only want to do this if the expansion would produce
5387   // a small number of multiplies, otherwise we do the full expansion.
5388   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5389     // Get the exponent as a positive value.
5390     unsigned Val = RHSC->getSExtValue();
5391     if ((int)Val < 0) Val = -Val;
5392 
5393     // powi(x, 0) -> 1.0
5394     if (Val == 0)
5395       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5396 
5397     bool OptForSize = DAG.shouldOptForSize();
5398     if (!OptForSize ||
5399         // If optimizing for size, don't insert too many multiplies.
5400         // This inserts up to 5 multiplies.
5401         countPopulation(Val) + Log2_32(Val) < 7) {
5402       // We use the simple binary decomposition method to generate the multiply
5403       // sequence.  There are more optimal ways to do this (for example,
5404       // powi(x,15) generates one more multiply than it should), but this has
5405       // the benefit of being both really simple and much better than a libcall.
5406       SDValue Res;  // Logically starts equal to 1.0
5407       SDValue CurSquare = LHS;
5408       // TODO: Intrinsics should have fast-math-flags that propagate to these
5409       // nodes.
5410       while (Val) {
5411         if (Val & 1) {
5412           if (Res.getNode())
5413             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5414           else
5415             Res = CurSquare;  // 1.0*CurSquare.
5416         }
5417 
5418         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5419                                 CurSquare, CurSquare);
5420         Val >>= 1;
5421       }
5422 
5423       // If the original was negative, invert the result, producing 1/(x*x*x).
5424       if (RHSC->getSExtValue() < 0)
5425         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5426                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5427       return Res;
5428     }
5429   }
5430 
5431   // Otherwise, expand to a libcall.
5432   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5433 }
5434 
5435 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5436 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5437 static void
5438 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5439                      const SDValue &N) {
5440   switch (N.getOpcode()) {
5441   case ISD::CopyFromReg: {
5442     SDValue Op = N.getOperand(1);
5443     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5444                       Op.getValueType().getSizeInBits());
5445     return;
5446   }
5447   case ISD::BITCAST:
5448   case ISD::AssertZext:
5449   case ISD::AssertSext:
5450   case ISD::TRUNCATE:
5451     getUnderlyingArgRegs(Regs, N.getOperand(0));
5452     return;
5453   case ISD::BUILD_PAIR:
5454   case ISD::BUILD_VECTOR:
5455   case ISD::CONCAT_VECTORS:
5456     for (SDValue Op : N->op_values())
5457       getUnderlyingArgRegs(Regs, Op);
5458     return;
5459   default:
5460     return;
5461   }
5462 }
5463 
5464 /// If the DbgValueInst is a dbg_value of a function argument, create the
5465 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5466 /// instruction selection, they will be inserted to the entry BB.
5467 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5468     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5469     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5470   const Argument *Arg = dyn_cast<Argument>(V);
5471   if (!Arg)
5472     return false;
5473 
5474   if (!IsDbgDeclare) {
5475     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5476     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5477     // the entry block.
5478     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5479     if (!IsInEntryBlock)
5480       return false;
5481 
5482     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5483     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5484     // variable that also is a param.
5485     //
5486     // Although, if we are at the top of the entry block already, we can still
5487     // emit using ArgDbgValue. This might catch some situations when the
5488     // dbg.value refers to an argument that isn't used in the entry block, so
5489     // any CopyToReg node would be optimized out and the only way to express
5490     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5491     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5492     // we should only emit as ArgDbgValue if the Variable is an argument to the
5493     // current function, and the dbg.value intrinsic is found in the entry
5494     // block.
5495     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5496         !DL->getInlinedAt();
5497     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5498     if (!IsInPrologue && !VariableIsFunctionInputArg)
5499       return false;
5500 
5501     // Here we assume that a function argument on IR level only can be used to
5502     // describe one input parameter on source level. If we for example have
5503     // source code like this
5504     //
5505     //    struct A { long x, y; };
5506     //    void foo(struct A a, long b) {
5507     //      ...
5508     //      b = a.x;
5509     //      ...
5510     //    }
5511     //
5512     // and IR like this
5513     //
5514     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5515     //  entry:
5516     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5517     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5518     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5519     //    ...
5520     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5521     //    ...
5522     //
5523     // then the last dbg.value is describing a parameter "b" using a value that
5524     // is an argument. But since we already has used %a1 to describe a parameter
5525     // we should not handle that last dbg.value here (that would result in an
5526     // incorrect hoisting of the DBG_VALUE to the function entry).
5527     // Notice that we allow one dbg.value per IR level argument, to accommodate
5528     // for the situation with fragments above.
5529     if (VariableIsFunctionInputArg) {
5530       unsigned ArgNo = Arg->getArgNo();
5531       if (ArgNo >= FuncInfo.DescribedArgs.size())
5532         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5533       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5534         return false;
5535       FuncInfo.DescribedArgs.set(ArgNo);
5536     }
5537   }
5538 
5539   MachineFunction &MF = DAG.getMachineFunction();
5540   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5541 
5542   Optional<MachineOperand> Op;
5543   // Some arguments' frame index is recorded during argument lowering.
5544   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5545   if (FI != std::numeric_limits<int>::max())
5546     Op = MachineOperand::CreateFI(FI);
5547 
5548   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5549   if (!Op && N.getNode()) {
5550     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5551     Register Reg;
5552     if (ArgRegsAndSizes.size() == 1)
5553       Reg = ArgRegsAndSizes.front().first;
5554 
5555     if (Reg && Reg.isVirtual()) {
5556       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5557       Register PR = RegInfo.getLiveInPhysReg(Reg);
5558       if (PR)
5559         Reg = PR;
5560     }
5561     if (Reg) {
5562       Op = MachineOperand::CreateReg(Reg, false);
5563     }
5564   }
5565 
5566   if (!Op && N.getNode()) {
5567     // Check if frame index is available.
5568     SDValue LCandidate = peekThroughBitcasts(N);
5569     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5570       if (FrameIndexSDNode *FINode =
5571           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5572         Op = MachineOperand::CreateFI(FINode->getIndex());
5573   }
5574 
5575   if (!Op) {
5576     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5577     auto splitMultiRegDbgValue
5578       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5579       unsigned Offset = 0;
5580       for (auto RegAndSize : SplitRegs) {
5581         // If the expression is already a fragment, the current register
5582         // offset+size might extend beyond the fragment. In this case, only
5583         // the register bits that are inside the fragment are relevant.
5584         int RegFragmentSizeInBits = RegAndSize.second;
5585         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5586           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5587           // The register is entirely outside the expression fragment,
5588           // so is irrelevant for debug info.
5589           if (Offset >= ExprFragmentSizeInBits)
5590             break;
5591           // The register is partially outside the expression fragment, only
5592           // the low bits within the fragment are relevant for debug info.
5593           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5594             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5595           }
5596         }
5597 
5598         auto FragmentExpr = DIExpression::createFragmentExpression(
5599             Expr, Offset, RegFragmentSizeInBits);
5600         Offset += RegAndSize.second;
5601         // If a valid fragment expression cannot be created, the variable's
5602         // correct value cannot be determined and so it is set as Undef.
5603         if (!FragmentExpr) {
5604           SDDbgValue *SDV = DAG.getConstantDbgValue(
5605               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5606           DAG.AddDbgValue(SDV, nullptr, false);
5607           continue;
5608         }
5609         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5610         FuncInfo.ArgDbgValues.push_back(
5611           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5612                   RegAndSize.first, Variable, *FragmentExpr));
5613       }
5614     };
5615 
5616     // Check if ValueMap has reg number.
5617     DenseMap<const Value *, unsigned>::const_iterator
5618       VMI = FuncInfo.ValueMap.find(V);
5619     if (VMI != FuncInfo.ValueMap.end()) {
5620       const auto &TLI = DAG.getTargetLoweringInfo();
5621       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5622                        V->getType(), getABIRegCopyCC(V));
5623       if (RFV.occupiesMultipleRegs()) {
5624         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5625         return true;
5626       }
5627 
5628       Op = MachineOperand::CreateReg(VMI->second, false);
5629     } else if (ArgRegsAndSizes.size() > 1) {
5630       // This was split due to the calling convention, and no virtual register
5631       // mapping exists for the value.
5632       splitMultiRegDbgValue(ArgRegsAndSizes);
5633       return true;
5634     }
5635   }
5636 
5637   if (!Op)
5638     return false;
5639 
5640   assert(Variable->isValidLocationForIntrinsic(DL) &&
5641          "Expected inlined-at fields to agree");
5642 
5643   // If the argument arrives in a stack slot, then what the IR thought was a
5644   // normal Value is actually in memory, and we must add a deref to load it.
5645   if (Op->isFI()) {
5646     int FI = Op->getIndex();
5647     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5648     if (Expr->isImplicit()) {
5649       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5650       Expr = DIExpression::prependOpcodes(Expr, Ops);
5651     } else {
5652       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5653     }
5654   }
5655 
5656   // If this location was specified with a dbg.declare, then it and its
5657   // expression calculate the address of the variable. Append a deref to
5658   // force it to be a memory location.
5659   if (IsDbgDeclare)
5660     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5661 
5662   FuncInfo.ArgDbgValues.push_back(
5663       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5664               *Op, Variable, Expr));
5665 
5666   return true;
5667 }
5668 
5669 /// Return the appropriate SDDbgValue based on N.
5670 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5671                                              DILocalVariable *Variable,
5672                                              DIExpression *Expr,
5673                                              const DebugLoc &dl,
5674                                              unsigned DbgSDNodeOrder) {
5675   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5676     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5677     // stack slot locations.
5678     //
5679     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5680     // debug values here after optimization:
5681     //
5682     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5683     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5684     //
5685     // Both describe the direct values of their associated variables.
5686     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5687                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5688   }
5689   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5690                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5691 }
5692 
5693 // VisualStudio defines setjmp as _setjmp
5694 #if defined(_MSC_VER) && defined(setjmp) && \
5695                          !defined(setjmp_undefined_for_msvc)
5696 #  pragma push_macro("setjmp")
5697 #  undef setjmp
5698 #  define setjmp_undefined_for_msvc
5699 #endif
5700 
5701 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5702   switch (Intrinsic) {
5703   case Intrinsic::smul_fix:
5704     return ISD::SMULFIX;
5705   case Intrinsic::umul_fix:
5706     return ISD::UMULFIX;
5707   default:
5708     llvm_unreachable("Unhandled fixed point intrinsic");
5709   }
5710 }
5711 
5712 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5713                                            const char *FunctionName) {
5714   assert(FunctionName && "FunctionName must not be nullptr");
5715   SDValue Callee = DAG.getExternalSymbol(
5716       FunctionName,
5717       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5718   LowerCallTo(&I, Callee, I.isTailCall());
5719 }
5720 
5721 /// Lower the call to the specified intrinsic function.
5722 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5723                                              unsigned Intrinsic) {
5724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5725   SDLoc sdl = getCurSDLoc();
5726   DebugLoc dl = getCurDebugLoc();
5727   SDValue Res;
5728 
5729   switch (Intrinsic) {
5730   default:
5731     // By default, turn this into a target intrinsic node.
5732     visitTargetIntrinsic(I, Intrinsic);
5733     return;
5734   case Intrinsic::vastart:  visitVAStart(I); return;
5735   case Intrinsic::vaend:    visitVAEnd(I); return;
5736   case Intrinsic::vacopy:   visitVACopy(I); return;
5737   case Intrinsic::returnaddress:
5738     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5739                              TLI.getPointerTy(DAG.getDataLayout()),
5740                              getValue(I.getArgOperand(0))));
5741     return;
5742   case Intrinsic::addressofreturnaddress:
5743     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5744                              TLI.getPointerTy(DAG.getDataLayout())));
5745     return;
5746   case Intrinsic::sponentry:
5747     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5748                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5749     return;
5750   case Intrinsic::frameaddress:
5751     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5752                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5753                              getValue(I.getArgOperand(0))));
5754     return;
5755   case Intrinsic::read_register: {
5756     Value *Reg = I.getArgOperand(0);
5757     SDValue Chain = getRoot();
5758     SDValue RegName =
5759         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5760     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5761     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5762       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5763     setValue(&I, Res);
5764     DAG.setRoot(Res.getValue(1));
5765     return;
5766   }
5767   case Intrinsic::write_register: {
5768     Value *Reg = I.getArgOperand(0);
5769     Value *RegValue = I.getArgOperand(1);
5770     SDValue Chain = getRoot();
5771     SDValue RegName =
5772         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5773     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5774                             RegName, getValue(RegValue)));
5775     return;
5776   }
5777   case Intrinsic::setjmp:
5778     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5779     return;
5780   case Intrinsic::longjmp:
5781     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5782     return;
5783   case Intrinsic::memcpy: {
5784     const auto &MCI = cast<MemCpyInst>(I);
5785     SDValue Op1 = getValue(I.getArgOperand(0));
5786     SDValue Op2 = getValue(I.getArgOperand(1));
5787     SDValue Op3 = getValue(I.getArgOperand(2));
5788     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5789     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5790     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5791     unsigned Align = MinAlign(DstAlign, SrcAlign);
5792     bool isVol = MCI.isVolatile();
5793     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5794     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5795     // node.
5796     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5797                                false, isTC,
5798                                MachinePointerInfo(I.getArgOperand(0)),
5799                                MachinePointerInfo(I.getArgOperand(1)));
5800     updateDAGForMaybeTailCall(MC);
5801     return;
5802   }
5803   case Intrinsic::memset: {
5804     const auto &MSI = cast<MemSetInst>(I);
5805     SDValue Op1 = getValue(I.getArgOperand(0));
5806     SDValue Op2 = getValue(I.getArgOperand(1));
5807     SDValue Op3 = getValue(I.getArgOperand(2));
5808     // @llvm.memset defines 0 and 1 to both mean no alignment.
5809     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5810     bool isVol = MSI.isVolatile();
5811     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5812     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5813                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5814     updateDAGForMaybeTailCall(MS);
5815     return;
5816   }
5817   case Intrinsic::memmove: {
5818     const auto &MMI = cast<MemMoveInst>(I);
5819     SDValue Op1 = getValue(I.getArgOperand(0));
5820     SDValue Op2 = getValue(I.getArgOperand(1));
5821     SDValue Op3 = getValue(I.getArgOperand(2));
5822     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5823     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5824     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5825     unsigned Align = MinAlign(DstAlign, SrcAlign);
5826     bool isVol = MMI.isVolatile();
5827     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5828     // FIXME: Support passing different dest/src alignments to the memmove DAG
5829     // node.
5830     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5831                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5832                                 MachinePointerInfo(I.getArgOperand(1)));
5833     updateDAGForMaybeTailCall(MM);
5834     return;
5835   }
5836   case Intrinsic::memcpy_element_unordered_atomic: {
5837     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5838     SDValue Dst = getValue(MI.getRawDest());
5839     SDValue Src = getValue(MI.getRawSource());
5840     SDValue Length = getValue(MI.getLength());
5841 
5842     unsigned DstAlign = MI.getDestAlignment();
5843     unsigned SrcAlign = MI.getSourceAlignment();
5844     Type *LengthTy = MI.getLength()->getType();
5845     unsigned ElemSz = MI.getElementSizeInBytes();
5846     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5847     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5848                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5849                                      MachinePointerInfo(MI.getRawDest()),
5850                                      MachinePointerInfo(MI.getRawSource()));
5851     updateDAGForMaybeTailCall(MC);
5852     return;
5853   }
5854   case Intrinsic::memmove_element_unordered_atomic: {
5855     auto &MI = cast<AtomicMemMoveInst>(I);
5856     SDValue Dst = getValue(MI.getRawDest());
5857     SDValue Src = getValue(MI.getRawSource());
5858     SDValue Length = getValue(MI.getLength());
5859 
5860     unsigned DstAlign = MI.getDestAlignment();
5861     unsigned SrcAlign = MI.getSourceAlignment();
5862     Type *LengthTy = MI.getLength()->getType();
5863     unsigned ElemSz = MI.getElementSizeInBytes();
5864     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5865     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5866                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5867                                       MachinePointerInfo(MI.getRawDest()),
5868                                       MachinePointerInfo(MI.getRawSource()));
5869     updateDAGForMaybeTailCall(MC);
5870     return;
5871   }
5872   case Intrinsic::memset_element_unordered_atomic: {
5873     auto &MI = cast<AtomicMemSetInst>(I);
5874     SDValue Dst = getValue(MI.getRawDest());
5875     SDValue Val = getValue(MI.getValue());
5876     SDValue Length = getValue(MI.getLength());
5877 
5878     unsigned DstAlign = MI.getDestAlignment();
5879     Type *LengthTy = MI.getLength()->getType();
5880     unsigned ElemSz = MI.getElementSizeInBytes();
5881     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5882     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5883                                      LengthTy, ElemSz, isTC,
5884                                      MachinePointerInfo(MI.getRawDest()));
5885     updateDAGForMaybeTailCall(MC);
5886     return;
5887   }
5888   case Intrinsic::dbg_addr:
5889   case Intrinsic::dbg_declare: {
5890     const auto &DI = cast<DbgVariableIntrinsic>(I);
5891     DILocalVariable *Variable = DI.getVariable();
5892     DIExpression *Expression = DI.getExpression();
5893     dropDanglingDebugInfo(Variable, Expression);
5894     assert(Variable && "Missing variable");
5895 
5896     // Check if address has undef value.
5897     const Value *Address = DI.getVariableLocation();
5898     if (!Address || isa<UndefValue>(Address) ||
5899         (Address->use_empty() && !isa<Argument>(Address))) {
5900       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5901       return;
5902     }
5903 
5904     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5905 
5906     // Check if this variable can be described by a frame index, typically
5907     // either as a static alloca or a byval parameter.
5908     int FI = std::numeric_limits<int>::max();
5909     if (const auto *AI =
5910             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5911       if (AI->isStaticAlloca()) {
5912         auto I = FuncInfo.StaticAllocaMap.find(AI);
5913         if (I != FuncInfo.StaticAllocaMap.end())
5914           FI = I->second;
5915       }
5916     } else if (const auto *Arg = dyn_cast<Argument>(
5917                    Address->stripInBoundsConstantOffsets())) {
5918       FI = FuncInfo.getArgumentFrameIndex(Arg);
5919     }
5920 
5921     // llvm.dbg.addr is control dependent and always generates indirect
5922     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5923     // the MachineFunction variable table.
5924     if (FI != std::numeric_limits<int>::max()) {
5925       if (Intrinsic == Intrinsic::dbg_addr) {
5926         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5927             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5928         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5929       }
5930       return;
5931     }
5932 
5933     SDValue &N = NodeMap[Address];
5934     if (!N.getNode() && isa<Argument>(Address))
5935       // Check unused arguments map.
5936       N = UnusedArgNodeMap[Address];
5937     SDDbgValue *SDV;
5938     if (N.getNode()) {
5939       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5940         Address = BCI->getOperand(0);
5941       // Parameters are handled specially.
5942       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5943       if (isParameter && FINode) {
5944         // Byval parameter. We have a frame index at this point.
5945         SDV =
5946             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5947                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5948       } else if (isa<Argument>(Address)) {
5949         // Address is an argument, so try to emit its dbg value using
5950         // virtual register info from the FuncInfo.ValueMap.
5951         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5952         return;
5953       } else {
5954         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5955                               true, dl, SDNodeOrder);
5956       }
5957       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5958     } else {
5959       // If Address is an argument then try to emit its dbg value using
5960       // virtual register info from the FuncInfo.ValueMap.
5961       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5962                                     N)) {
5963         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5964       }
5965     }
5966     return;
5967   }
5968   case Intrinsic::dbg_label: {
5969     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5970     DILabel *Label = DI.getLabel();
5971     assert(Label && "Missing label");
5972 
5973     SDDbgLabel *SDV;
5974     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5975     DAG.AddDbgLabel(SDV);
5976     return;
5977   }
5978   case Intrinsic::dbg_value: {
5979     const DbgValueInst &DI = cast<DbgValueInst>(I);
5980     assert(DI.getVariable() && "Missing variable");
5981 
5982     DILocalVariable *Variable = DI.getVariable();
5983     DIExpression *Expression = DI.getExpression();
5984     dropDanglingDebugInfo(Variable, Expression);
5985     const Value *V = DI.getValue();
5986     if (!V)
5987       return;
5988 
5989     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5990         SDNodeOrder))
5991       return;
5992 
5993     // TODO: Dangling debug info will eventually either be resolved or produce
5994     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5995     // between the original dbg.value location and its resolved DBG_VALUE, which
5996     // we should ideally fill with an extra Undef DBG_VALUE.
5997 
5998     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5999     return;
6000   }
6001 
6002   case Intrinsic::eh_typeid_for: {
6003     // Find the type id for the given typeinfo.
6004     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6005     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6006     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6007     setValue(&I, Res);
6008     return;
6009   }
6010 
6011   case Intrinsic::eh_return_i32:
6012   case Intrinsic::eh_return_i64:
6013     DAG.getMachineFunction().setCallsEHReturn(true);
6014     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6015                             MVT::Other,
6016                             getControlRoot(),
6017                             getValue(I.getArgOperand(0)),
6018                             getValue(I.getArgOperand(1))));
6019     return;
6020   case Intrinsic::eh_unwind_init:
6021     DAG.getMachineFunction().setCallsUnwindInit(true);
6022     return;
6023   case Intrinsic::eh_dwarf_cfa:
6024     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6025                              TLI.getPointerTy(DAG.getDataLayout()),
6026                              getValue(I.getArgOperand(0))));
6027     return;
6028   case Intrinsic::eh_sjlj_callsite: {
6029     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6030     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6031     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6032     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6033 
6034     MMI.setCurrentCallSite(CI->getZExtValue());
6035     return;
6036   }
6037   case Intrinsic::eh_sjlj_functioncontext: {
6038     // Get and store the index of the function context.
6039     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6040     AllocaInst *FnCtx =
6041       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6042     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6043     MFI.setFunctionContextIndex(FI);
6044     return;
6045   }
6046   case Intrinsic::eh_sjlj_setjmp: {
6047     SDValue Ops[2];
6048     Ops[0] = getRoot();
6049     Ops[1] = getValue(I.getArgOperand(0));
6050     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6051                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6052     setValue(&I, Op.getValue(0));
6053     DAG.setRoot(Op.getValue(1));
6054     return;
6055   }
6056   case Intrinsic::eh_sjlj_longjmp:
6057     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6058                             getRoot(), getValue(I.getArgOperand(0))));
6059     return;
6060   case Intrinsic::eh_sjlj_setup_dispatch:
6061     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6062                             getRoot()));
6063     return;
6064   case Intrinsic::masked_gather:
6065     visitMaskedGather(I);
6066     return;
6067   case Intrinsic::masked_load:
6068     visitMaskedLoad(I);
6069     return;
6070   case Intrinsic::masked_scatter:
6071     visitMaskedScatter(I);
6072     return;
6073   case Intrinsic::masked_store:
6074     visitMaskedStore(I);
6075     return;
6076   case Intrinsic::masked_expandload:
6077     visitMaskedLoad(I, true /* IsExpanding */);
6078     return;
6079   case Intrinsic::masked_compressstore:
6080     visitMaskedStore(I, true /* IsCompressing */);
6081     return;
6082   case Intrinsic::powi:
6083     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6084                             getValue(I.getArgOperand(1)), DAG));
6085     return;
6086   case Intrinsic::log:
6087     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6088     return;
6089   case Intrinsic::log2:
6090     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6091     return;
6092   case Intrinsic::log10:
6093     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6094     return;
6095   case Intrinsic::exp:
6096     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6097     return;
6098   case Intrinsic::exp2:
6099     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6100     return;
6101   case Intrinsic::pow:
6102     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6103                            getValue(I.getArgOperand(1)), DAG, TLI));
6104     return;
6105   case Intrinsic::sqrt:
6106   case Intrinsic::fabs:
6107   case Intrinsic::sin:
6108   case Intrinsic::cos:
6109   case Intrinsic::floor:
6110   case Intrinsic::ceil:
6111   case Intrinsic::trunc:
6112   case Intrinsic::rint:
6113   case Intrinsic::nearbyint:
6114   case Intrinsic::round:
6115   case Intrinsic::canonicalize: {
6116     unsigned Opcode;
6117     switch (Intrinsic) {
6118     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6119     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6120     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6121     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6122     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6123     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6124     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6125     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6126     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6127     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6128     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6129     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6130     }
6131 
6132     setValue(&I, DAG.getNode(Opcode, sdl,
6133                              getValue(I.getArgOperand(0)).getValueType(),
6134                              getValue(I.getArgOperand(0))));
6135     return;
6136   }
6137   case Intrinsic::lround:
6138   case Intrinsic::llround:
6139   case Intrinsic::lrint:
6140   case Intrinsic::llrint: {
6141     unsigned Opcode;
6142     switch (Intrinsic) {
6143     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6144     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6145     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6146     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6147     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6148     }
6149 
6150     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6151     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6152                              getValue(I.getArgOperand(0))));
6153     return;
6154   }
6155   case Intrinsic::minnum:
6156     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6157                              getValue(I.getArgOperand(0)).getValueType(),
6158                              getValue(I.getArgOperand(0)),
6159                              getValue(I.getArgOperand(1))));
6160     return;
6161   case Intrinsic::maxnum:
6162     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6163                              getValue(I.getArgOperand(0)).getValueType(),
6164                              getValue(I.getArgOperand(0)),
6165                              getValue(I.getArgOperand(1))));
6166     return;
6167   case Intrinsic::minimum:
6168     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6169                              getValue(I.getArgOperand(0)).getValueType(),
6170                              getValue(I.getArgOperand(0)),
6171                              getValue(I.getArgOperand(1))));
6172     return;
6173   case Intrinsic::maximum:
6174     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6175                              getValue(I.getArgOperand(0)).getValueType(),
6176                              getValue(I.getArgOperand(0)),
6177                              getValue(I.getArgOperand(1))));
6178     return;
6179   case Intrinsic::copysign:
6180     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6181                              getValue(I.getArgOperand(0)).getValueType(),
6182                              getValue(I.getArgOperand(0)),
6183                              getValue(I.getArgOperand(1))));
6184     return;
6185   case Intrinsic::fma:
6186     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6187                              getValue(I.getArgOperand(0)).getValueType(),
6188                              getValue(I.getArgOperand(0)),
6189                              getValue(I.getArgOperand(1)),
6190                              getValue(I.getArgOperand(2))));
6191     return;
6192 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6193   case Intrinsic::INTRINSIC:
6194 #include "llvm/IR/ConstrainedOps.def"
6195     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6196     return;
6197   case Intrinsic::fmuladd: {
6198     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6199     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6200         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6201       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6202                                getValue(I.getArgOperand(0)).getValueType(),
6203                                getValue(I.getArgOperand(0)),
6204                                getValue(I.getArgOperand(1)),
6205                                getValue(I.getArgOperand(2))));
6206     } else {
6207       // TODO: Intrinsic calls should have fast-math-flags.
6208       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6209                                 getValue(I.getArgOperand(0)).getValueType(),
6210                                 getValue(I.getArgOperand(0)),
6211                                 getValue(I.getArgOperand(1)));
6212       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6213                                 getValue(I.getArgOperand(0)).getValueType(),
6214                                 Mul,
6215                                 getValue(I.getArgOperand(2)));
6216       setValue(&I, Add);
6217     }
6218     return;
6219   }
6220   case Intrinsic::convert_to_fp16:
6221     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6222                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6223                                          getValue(I.getArgOperand(0)),
6224                                          DAG.getTargetConstant(0, sdl,
6225                                                                MVT::i32))));
6226     return;
6227   case Intrinsic::convert_from_fp16:
6228     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6229                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6230                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6231                                          getValue(I.getArgOperand(0)))));
6232     return;
6233   case Intrinsic::pcmarker: {
6234     SDValue Tmp = getValue(I.getArgOperand(0));
6235     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6236     return;
6237   }
6238   case Intrinsic::readcyclecounter: {
6239     SDValue Op = getRoot();
6240     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6241                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6242     setValue(&I, Res);
6243     DAG.setRoot(Res.getValue(1));
6244     return;
6245   }
6246   case Intrinsic::bitreverse:
6247     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6248                              getValue(I.getArgOperand(0)).getValueType(),
6249                              getValue(I.getArgOperand(0))));
6250     return;
6251   case Intrinsic::bswap:
6252     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6253                              getValue(I.getArgOperand(0)).getValueType(),
6254                              getValue(I.getArgOperand(0))));
6255     return;
6256   case Intrinsic::cttz: {
6257     SDValue Arg = getValue(I.getArgOperand(0));
6258     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6259     EVT Ty = Arg.getValueType();
6260     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6261                              sdl, Ty, Arg));
6262     return;
6263   }
6264   case Intrinsic::ctlz: {
6265     SDValue Arg = getValue(I.getArgOperand(0));
6266     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6267     EVT Ty = Arg.getValueType();
6268     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6269                              sdl, Ty, Arg));
6270     return;
6271   }
6272   case Intrinsic::ctpop: {
6273     SDValue Arg = getValue(I.getArgOperand(0));
6274     EVT Ty = Arg.getValueType();
6275     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6276     return;
6277   }
6278   case Intrinsic::fshl:
6279   case Intrinsic::fshr: {
6280     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6281     SDValue X = getValue(I.getArgOperand(0));
6282     SDValue Y = getValue(I.getArgOperand(1));
6283     SDValue Z = getValue(I.getArgOperand(2));
6284     EVT VT = X.getValueType();
6285     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6286     SDValue Zero = DAG.getConstant(0, sdl, VT);
6287     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6288 
6289     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6290     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6291       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6292       return;
6293     }
6294 
6295     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6296     // avoid the select that is necessary in the general case to filter out
6297     // the 0-shift possibility that leads to UB.
6298     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6299       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6300       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6301         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6302         return;
6303       }
6304 
6305       // Some targets only rotate one way. Try the opposite direction.
6306       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6307       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6308         // Negate the shift amount because it is safe to ignore the high bits.
6309         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6310         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6311         return;
6312       }
6313 
6314       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6315       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6316       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6317       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6318       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6319       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6320       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6321       return;
6322     }
6323 
6324     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6325     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6326     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6327     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6328     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6329     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6330 
6331     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6332     // and that is undefined. We must compare and select to avoid UB.
6333     EVT CCVT = MVT::i1;
6334     if (VT.isVector())
6335       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6336 
6337     // For fshl, 0-shift returns the 1st arg (X).
6338     // For fshr, 0-shift returns the 2nd arg (Y).
6339     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6340     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6341     return;
6342   }
6343   case Intrinsic::sadd_sat: {
6344     SDValue Op1 = getValue(I.getArgOperand(0));
6345     SDValue Op2 = getValue(I.getArgOperand(1));
6346     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6347     return;
6348   }
6349   case Intrinsic::uadd_sat: {
6350     SDValue Op1 = getValue(I.getArgOperand(0));
6351     SDValue Op2 = getValue(I.getArgOperand(1));
6352     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6353     return;
6354   }
6355   case Intrinsic::ssub_sat: {
6356     SDValue Op1 = getValue(I.getArgOperand(0));
6357     SDValue Op2 = getValue(I.getArgOperand(1));
6358     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6359     return;
6360   }
6361   case Intrinsic::usub_sat: {
6362     SDValue Op1 = getValue(I.getArgOperand(0));
6363     SDValue Op2 = getValue(I.getArgOperand(1));
6364     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6365     return;
6366   }
6367   case Intrinsic::smul_fix:
6368   case Intrinsic::umul_fix: {
6369     SDValue Op1 = getValue(I.getArgOperand(0));
6370     SDValue Op2 = getValue(I.getArgOperand(1));
6371     SDValue Op3 = getValue(I.getArgOperand(2));
6372     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6373                              Op1.getValueType(), Op1, Op2, Op3));
6374     return;
6375   }
6376   case Intrinsic::smul_fix_sat: {
6377     SDValue Op1 = getValue(I.getArgOperand(0));
6378     SDValue Op2 = getValue(I.getArgOperand(1));
6379     SDValue Op3 = getValue(I.getArgOperand(2));
6380     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6381                              Op3));
6382     return;
6383   }
6384   case Intrinsic::umul_fix_sat: {
6385     SDValue Op1 = getValue(I.getArgOperand(0));
6386     SDValue Op2 = getValue(I.getArgOperand(1));
6387     SDValue Op3 = getValue(I.getArgOperand(2));
6388     setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6389                              Op3));
6390     return;
6391   }
6392   case Intrinsic::stacksave: {
6393     SDValue Op = getRoot();
6394     Res = DAG.getNode(
6395         ISD::STACKSAVE, sdl,
6396         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6397     setValue(&I, Res);
6398     DAG.setRoot(Res.getValue(1));
6399     return;
6400   }
6401   case Intrinsic::stackrestore:
6402     Res = getValue(I.getArgOperand(0));
6403     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6404     return;
6405   case Intrinsic::get_dynamic_area_offset: {
6406     SDValue Op = getRoot();
6407     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6408     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6409     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6410     // target.
6411     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6412       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6413                          " intrinsic!");
6414     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6415                       Op);
6416     DAG.setRoot(Op);
6417     setValue(&I, Res);
6418     return;
6419   }
6420   case Intrinsic::stackguard: {
6421     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6422     MachineFunction &MF = DAG.getMachineFunction();
6423     const Module &M = *MF.getFunction().getParent();
6424     SDValue Chain = getRoot();
6425     if (TLI.useLoadStackGuardNode()) {
6426       Res = getLoadStackGuard(DAG, sdl, Chain);
6427     } else {
6428       const Value *Global = TLI.getSDagStackGuard(M);
6429       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6430       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6431                         MachinePointerInfo(Global, 0), Align,
6432                         MachineMemOperand::MOVolatile);
6433     }
6434     if (TLI.useStackGuardXorFP())
6435       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6436     DAG.setRoot(Chain);
6437     setValue(&I, Res);
6438     return;
6439   }
6440   case Intrinsic::stackprotector: {
6441     // Emit code into the DAG to store the stack guard onto the stack.
6442     MachineFunction &MF = DAG.getMachineFunction();
6443     MachineFrameInfo &MFI = MF.getFrameInfo();
6444     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6445     SDValue Src, Chain = getRoot();
6446 
6447     if (TLI.useLoadStackGuardNode())
6448       Src = getLoadStackGuard(DAG, sdl, Chain);
6449     else
6450       Src = getValue(I.getArgOperand(0));   // The guard's value.
6451 
6452     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6453 
6454     int FI = FuncInfo.StaticAllocaMap[Slot];
6455     MFI.setStackProtectorIndex(FI);
6456 
6457     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6458 
6459     // Store the stack protector onto the stack.
6460     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6461                                                  DAG.getMachineFunction(), FI),
6462                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6463     setValue(&I, Res);
6464     DAG.setRoot(Res);
6465     return;
6466   }
6467   case Intrinsic::objectsize:
6468     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6469 
6470   case Intrinsic::is_constant:
6471     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6472 
6473   case Intrinsic::annotation:
6474   case Intrinsic::ptr_annotation:
6475   case Intrinsic::launder_invariant_group:
6476   case Intrinsic::strip_invariant_group:
6477     // Drop the intrinsic, but forward the value
6478     setValue(&I, getValue(I.getOperand(0)));
6479     return;
6480   case Intrinsic::assume:
6481   case Intrinsic::var_annotation:
6482   case Intrinsic::sideeffect:
6483     // Discard annotate attributes, assumptions, and artificial side-effects.
6484     return;
6485 
6486   case Intrinsic::codeview_annotation: {
6487     // Emit a label associated with this metadata.
6488     MachineFunction &MF = DAG.getMachineFunction();
6489     MCSymbol *Label =
6490         MF.getMMI().getContext().createTempSymbol("annotation", true);
6491     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6492     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6493     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6494     DAG.setRoot(Res);
6495     return;
6496   }
6497 
6498   case Intrinsic::init_trampoline: {
6499     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6500 
6501     SDValue Ops[6];
6502     Ops[0] = getRoot();
6503     Ops[1] = getValue(I.getArgOperand(0));
6504     Ops[2] = getValue(I.getArgOperand(1));
6505     Ops[3] = getValue(I.getArgOperand(2));
6506     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6507     Ops[5] = DAG.getSrcValue(F);
6508 
6509     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6510 
6511     DAG.setRoot(Res);
6512     return;
6513   }
6514   case Intrinsic::adjust_trampoline:
6515     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6516                              TLI.getPointerTy(DAG.getDataLayout()),
6517                              getValue(I.getArgOperand(0))));
6518     return;
6519   case Intrinsic::gcroot: {
6520     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6521            "only valid in functions with gc specified, enforced by Verifier");
6522     assert(GFI && "implied by previous");
6523     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6524     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6525 
6526     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6527     GFI->addStackRoot(FI->getIndex(), TypeMap);
6528     return;
6529   }
6530   case Intrinsic::gcread:
6531   case Intrinsic::gcwrite:
6532     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6533   case Intrinsic::flt_rounds:
6534     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6535     return;
6536 
6537   case Intrinsic::expect:
6538     // Just replace __builtin_expect(exp, c) with EXP.
6539     setValue(&I, getValue(I.getArgOperand(0)));
6540     return;
6541 
6542   case Intrinsic::debugtrap:
6543   case Intrinsic::trap: {
6544     StringRef TrapFuncName =
6545         I.getAttributes()
6546             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6547             .getValueAsString();
6548     if (TrapFuncName.empty()) {
6549       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6550         ISD::TRAP : ISD::DEBUGTRAP;
6551       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6552       return;
6553     }
6554     TargetLowering::ArgListTy Args;
6555 
6556     TargetLowering::CallLoweringInfo CLI(DAG);
6557     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6558         CallingConv::C, I.getType(),
6559         DAG.getExternalSymbol(TrapFuncName.data(),
6560                               TLI.getPointerTy(DAG.getDataLayout())),
6561         std::move(Args));
6562 
6563     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6564     DAG.setRoot(Result.second);
6565     return;
6566   }
6567 
6568   case Intrinsic::uadd_with_overflow:
6569   case Intrinsic::sadd_with_overflow:
6570   case Intrinsic::usub_with_overflow:
6571   case Intrinsic::ssub_with_overflow:
6572   case Intrinsic::umul_with_overflow:
6573   case Intrinsic::smul_with_overflow: {
6574     ISD::NodeType Op;
6575     switch (Intrinsic) {
6576     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6577     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6578     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6579     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6580     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6581     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6582     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6583     }
6584     SDValue Op1 = getValue(I.getArgOperand(0));
6585     SDValue Op2 = getValue(I.getArgOperand(1));
6586 
6587     EVT ResultVT = Op1.getValueType();
6588     EVT OverflowVT = MVT::i1;
6589     if (ResultVT.isVector())
6590       OverflowVT = EVT::getVectorVT(
6591           *Context, OverflowVT, ResultVT.getVectorNumElements());
6592 
6593     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6594     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6595     return;
6596   }
6597   case Intrinsic::prefetch: {
6598     SDValue Ops[5];
6599     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6600     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6601     Ops[0] = DAG.getRoot();
6602     Ops[1] = getValue(I.getArgOperand(0));
6603     Ops[2] = getValue(I.getArgOperand(1));
6604     Ops[3] = getValue(I.getArgOperand(2));
6605     Ops[4] = getValue(I.getArgOperand(3));
6606     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6607                                              DAG.getVTList(MVT::Other), Ops,
6608                                              EVT::getIntegerVT(*Context, 8),
6609                                              MachinePointerInfo(I.getArgOperand(0)),
6610                                              0, /* align */
6611                                              Flags);
6612 
6613     // Chain the prefetch in parallell with any pending loads, to stay out of
6614     // the way of later optimizations.
6615     PendingLoads.push_back(Result);
6616     Result = getRoot();
6617     DAG.setRoot(Result);
6618     return;
6619   }
6620   case Intrinsic::lifetime_start:
6621   case Intrinsic::lifetime_end: {
6622     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6623     // Stack coloring is not enabled in O0, discard region information.
6624     if (TM.getOptLevel() == CodeGenOpt::None)
6625       return;
6626 
6627     const int64_t ObjectSize =
6628         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6629     Value *const ObjectPtr = I.getArgOperand(1);
6630     SmallVector<const Value *, 4> Allocas;
6631     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6632 
6633     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6634            E = Allocas.end(); Object != E; ++Object) {
6635       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6636 
6637       // Could not find an Alloca.
6638       if (!LifetimeObject)
6639         continue;
6640 
6641       // First check that the Alloca is static, otherwise it won't have a
6642       // valid frame index.
6643       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6644       if (SI == FuncInfo.StaticAllocaMap.end())
6645         return;
6646 
6647       const int FrameIndex = SI->second;
6648       int64_t Offset;
6649       if (GetPointerBaseWithConstantOffset(
6650               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6651         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6652       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6653                                 Offset);
6654       DAG.setRoot(Res);
6655     }
6656     return;
6657   }
6658   case Intrinsic::invariant_start:
6659     // Discard region information.
6660     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6661     return;
6662   case Intrinsic::invariant_end:
6663     // Discard region information.
6664     return;
6665   case Intrinsic::clear_cache:
6666     /// FunctionName may be null.
6667     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6668       lowerCallToExternalSymbol(I, FunctionName);
6669     return;
6670   case Intrinsic::donothing:
6671     // ignore
6672     return;
6673   case Intrinsic::experimental_stackmap:
6674     visitStackmap(I);
6675     return;
6676   case Intrinsic::experimental_patchpoint_void:
6677   case Intrinsic::experimental_patchpoint_i64:
6678     visitPatchpoint(&I);
6679     return;
6680   case Intrinsic::experimental_gc_statepoint:
6681     LowerStatepoint(ImmutableStatepoint(&I));
6682     return;
6683   case Intrinsic::experimental_gc_result:
6684     visitGCResult(cast<GCResultInst>(I));
6685     return;
6686   case Intrinsic::experimental_gc_relocate:
6687     visitGCRelocate(cast<GCRelocateInst>(I));
6688     return;
6689   case Intrinsic::instrprof_increment:
6690     llvm_unreachable("instrprof failed to lower an increment");
6691   case Intrinsic::instrprof_value_profile:
6692     llvm_unreachable("instrprof failed to lower a value profiling call");
6693   case Intrinsic::localescape: {
6694     MachineFunction &MF = DAG.getMachineFunction();
6695     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6696 
6697     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6698     // is the same on all targets.
6699     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6700       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6701       if (isa<ConstantPointerNull>(Arg))
6702         continue; // Skip null pointers. They represent a hole in index space.
6703       AllocaInst *Slot = cast<AllocaInst>(Arg);
6704       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6705              "can only escape static allocas");
6706       int FI = FuncInfo.StaticAllocaMap[Slot];
6707       MCSymbol *FrameAllocSym =
6708           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6709               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6710       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6711               TII->get(TargetOpcode::LOCAL_ESCAPE))
6712           .addSym(FrameAllocSym)
6713           .addFrameIndex(FI);
6714     }
6715 
6716     return;
6717   }
6718 
6719   case Intrinsic::localrecover: {
6720     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6721     MachineFunction &MF = DAG.getMachineFunction();
6722     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6723 
6724     // Get the symbol that defines the frame offset.
6725     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6726     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6727     unsigned IdxVal =
6728         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6729     MCSymbol *FrameAllocSym =
6730         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6731             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6732 
6733     // Create a MCSymbol for the label to avoid any target lowering
6734     // that would make this PC relative.
6735     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6736     SDValue OffsetVal =
6737         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6738 
6739     // Add the offset to the FP.
6740     Value *FP = I.getArgOperand(1);
6741     SDValue FPVal = getValue(FP);
6742     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6743     setValue(&I, Add);
6744 
6745     return;
6746   }
6747 
6748   case Intrinsic::eh_exceptionpointer:
6749   case Intrinsic::eh_exceptioncode: {
6750     // Get the exception pointer vreg, copy from it, and resize it to fit.
6751     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6752     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6753     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6754     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6755     SDValue N =
6756         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6757     if (Intrinsic == Intrinsic::eh_exceptioncode)
6758       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6759     setValue(&I, N);
6760     return;
6761   }
6762   case Intrinsic::xray_customevent: {
6763     // Here we want to make sure that the intrinsic behaves as if it has a
6764     // specific calling convention, and only for x86_64.
6765     // FIXME: Support other platforms later.
6766     const auto &Triple = DAG.getTarget().getTargetTriple();
6767     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6768       return;
6769 
6770     SDLoc DL = getCurSDLoc();
6771     SmallVector<SDValue, 8> Ops;
6772 
6773     // We want to say that we always want the arguments in registers.
6774     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6775     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6776     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6777     SDValue Chain = getRoot();
6778     Ops.push_back(LogEntryVal);
6779     Ops.push_back(StrSizeVal);
6780     Ops.push_back(Chain);
6781 
6782     // We need to enforce the calling convention for the callsite, so that
6783     // argument ordering is enforced correctly, and that register allocation can
6784     // see that some registers may be assumed clobbered and have to preserve
6785     // them across calls to the intrinsic.
6786     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6787                                            DL, NodeTys, Ops);
6788     SDValue patchableNode = SDValue(MN, 0);
6789     DAG.setRoot(patchableNode);
6790     setValue(&I, patchableNode);
6791     return;
6792   }
6793   case Intrinsic::xray_typedevent: {
6794     // Here we want to make sure that the intrinsic behaves as if it has a
6795     // specific calling convention, and only for x86_64.
6796     // FIXME: Support other platforms later.
6797     const auto &Triple = DAG.getTarget().getTargetTriple();
6798     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6799       return;
6800 
6801     SDLoc DL = getCurSDLoc();
6802     SmallVector<SDValue, 8> Ops;
6803 
6804     // We want to say that we always want the arguments in registers.
6805     // It's unclear to me how manipulating the selection DAG here forces callers
6806     // to provide arguments in registers instead of on the stack.
6807     SDValue LogTypeId = getValue(I.getArgOperand(0));
6808     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6809     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6810     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6811     SDValue Chain = getRoot();
6812     Ops.push_back(LogTypeId);
6813     Ops.push_back(LogEntryVal);
6814     Ops.push_back(StrSizeVal);
6815     Ops.push_back(Chain);
6816 
6817     // We need to enforce the calling convention for the callsite, so that
6818     // argument ordering is enforced correctly, and that register allocation can
6819     // see that some registers may be assumed clobbered and have to preserve
6820     // them across calls to the intrinsic.
6821     MachineSDNode *MN = DAG.getMachineNode(
6822         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6823     SDValue patchableNode = SDValue(MN, 0);
6824     DAG.setRoot(patchableNode);
6825     setValue(&I, patchableNode);
6826     return;
6827   }
6828   case Intrinsic::experimental_deoptimize:
6829     LowerDeoptimizeCall(&I);
6830     return;
6831 
6832   case Intrinsic::experimental_vector_reduce_v2_fadd:
6833   case Intrinsic::experimental_vector_reduce_v2_fmul:
6834   case Intrinsic::experimental_vector_reduce_add:
6835   case Intrinsic::experimental_vector_reduce_mul:
6836   case Intrinsic::experimental_vector_reduce_and:
6837   case Intrinsic::experimental_vector_reduce_or:
6838   case Intrinsic::experimental_vector_reduce_xor:
6839   case Intrinsic::experimental_vector_reduce_smax:
6840   case Intrinsic::experimental_vector_reduce_smin:
6841   case Intrinsic::experimental_vector_reduce_umax:
6842   case Intrinsic::experimental_vector_reduce_umin:
6843   case Intrinsic::experimental_vector_reduce_fmax:
6844   case Intrinsic::experimental_vector_reduce_fmin:
6845     visitVectorReduce(I, Intrinsic);
6846     return;
6847 
6848   case Intrinsic::icall_branch_funnel: {
6849     SmallVector<SDValue, 16> Ops;
6850     Ops.push_back(getValue(I.getArgOperand(0)));
6851 
6852     int64_t Offset;
6853     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6854         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6855     if (!Base)
6856       report_fatal_error(
6857           "llvm.icall.branch.funnel operand must be a GlobalValue");
6858     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6859 
6860     struct BranchFunnelTarget {
6861       int64_t Offset;
6862       SDValue Target;
6863     };
6864     SmallVector<BranchFunnelTarget, 8> Targets;
6865 
6866     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6867       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6868           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6869       if (ElemBase != Base)
6870         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6871                            "to the same GlobalValue");
6872 
6873       SDValue Val = getValue(I.getArgOperand(Op + 1));
6874       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6875       if (!GA)
6876         report_fatal_error(
6877             "llvm.icall.branch.funnel operand must be a GlobalValue");
6878       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6879                                      GA->getGlobal(), getCurSDLoc(),
6880                                      Val.getValueType(), GA->getOffset())});
6881     }
6882     llvm::sort(Targets,
6883                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6884                  return T1.Offset < T2.Offset;
6885                });
6886 
6887     for (auto &T : Targets) {
6888       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6889       Ops.push_back(T.Target);
6890     }
6891 
6892     Ops.push_back(DAG.getRoot()); // Chain
6893     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6894                                  getCurSDLoc(), MVT::Other, Ops),
6895               0);
6896     DAG.setRoot(N);
6897     setValue(&I, N);
6898     HasTailCall = true;
6899     return;
6900   }
6901 
6902   case Intrinsic::wasm_landingpad_index:
6903     // Information this intrinsic contained has been transferred to
6904     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6905     // delete it now.
6906     return;
6907 
6908   case Intrinsic::aarch64_settag:
6909   case Intrinsic::aarch64_settag_zero: {
6910     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6911     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6912     SDValue Val = TSI.EmitTargetCodeForSetTag(
6913         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6914         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6915         ZeroMemory);
6916     DAG.setRoot(Val);
6917     setValue(&I, Val);
6918     return;
6919   }
6920   case Intrinsic::ptrmask: {
6921     SDValue Ptr = getValue(I.getOperand(0));
6922     SDValue Const = getValue(I.getOperand(1));
6923 
6924     EVT DestVT =
6925         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6926 
6927     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6928                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6929     return;
6930   }
6931   }
6932 }
6933 
6934 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6935     const ConstrainedFPIntrinsic &FPI) {
6936   SDLoc sdl = getCurSDLoc();
6937 
6938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6939   SmallVector<EVT, 4> ValueVTs;
6940   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6941   ValueVTs.push_back(MVT::Other); // Out chain
6942 
6943   // We do not need to serialize constrained FP intrinsics against
6944   // each other or against (nonvolatile) loads, so they can be
6945   // chained like loads.
6946   SDValue Chain = DAG.getRoot();
6947   SmallVector<SDValue, 4> Opers;
6948   Opers.push_back(Chain);
6949   if (FPI.isUnaryOp()) {
6950     Opers.push_back(getValue(FPI.getArgOperand(0)));
6951   } else if (FPI.isTernaryOp()) {
6952     Opers.push_back(getValue(FPI.getArgOperand(0)));
6953     Opers.push_back(getValue(FPI.getArgOperand(1)));
6954     Opers.push_back(getValue(FPI.getArgOperand(2)));
6955   } else {
6956     Opers.push_back(getValue(FPI.getArgOperand(0)));
6957     Opers.push_back(getValue(FPI.getArgOperand(1)));
6958   }
6959 
6960   unsigned Opcode;
6961   switch (FPI.getIntrinsicID()) {
6962   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6963 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6964   case Intrinsic::INTRINSIC:                                                   \
6965     Opcode = ISD::STRICT_##DAGN;                                               \
6966     break;
6967 #include "llvm/IR/ConstrainedOps.def"
6968   }
6969 
6970   // A few strict DAG nodes carry additional operands that are not
6971   // set up by the default code above.
6972   switch (Opcode) {
6973   default: break;
6974   case ISD::STRICT_FP_ROUND:
6975     Opers.push_back(
6976         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6977     break;
6978   case ISD::STRICT_FSETCC:
6979   case ISD::STRICT_FSETCCS: {
6980     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6981     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6982     break;
6983   }
6984   }
6985 
6986   SDVTList VTs = DAG.getVTList(ValueVTs);
6987   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
6988 
6989   if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) {
6990     SDNodeFlags Flags;
6991     Flags.setFPExcept(true);
6992     Result->setFlags(Flags);
6993   }
6994 
6995   assert(Result.getNode()->getNumValues() == 2);
6996   // See above -- chain is handled like for loads here.
6997   SDValue OutChain = Result.getValue(1);
6998   PendingLoads.push_back(OutChain);
6999   SDValue FPResult = Result.getValue(0);
7000   setValue(&FPI, FPResult);
7001 }
7002 
7003 std::pair<SDValue, SDValue>
7004 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7005                                     const BasicBlock *EHPadBB) {
7006   MachineFunction &MF = DAG.getMachineFunction();
7007   MachineModuleInfo &MMI = MF.getMMI();
7008   MCSymbol *BeginLabel = nullptr;
7009 
7010   if (EHPadBB) {
7011     // Insert a label before the invoke call to mark the try range.  This can be
7012     // used to detect deletion of the invoke via the MachineModuleInfo.
7013     BeginLabel = MMI.getContext().createTempSymbol();
7014 
7015     // For SjLj, keep track of which landing pads go with which invokes
7016     // so as to maintain the ordering of pads in the LSDA.
7017     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7018     if (CallSiteIndex) {
7019       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7020       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7021 
7022       // Now that the call site is handled, stop tracking it.
7023       MMI.setCurrentCallSite(0);
7024     }
7025 
7026     // Both PendingLoads and PendingExports must be flushed here;
7027     // this call might not return.
7028     (void)getRoot();
7029     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7030 
7031     CLI.setChain(getRoot());
7032   }
7033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7034   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7035 
7036   assert((CLI.IsTailCall || Result.second.getNode()) &&
7037          "Non-null chain expected with non-tail call!");
7038   assert((Result.second.getNode() || !Result.first.getNode()) &&
7039          "Null value expected with tail call!");
7040 
7041   if (!Result.second.getNode()) {
7042     // As a special case, a null chain means that a tail call has been emitted
7043     // and the DAG root is already updated.
7044     HasTailCall = true;
7045 
7046     // Since there's no actual continuation from this block, nothing can be
7047     // relying on us setting vregs for them.
7048     PendingExports.clear();
7049   } else {
7050     DAG.setRoot(Result.second);
7051   }
7052 
7053   if (EHPadBB) {
7054     // Insert a label at the end of the invoke call to mark the try range.  This
7055     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7056     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7057     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7058 
7059     // Inform MachineModuleInfo of range.
7060     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7061     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7062     // actually use outlined funclets and their LSDA info style.
7063     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7064       assert(CLI.CS);
7065       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7066       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7067                                 BeginLabel, EndLabel);
7068     } else if (!isScopedEHPersonality(Pers)) {
7069       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7070     }
7071   }
7072 
7073   return Result;
7074 }
7075 
7076 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7077                                       bool isTailCall,
7078                                       const BasicBlock *EHPadBB) {
7079   auto &DL = DAG.getDataLayout();
7080   FunctionType *FTy = CS.getFunctionType();
7081   Type *RetTy = CS.getType();
7082 
7083   TargetLowering::ArgListTy Args;
7084   Args.reserve(CS.arg_size());
7085 
7086   const Value *SwiftErrorVal = nullptr;
7087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7088 
7089   // We can't tail call inside a function with a swifterror argument. Lowering
7090   // does not support this yet. It would have to move into the swifterror
7091   // register before the call.
7092   auto *Caller = CS.getInstruction()->getParent()->getParent();
7093   if (TLI.supportSwiftError() &&
7094       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7095     isTailCall = false;
7096 
7097   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7098        i != e; ++i) {
7099     TargetLowering::ArgListEntry Entry;
7100     const Value *V = *i;
7101 
7102     // Skip empty types
7103     if (V->getType()->isEmptyTy())
7104       continue;
7105 
7106     SDValue ArgNode = getValue(V);
7107     Entry.Node = ArgNode; Entry.Ty = V->getType();
7108 
7109     Entry.setAttributes(&CS, i - CS.arg_begin());
7110 
7111     // Use swifterror virtual register as input to the call.
7112     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7113       SwiftErrorVal = V;
7114       // We find the virtual register for the actual swifterror argument.
7115       // Instead of using the Value, we use the virtual register instead.
7116       Entry.Node = DAG.getRegister(
7117           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7118           EVT(TLI.getPointerTy(DL)));
7119     }
7120 
7121     Args.push_back(Entry);
7122 
7123     // If we have an explicit sret argument that is an Instruction, (i.e., it
7124     // might point to function-local memory), we can't meaningfully tail-call.
7125     if (Entry.IsSRet && isa<Instruction>(V))
7126       isTailCall = false;
7127   }
7128 
7129   // If call site has a cfguardtarget operand bundle, create and add an
7130   // additional ArgListEntry.
7131   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7132     TargetLowering::ArgListEntry Entry;
7133     Value *V = Bundle->Inputs[0];
7134     SDValue ArgNode = getValue(V);
7135     Entry.Node = ArgNode;
7136     Entry.Ty = V->getType();
7137     Entry.IsCFGuardTarget = true;
7138     Args.push_back(Entry);
7139   }
7140 
7141   // Check if target-independent constraints permit a tail call here.
7142   // Target-dependent constraints are checked within TLI->LowerCallTo.
7143   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7144     isTailCall = false;
7145 
7146   // Disable tail calls if there is an swifterror argument. Targets have not
7147   // been updated to support tail calls.
7148   if (TLI.supportSwiftError() && SwiftErrorVal)
7149     isTailCall = false;
7150 
7151   TargetLowering::CallLoweringInfo CLI(DAG);
7152   CLI.setDebugLoc(getCurSDLoc())
7153       .setChain(getRoot())
7154       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7155       .setTailCall(isTailCall)
7156       .setConvergent(CS.isConvergent());
7157   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7158 
7159   if (Result.first.getNode()) {
7160     const Instruction *Inst = CS.getInstruction();
7161     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7162     setValue(Inst, Result.first);
7163   }
7164 
7165   // The last element of CLI.InVals has the SDValue for swifterror return.
7166   // Here we copy it to a virtual register and update SwiftErrorMap for
7167   // book-keeping.
7168   if (SwiftErrorVal && TLI.supportSwiftError()) {
7169     // Get the last element of InVals.
7170     SDValue Src = CLI.InVals.back();
7171     Register VReg = SwiftError.getOrCreateVRegDefAt(
7172         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7173     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7174     DAG.setRoot(CopyNode);
7175   }
7176 }
7177 
7178 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7179                              SelectionDAGBuilder &Builder) {
7180   // Check to see if this load can be trivially constant folded, e.g. if the
7181   // input is from a string literal.
7182   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7183     // Cast pointer to the type we really want to load.
7184     Type *LoadTy =
7185         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7186     if (LoadVT.isVector())
7187       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7188 
7189     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7190                                          PointerType::getUnqual(LoadTy));
7191 
7192     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7193             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7194       return Builder.getValue(LoadCst);
7195   }
7196 
7197   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7198   // still constant memory, the input chain can be the entry node.
7199   SDValue Root;
7200   bool ConstantMemory = false;
7201 
7202   // Do not serialize (non-volatile) loads of constant memory with anything.
7203   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7204     Root = Builder.DAG.getEntryNode();
7205     ConstantMemory = true;
7206   } else {
7207     // Do not serialize non-volatile loads against each other.
7208     Root = Builder.DAG.getRoot();
7209   }
7210 
7211   SDValue Ptr = Builder.getValue(PtrVal);
7212   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7213                                         Ptr, MachinePointerInfo(PtrVal),
7214                                         /* Alignment = */ 1);
7215 
7216   if (!ConstantMemory)
7217     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7218   return LoadVal;
7219 }
7220 
7221 /// Record the value for an instruction that produces an integer result,
7222 /// converting the type where necessary.
7223 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7224                                                   SDValue Value,
7225                                                   bool IsSigned) {
7226   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7227                                                     I.getType(), true);
7228   if (IsSigned)
7229     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7230   else
7231     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7232   setValue(&I, Value);
7233 }
7234 
7235 /// See if we can lower a memcmp call into an optimized form. If so, return
7236 /// true and lower it. Otherwise return false, and it will be lowered like a
7237 /// normal call.
7238 /// The caller already checked that \p I calls the appropriate LibFunc with a
7239 /// correct prototype.
7240 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7241   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7242   const Value *Size = I.getArgOperand(2);
7243   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7244   if (CSize && CSize->getZExtValue() == 0) {
7245     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7246                                                           I.getType(), true);
7247     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7248     return true;
7249   }
7250 
7251   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7252   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7253       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7254       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7255   if (Res.first.getNode()) {
7256     processIntegerCallValue(I, Res.first, true);
7257     PendingLoads.push_back(Res.second);
7258     return true;
7259   }
7260 
7261   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7262   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7263   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7264     return false;
7265 
7266   // If the target has a fast compare for the given size, it will return a
7267   // preferred load type for that size. Require that the load VT is legal and
7268   // that the target supports unaligned loads of that type. Otherwise, return
7269   // INVALID.
7270   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7271     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7272     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7273     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7274       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7275       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7276       // TODO: Check alignment of src and dest ptrs.
7277       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7278       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7279       if (!TLI.isTypeLegal(LVT) ||
7280           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7281           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7282         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7283     }
7284 
7285     return LVT;
7286   };
7287 
7288   // This turns into unaligned loads. We only do this if the target natively
7289   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7290   // we'll only produce a small number of byte loads.
7291   MVT LoadVT;
7292   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7293   switch (NumBitsToCompare) {
7294   default:
7295     return false;
7296   case 16:
7297     LoadVT = MVT::i16;
7298     break;
7299   case 32:
7300     LoadVT = MVT::i32;
7301     break;
7302   case 64:
7303   case 128:
7304   case 256:
7305     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7306     break;
7307   }
7308 
7309   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7310     return false;
7311 
7312   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7313   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7314 
7315   // Bitcast to a wide integer type if the loads are vectors.
7316   if (LoadVT.isVector()) {
7317     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7318     LoadL = DAG.getBitcast(CmpVT, LoadL);
7319     LoadR = DAG.getBitcast(CmpVT, LoadR);
7320   }
7321 
7322   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7323   processIntegerCallValue(I, Cmp, false);
7324   return true;
7325 }
7326 
7327 /// See if we can lower a memchr call into an optimized form. If so, return
7328 /// true and lower it. Otherwise return false, and it will be lowered like a
7329 /// normal call.
7330 /// The caller already checked that \p I calls the appropriate LibFunc with a
7331 /// correct prototype.
7332 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7333   const Value *Src = I.getArgOperand(0);
7334   const Value *Char = I.getArgOperand(1);
7335   const Value *Length = I.getArgOperand(2);
7336 
7337   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7338   std::pair<SDValue, SDValue> Res =
7339     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7340                                 getValue(Src), getValue(Char), getValue(Length),
7341                                 MachinePointerInfo(Src));
7342   if (Res.first.getNode()) {
7343     setValue(&I, Res.first);
7344     PendingLoads.push_back(Res.second);
7345     return true;
7346   }
7347 
7348   return false;
7349 }
7350 
7351 /// See if we can lower a mempcpy call into an optimized form. If so, return
7352 /// true and lower it. Otherwise return false, and it will be lowered like a
7353 /// normal call.
7354 /// The caller already checked that \p I calls the appropriate LibFunc with a
7355 /// correct prototype.
7356 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7357   SDValue Dst = getValue(I.getArgOperand(0));
7358   SDValue Src = getValue(I.getArgOperand(1));
7359   SDValue Size = getValue(I.getArgOperand(2));
7360 
7361   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7362   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7363   unsigned Align = std::min(DstAlign, SrcAlign);
7364   if (Align == 0) // Alignment of one or both could not be inferred.
7365     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7366 
7367   bool isVol = false;
7368   SDLoc sdl = getCurSDLoc();
7369 
7370   // In the mempcpy context we need to pass in a false value for isTailCall
7371   // because the return pointer needs to be adjusted by the size of
7372   // the copied memory.
7373   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7374                              false, /*isTailCall=*/false,
7375                              MachinePointerInfo(I.getArgOperand(0)),
7376                              MachinePointerInfo(I.getArgOperand(1)));
7377   assert(MC.getNode() != nullptr &&
7378          "** memcpy should not be lowered as TailCall in mempcpy context **");
7379   DAG.setRoot(MC);
7380 
7381   // Check if Size needs to be truncated or extended.
7382   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7383 
7384   // Adjust return pointer to point just past the last dst byte.
7385   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7386                                     Dst, Size);
7387   setValue(&I, DstPlusSize);
7388   return true;
7389 }
7390 
7391 /// See if we can lower a strcpy call into an optimized form.  If so, return
7392 /// true and lower it, otherwise return false and it will be lowered like a
7393 /// normal call.
7394 /// The caller already checked that \p I calls the appropriate LibFunc with a
7395 /// correct prototype.
7396 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7397   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7398 
7399   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7400   std::pair<SDValue, SDValue> Res =
7401     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7402                                 getValue(Arg0), getValue(Arg1),
7403                                 MachinePointerInfo(Arg0),
7404                                 MachinePointerInfo(Arg1), isStpcpy);
7405   if (Res.first.getNode()) {
7406     setValue(&I, Res.first);
7407     DAG.setRoot(Res.second);
7408     return true;
7409   }
7410 
7411   return false;
7412 }
7413 
7414 /// See if we can lower a strcmp call into an optimized form.  If so, return
7415 /// true and lower it, otherwise return false and it will be lowered like a
7416 /// normal call.
7417 /// The caller already checked that \p I calls the appropriate LibFunc with a
7418 /// correct prototype.
7419 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7420   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7421 
7422   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7423   std::pair<SDValue, SDValue> Res =
7424     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7425                                 getValue(Arg0), getValue(Arg1),
7426                                 MachinePointerInfo(Arg0),
7427                                 MachinePointerInfo(Arg1));
7428   if (Res.first.getNode()) {
7429     processIntegerCallValue(I, Res.first, true);
7430     PendingLoads.push_back(Res.second);
7431     return true;
7432   }
7433 
7434   return false;
7435 }
7436 
7437 /// See if we can lower a strlen call into an optimized form.  If so, return
7438 /// true and lower it, otherwise return false and it will be lowered like a
7439 /// normal call.
7440 /// The caller already checked that \p I calls the appropriate LibFunc with a
7441 /// correct prototype.
7442 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7443   const Value *Arg0 = I.getArgOperand(0);
7444 
7445   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7446   std::pair<SDValue, SDValue> Res =
7447     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7448                                 getValue(Arg0), MachinePointerInfo(Arg0));
7449   if (Res.first.getNode()) {
7450     processIntegerCallValue(I, Res.first, false);
7451     PendingLoads.push_back(Res.second);
7452     return true;
7453   }
7454 
7455   return false;
7456 }
7457 
7458 /// See if we can lower a strnlen call into an optimized form.  If so, return
7459 /// true and lower it, otherwise return false and it will be lowered like a
7460 /// normal call.
7461 /// The caller already checked that \p I calls the appropriate LibFunc with a
7462 /// correct prototype.
7463 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7464   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7465 
7466   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7467   std::pair<SDValue, SDValue> Res =
7468     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7469                                  getValue(Arg0), getValue(Arg1),
7470                                  MachinePointerInfo(Arg0));
7471   if (Res.first.getNode()) {
7472     processIntegerCallValue(I, Res.first, false);
7473     PendingLoads.push_back(Res.second);
7474     return true;
7475   }
7476 
7477   return false;
7478 }
7479 
7480 /// See if we can lower a unary floating-point operation into an SDNode with
7481 /// the specified Opcode.  If so, return true and lower it, otherwise return
7482 /// false and it will be lowered like a normal call.
7483 /// The caller already checked that \p I calls the appropriate LibFunc with a
7484 /// correct prototype.
7485 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7486                                               unsigned Opcode) {
7487   // We already checked this call's prototype; verify it doesn't modify errno.
7488   if (!I.onlyReadsMemory())
7489     return false;
7490 
7491   SDValue Tmp = getValue(I.getArgOperand(0));
7492   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7493   return true;
7494 }
7495 
7496 /// See if we can lower a binary floating-point operation into an SDNode with
7497 /// the specified Opcode. If so, return true and lower it. Otherwise return
7498 /// false, and it will be lowered like a normal call.
7499 /// The caller already checked that \p I calls the appropriate LibFunc with a
7500 /// correct prototype.
7501 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7502                                                unsigned Opcode) {
7503   // We already checked this call's prototype; verify it doesn't modify errno.
7504   if (!I.onlyReadsMemory())
7505     return false;
7506 
7507   SDValue Tmp0 = getValue(I.getArgOperand(0));
7508   SDValue Tmp1 = getValue(I.getArgOperand(1));
7509   EVT VT = Tmp0.getValueType();
7510   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7511   return true;
7512 }
7513 
7514 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7515   // Handle inline assembly differently.
7516   if (isa<InlineAsm>(I.getCalledValue())) {
7517     visitInlineAsm(&I);
7518     return;
7519   }
7520 
7521   if (Function *F = I.getCalledFunction()) {
7522     if (F->isDeclaration()) {
7523       // Is this an LLVM intrinsic or a target-specific intrinsic?
7524       unsigned IID = F->getIntrinsicID();
7525       if (!IID)
7526         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7527           IID = II->getIntrinsicID(F);
7528 
7529       if (IID) {
7530         visitIntrinsicCall(I, IID);
7531         return;
7532       }
7533     }
7534 
7535     // Check for well-known libc/libm calls.  If the function is internal, it
7536     // can't be a library call.  Don't do the check if marked as nobuiltin for
7537     // some reason or the call site requires strict floating point semantics.
7538     LibFunc Func;
7539     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7540         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7541         LibInfo->hasOptimizedCodeGen(Func)) {
7542       switch (Func) {
7543       default: break;
7544       case LibFunc_copysign:
7545       case LibFunc_copysignf:
7546       case LibFunc_copysignl:
7547         // We already checked this call's prototype; verify it doesn't modify
7548         // errno.
7549         if (I.onlyReadsMemory()) {
7550           SDValue LHS = getValue(I.getArgOperand(0));
7551           SDValue RHS = getValue(I.getArgOperand(1));
7552           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7553                                    LHS.getValueType(), LHS, RHS));
7554           return;
7555         }
7556         break;
7557       case LibFunc_fabs:
7558       case LibFunc_fabsf:
7559       case LibFunc_fabsl:
7560         if (visitUnaryFloatCall(I, ISD::FABS))
7561           return;
7562         break;
7563       case LibFunc_fmin:
7564       case LibFunc_fminf:
7565       case LibFunc_fminl:
7566         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7567           return;
7568         break;
7569       case LibFunc_fmax:
7570       case LibFunc_fmaxf:
7571       case LibFunc_fmaxl:
7572         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7573           return;
7574         break;
7575       case LibFunc_sin:
7576       case LibFunc_sinf:
7577       case LibFunc_sinl:
7578         if (visitUnaryFloatCall(I, ISD::FSIN))
7579           return;
7580         break;
7581       case LibFunc_cos:
7582       case LibFunc_cosf:
7583       case LibFunc_cosl:
7584         if (visitUnaryFloatCall(I, ISD::FCOS))
7585           return;
7586         break;
7587       case LibFunc_sqrt:
7588       case LibFunc_sqrtf:
7589       case LibFunc_sqrtl:
7590       case LibFunc_sqrt_finite:
7591       case LibFunc_sqrtf_finite:
7592       case LibFunc_sqrtl_finite:
7593         if (visitUnaryFloatCall(I, ISD::FSQRT))
7594           return;
7595         break;
7596       case LibFunc_floor:
7597       case LibFunc_floorf:
7598       case LibFunc_floorl:
7599         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7600           return;
7601         break;
7602       case LibFunc_nearbyint:
7603       case LibFunc_nearbyintf:
7604       case LibFunc_nearbyintl:
7605         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7606           return;
7607         break;
7608       case LibFunc_ceil:
7609       case LibFunc_ceilf:
7610       case LibFunc_ceill:
7611         if (visitUnaryFloatCall(I, ISD::FCEIL))
7612           return;
7613         break;
7614       case LibFunc_rint:
7615       case LibFunc_rintf:
7616       case LibFunc_rintl:
7617         if (visitUnaryFloatCall(I, ISD::FRINT))
7618           return;
7619         break;
7620       case LibFunc_round:
7621       case LibFunc_roundf:
7622       case LibFunc_roundl:
7623         if (visitUnaryFloatCall(I, ISD::FROUND))
7624           return;
7625         break;
7626       case LibFunc_trunc:
7627       case LibFunc_truncf:
7628       case LibFunc_truncl:
7629         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7630           return;
7631         break;
7632       case LibFunc_log2:
7633       case LibFunc_log2f:
7634       case LibFunc_log2l:
7635         if (visitUnaryFloatCall(I, ISD::FLOG2))
7636           return;
7637         break;
7638       case LibFunc_exp2:
7639       case LibFunc_exp2f:
7640       case LibFunc_exp2l:
7641         if (visitUnaryFloatCall(I, ISD::FEXP2))
7642           return;
7643         break;
7644       case LibFunc_memcmp:
7645         if (visitMemCmpCall(I))
7646           return;
7647         break;
7648       case LibFunc_mempcpy:
7649         if (visitMemPCpyCall(I))
7650           return;
7651         break;
7652       case LibFunc_memchr:
7653         if (visitMemChrCall(I))
7654           return;
7655         break;
7656       case LibFunc_strcpy:
7657         if (visitStrCpyCall(I, false))
7658           return;
7659         break;
7660       case LibFunc_stpcpy:
7661         if (visitStrCpyCall(I, true))
7662           return;
7663         break;
7664       case LibFunc_strcmp:
7665         if (visitStrCmpCall(I))
7666           return;
7667         break;
7668       case LibFunc_strlen:
7669         if (visitStrLenCall(I))
7670           return;
7671         break;
7672       case LibFunc_strnlen:
7673         if (visitStrNLenCall(I))
7674           return;
7675         break;
7676       }
7677     }
7678   }
7679 
7680   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7681   // have to do anything here to lower funclet bundles.
7682   // CFGuardTarget bundles are lowered in LowerCallTo.
7683   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7684                                         LLVMContext::OB_funclet,
7685                                         LLVMContext::OB_cfguardtarget}) &&
7686          "Cannot lower calls with arbitrary operand bundles!");
7687 
7688   SDValue Callee = getValue(I.getCalledValue());
7689 
7690   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7691     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7692   else
7693     // Check if we can potentially perform a tail call. More detailed checking
7694     // is be done within LowerCallTo, after more information about the call is
7695     // known.
7696     LowerCallTo(&I, Callee, I.isTailCall());
7697 }
7698 
7699 namespace {
7700 
7701 /// AsmOperandInfo - This contains information for each constraint that we are
7702 /// lowering.
7703 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7704 public:
7705   /// CallOperand - If this is the result output operand or a clobber
7706   /// this is null, otherwise it is the incoming operand to the CallInst.
7707   /// This gets modified as the asm is processed.
7708   SDValue CallOperand;
7709 
7710   /// AssignedRegs - If this is a register or register class operand, this
7711   /// contains the set of register corresponding to the operand.
7712   RegsForValue AssignedRegs;
7713 
7714   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7715     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7716   }
7717 
7718   /// Whether or not this operand accesses memory
7719   bool hasMemory(const TargetLowering &TLI) const {
7720     // Indirect operand accesses access memory.
7721     if (isIndirect)
7722       return true;
7723 
7724     for (const auto &Code : Codes)
7725       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7726         return true;
7727 
7728     return false;
7729   }
7730 
7731   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7732   /// corresponds to.  If there is no Value* for this operand, it returns
7733   /// MVT::Other.
7734   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7735                            const DataLayout &DL) const {
7736     if (!CallOperandVal) return MVT::Other;
7737 
7738     if (isa<BasicBlock>(CallOperandVal))
7739       return TLI.getPointerTy(DL);
7740 
7741     llvm::Type *OpTy = CallOperandVal->getType();
7742 
7743     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7744     // If this is an indirect operand, the operand is a pointer to the
7745     // accessed type.
7746     if (isIndirect) {
7747       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7748       if (!PtrTy)
7749         report_fatal_error("Indirect operand for inline asm not a pointer!");
7750       OpTy = PtrTy->getElementType();
7751     }
7752 
7753     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7754     if (StructType *STy = dyn_cast<StructType>(OpTy))
7755       if (STy->getNumElements() == 1)
7756         OpTy = STy->getElementType(0);
7757 
7758     // If OpTy is not a single value, it may be a struct/union that we
7759     // can tile with integers.
7760     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7761       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7762       switch (BitSize) {
7763       default: break;
7764       case 1:
7765       case 8:
7766       case 16:
7767       case 32:
7768       case 64:
7769       case 128:
7770         OpTy = IntegerType::get(Context, BitSize);
7771         break;
7772       }
7773     }
7774 
7775     return TLI.getValueType(DL, OpTy, true);
7776   }
7777 };
7778 
7779 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7780 
7781 } // end anonymous namespace
7782 
7783 /// Make sure that the output operand \p OpInfo and its corresponding input
7784 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7785 /// out).
7786 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7787                                SDISelAsmOperandInfo &MatchingOpInfo,
7788                                SelectionDAG &DAG) {
7789   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7790     return;
7791 
7792   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7793   const auto &TLI = DAG.getTargetLoweringInfo();
7794 
7795   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7796       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7797                                        OpInfo.ConstraintVT);
7798   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7799       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7800                                        MatchingOpInfo.ConstraintVT);
7801   if ((OpInfo.ConstraintVT.isInteger() !=
7802        MatchingOpInfo.ConstraintVT.isInteger()) ||
7803       (MatchRC.second != InputRC.second)) {
7804     // FIXME: error out in a more elegant fashion
7805     report_fatal_error("Unsupported asm: input constraint"
7806                        " with a matching output constraint of"
7807                        " incompatible type!");
7808   }
7809   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7810 }
7811 
7812 /// Get a direct memory input to behave well as an indirect operand.
7813 /// This may introduce stores, hence the need for a \p Chain.
7814 /// \return The (possibly updated) chain.
7815 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7816                                         SDISelAsmOperandInfo &OpInfo,
7817                                         SelectionDAG &DAG) {
7818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7819 
7820   // If we don't have an indirect input, put it in the constpool if we can,
7821   // otherwise spill it to a stack slot.
7822   // TODO: This isn't quite right. We need to handle these according to
7823   // the addressing mode that the constraint wants. Also, this may take
7824   // an additional register for the computation and we don't want that
7825   // either.
7826 
7827   // If the operand is a float, integer, or vector constant, spill to a
7828   // constant pool entry to get its address.
7829   const Value *OpVal = OpInfo.CallOperandVal;
7830   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7831       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7832     OpInfo.CallOperand = DAG.getConstantPool(
7833         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7834     return Chain;
7835   }
7836 
7837   // Otherwise, create a stack slot and emit a store to it before the asm.
7838   Type *Ty = OpVal->getType();
7839   auto &DL = DAG.getDataLayout();
7840   uint64_t TySize = DL.getTypeAllocSize(Ty);
7841   unsigned Align = DL.getPrefTypeAlignment(Ty);
7842   MachineFunction &MF = DAG.getMachineFunction();
7843   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7844   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7845   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7846                             MachinePointerInfo::getFixedStack(MF, SSFI),
7847                             TLI.getMemValueType(DL, Ty));
7848   OpInfo.CallOperand = StackSlot;
7849 
7850   return Chain;
7851 }
7852 
7853 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7854 /// specified operand.  We prefer to assign virtual registers, to allow the
7855 /// register allocator to handle the assignment process.  However, if the asm
7856 /// uses features that we can't model on machineinstrs, we have SDISel do the
7857 /// allocation.  This produces generally horrible, but correct, code.
7858 ///
7859 ///   OpInfo describes the operand
7860 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7861 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7862                                  SDISelAsmOperandInfo &OpInfo,
7863                                  SDISelAsmOperandInfo &RefOpInfo) {
7864   LLVMContext &Context = *DAG.getContext();
7865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7866 
7867   MachineFunction &MF = DAG.getMachineFunction();
7868   SmallVector<unsigned, 4> Regs;
7869   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7870 
7871   // No work to do for memory operations.
7872   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7873     return;
7874 
7875   // If this is a constraint for a single physreg, or a constraint for a
7876   // register class, find it.
7877   unsigned AssignedReg;
7878   const TargetRegisterClass *RC;
7879   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7880       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7881   // RC is unset only on failure. Return immediately.
7882   if (!RC)
7883     return;
7884 
7885   // Get the actual register value type.  This is important, because the user
7886   // may have asked for (e.g.) the AX register in i32 type.  We need to
7887   // remember that AX is actually i16 to get the right extension.
7888   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7889 
7890   if (OpInfo.ConstraintVT != MVT::Other) {
7891     // If this is an FP operand in an integer register (or visa versa), or more
7892     // generally if the operand value disagrees with the register class we plan
7893     // to stick it in, fix the operand type.
7894     //
7895     // If this is an input value, the bitcast to the new type is done now.
7896     // Bitcast for output value is done at the end of visitInlineAsm().
7897     if ((OpInfo.Type == InlineAsm::isOutput ||
7898          OpInfo.Type == InlineAsm::isInput) &&
7899         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7900       // Try to convert to the first EVT that the reg class contains.  If the
7901       // types are identical size, use a bitcast to convert (e.g. two differing
7902       // vector types).  Note: output bitcast is done at the end of
7903       // visitInlineAsm().
7904       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7905         // Exclude indirect inputs while they are unsupported because the code
7906         // to perform the load is missing and thus OpInfo.CallOperand still
7907         // refers to the input address rather than the pointed-to value.
7908         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7909           OpInfo.CallOperand =
7910               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7911         OpInfo.ConstraintVT = RegVT;
7912         // If the operand is an FP value and we want it in integer registers,
7913         // use the corresponding integer type. This turns an f64 value into
7914         // i64, which can be passed with two i32 values on a 32-bit machine.
7915       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7916         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7917         if (OpInfo.Type == InlineAsm::isInput)
7918           OpInfo.CallOperand =
7919               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7920         OpInfo.ConstraintVT = VT;
7921       }
7922     }
7923   }
7924 
7925   // No need to allocate a matching input constraint since the constraint it's
7926   // matching to has already been allocated.
7927   if (OpInfo.isMatchingInputConstraint())
7928     return;
7929 
7930   EVT ValueVT = OpInfo.ConstraintVT;
7931   if (OpInfo.ConstraintVT == MVT::Other)
7932     ValueVT = RegVT;
7933 
7934   // Initialize NumRegs.
7935   unsigned NumRegs = 1;
7936   if (OpInfo.ConstraintVT != MVT::Other)
7937     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7938 
7939   // If this is a constraint for a specific physical register, like {r17},
7940   // assign it now.
7941 
7942   // If this associated to a specific register, initialize iterator to correct
7943   // place. If virtual, make sure we have enough registers
7944 
7945   // Initialize iterator if necessary
7946   TargetRegisterClass::iterator I = RC->begin();
7947   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7948 
7949   // Do not check for single registers.
7950   if (AssignedReg) {
7951       for (; *I != AssignedReg; ++I)
7952         assert(I != RC->end() && "AssignedReg should be member of RC");
7953   }
7954 
7955   for (; NumRegs; --NumRegs, ++I) {
7956     assert(I != RC->end() && "Ran out of registers to allocate!");
7957     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7958     Regs.push_back(R);
7959   }
7960 
7961   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7962 }
7963 
7964 static unsigned
7965 findMatchingInlineAsmOperand(unsigned OperandNo,
7966                              const std::vector<SDValue> &AsmNodeOperands) {
7967   // Scan until we find the definition we already emitted of this operand.
7968   unsigned CurOp = InlineAsm::Op_FirstOperand;
7969   for (; OperandNo; --OperandNo) {
7970     // Advance to the next operand.
7971     unsigned OpFlag =
7972         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7973     assert((InlineAsm::isRegDefKind(OpFlag) ||
7974             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7975             InlineAsm::isMemKind(OpFlag)) &&
7976            "Skipped past definitions?");
7977     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7978   }
7979   return CurOp;
7980 }
7981 
7982 namespace {
7983 
7984 class ExtraFlags {
7985   unsigned Flags = 0;
7986 
7987 public:
7988   explicit ExtraFlags(ImmutableCallSite CS) {
7989     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7990     if (IA->hasSideEffects())
7991       Flags |= InlineAsm::Extra_HasSideEffects;
7992     if (IA->isAlignStack())
7993       Flags |= InlineAsm::Extra_IsAlignStack;
7994     if (CS.isConvergent())
7995       Flags |= InlineAsm::Extra_IsConvergent;
7996     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7997   }
7998 
7999   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8000     // Ideally, we would only check against memory constraints.  However, the
8001     // meaning of an Other constraint can be target-specific and we can't easily
8002     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8003     // for Other constraints as well.
8004     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8005         OpInfo.ConstraintType == TargetLowering::C_Other) {
8006       if (OpInfo.Type == InlineAsm::isInput)
8007         Flags |= InlineAsm::Extra_MayLoad;
8008       else if (OpInfo.Type == InlineAsm::isOutput)
8009         Flags |= InlineAsm::Extra_MayStore;
8010       else if (OpInfo.Type == InlineAsm::isClobber)
8011         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8012     }
8013   }
8014 
8015   unsigned get() const { return Flags; }
8016 };
8017 
8018 } // end anonymous namespace
8019 
8020 /// visitInlineAsm - Handle a call to an InlineAsm object.
8021 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8022   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8023 
8024   /// ConstraintOperands - Information about all of the constraints.
8025   SDISelAsmOperandInfoVector ConstraintOperands;
8026 
8027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8028   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8029       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8030 
8031   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8032   // AsmDialect, MayLoad, MayStore).
8033   bool HasSideEffect = IA->hasSideEffects();
8034   ExtraFlags ExtraInfo(CS);
8035 
8036   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8037   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8038   for (auto &T : TargetConstraints) {
8039     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8040     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8041 
8042     // Compute the value type for each operand.
8043     if (OpInfo.Type == InlineAsm::isInput ||
8044         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8045       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8046 
8047       // Process the call argument. BasicBlocks are labels, currently appearing
8048       // only in asm's.
8049       const Instruction *I = CS.getInstruction();
8050       if (isa<CallBrInst>(I) &&
8051           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8052                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8053         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8054         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8055         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8056       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8057         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8058       } else {
8059         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8060       }
8061 
8062       OpInfo.ConstraintVT =
8063           OpInfo
8064               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8065               .getSimpleVT();
8066     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8067       // The return value of the call is this value.  As such, there is no
8068       // corresponding argument.
8069       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8070       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8071         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8072             DAG.getDataLayout(), STy->getElementType(ResNo));
8073       } else {
8074         assert(ResNo == 0 && "Asm only has one result!");
8075         OpInfo.ConstraintVT =
8076             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8077       }
8078       ++ResNo;
8079     } else {
8080       OpInfo.ConstraintVT = MVT::Other;
8081     }
8082 
8083     if (!HasSideEffect)
8084       HasSideEffect = OpInfo.hasMemory(TLI);
8085 
8086     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8087     // FIXME: Could we compute this on OpInfo rather than T?
8088 
8089     // Compute the constraint code and ConstraintType to use.
8090     TLI.ComputeConstraintToUse(T, SDValue());
8091 
8092     if (T.ConstraintType == TargetLowering::C_Immediate &&
8093         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8094       // We've delayed emitting a diagnostic like the "n" constraint because
8095       // inlining could cause an integer showing up.
8096       return emitInlineAsmError(
8097           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8098                   "integer constant expression");
8099 
8100     ExtraInfo.update(T);
8101   }
8102 
8103 
8104   // We won't need to flush pending loads if this asm doesn't touch
8105   // memory and is nonvolatile.
8106   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8107 
8108   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8109   if (IsCallBr) {
8110     // If this is a callbr we need to flush pending exports since inlineasm_br
8111     // is a terminator. We need to do this before nodes are glued to
8112     // the inlineasm_br node.
8113     Chain = getControlRoot();
8114   }
8115 
8116   // Second pass over the constraints: compute which constraint option to use.
8117   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8118     // If this is an output operand with a matching input operand, look up the
8119     // matching input. If their types mismatch, e.g. one is an integer, the
8120     // other is floating point, or their sizes are different, flag it as an
8121     // error.
8122     if (OpInfo.hasMatchingInput()) {
8123       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8124       patchMatchingInput(OpInfo, Input, DAG);
8125     }
8126 
8127     // Compute the constraint code and ConstraintType to use.
8128     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8129 
8130     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8131         OpInfo.Type == InlineAsm::isClobber)
8132       continue;
8133 
8134     // If this is a memory input, and if the operand is not indirect, do what we
8135     // need to provide an address for the memory input.
8136     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8137         !OpInfo.isIndirect) {
8138       assert((OpInfo.isMultipleAlternative ||
8139               (OpInfo.Type == InlineAsm::isInput)) &&
8140              "Can only indirectify direct input operands!");
8141 
8142       // Memory operands really want the address of the value.
8143       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8144 
8145       // There is no longer a Value* corresponding to this operand.
8146       OpInfo.CallOperandVal = nullptr;
8147 
8148       // It is now an indirect operand.
8149       OpInfo.isIndirect = true;
8150     }
8151 
8152   }
8153 
8154   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8155   std::vector<SDValue> AsmNodeOperands;
8156   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8157   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8158       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8159 
8160   // If we have a !srcloc metadata node associated with it, we want to attach
8161   // this to the ultimately generated inline asm machineinstr.  To do this, we
8162   // pass in the third operand as this (potentially null) inline asm MDNode.
8163   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8164   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8165 
8166   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8167   // bits as operand 3.
8168   AsmNodeOperands.push_back(DAG.getTargetConstant(
8169       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8170 
8171   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8172   // this, assign virtual and physical registers for inputs and otput.
8173   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8174     // Assign Registers.
8175     SDISelAsmOperandInfo &RefOpInfo =
8176         OpInfo.isMatchingInputConstraint()
8177             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8178             : OpInfo;
8179     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8180 
8181     switch (OpInfo.Type) {
8182     case InlineAsm::isOutput:
8183       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8184           ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8185             OpInfo.ConstraintType == TargetLowering::C_Other) &&
8186            OpInfo.isIndirect)) {
8187         unsigned ConstraintID =
8188             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8189         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8190                "Failed to convert memory constraint code to constraint id.");
8191 
8192         // Add information to the INLINEASM node to know about this output.
8193         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8194         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8195         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8196                                                         MVT::i32));
8197         AsmNodeOperands.push_back(OpInfo.CallOperand);
8198         break;
8199       } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8200                    OpInfo.ConstraintType == TargetLowering::C_Other) &&
8201                   !OpInfo.isIndirect) ||
8202                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8203                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8204         // Otherwise, this outputs to a register (directly for C_Register /
8205         // C_RegisterClass, and a target-defined fashion for
8206         // C_Immediate/C_Other). Find a register that we can use.
8207         if (OpInfo.AssignedRegs.Regs.empty()) {
8208           emitInlineAsmError(
8209               CS, "couldn't allocate output register for constraint '" +
8210                       Twine(OpInfo.ConstraintCode) + "'");
8211           return;
8212         }
8213 
8214         // Add information to the INLINEASM node to know that this register is
8215         // set.
8216         OpInfo.AssignedRegs.AddInlineAsmOperands(
8217             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8218                                   : InlineAsm::Kind_RegDef,
8219             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8220       }
8221       break;
8222 
8223     case InlineAsm::isInput: {
8224       SDValue InOperandVal = OpInfo.CallOperand;
8225 
8226       if (OpInfo.isMatchingInputConstraint()) {
8227         // If this is required to match an output register we have already set,
8228         // just use its register.
8229         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8230                                                   AsmNodeOperands);
8231         unsigned OpFlag =
8232           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8233         if (InlineAsm::isRegDefKind(OpFlag) ||
8234             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8235           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8236           if (OpInfo.isIndirect) {
8237             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8238             emitInlineAsmError(CS, "inline asm not supported yet:"
8239                                    " don't know how to handle tied "
8240                                    "indirect register inputs");
8241             return;
8242           }
8243 
8244           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8245           SmallVector<unsigned, 4> Regs;
8246 
8247           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8248             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8249             MachineRegisterInfo &RegInfo =
8250                 DAG.getMachineFunction().getRegInfo();
8251             for (unsigned i = 0; i != NumRegs; ++i)
8252               Regs.push_back(RegInfo.createVirtualRegister(RC));
8253           } else {
8254             emitInlineAsmError(CS, "inline asm error: This value type register "
8255                                    "class is not natively supported!");
8256             return;
8257           }
8258 
8259           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8260 
8261           SDLoc dl = getCurSDLoc();
8262           // Use the produced MatchedRegs object to
8263           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8264                                     CS.getInstruction());
8265           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8266                                            true, OpInfo.getMatchedOperand(), dl,
8267                                            DAG, AsmNodeOperands);
8268           break;
8269         }
8270 
8271         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8272         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8273                "Unexpected number of operands");
8274         // Add information to the INLINEASM node to know about this input.
8275         // See InlineAsm.h isUseOperandTiedToDef.
8276         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8277         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8278                                                     OpInfo.getMatchedOperand());
8279         AsmNodeOperands.push_back(DAG.getTargetConstant(
8280             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8281         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8282         break;
8283       }
8284 
8285       // Treat indirect 'X' constraint as memory.
8286       if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8287            OpInfo.ConstraintType == TargetLowering::C_Other) &&
8288           OpInfo.isIndirect)
8289         OpInfo.ConstraintType = TargetLowering::C_Memory;
8290 
8291       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8292           OpInfo.ConstraintType == TargetLowering::C_Other) {
8293         std::vector<SDValue> Ops;
8294         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8295                                           Ops, DAG);
8296         if (Ops.empty()) {
8297           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8298             if (isa<ConstantSDNode>(InOperandVal)) {
8299               emitInlineAsmError(CS, "value out of range for constraint '" +
8300                                  Twine(OpInfo.ConstraintCode) + "'");
8301               return;
8302             }
8303 
8304           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8305                                      Twine(OpInfo.ConstraintCode) + "'");
8306           return;
8307         }
8308 
8309         // Add information to the INLINEASM node to know about this input.
8310         unsigned ResOpType =
8311           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8312         AsmNodeOperands.push_back(DAG.getTargetConstant(
8313             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8314         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8315         break;
8316       }
8317 
8318       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8319         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8320         assert(InOperandVal.getValueType() ==
8321                    TLI.getPointerTy(DAG.getDataLayout()) &&
8322                "Memory operands expect pointer values");
8323 
8324         unsigned ConstraintID =
8325             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8326         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8327                "Failed to convert memory constraint code to constraint id.");
8328 
8329         // Add information to the INLINEASM node to know about this input.
8330         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8331         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8332         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8333                                                         getCurSDLoc(),
8334                                                         MVT::i32));
8335         AsmNodeOperands.push_back(InOperandVal);
8336         break;
8337       }
8338 
8339       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8340               OpInfo.ConstraintType == TargetLowering::C_Register ||
8341               OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8342              "Unknown constraint type!");
8343 
8344       // TODO: Support this.
8345       if (OpInfo.isIndirect) {
8346         emitInlineAsmError(
8347             CS, "Don't know how to handle indirect register inputs yet "
8348                 "for constraint '" +
8349                     Twine(OpInfo.ConstraintCode) + "'");
8350         return;
8351       }
8352 
8353       // Copy the input into the appropriate registers.
8354       if (OpInfo.AssignedRegs.Regs.empty()) {
8355         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8356                                    Twine(OpInfo.ConstraintCode) + "'");
8357         return;
8358       }
8359 
8360       SDLoc dl = getCurSDLoc();
8361 
8362       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8363                                         Chain, &Flag, CS.getInstruction());
8364 
8365       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8366                                                dl, DAG, AsmNodeOperands);
8367       break;
8368     }
8369     case InlineAsm::isClobber:
8370       // Add the clobbered value to the operand list, so that the register
8371       // allocator is aware that the physreg got clobbered.
8372       if (!OpInfo.AssignedRegs.Regs.empty())
8373         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8374                                                  false, 0, getCurSDLoc(), DAG,
8375                                                  AsmNodeOperands);
8376       break;
8377     }
8378   }
8379 
8380   // Finish up input operands.  Set the input chain and add the flag last.
8381   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8382   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8383 
8384   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8385   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8386                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8387   Flag = Chain.getValue(1);
8388 
8389   // Do additional work to generate outputs.
8390 
8391   SmallVector<EVT, 1> ResultVTs;
8392   SmallVector<SDValue, 1> ResultValues;
8393   SmallVector<SDValue, 8> OutChains;
8394 
8395   llvm::Type *CSResultType = CS.getType();
8396   ArrayRef<Type *> ResultTypes;
8397   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8398     ResultTypes = StructResult->elements();
8399   else if (!CSResultType->isVoidTy())
8400     ResultTypes = makeArrayRef(CSResultType);
8401 
8402   auto CurResultType = ResultTypes.begin();
8403   auto handleRegAssign = [&](SDValue V) {
8404     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8405     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8406     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8407     ++CurResultType;
8408     // If the type of the inline asm call site return value is different but has
8409     // same size as the type of the asm output bitcast it.  One example of this
8410     // is for vectors with different width / number of elements.  This can
8411     // happen for register classes that can contain multiple different value
8412     // types.  The preg or vreg allocated may not have the same VT as was
8413     // expected.
8414     //
8415     // This can also happen for a return value that disagrees with the register
8416     // class it is put in, eg. a double in a general-purpose register on a
8417     // 32-bit machine.
8418     if (ResultVT != V.getValueType() &&
8419         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8420       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8421     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8422              V.getValueType().isInteger()) {
8423       // If a result value was tied to an input value, the computed result
8424       // may have a wider width than the expected result.  Extract the
8425       // relevant portion.
8426       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8427     }
8428     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8429     ResultVTs.push_back(ResultVT);
8430     ResultValues.push_back(V);
8431   };
8432 
8433   // Deal with output operands.
8434   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8435     if (OpInfo.Type == InlineAsm::isOutput) {
8436       SDValue Val;
8437       // Skip trivial output operands.
8438       if (OpInfo.AssignedRegs.Regs.empty())
8439         continue;
8440 
8441       switch (OpInfo.ConstraintType) {
8442       case TargetLowering::C_Register:
8443       case TargetLowering::C_RegisterClass:
8444         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8445             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8446         break;
8447       case TargetLowering::C_Immediate:
8448       case TargetLowering::C_Other:
8449         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8450                                               OpInfo, DAG);
8451         break;
8452       case TargetLowering::C_Memory:
8453         break; // Already handled.
8454       case TargetLowering::C_Unknown:
8455         assert(false && "Unexpected unknown constraint");
8456       }
8457 
8458       // Indirect output manifest as stores. Record output chains.
8459       if (OpInfo.isIndirect) {
8460         const Value *Ptr = OpInfo.CallOperandVal;
8461         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8462         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8463                                      MachinePointerInfo(Ptr));
8464         OutChains.push_back(Store);
8465       } else {
8466         // generate CopyFromRegs to associated registers.
8467         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8468         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8469           for (const SDValue &V : Val->op_values())
8470             handleRegAssign(V);
8471         } else
8472           handleRegAssign(Val);
8473       }
8474     }
8475   }
8476 
8477   // Set results.
8478   if (!ResultValues.empty()) {
8479     assert(CurResultType == ResultTypes.end() &&
8480            "Mismatch in number of ResultTypes");
8481     assert(ResultValues.size() == ResultTypes.size() &&
8482            "Mismatch in number of output operands in asm result");
8483 
8484     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8485                             DAG.getVTList(ResultVTs), ResultValues);
8486     setValue(CS.getInstruction(), V);
8487   }
8488 
8489   // Collect store chains.
8490   if (!OutChains.empty())
8491     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8492 
8493   // Only Update Root if inline assembly has a memory effect.
8494   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8495     DAG.setRoot(Chain);
8496 }
8497 
8498 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8499                                              const Twine &Message) {
8500   LLVMContext &Ctx = *DAG.getContext();
8501   Ctx.emitError(CS.getInstruction(), Message);
8502 
8503   // Make sure we leave the DAG in a valid state
8504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8505   SmallVector<EVT, 1> ValueVTs;
8506   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8507 
8508   if (ValueVTs.empty())
8509     return;
8510 
8511   SmallVector<SDValue, 1> Ops;
8512   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8513     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8514 
8515   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8516 }
8517 
8518 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8519   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8520                           MVT::Other, getRoot(),
8521                           getValue(I.getArgOperand(0)),
8522                           DAG.getSrcValue(I.getArgOperand(0))));
8523 }
8524 
8525 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8527   const DataLayout &DL = DAG.getDataLayout();
8528   SDValue V = DAG.getVAArg(
8529       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8530       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8531       DL.getABITypeAlignment(I.getType()));
8532   DAG.setRoot(V.getValue(1));
8533 
8534   if (I.getType()->isPointerTy())
8535     V = DAG.getPtrExtOrTrunc(
8536         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8537   setValue(&I, V);
8538 }
8539 
8540 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8541   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8542                           MVT::Other, getRoot(),
8543                           getValue(I.getArgOperand(0)),
8544                           DAG.getSrcValue(I.getArgOperand(0))));
8545 }
8546 
8547 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8548   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8549                           MVT::Other, getRoot(),
8550                           getValue(I.getArgOperand(0)),
8551                           getValue(I.getArgOperand(1)),
8552                           DAG.getSrcValue(I.getArgOperand(0)),
8553                           DAG.getSrcValue(I.getArgOperand(1))));
8554 }
8555 
8556 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8557                                                     const Instruction &I,
8558                                                     SDValue Op) {
8559   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8560   if (!Range)
8561     return Op;
8562 
8563   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8564   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8565     return Op;
8566 
8567   APInt Lo = CR.getUnsignedMin();
8568   if (!Lo.isMinValue())
8569     return Op;
8570 
8571   APInt Hi = CR.getUnsignedMax();
8572   unsigned Bits = std::max(Hi.getActiveBits(),
8573                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8574 
8575   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8576 
8577   SDLoc SL = getCurSDLoc();
8578 
8579   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8580                              DAG.getValueType(SmallVT));
8581   unsigned NumVals = Op.getNode()->getNumValues();
8582   if (NumVals == 1)
8583     return ZExt;
8584 
8585   SmallVector<SDValue, 4> Ops;
8586 
8587   Ops.push_back(ZExt);
8588   for (unsigned I = 1; I != NumVals; ++I)
8589     Ops.push_back(Op.getValue(I));
8590 
8591   return DAG.getMergeValues(Ops, SL);
8592 }
8593 
8594 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8595 /// the call being lowered.
8596 ///
8597 /// This is a helper for lowering intrinsics that follow a target calling
8598 /// convention or require stack pointer adjustment. Only a subset of the
8599 /// intrinsic's operands need to participate in the calling convention.
8600 void SelectionDAGBuilder::populateCallLoweringInfo(
8601     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8602     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8603     bool IsPatchPoint) {
8604   TargetLowering::ArgListTy Args;
8605   Args.reserve(NumArgs);
8606 
8607   // Populate the argument list.
8608   // Attributes for args start at offset 1, after the return attribute.
8609   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8610        ArgI != ArgE; ++ArgI) {
8611     const Value *V = Call->getOperand(ArgI);
8612 
8613     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8614 
8615     TargetLowering::ArgListEntry Entry;
8616     Entry.Node = getValue(V);
8617     Entry.Ty = V->getType();
8618     Entry.setAttributes(Call, ArgI);
8619     Args.push_back(Entry);
8620   }
8621 
8622   CLI.setDebugLoc(getCurSDLoc())
8623       .setChain(getRoot())
8624       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8625       .setDiscardResult(Call->use_empty())
8626       .setIsPatchPoint(IsPatchPoint);
8627 }
8628 
8629 /// Add a stack map intrinsic call's live variable operands to a stackmap
8630 /// or patchpoint target node's operand list.
8631 ///
8632 /// Constants are converted to TargetConstants purely as an optimization to
8633 /// avoid constant materialization and register allocation.
8634 ///
8635 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8636 /// generate addess computation nodes, and so FinalizeISel can convert the
8637 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8638 /// address materialization and register allocation, but may also be required
8639 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8640 /// alloca in the entry block, then the runtime may assume that the alloca's
8641 /// StackMap location can be read immediately after compilation and that the
8642 /// location is valid at any point during execution (this is similar to the
8643 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8644 /// only available in a register, then the runtime would need to trap when
8645 /// execution reaches the StackMap in order to read the alloca's location.
8646 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8647                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8648                                 SelectionDAGBuilder &Builder) {
8649   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8650     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8651     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8652       Ops.push_back(
8653         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8654       Ops.push_back(
8655         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8656     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8657       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8658       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8659           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8660     } else
8661       Ops.push_back(OpVal);
8662   }
8663 }
8664 
8665 /// Lower llvm.experimental.stackmap directly to its target opcode.
8666 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8667   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8668   //                                  [live variables...])
8669 
8670   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8671 
8672   SDValue Chain, InFlag, Callee, NullPtr;
8673   SmallVector<SDValue, 32> Ops;
8674 
8675   SDLoc DL = getCurSDLoc();
8676   Callee = getValue(CI.getCalledValue());
8677   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8678 
8679   // The stackmap intrinsic only records the live variables (the arguments
8680   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8681   // intrinsic, this won't be lowered to a function call. This means we don't
8682   // have to worry about calling conventions and target specific lowering code.
8683   // Instead we perform the call lowering right here.
8684   //
8685   // chain, flag = CALLSEQ_START(chain, 0, 0)
8686   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8687   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8688   //
8689   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8690   InFlag = Chain.getValue(1);
8691 
8692   // Add the <id> and <numBytes> constants.
8693   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8694   Ops.push_back(DAG.getTargetConstant(
8695                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8696   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8697   Ops.push_back(DAG.getTargetConstant(
8698                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8699                   MVT::i32));
8700 
8701   // Push live variables for the stack map.
8702   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8703 
8704   // We are not pushing any register mask info here on the operands list,
8705   // because the stackmap doesn't clobber anything.
8706 
8707   // Push the chain and the glue flag.
8708   Ops.push_back(Chain);
8709   Ops.push_back(InFlag);
8710 
8711   // Create the STACKMAP node.
8712   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8713   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8714   Chain = SDValue(SM, 0);
8715   InFlag = Chain.getValue(1);
8716 
8717   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8718 
8719   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8720 
8721   // Set the root to the target-lowered call chain.
8722   DAG.setRoot(Chain);
8723 
8724   // Inform the Frame Information that we have a stackmap in this function.
8725   FuncInfo.MF->getFrameInfo().setHasStackMap();
8726 }
8727 
8728 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8729 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8730                                           const BasicBlock *EHPadBB) {
8731   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8732   //                                                 i32 <numBytes>,
8733   //                                                 i8* <target>,
8734   //                                                 i32 <numArgs>,
8735   //                                                 [Args...],
8736   //                                                 [live variables...])
8737 
8738   CallingConv::ID CC = CS.getCallingConv();
8739   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8740   bool HasDef = !CS->getType()->isVoidTy();
8741   SDLoc dl = getCurSDLoc();
8742   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8743 
8744   // Handle immediate and symbolic callees.
8745   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8746     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8747                                    /*isTarget=*/true);
8748   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8749     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8750                                          SDLoc(SymbolicCallee),
8751                                          SymbolicCallee->getValueType(0));
8752 
8753   // Get the real number of arguments participating in the call <numArgs>
8754   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8755   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8756 
8757   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8758   // Intrinsics include all meta-operands up to but not including CC.
8759   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8760   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8761          "Not enough arguments provided to the patchpoint intrinsic");
8762 
8763   // For AnyRegCC the arguments are lowered later on manually.
8764   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8765   Type *ReturnTy =
8766     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8767 
8768   TargetLowering::CallLoweringInfo CLI(DAG);
8769   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8770                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8771   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8772 
8773   SDNode *CallEnd = Result.second.getNode();
8774   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8775     CallEnd = CallEnd->getOperand(0).getNode();
8776 
8777   /// Get a call instruction from the call sequence chain.
8778   /// Tail calls are not allowed.
8779   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8780          "Expected a callseq node.");
8781   SDNode *Call = CallEnd->getOperand(0).getNode();
8782   bool HasGlue = Call->getGluedNode();
8783 
8784   // Replace the target specific call node with the patchable intrinsic.
8785   SmallVector<SDValue, 8> Ops;
8786 
8787   // Add the <id> and <numBytes> constants.
8788   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8789   Ops.push_back(DAG.getTargetConstant(
8790                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8791   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8792   Ops.push_back(DAG.getTargetConstant(
8793                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8794                   MVT::i32));
8795 
8796   // Add the callee.
8797   Ops.push_back(Callee);
8798 
8799   // Adjust <numArgs> to account for any arguments that have been passed on the
8800   // stack instead.
8801   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8802   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8803   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8804   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8805 
8806   // Add the calling convention
8807   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8808 
8809   // Add the arguments we omitted previously. The register allocator should
8810   // place these in any free register.
8811   if (IsAnyRegCC)
8812     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8813       Ops.push_back(getValue(CS.getArgument(i)));
8814 
8815   // Push the arguments from the call instruction up to the register mask.
8816   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8817   Ops.append(Call->op_begin() + 2, e);
8818 
8819   // Push live variables for the stack map.
8820   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8821 
8822   // Push the register mask info.
8823   if (HasGlue)
8824     Ops.push_back(*(Call->op_end()-2));
8825   else
8826     Ops.push_back(*(Call->op_end()-1));
8827 
8828   // Push the chain (this is originally the first operand of the call, but
8829   // becomes now the last or second to last operand).
8830   Ops.push_back(*(Call->op_begin()));
8831 
8832   // Push the glue flag (last operand).
8833   if (HasGlue)
8834     Ops.push_back(*(Call->op_end()-1));
8835 
8836   SDVTList NodeTys;
8837   if (IsAnyRegCC && HasDef) {
8838     // Create the return types based on the intrinsic definition
8839     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8840     SmallVector<EVT, 3> ValueVTs;
8841     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8842     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8843 
8844     // There is always a chain and a glue type at the end
8845     ValueVTs.push_back(MVT::Other);
8846     ValueVTs.push_back(MVT::Glue);
8847     NodeTys = DAG.getVTList(ValueVTs);
8848   } else
8849     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8850 
8851   // Replace the target specific call node with a PATCHPOINT node.
8852   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8853                                          dl, NodeTys, Ops);
8854 
8855   // Update the NodeMap.
8856   if (HasDef) {
8857     if (IsAnyRegCC)
8858       setValue(CS.getInstruction(), SDValue(MN, 0));
8859     else
8860       setValue(CS.getInstruction(), Result.first);
8861   }
8862 
8863   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8864   // call sequence. Furthermore the location of the chain and glue can change
8865   // when the AnyReg calling convention is used and the intrinsic returns a
8866   // value.
8867   if (IsAnyRegCC && HasDef) {
8868     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8869     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8870     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8871   } else
8872     DAG.ReplaceAllUsesWith(Call, MN);
8873   DAG.DeleteNode(Call);
8874 
8875   // Inform the Frame Information that we have a patchpoint in this function.
8876   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8877 }
8878 
8879 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8880                                             unsigned Intrinsic) {
8881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8882   SDValue Op1 = getValue(I.getArgOperand(0));
8883   SDValue Op2;
8884   if (I.getNumArgOperands() > 1)
8885     Op2 = getValue(I.getArgOperand(1));
8886   SDLoc dl = getCurSDLoc();
8887   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8888   SDValue Res;
8889   FastMathFlags FMF;
8890   if (isa<FPMathOperator>(I))
8891     FMF = I.getFastMathFlags();
8892 
8893   switch (Intrinsic) {
8894   case Intrinsic::experimental_vector_reduce_v2_fadd:
8895     if (FMF.allowReassoc())
8896       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8897                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8898     else
8899       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8900     break;
8901   case Intrinsic::experimental_vector_reduce_v2_fmul:
8902     if (FMF.allowReassoc())
8903       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8904                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8905     else
8906       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8907     break;
8908   case Intrinsic::experimental_vector_reduce_add:
8909     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8910     break;
8911   case Intrinsic::experimental_vector_reduce_mul:
8912     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8913     break;
8914   case Intrinsic::experimental_vector_reduce_and:
8915     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8916     break;
8917   case Intrinsic::experimental_vector_reduce_or:
8918     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8919     break;
8920   case Intrinsic::experimental_vector_reduce_xor:
8921     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8922     break;
8923   case Intrinsic::experimental_vector_reduce_smax:
8924     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8925     break;
8926   case Intrinsic::experimental_vector_reduce_smin:
8927     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8928     break;
8929   case Intrinsic::experimental_vector_reduce_umax:
8930     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8931     break;
8932   case Intrinsic::experimental_vector_reduce_umin:
8933     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8934     break;
8935   case Intrinsic::experimental_vector_reduce_fmax:
8936     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8937     break;
8938   case Intrinsic::experimental_vector_reduce_fmin:
8939     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8940     break;
8941   default:
8942     llvm_unreachable("Unhandled vector reduce intrinsic");
8943   }
8944   setValue(&I, Res);
8945 }
8946 
8947 /// Returns an AttributeList representing the attributes applied to the return
8948 /// value of the given call.
8949 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8950   SmallVector<Attribute::AttrKind, 2> Attrs;
8951   if (CLI.RetSExt)
8952     Attrs.push_back(Attribute::SExt);
8953   if (CLI.RetZExt)
8954     Attrs.push_back(Attribute::ZExt);
8955   if (CLI.IsInReg)
8956     Attrs.push_back(Attribute::InReg);
8957 
8958   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8959                             Attrs);
8960 }
8961 
8962 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8963 /// implementation, which just calls LowerCall.
8964 /// FIXME: When all targets are
8965 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8966 std::pair<SDValue, SDValue>
8967 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8968   // Handle the incoming return values from the call.
8969   CLI.Ins.clear();
8970   Type *OrigRetTy = CLI.RetTy;
8971   SmallVector<EVT, 4> RetTys;
8972   SmallVector<uint64_t, 4> Offsets;
8973   auto &DL = CLI.DAG.getDataLayout();
8974   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8975 
8976   if (CLI.IsPostTypeLegalization) {
8977     // If we are lowering a libcall after legalization, split the return type.
8978     SmallVector<EVT, 4> OldRetTys;
8979     SmallVector<uint64_t, 4> OldOffsets;
8980     RetTys.swap(OldRetTys);
8981     Offsets.swap(OldOffsets);
8982 
8983     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8984       EVT RetVT = OldRetTys[i];
8985       uint64_t Offset = OldOffsets[i];
8986       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8987       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8988       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8989       RetTys.append(NumRegs, RegisterVT);
8990       for (unsigned j = 0; j != NumRegs; ++j)
8991         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8992     }
8993   }
8994 
8995   SmallVector<ISD::OutputArg, 4> Outs;
8996   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8997 
8998   bool CanLowerReturn =
8999       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9000                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9001 
9002   SDValue DemoteStackSlot;
9003   int DemoteStackIdx = -100;
9004   if (!CanLowerReturn) {
9005     // FIXME: equivalent assert?
9006     // assert(!CS.hasInAllocaArgument() &&
9007     //        "sret demotion is incompatible with inalloca");
9008     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9009     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9010     MachineFunction &MF = CLI.DAG.getMachineFunction();
9011     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9012     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9013                                               DL.getAllocaAddrSpace());
9014 
9015     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9016     ArgListEntry Entry;
9017     Entry.Node = DemoteStackSlot;
9018     Entry.Ty = StackSlotPtrType;
9019     Entry.IsSExt = false;
9020     Entry.IsZExt = false;
9021     Entry.IsInReg = false;
9022     Entry.IsSRet = true;
9023     Entry.IsNest = false;
9024     Entry.IsByVal = false;
9025     Entry.IsReturned = false;
9026     Entry.IsSwiftSelf = false;
9027     Entry.IsSwiftError = false;
9028     Entry.IsCFGuardTarget = false;
9029     Entry.Alignment = Align;
9030     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9031     CLI.NumFixedArgs += 1;
9032     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9033 
9034     // sret demotion isn't compatible with tail-calls, since the sret argument
9035     // points into the callers stack frame.
9036     CLI.IsTailCall = false;
9037   } else {
9038     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9039         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9040     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9041       ISD::ArgFlagsTy Flags;
9042       if (NeedsRegBlock) {
9043         Flags.setInConsecutiveRegs();
9044         if (I == RetTys.size() - 1)
9045           Flags.setInConsecutiveRegsLast();
9046       }
9047       EVT VT = RetTys[I];
9048       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9049                                                      CLI.CallConv, VT);
9050       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9051                                                        CLI.CallConv, VT);
9052       for (unsigned i = 0; i != NumRegs; ++i) {
9053         ISD::InputArg MyFlags;
9054         MyFlags.Flags = Flags;
9055         MyFlags.VT = RegisterVT;
9056         MyFlags.ArgVT = VT;
9057         MyFlags.Used = CLI.IsReturnValueUsed;
9058         if (CLI.RetTy->isPointerTy()) {
9059           MyFlags.Flags.setPointer();
9060           MyFlags.Flags.setPointerAddrSpace(
9061               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9062         }
9063         if (CLI.RetSExt)
9064           MyFlags.Flags.setSExt();
9065         if (CLI.RetZExt)
9066           MyFlags.Flags.setZExt();
9067         if (CLI.IsInReg)
9068           MyFlags.Flags.setInReg();
9069         CLI.Ins.push_back(MyFlags);
9070       }
9071     }
9072   }
9073 
9074   // We push in swifterror return as the last element of CLI.Ins.
9075   ArgListTy &Args = CLI.getArgs();
9076   if (supportSwiftError()) {
9077     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9078       if (Args[i].IsSwiftError) {
9079         ISD::InputArg MyFlags;
9080         MyFlags.VT = getPointerTy(DL);
9081         MyFlags.ArgVT = EVT(getPointerTy(DL));
9082         MyFlags.Flags.setSwiftError();
9083         CLI.Ins.push_back(MyFlags);
9084       }
9085     }
9086   }
9087 
9088   // Handle all of the outgoing arguments.
9089   CLI.Outs.clear();
9090   CLI.OutVals.clear();
9091   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9092     SmallVector<EVT, 4> ValueVTs;
9093     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9094     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9095     Type *FinalType = Args[i].Ty;
9096     if (Args[i].IsByVal)
9097       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9098     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9099         FinalType, CLI.CallConv, CLI.IsVarArg);
9100     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9101          ++Value) {
9102       EVT VT = ValueVTs[Value];
9103       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9104       SDValue Op = SDValue(Args[i].Node.getNode(),
9105                            Args[i].Node.getResNo() + Value);
9106       ISD::ArgFlagsTy Flags;
9107 
9108       // Certain targets (such as MIPS), may have a different ABI alignment
9109       // for a type depending on the context. Give the target a chance to
9110       // specify the alignment it wants.
9111       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9112 
9113       if (Args[i].Ty->isPointerTy()) {
9114         Flags.setPointer();
9115         Flags.setPointerAddrSpace(
9116             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9117       }
9118       if (Args[i].IsZExt)
9119         Flags.setZExt();
9120       if (Args[i].IsSExt)
9121         Flags.setSExt();
9122       if (Args[i].IsInReg) {
9123         // If we are using vectorcall calling convention, a structure that is
9124         // passed InReg - is surely an HVA
9125         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9126             isa<StructType>(FinalType)) {
9127           // The first value of a structure is marked
9128           if (0 == Value)
9129             Flags.setHvaStart();
9130           Flags.setHva();
9131         }
9132         // Set InReg Flag
9133         Flags.setInReg();
9134       }
9135       if (Args[i].IsSRet)
9136         Flags.setSRet();
9137       if (Args[i].IsSwiftSelf)
9138         Flags.setSwiftSelf();
9139       if (Args[i].IsSwiftError)
9140         Flags.setSwiftError();
9141       if (Args[i].IsCFGuardTarget)
9142         Flags.setCFGuardTarget();
9143       if (Args[i].IsByVal)
9144         Flags.setByVal();
9145       if (Args[i].IsInAlloca) {
9146         Flags.setInAlloca();
9147         // Set the byval flag for CCAssignFn callbacks that don't know about
9148         // inalloca.  This way we can know how many bytes we should've allocated
9149         // and how many bytes a callee cleanup function will pop.  If we port
9150         // inalloca to more targets, we'll have to add custom inalloca handling
9151         // in the various CC lowering callbacks.
9152         Flags.setByVal();
9153       }
9154       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9155         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9156         Type *ElementTy = Ty->getElementType();
9157 
9158         unsigned FrameSize = DL.getTypeAllocSize(
9159             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9160         Flags.setByValSize(FrameSize);
9161 
9162         // info is not there but there are cases it cannot get right.
9163         unsigned FrameAlign;
9164         if (Args[i].Alignment)
9165           FrameAlign = Args[i].Alignment;
9166         else
9167           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9168         Flags.setByValAlign(Align(FrameAlign));
9169       }
9170       if (Args[i].IsNest)
9171         Flags.setNest();
9172       if (NeedsRegBlock)
9173         Flags.setInConsecutiveRegs();
9174       Flags.setOrigAlign(OriginalAlignment);
9175 
9176       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9177                                                  CLI.CallConv, VT);
9178       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9179                                                         CLI.CallConv, VT);
9180       SmallVector<SDValue, 4> Parts(NumParts);
9181       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9182 
9183       if (Args[i].IsSExt)
9184         ExtendKind = ISD::SIGN_EXTEND;
9185       else if (Args[i].IsZExt)
9186         ExtendKind = ISD::ZERO_EXTEND;
9187 
9188       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9189       // for now.
9190       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9191           CanLowerReturn) {
9192         assert((CLI.RetTy == Args[i].Ty ||
9193                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9194                  CLI.RetTy->getPointerAddressSpace() ==
9195                      Args[i].Ty->getPointerAddressSpace())) &&
9196                RetTys.size() == NumValues && "unexpected use of 'returned'");
9197         // Before passing 'returned' to the target lowering code, ensure that
9198         // either the register MVT and the actual EVT are the same size or that
9199         // the return value and argument are extended in the same way; in these
9200         // cases it's safe to pass the argument register value unchanged as the
9201         // return register value (although it's at the target's option whether
9202         // to do so)
9203         // TODO: allow code generation to take advantage of partially preserved
9204         // registers rather than clobbering the entire register when the
9205         // parameter extension method is not compatible with the return
9206         // extension method
9207         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9208             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9209              CLI.RetZExt == Args[i].IsZExt))
9210           Flags.setReturned();
9211       }
9212 
9213       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9214                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9215 
9216       for (unsigned j = 0; j != NumParts; ++j) {
9217         // if it isn't first piece, alignment must be 1
9218         // For scalable vectors the scalable part is currently handled
9219         // by individual targets, so we just use the known minimum size here.
9220         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9221                     i < CLI.NumFixedArgs, i,
9222                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9223         if (NumParts > 1 && j == 0)
9224           MyFlags.Flags.setSplit();
9225         else if (j != 0) {
9226           MyFlags.Flags.setOrigAlign(Align::None());
9227           if (j == NumParts - 1)
9228             MyFlags.Flags.setSplitEnd();
9229         }
9230 
9231         CLI.Outs.push_back(MyFlags);
9232         CLI.OutVals.push_back(Parts[j]);
9233       }
9234 
9235       if (NeedsRegBlock && Value == NumValues - 1)
9236         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9237     }
9238   }
9239 
9240   SmallVector<SDValue, 4> InVals;
9241   CLI.Chain = LowerCall(CLI, InVals);
9242 
9243   // Update CLI.InVals to use outside of this function.
9244   CLI.InVals = InVals;
9245 
9246   // Verify that the target's LowerCall behaved as expected.
9247   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9248          "LowerCall didn't return a valid chain!");
9249   assert((!CLI.IsTailCall || InVals.empty()) &&
9250          "LowerCall emitted a return value for a tail call!");
9251   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9252          "LowerCall didn't emit the correct number of values!");
9253 
9254   // For a tail call, the return value is merely live-out and there aren't
9255   // any nodes in the DAG representing it. Return a special value to
9256   // indicate that a tail call has been emitted and no more Instructions
9257   // should be processed in the current block.
9258   if (CLI.IsTailCall) {
9259     CLI.DAG.setRoot(CLI.Chain);
9260     return std::make_pair(SDValue(), SDValue());
9261   }
9262 
9263 #ifndef NDEBUG
9264   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9265     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9266     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9267            "LowerCall emitted a value with the wrong type!");
9268   }
9269 #endif
9270 
9271   SmallVector<SDValue, 4> ReturnValues;
9272   if (!CanLowerReturn) {
9273     // The instruction result is the result of loading from the
9274     // hidden sret parameter.
9275     SmallVector<EVT, 1> PVTs;
9276     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9277 
9278     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9279     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9280     EVT PtrVT = PVTs[0];
9281 
9282     unsigned NumValues = RetTys.size();
9283     ReturnValues.resize(NumValues);
9284     SmallVector<SDValue, 4> Chains(NumValues);
9285 
9286     // An aggregate return value cannot wrap around the address space, so
9287     // offsets to its parts don't wrap either.
9288     SDNodeFlags Flags;
9289     Flags.setNoUnsignedWrap(true);
9290 
9291     for (unsigned i = 0; i < NumValues; ++i) {
9292       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9293                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9294                                                         PtrVT), Flags);
9295       SDValue L = CLI.DAG.getLoad(
9296           RetTys[i], CLI.DL, CLI.Chain, Add,
9297           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9298                                             DemoteStackIdx, Offsets[i]),
9299           /* Alignment = */ 1);
9300       ReturnValues[i] = L;
9301       Chains[i] = L.getValue(1);
9302     }
9303 
9304     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9305   } else {
9306     // Collect the legal value parts into potentially illegal values
9307     // that correspond to the original function's return values.
9308     Optional<ISD::NodeType> AssertOp;
9309     if (CLI.RetSExt)
9310       AssertOp = ISD::AssertSext;
9311     else if (CLI.RetZExt)
9312       AssertOp = ISD::AssertZext;
9313     unsigned CurReg = 0;
9314     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9315       EVT VT = RetTys[I];
9316       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9317                                                      CLI.CallConv, VT);
9318       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9319                                                        CLI.CallConv, VT);
9320 
9321       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9322                                               NumRegs, RegisterVT, VT, nullptr,
9323                                               CLI.CallConv, AssertOp));
9324       CurReg += NumRegs;
9325     }
9326 
9327     // For a function returning void, there is no return value. We can't create
9328     // such a node, so we just return a null return value in that case. In
9329     // that case, nothing will actually look at the value.
9330     if (ReturnValues.empty())
9331       return std::make_pair(SDValue(), CLI.Chain);
9332   }
9333 
9334   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9335                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9336   return std::make_pair(Res, CLI.Chain);
9337 }
9338 
9339 void TargetLowering::LowerOperationWrapper(SDNode *N,
9340                                            SmallVectorImpl<SDValue> &Results,
9341                                            SelectionDAG &DAG) const {
9342   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9343     Results.push_back(Res);
9344 }
9345 
9346 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9347   llvm_unreachable("LowerOperation not implemented for this target!");
9348 }
9349 
9350 void
9351 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9352   SDValue Op = getNonRegisterValue(V);
9353   assert((Op.getOpcode() != ISD::CopyFromReg ||
9354           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9355          "Copy from a reg to the same reg!");
9356   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9357 
9358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9359   // If this is an InlineAsm we have to match the registers required, not the
9360   // notional registers required by the type.
9361 
9362   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9363                    None); // This is not an ABI copy.
9364   SDValue Chain = DAG.getEntryNode();
9365 
9366   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9367                               FuncInfo.PreferredExtendType.end())
9368                                  ? ISD::ANY_EXTEND
9369                                  : FuncInfo.PreferredExtendType[V];
9370   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9371   PendingExports.push_back(Chain);
9372 }
9373 
9374 #include "llvm/CodeGen/SelectionDAGISel.h"
9375 
9376 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9377 /// entry block, return true.  This includes arguments used by switches, since
9378 /// the switch may expand into multiple basic blocks.
9379 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9380   // With FastISel active, we may be splitting blocks, so force creation
9381   // of virtual registers for all non-dead arguments.
9382   if (FastISel)
9383     return A->use_empty();
9384 
9385   const BasicBlock &Entry = A->getParent()->front();
9386   for (const User *U : A->users())
9387     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9388       return false;  // Use not in entry block.
9389 
9390   return true;
9391 }
9392 
9393 using ArgCopyElisionMapTy =
9394     DenseMap<const Argument *,
9395              std::pair<const AllocaInst *, const StoreInst *>>;
9396 
9397 /// Scan the entry block of the function in FuncInfo for arguments that look
9398 /// like copies into a local alloca. Record any copied arguments in
9399 /// ArgCopyElisionCandidates.
9400 static void
9401 findArgumentCopyElisionCandidates(const DataLayout &DL,
9402                                   FunctionLoweringInfo *FuncInfo,
9403                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9404   // Record the state of every static alloca used in the entry block. Argument
9405   // allocas are all used in the entry block, so we need approximately as many
9406   // entries as we have arguments.
9407   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9408   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9409   unsigned NumArgs = FuncInfo->Fn->arg_size();
9410   StaticAllocas.reserve(NumArgs * 2);
9411 
9412   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9413     if (!V)
9414       return nullptr;
9415     V = V->stripPointerCasts();
9416     const auto *AI = dyn_cast<AllocaInst>(V);
9417     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9418       return nullptr;
9419     auto Iter = StaticAllocas.insert({AI, Unknown});
9420     return &Iter.first->second;
9421   };
9422 
9423   // Look for stores of arguments to static allocas. Look through bitcasts and
9424   // GEPs to handle type coercions, as long as the alloca is fully initialized
9425   // by the store. Any non-store use of an alloca escapes it and any subsequent
9426   // unanalyzed store might write it.
9427   // FIXME: Handle structs initialized with multiple stores.
9428   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9429     // Look for stores, and handle non-store uses conservatively.
9430     const auto *SI = dyn_cast<StoreInst>(&I);
9431     if (!SI) {
9432       // We will look through cast uses, so ignore them completely.
9433       if (I.isCast())
9434         continue;
9435       // Ignore debug info intrinsics, they don't escape or store to allocas.
9436       if (isa<DbgInfoIntrinsic>(I))
9437         continue;
9438       // This is an unknown instruction. Assume it escapes or writes to all
9439       // static alloca operands.
9440       for (const Use &U : I.operands()) {
9441         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9442           *Info = StaticAllocaInfo::Clobbered;
9443       }
9444       continue;
9445     }
9446 
9447     // If the stored value is a static alloca, mark it as escaped.
9448     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9449       *Info = StaticAllocaInfo::Clobbered;
9450 
9451     // Check if the destination is a static alloca.
9452     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9453     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9454     if (!Info)
9455       continue;
9456     const AllocaInst *AI = cast<AllocaInst>(Dst);
9457 
9458     // Skip allocas that have been initialized or clobbered.
9459     if (*Info != StaticAllocaInfo::Unknown)
9460       continue;
9461 
9462     // Check if the stored value is an argument, and that this store fully
9463     // initializes the alloca. Don't elide copies from the same argument twice.
9464     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9465     const auto *Arg = dyn_cast<Argument>(Val);
9466     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9467         Arg->getType()->isEmptyTy() ||
9468         DL.getTypeStoreSize(Arg->getType()) !=
9469             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9470         ArgCopyElisionCandidates.count(Arg)) {
9471       *Info = StaticAllocaInfo::Clobbered;
9472       continue;
9473     }
9474 
9475     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9476                       << '\n');
9477 
9478     // Mark this alloca and store for argument copy elision.
9479     *Info = StaticAllocaInfo::Elidable;
9480     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9481 
9482     // Stop scanning if we've seen all arguments. This will happen early in -O0
9483     // builds, which is useful, because -O0 builds have large entry blocks and
9484     // many allocas.
9485     if (ArgCopyElisionCandidates.size() == NumArgs)
9486       break;
9487   }
9488 }
9489 
9490 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9491 /// ArgVal is a load from a suitable fixed stack object.
9492 static void tryToElideArgumentCopy(
9493     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9494     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9495     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9496     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9497     SDValue ArgVal, bool &ArgHasUses) {
9498   // Check if this is a load from a fixed stack object.
9499   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9500   if (!LNode)
9501     return;
9502   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9503   if (!FINode)
9504     return;
9505 
9506   // Check that the fixed stack object is the right size and alignment.
9507   // Look at the alignment that the user wrote on the alloca instead of looking
9508   // at the stack object.
9509   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9510   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9511   const AllocaInst *AI = ArgCopyIter->second.first;
9512   int FixedIndex = FINode->getIndex();
9513   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9514   int OldIndex = AllocaIndex;
9515   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9516   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9517     LLVM_DEBUG(
9518         dbgs() << "  argument copy elision failed due to bad fixed stack "
9519                   "object size\n");
9520     return;
9521   }
9522   unsigned RequiredAlignment = AI->getAlignment();
9523   if (!RequiredAlignment) {
9524     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9525         AI->getAllocatedType());
9526   }
9527   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9528     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9529                          "greater than stack argument alignment ("
9530                       << RequiredAlignment << " vs "
9531                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9532     return;
9533   }
9534 
9535   // Perform the elision. Delete the old stack object and replace its only use
9536   // in the variable info map. Mark the stack object as mutable.
9537   LLVM_DEBUG({
9538     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9539            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9540            << '\n';
9541   });
9542   MFI.RemoveStackObject(OldIndex);
9543   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9544   AllocaIndex = FixedIndex;
9545   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9546   Chains.push_back(ArgVal.getValue(1));
9547 
9548   // Avoid emitting code for the store implementing the copy.
9549   const StoreInst *SI = ArgCopyIter->second.second;
9550   ElidedArgCopyInstrs.insert(SI);
9551 
9552   // Check for uses of the argument again so that we can avoid exporting ArgVal
9553   // if it is't used by anything other than the store.
9554   for (const Value *U : Arg.users()) {
9555     if (U != SI) {
9556       ArgHasUses = true;
9557       break;
9558     }
9559   }
9560 }
9561 
9562 void SelectionDAGISel::LowerArguments(const Function &F) {
9563   SelectionDAG &DAG = SDB->DAG;
9564   SDLoc dl = SDB->getCurSDLoc();
9565   const DataLayout &DL = DAG.getDataLayout();
9566   SmallVector<ISD::InputArg, 16> Ins;
9567 
9568   if (!FuncInfo->CanLowerReturn) {
9569     // Put in an sret pointer parameter before all the other parameters.
9570     SmallVector<EVT, 1> ValueVTs;
9571     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9572                     F.getReturnType()->getPointerTo(
9573                         DAG.getDataLayout().getAllocaAddrSpace()),
9574                     ValueVTs);
9575 
9576     // NOTE: Assuming that a pointer will never break down to more than one VT
9577     // or one register.
9578     ISD::ArgFlagsTy Flags;
9579     Flags.setSRet();
9580     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9581     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9582                          ISD::InputArg::NoArgIndex, 0);
9583     Ins.push_back(RetArg);
9584   }
9585 
9586   // Look for stores of arguments to static allocas. Mark such arguments with a
9587   // flag to ask the target to give us the memory location of that argument if
9588   // available.
9589   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9590   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9591 
9592   // Set up the incoming argument description vector.
9593   for (const Argument &Arg : F.args()) {
9594     unsigned ArgNo = Arg.getArgNo();
9595     SmallVector<EVT, 4> ValueVTs;
9596     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9597     bool isArgValueUsed = !Arg.use_empty();
9598     unsigned PartBase = 0;
9599     Type *FinalType = Arg.getType();
9600     if (Arg.hasAttribute(Attribute::ByVal))
9601       FinalType = Arg.getParamByValType();
9602     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9603         FinalType, F.getCallingConv(), F.isVarArg());
9604     for (unsigned Value = 0, NumValues = ValueVTs.size();
9605          Value != NumValues; ++Value) {
9606       EVT VT = ValueVTs[Value];
9607       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9608       ISD::ArgFlagsTy Flags;
9609 
9610       // Certain targets (such as MIPS), may have a different ABI alignment
9611       // for a type depending on the context. Give the target a chance to
9612       // specify the alignment it wants.
9613       const Align OriginalAlignment(
9614           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9615 
9616       if (Arg.getType()->isPointerTy()) {
9617         Flags.setPointer();
9618         Flags.setPointerAddrSpace(
9619             cast<PointerType>(Arg.getType())->getAddressSpace());
9620       }
9621       if (Arg.hasAttribute(Attribute::ZExt))
9622         Flags.setZExt();
9623       if (Arg.hasAttribute(Attribute::SExt))
9624         Flags.setSExt();
9625       if (Arg.hasAttribute(Attribute::InReg)) {
9626         // If we are using vectorcall calling convention, a structure that is
9627         // passed InReg - is surely an HVA
9628         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9629             isa<StructType>(Arg.getType())) {
9630           // The first value of a structure is marked
9631           if (0 == Value)
9632             Flags.setHvaStart();
9633           Flags.setHva();
9634         }
9635         // Set InReg Flag
9636         Flags.setInReg();
9637       }
9638       if (Arg.hasAttribute(Attribute::StructRet))
9639         Flags.setSRet();
9640       if (Arg.hasAttribute(Attribute::SwiftSelf))
9641         Flags.setSwiftSelf();
9642       if (Arg.hasAttribute(Attribute::SwiftError))
9643         Flags.setSwiftError();
9644       if (Arg.hasAttribute(Attribute::ByVal))
9645         Flags.setByVal();
9646       if (Arg.hasAttribute(Attribute::InAlloca)) {
9647         Flags.setInAlloca();
9648         // Set the byval flag for CCAssignFn callbacks that don't know about
9649         // inalloca.  This way we can know how many bytes we should've allocated
9650         // and how many bytes a callee cleanup function will pop.  If we port
9651         // inalloca to more targets, we'll have to add custom inalloca handling
9652         // in the various CC lowering callbacks.
9653         Flags.setByVal();
9654       }
9655       if (F.getCallingConv() == CallingConv::X86_INTR) {
9656         // IA Interrupt passes frame (1st parameter) by value in the stack.
9657         if (ArgNo == 0)
9658           Flags.setByVal();
9659       }
9660       if (Flags.isByVal() || Flags.isInAlloca()) {
9661         Type *ElementTy = Arg.getParamByValType();
9662 
9663         // For ByVal, size and alignment should be passed from FE.  BE will
9664         // guess if this info is not there but there are cases it cannot get
9665         // right.
9666         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9667         Flags.setByValSize(FrameSize);
9668 
9669         unsigned FrameAlign;
9670         if (Arg.getParamAlignment())
9671           FrameAlign = Arg.getParamAlignment();
9672         else
9673           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9674         Flags.setByValAlign(Align(FrameAlign));
9675       }
9676       if (Arg.hasAttribute(Attribute::Nest))
9677         Flags.setNest();
9678       if (NeedsRegBlock)
9679         Flags.setInConsecutiveRegs();
9680       Flags.setOrigAlign(OriginalAlignment);
9681       if (ArgCopyElisionCandidates.count(&Arg))
9682         Flags.setCopyElisionCandidate();
9683       if (Arg.hasAttribute(Attribute::Returned))
9684         Flags.setReturned();
9685 
9686       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9687           *CurDAG->getContext(), F.getCallingConv(), VT);
9688       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9689           *CurDAG->getContext(), F.getCallingConv(), VT);
9690       for (unsigned i = 0; i != NumRegs; ++i) {
9691         // For scalable vectors, use the minimum size; individual targets
9692         // are responsible for handling scalable vector arguments and
9693         // return values.
9694         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9695                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9696         if (NumRegs > 1 && i == 0)
9697           MyFlags.Flags.setSplit();
9698         // if it isn't first piece, alignment must be 1
9699         else if (i > 0) {
9700           MyFlags.Flags.setOrigAlign(Align::None());
9701           if (i == NumRegs - 1)
9702             MyFlags.Flags.setSplitEnd();
9703         }
9704         Ins.push_back(MyFlags);
9705       }
9706       if (NeedsRegBlock && Value == NumValues - 1)
9707         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9708       PartBase += VT.getStoreSize().getKnownMinSize();
9709     }
9710   }
9711 
9712   // Call the target to set up the argument values.
9713   SmallVector<SDValue, 8> InVals;
9714   SDValue NewRoot = TLI->LowerFormalArguments(
9715       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9716 
9717   // Verify that the target's LowerFormalArguments behaved as expected.
9718   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9719          "LowerFormalArguments didn't return a valid chain!");
9720   assert(InVals.size() == Ins.size() &&
9721          "LowerFormalArguments didn't emit the correct number of values!");
9722   LLVM_DEBUG({
9723     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9724       assert(InVals[i].getNode() &&
9725              "LowerFormalArguments emitted a null value!");
9726       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9727              "LowerFormalArguments emitted a value with the wrong type!");
9728     }
9729   });
9730 
9731   // Update the DAG with the new chain value resulting from argument lowering.
9732   DAG.setRoot(NewRoot);
9733 
9734   // Set up the argument values.
9735   unsigned i = 0;
9736   if (!FuncInfo->CanLowerReturn) {
9737     // Create a virtual register for the sret pointer, and put in a copy
9738     // from the sret argument into it.
9739     SmallVector<EVT, 1> ValueVTs;
9740     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9741                     F.getReturnType()->getPointerTo(
9742                         DAG.getDataLayout().getAllocaAddrSpace()),
9743                     ValueVTs);
9744     MVT VT = ValueVTs[0].getSimpleVT();
9745     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9746     Optional<ISD::NodeType> AssertOp = None;
9747     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9748                                         nullptr, F.getCallingConv(), AssertOp);
9749 
9750     MachineFunction& MF = SDB->DAG.getMachineFunction();
9751     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9752     Register SRetReg =
9753         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9754     FuncInfo->DemoteRegister = SRetReg;
9755     NewRoot =
9756         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9757     DAG.setRoot(NewRoot);
9758 
9759     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9760     ++i;
9761   }
9762 
9763   SmallVector<SDValue, 4> Chains;
9764   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9765   for (const Argument &Arg : F.args()) {
9766     SmallVector<SDValue, 4> ArgValues;
9767     SmallVector<EVT, 4> ValueVTs;
9768     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9769     unsigned NumValues = ValueVTs.size();
9770     if (NumValues == 0)
9771       continue;
9772 
9773     bool ArgHasUses = !Arg.use_empty();
9774 
9775     // Elide the copying store if the target loaded this argument from a
9776     // suitable fixed stack object.
9777     if (Ins[i].Flags.isCopyElisionCandidate()) {
9778       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9779                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9780                              InVals[i], ArgHasUses);
9781     }
9782 
9783     // If this argument is unused then remember its value. It is used to generate
9784     // debugging information.
9785     bool isSwiftErrorArg =
9786         TLI->supportSwiftError() &&
9787         Arg.hasAttribute(Attribute::SwiftError);
9788     if (!ArgHasUses && !isSwiftErrorArg) {
9789       SDB->setUnusedArgValue(&Arg, InVals[i]);
9790 
9791       // Also remember any frame index for use in FastISel.
9792       if (FrameIndexSDNode *FI =
9793           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9794         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9795     }
9796 
9797     for (unsigned Val = 0; Val != NumValues; ++Val) {
9798       EVT VT = ValueVTs[Val];
9799       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9800                                                       F.getCallingConv(), VT);
9801       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9802           *CurDAG->getContext(), F.getCallingConv(), VT);
9803 
9804       // Even an apparent 'unused' swifterror argument needs to be returned. So
9805       // we do generate a copy for it that can be used on return from the
9806       // function.
9807       if (ArgHasUses || isSwiftErrorArg) {
9808         Optional<ISD::NodeType> AssertOp;
9809         if (Arg.hasAttribute(Attribute::SExt))
9810           AssertOp = ISD::AssertSext;
9811         else if (Arg.hasAttribute(Attribute::ZExt))
9812           AssertOp = ISD::AssertZext;
9813 
9814         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9815                                              PartVT, VT, nullptr,
9816                                              F.getCallingConv(), AssertOp));
9817       }
9818 
9819       i += NumParts;
9820     }
9821 
9822     // We don't need to do anything else for unused arguments.
9823     if (ArgValues.empty())
9824       continue;
9825 
9826     // Note down frame index.
9827     if (FrameIndexSDNode *FI =
9828         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9829       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9830 
9831     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9832                                      SDB->getCurSDLoc());
9833 
9834     SDB->setValue(&Arg, Res);
9835     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9836       // We want to associate the argument with the frame index, among
9837       // involved operands, that correspond to the lowest address. The
9838       // getCopyFromParts function, called earlier, is swapping the order of
9839       // the operands to BUILD_PAIR depending on endianness. The result of
9840       // that swapping is that the least significant bits of the argument will
9841       // be in the first operand of the BUILD_PAIR node, and the most
9842       // significant bits will be in the second operand.
9843       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9844       if (LoadSDNode *LNode =
9845           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9846         if (FrameIndexSDNode *FI =
9847             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9848           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9849     }
9850 
9851     // Analyses past this point are naive and don't expect an assertion.
9852     if (Res.getOpcode() == ISD::AssertZext)
9853       Res = Res.getOperand(0);
9854 
9855     // Update the SwiftErrorVRegDefMap.
9856     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9857       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9858       if (Register::isVirtualRegister(Reg))
9859         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9860                                    Reg);
9861     }
9862 
9863     // If this argument is live outside of the entry block, insert a copy from
9864     // wherever we got it to the vreg that other BB's will reference it as.
9865     if (Res.getOpcode() == ISD::CopyFromReg) {
9866       // If we can, though, try to skip creating an unnecessary vreg.
9867       // FIXME: This isn't very clean... it would be nice to make this more
9868       // general.
9869       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9870       if (Register::isVirtualRegister(Reg)) {
9871         FuncInfo->ValueMap[&Arg] = Reg;
9872         continue;
9873       }
9874     }
9875     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9876       FuncInfo->InitializeRegForValue(&Arg);
9877       SDB->CopyToExportRegsIfNeeded(&Arg);
9878     }
9879   }
9880 
9881   if (!Chains.empty()) {
9882     Chains.push_back(NewRoot);
9883     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9884   }
9885 
9886   DAG.setRoot(NewRoot);
9887 
9888   assert(i == InVals.size() && "Argument register count mismatch!");
9889 
9890   // If any argument copy elisions occurred and we have debug info, update the
9891   // stale frame indices used in the dbg.declare variable info table.
9892   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9893   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9894     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9895       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9896       if (I != ArgCopyElisionFrameIndexMap.end())
9897         VI.Slot = I->second;
9898     }
9899   }
9900 
9901   // Finally, if the target has anything special to do, allow it to do so.
9902   EmitFunctionEntryCode();
9903 }
9904 
9905 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9906 /// ensure constants are generated when needed.  Remember the virtual registers
9907 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9908 /// directly add them, because expansion might result in multiple MBB's for one
9909 /// BB.  As such, the start of the BB might correspond to a different MBB than
9910 /// the end.
9911 void
9912 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9913   const Instruction *TI = LLVMBB->getTerminator();
9914 
9915   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9916 
9917   // Check PHI nodes in successors that expect a value to be available from this
9918   // block.
9919   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9920     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9921     if (!isa<PHINode>(SuccBB->begin())) continue;
9922     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9923 
9924     // If this terminator has multiple identical successors (common for
9925     // switches), only handle each succ once.
9926     if (!SuccsHandled.insert(SuccMBB).second)
9927       continue;
9928 
9929     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9930 
9931     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9932     // nodes and Machine PHI nodes, but the incoming operands have not been
9933     // emitted yet.
9934     for (const PHINode &PN : SuccBB->phis()) {
9935       // Ignore dead phi's.
9936       if (PN.use_empty())
9937         continue;
9938 
9939       // Skip empty types
9940       if (PN.getType()->isEmptyTy())
9941         continue;
9942 
9943       unsigned Reg;
9944       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9945 
9946       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9947         unsigned &RegOut = ConstantsOut[C];
9948         if (RegOut == 0) {
9949           RegOut = FuncInfo.CreateRegs(C);
9950           CopyValueToVirtualRegister(C, RegOut);
9951         }
9952         Reg = RegOut;
9953       } else {
9954         DenseMap<const Value *, unsigned>::iterator I =
9955           FuncInfo.ValueMap.find(PHIOp);
9956         if (I != FuncInfo.ValueMap.end())
9957           Reg = I->second;
9958         else {
9959           assert(isa<AllocaInst>(PHIOp) &&
9960                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9961                  "Didn't codegen value into a register!??");
9962           Reg = FuncInfo.CreateRegs(PHIOp);
9963           CopyValueToVirtualRegister(PHIOp, Reg);
9964         }
9965       }
9966 
9967       // Remember that this register needs to added to the machine PHI node as
9968       // the input for this MBB.
9969       SmallVector<EVT, 4> ValueVTs;
9970       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9971       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9972       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9973         EVT VT = ValueVTs[vti];
9974         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9975         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9976           FuncInfo.PHINodesToUpdate.push_back(
9977               std::make_pair(&*MBBI++, Reg + i));
9978         Reg += NumRegisters;
9979       }
9980     }
9981   }
9982 
9983   ConstantsOut.clear();
9984 }
9985 
9986 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9987 /// is 0.
9988 MachineBasicBlock *
9989 SelectionDAGBuilder::StackProtectorDescriptor::
9990 AddSuccessorMBB(const BasicBlock *BB,
9991                 MachineBasicBlock *ParentMBB,
9992                 bool IsLikely,
9993                 MachineBasicBlock *SuccMBB) {
9994   // If SuccBB has not been created yet, create it.
9995   if (!SuccMBB) {
9996     MachineFunction *MF = ParentMBB->getParent();
9997     MachineFunction::iterator BBI(ParentMBB);
9998     SuccMBB = MF->CreateMachineBasicBlock(BB);
9999     MF->insert(++BBI, SuccMBB);
10000   }
10001   // Add it as a successor of ParentMBB.
10002   ParentMBB->addSuccessor(
10003       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10004   return SuccMBB;
10005 }
10006 
10007 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10008   MachineFunction::iterator I(MBB);
10009   if (++I == FuncInfo.MF->end())
10010     return nullptr;
10011   return &*I;
10012 }
10013 
10014 /// During lowering new call nodes can be created (such as memset, etc.).
10015 /// Those will become new roots of the current DAG, but complications arise
10016 /// when they are tail calls. In such cases, the call lowering will update
10017 /// the root, but the builder still needs to know that a tail call has been
10018 /// lowered in order to avoid generating an additional return.
10019 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10020   // If the node is null, we do have a tail call.
10021   if (MaybeTC.getNode() != nullptr)
10022     DAG.setRoot(MaybeTC);
10023   else
10024     HasTailCall = true;
10025 }
10026 
10027 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10028                                         MachineBasicBlock *SwitchMBB,
10029                                         MachineBasicBlock *DefaultMBB) {
10030   MachineFunction *CurMF = FuncInfo.MF;
10031   MachineBasicBlock *NextMBB = nullptr;
10032   MachineFunction::iterator BBI(W.MBB);
10033   if (++BBI != FuncInfo.MF->end())
10034     NextMBB = &*BBI;
10035 
10036   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10037 
10038   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10039 
10040   if (Size == 2 && W.MBB == SwitchMBB) {
10041     // If any two of the cases has the same destination, and if one value
10042     // is the same as the other, but has one bit unset that the other has set,
10043     // use bit manipulation to do two compares at once.  For example:
10044     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10045     // TODO: This could be extended to merge any 2 cases in switches with 3
10046     // cases.
10047     // TODO: Handle cases where W.CaseBB != SwitchBB.
10048     CaseCluster &Small = *W.FirstCluster;
10049     CaseCluster &Big = *W.LastCluster;
10050 
10051     if (Small.Low == Small.High && Big.Low == Big.High &&
10052         Small.MBB == Big.MBB) {
10053       const APInt &SmallValue = Small.Low->getValue();
10054       const APInt &BigValue = Big.Low->getValue();
10055 
10056       // Check that there is only one bit different.
10057       APInt CommonBit = BigValue ^ SmallValue;
10058       if (CommonBit.isPowerOf2()) {
10059         SDValue CondLHS = getValue(Cond);
10060         EVT VT = CondLHS.getValueType();
10061         SDLoc DL = getCurSDLoc();
10062 
10063         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10064                                  DAG.getConstant(CommonBit, DL, VT));
10065         SDValue Cond = DAG.getSetCC(
10066             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10067             ISD::SETEQ);
10068 
10069         // Update successor info.
10070         // Both Small and Big will jump to Small.BB, so we sum up the
10071         // probabilities.
10072         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10073         if (BPI)
10074           addSuccessorWithProb(
10075               SwitchMBB, DefaultMBB,
10076               // The default destination is the first successor in IR.
10077               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10078         else
10079           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10080 
10081         // Insert the true branch.
10082         SDValue BrCond =
10083             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10084                         DAG.getBasicBlock(Small.MBB));
10085         // Insert the false branch.
10086         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10087                              DAG.getBasicBlock(DefaultMBB));
10088 
10089         DAG.setRoot(BrCond);
10090         return;
10091       }
10092     }
10093   }
10094 
10095   if (TM.getOptLevel() != CodeGenOpt::None) {
10096     // Here, we order cases by probability so the most likely case will be
10097     // checked first. However, two clusters can have the same probability in
10098     // which case their relative ordering is non-deterministic. So we use Low
10099     // as a tie-breaker as clusters are guaranteed to never overlap.
10100     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10101                [](const CaseCluster &a, const CaseCluster &b) {
10102       return a.Prob != b.Prob ?
10103              a.Prob > b.Prob :
10104              a.Low->getValue().slt(b.Low->getValue());
10105     });
10106 
10107     // Rearrange the case blocks so that the last one falls through if possible
10108     // without changing the order of probabilities.
10109     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10110       --I;
10111       if (I->Prob > W.LastCluster->Prob)
10112         break;
10113       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10114         std::swap(*I, *W.LastCluster);
10115         break;
10116       }
10117     }
10118   }
10119 
10120   // Compute total probability.
10121   BranchProbability DefaultProb = W.DefaultProb;
10122   BranchProbability UnhandledProbs = DefaultProb;
10123   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10124     UnhandledProbs += I->Prob;
10125 
10126   MachineBasicBlock *CurMBB = W.MBB;
10127   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10128     bool FallthroughUnreachable = false;
10129     MachineBasicBlock *Fallthrough;
10130     if (I == W.LastCluster) {
10131       // For the last cluster, fall through to the default destination.
10132       Fallthrough = DefaultMBB;
10133       FallthroughUnreachable = isa<UnreachableInst>(
10134           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10135     } else {
10136       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10137       CurMF->insert(BBI, Fallthrough);
10138       // Put Cond in a virtual register to make it available from the new blocks.
10139       ExportFromCurrentBlock(Cond);
10140     }
10141     UnhandledProbs -= I->Prob;
10142 
10143     switch (I->Kind) {
10144       case CC_JumpTable: {
10145         // FIXME: Optimize away range check based on pivot comparisons.
10146         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10147         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10148 
10149         // The jump block hasn't been inserted yet; insert it here.
10150         MachineBasicBlock *JumpMBB = JT->MBB;
10151         CurMF->insert(BBI, JumpMBB);
10152 
10153         auto JumpProb = I->Prob;
10154         auto FallthroughProb = UnhandledProbs;
10155 
10156         // If the default statement is a target of the jump table, we evenly
10157         // distribute the default probability to successors of CurMBB. Also
10158         // update the probability on the edge from JumpMBB to Fallthrough.
10159         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10160                                               SE = JumpMBB->succ_end();
10161              SI != SE; ++SI) {
10162           if (*SI == DefaultMBB) {
10163             JumpProb += DefaultProb / 2;
10164             FallthroughProb -= DefaultProb / 2;
10165             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10166             JumpMBB->normalizeSuccProbs();
10167             break;
10168           }
10169         }
10170 
10171         if (FallthroughUnreachable) {
10172           // Skip the range check if the fallthrough block is unreachable.
10173           JTH->OmitRangeCheck = true;
10174         }
10175 
10176         if (!JTH->OmitRangeCheck)
10177           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10178         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10179         CurMBB->normalizeSuccProbs();
10180 
10181         // The jump table header will be inserted in our current block, do the
10182         // range check, and fall through to our fallthrough block.
10183         JTH->HeaderBB = CurMBB;
10184         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10185 
10186         // If we're in the right place, emit the jump table header right now.
10187         if (CurMBB == SwitchMBB) {
10188           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10189           JTH->Emitted = true;
10190         }
10191         break;
10192       }
10193       case CC_BitTests: {
10194         // FIXME: Optimize away range check based on pivot comparisons.
10195         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10196 
10197         // The bit test blocks haven't been inserted yet; insert them here.
10198         for (BitTestCase &BTC : BTB->Cases)
10199           CurMF->insert(BBI, BTC.ThisBB);
10200 
10201         // Fill in fields of the BitTestBlock.
10202         BTB->Parent = CurMBB;
10203         BTB->Default = Fallthrough;
10204 
10205         BTB->DefaultProb = UnhandledProbs;
10206         // If the cases in bit test don't form a contiguous range, we evenly
10207         // distribute the probability on the edge to Fallthrough to two
10208         // successors of CurMBB.
10209         if (!BTB->ContiguousRange) {
10210           BTB->Prob += DefaultProb / 2;
10211           BTB->DefaultProb -= DefaultProb / 2;
10212         }
10213 
10214         if (FallthroughUnreachable) {
10215           // Skip the range check if the fallthrough block is unreachable.
10216           BTB->OmitRangeCheck = true;
10217         }
10218 
10219         // If we're in the right place, emit the bit test header right now.
10220         if (CurMBB == SwitchMBB) {
10221           visitBitTestHeader(*BTB, SwitchMBB);
10222           BTB->Emitted = true;
10223         }
10224         break;
10225       }
10226       case CC_Range: {
10227         const Value *RHS, *LHS, *MHS;
10228         ISD::CondCode CC;
10229         if (I->Low == I->High) {
10230           // Check Cond == I->Low.
10231           CC = ISD::SETEQ;
10232           LHS = Cond;
10233           RHS=I->Low;
10234           MHS = nullptr;
10235         } else {
10236           // Check I->Low <= Cond <= I->High.
10237           CC = ISD::SETLE;
10238           LHS = I->Low;
10239           MHS = Cond;
10240           RHS = I->High;
10241         }
10242 
10243         // If Fallthrough is unreachable, fold away the comparison.
10244         if (FallthroughUnreachable)
10245           CC = ISD::SETTRUE;
10246 
10247         // The false probability is the sum of all unhandled cases.
10248         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10249                      getCurSDLoc(), I->Prob, UnhandledProbs);
10250 
10251         if (CurMBB == SwitchMBB)
10252           visitSwitchCase(CB, SwitchMBB);
10253         else
10254           SL->SwitchCases.push_back(CB);
10255 
10256         break;
10257       }
10258     }
10259     CurMBB = Fallthrough;
10260   }
10261 }
10262 
10263 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10264                                               CaseClusterIt First,
10265                                               CaseClusterIt Last) {
10266   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10267     if (X.Prob != CC.Prob)
10268       return X.Prob > CC.Prob;
10269 
10270     // Ties are broken by comparing the case value.
10271     return X.Low->getValue().slt(CC.Low->getValue());
10272   });
10273 }
10274 
10275 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10276                                         const SwitchWorkListItem &W,
10277                                         Value *Cond,
10278                                         MachineBasicBlock *SwitchMBB) {
10279   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10280          "Clusters not sorted?");
10281 
10282   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10283 
10284   // Balance the tree based on branch probabilities to create a near-optimal (in
10285   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10286   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10287   CaseClusterIt LastLeft = W.FirstCluster;
10288   CaseClusterIt FirstRight = W.LastCluster;
10289   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10290   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10291 
10292   // Move LastLeft and FirstRight towards each other from opposite directions to
10293   // find a partitioning of the clusters which balances the probability on both
10294   // sides. If LeftProb and RightProb are equal, alternate which side is
10295   // taken to ensure 0-probability nodes are distributed evenly.
10296   unsigned I = 0;
10297   while (LastLeft + 1 < FirstRight) {
10298     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10299       LeftProb += (++LastLeft)->Prob;
10300     else
10301       RightProb += (--FirstRight)->Prob;
10302     I++;
10303   }
10304 
10305   while (true) {
10306     // Our binary search tree differs from a typical BST in that ours can have up
10307     // to three values in each leaf. The pivot selection above doesn't take that
10308     // into account, which means the tree might require more nodes and be less
10309     // efficient. We compensate for this here.
10310 
10311     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10312     unsigned NumRight = W.LastCluster - FirstRight + 1;
10313 
10314     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10315       // If one side has less than 3 clusters, and the other has more than 3,
10316       // consider taking a cluster from the other side.
10317 
10318       if (NumLeft < NumRight) {
10319         // Consider moving the first cluster on the right to the left side.
10320         CaseCluster &CC = *FirstRight;
10321         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10322         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10323         if (LeftSideRank <= RightSideRank) {
10324           // Moving the cluster to the left does not demote it.
10325           ++LastLeft;
10326           ++FirstRight;
10327           continue;
10328         }
10329       } else {
10330         assert(NumRight < NumLeft);
10331         // Consider moving the last element on the left to the right side.
10332         CaseCluster &CC = *LastLeft;
10333         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10334         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10335         if (RightSideRank <= LeftSideRank) {
10336           // Moving the cluster to the right does not demot it.
10337           --LastLeft;
10338           --FirstRight;
10339           continue;
10340         }
10341       }
10342     }
10343     break;
10344   }
10345 
10346   assert(LastLeft + 1 == FirstRight);
10347   assert(LastLeft >= W.FirstCluster);
10348   assert(FirstRight <= W.LastCluster);
10349 
10350   // Use the first element on the right as pivot since we will make less-than
10351   // comparisons against it.
10352   CaseClusterIt PivotCluster = FirstRight;
10353   assert(PivotCluster > W.FirstCluster);
10354   assert(PivotCluster <= W.LastCluster);
10355 
10356   CaseClusterIt FirstLeft = W.FirstCluster;
10357   CaseClusterIt LastRight = W.LastCluster;
10358 
10359   const ConstantInt *Pivot = PivotCluster->Low;
10360 
10361   // New blocks will be inserted immediately after the current one.
10362   MachineFunction::iterator BBI(W.MBB);
10363   ++BBI;
10364 
10365   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10366   // we can branch to its destination directly if it's squeezed exactly in
10367   // between the known lower bound and Pivot - 1.
10368   MachineBasicBlock *LeftMBB;
10369   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10370       FirstLeft->Low == W.GE &&
10371       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10372     LeftMBB = FirstLeft->MBB;
10373   } else {
10374     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10375     FuncInfo.MF->insert(BBI, LeftMBB);
10376     WorkList.push_back(
10377         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10378     // Put Cond in a virtual register to make it available from the new blocks.
10379     ExportFromCurrentBlock(Cond);
10380   }
10381 
10382   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10383   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10384   // directly if RHS.High equals the current upper bound.
10385   MachineBasicBlock *RightMBB;
10386   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10387       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10388     RightMBB = FirstRight->MBB;
10389   } else {
10390     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10391     FuncInfo.MF->insert(BBI, RightMBB);
10392     WorkList.push_back(
10393         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10394     // Put Cond in a virtual register to make it available from the new blocks.
10395     ExportFromCurrentBlock(Cond);
10396   }
10397 
10398   // Create the CaseBlock record that will be used to lower the branch.
10399   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10400                getCurSDLoc(), LeftProb, RightProb);
10401 
10402   if (W.MBB == SwitchMBB)
10403     visitSwitchCase(CB, SwitchMBB);
10404   else
10405     SL->SwitchCases.push_back(CB);
10406 }
10407 
10408 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10409 // from the swith statement.
10410 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10411                                             BranchProbability PeeledCaseProb) {
10412   if (PeeledCaseProb == BranchProbability::getOne())
10413     return BranchProbability::getZero();
10414   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10415 
10416   uint32_t Numerator = CaseProb.getNumerator();
10417   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10418   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10419 }
10420 
10421 // Try to peel the top probability case if it exceeds the threshold.
10422 // Return current MachineBasicBlock for the switch statement if the peeling
10423 // does not occur.
10424 // If the peeling is performed, return the newly created MachineBasicBlock
10425 // for the peeled switch statement. Also update Clusters to remove the peeled
10426 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10427 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10428     const SwitchInst &SI, CaseClusterVector &Clusters,
10429     BranchProbability &PeeledCaseProb) {
10430   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10431   // Don't perform if there is only one cluster or optimizing for size.
10432   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10433       TM.getOptLevel() == CodeGenOpt::None ||
10434       SwitchMBB->getParent()->getFunction().hasMinSize())
10435     return SwitchMBB;
10436 
10437   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10438   unsigned PeeledCaseIndex = 0;
10439   bool SwitchPeeled = false;
10440   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10441     CaseCluster &CC = Clusters[Index];
10442     if (CC.Prob < TopCaseProb)
10443       continue;
10444     TopCaseProb = CC.Prob;
10445     PeeledCaseIndex = Index;
10446     SwitchPeeled = true;
10447   }
10448   if (!SwitchPeeled)
10449     return SwitchMBB;
10450 
10451   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10452                     << TopCaseProb << "\n");
10453 
10454   // Record the MBB for the peeled switch statement.
10455   MachineFunction::iterator BBI(SwitchMBB);
10456   ++BBI;
10457   MachineBasicBlock *PeeledSwitchMBB =
10458       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10459   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10460 
10461   ExportFromCurrentBlock(SI.getCondition());
10462   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10463   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10464                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10465   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10466 
10467   Clusters.erase(PeeledCaseIt);
10468   for (CaseCluster &CC : Clusters) {
10469     LLVM_DEBUG(
10470         dbgs() << "Scale the probablity for one cluster, before scaling: "
10471                << CC.Prob << "\n");
10472     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10473     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10474   }
10475   PeeledCaseProb = TopCaseProb;
10476   return PeeledSwitchMBB;
10477 }
10478 
10479 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10480   // Extract cases from the switch.
10481   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10482   CaseClusterVector Clusters;
10483   Clusters.reserve(SI.getNumCases());
10484   for (auto I : SI.cases()) {
10485     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10486     const ConstantInt *CaseVal = I.getCaseValue();
10487     BranchProbability Prob =
10488         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10489             : BranchProbability(1, SI.getNumCases() + 1);
10490     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10491   }
10492 
10493   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10494 
10495   // Cluster adjacent cases with the same destination. We do this at all
10496   // optimization levels because it's cheap to do and will make codegen faster
10497   // if there are many clusters.
10498   sortAndRangeify(Clusters);
10499 
10500   // The branch probablity of the peeled case.
10501   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10502   MachineBasicBlock *PeeledSwitchMBB =
10503       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10504 
10505   // If there is only the default destination, jump there directly.
10506   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10507   if (Clusters.empty()) {
10508     assert(PeeledSwitchMBB == SwitchMBB);
10509     SwitchMBB->addSuccessor(DefaultMBB);
10510     if (DefaultMBB != NextBlock(SwitchMBB)) {
10511       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10512                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10513     }
10514     return;
10515   }
10516 
10517   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10518   SL->findBitTestClusters(Clusters, &SI);
10519 
10520   LLVM_DEBUG({
10521     dbgs() << "Case clusters: ";
10522     for (const CaseCluster &C : Clusters) {
10523       if (C.Kind == CC_JumpTable)
10524         dbgs() << "JT:";
10525       if (C.Kind == CC_BitTests)
10526         dbgs() << "BT:";
10527 
10528       C.Low->getValue().print(dbgs(), true);
10529       if (C.Low != C.High) {
10530         dbgs() << '-';
10531         C.High->getValue().print(dbgs(), true);
10532       }
10533       dbgs() << ' ';
10534     }
10535     dbgs() << '\n';
10536   });
10537 
10538   assert(!Clusters.empty());
10539   SwitchWorkList WorkList;
10540   CaseClusterIt First = Clusters.begin();
10541   CaseClusterIt Last = Clusters.end() - 1;
10542   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10543   // Scale the branchprobability for DefaultMBB if the peel occurs and
10544   // DefaultMBB is not replaced.
10545   if (PeeledCaseProb != BranchProbability::getZero() &&
10546       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10547     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10548   WorkList.push_back(
10549       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10550 
10551   while (!WorkList.empty()) {
10552     SwitchWorkListItem W = WorkList.back();
10553     WorkList.pop_back();
10554     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10555 
10556     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10557         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10558       // For optimized builds, lower large range as a balanced binary tree.
10559       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10560       continue;
10561     }
10562 
10563     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10564   }
10565 }
10566 
10567 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10568   SDValue N = getValue(I.getOperand(0));
10569   setValue(&I, N);
10570 }
10571