xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 333f2ad8b840abee8b3dcb112329e380ff3b5afd)
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(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
442                          DAG.getVectorIdxConstant(0, DL));
443     }
444 
445     // Vector/Vector bitcast.
446     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
447       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
450       "Cannot handle this kind of promotion");
451     // Promoted vector extract
452     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 
454   }
455 
456   // Trivial bitcast if the types are the same size and the destination
457   // vector type is legal.
458   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
459       TLI.isTypeLegal(ValueVT))
460     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461 
462   if (ValueVT.getVectorNumElements() != 1) {
463      // Certain ABIs require that vectors are passed as integers. For vectors
464      // are the same size, this is an obvious bitcast.
465      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
466        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
467      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
468        // Bitcast Val back the original type and extract the corresponding
469        // vector we want.
470        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
471        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
472                                            ValueVT.getVectorElementType(), Elts);
473        Val = DAG.getBitcast(WiderVecType, Val);
474        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
475                           DAG.getVectorIdxConstant(0, DL));
476      }
477 
478      diagnosePossiblyInvalidConstraint(
479          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
480      return DAG.getUNDEF(ValueVT);
481   }
482 
483   // Handle cases such as i8 -> <1 x i1>
484   EVT ValueSVT = ValueVT.getVectorElementType();
485   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
486     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
487       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
488     else
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  Optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
506                            SDValue *Parts, unsigned NumParts, MVT PartVT,
507                            const Value *V,
508                            Optional<CallingConv::ID> CallConv = None,
509                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   EVT ValueVT = Val.getValueType();
511 
512   // Handle the vector case separately.
513   if (ValueVT.isVector())
514     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
515                                 CallConv);
516 
517   unsigned PartBits = PartVT.getSizeInBits();
518   unsigned OrigNumParts = NumParts;
519   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
520          "Copying to an illegal type!");
521 
522   if (NumParts == 0)
523     return;
524 
525   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
526   EVT PartEVT = PartVT;
527   if (PartEVT == ValueVT) {
528     assert(NumParts == 1 && "No-op copy with multiple parts!");
529     Parts[0] = Val;
530     return;
531   }
532 
533   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
534     // If the parts cover more bits than the value has, promote the value.
535     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
536       assert(NumParts == 1 && "Do not know what to promote to!");
537       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
538     } else {
539       if (ValueVT.isFloatingPoint()) {
540         // FP values need to be bitcast, then extended if they are being put
541         // into a larger container.
542         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
543         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
544       }
545       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
546              ValueVT.isInteger() &&
547              "Unknown mismatch!");
548       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
549       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
550       if (PartVT == MVT::x86mmx)
551         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552     }
553   } else if (PartBits == ValueVT.getSizeInBits()) {
554     // Different types of the same size.
555     assert(NumParts == 1 && PartEVT != ValueVT);
556     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558     // If the parts cover less bits than value has, truncate the value.
559     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
560            ValueVT.isInteger() &&
561            "Unknown mismatch!");
562     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
563     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
564     if (PartVT == MVT::x86mmx)
565       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
566   }
567 
568   // The value may have changed - recompute ValueVT.
569   ValueVT = Val.getValueType();
570   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
571          "Failed to tile the value with PartVT!");
572 
573   if (NumParts == 1) {
574     if (PartEVT != ValueVT) {
575       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
576                                         "scalar-to-vector conversion failed");
577       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
578     }
579 
580     Parts[0] = Val;
581     return;
582   }
583 
584   // Expand the value into multiple parts.
585   if (NumParts & (NumParts - 1)) {
586     // The number of parts is not a power of 2.  Split off and copy the tail.
587     assert(PartVT.isInteger() && ValueVT.isInteger() &&
588            "Do not know what to expand to!");
589     unsigned RoundParts = 1 << Log2_32(NumParts);
590     unsigned RoundBits = RoundParts * PartBits;
591     unsigned OddParts = NumParts - RoundParts;
592     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
593       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
594 
595     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
596                    CallConv);
597 
598     if (DAG.getDataLayout().isBigEndian())
599       // The odd parts were reversed by getCopyToParts - unreverse them.
600       std::reverse(Parts + RoundParts, Parts + NumParts);
601 
602     NumParts = RoundParts;
603     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
604     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
605   }
606 
607   // The number of parts is a power of 2.  Repeatedly bisect the value using
608   // EXTRACT_ELEMENT.
609   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
610                          EVT::getIntegerVT(*DAG.getContext(),
611                                            ValueVT.getSizeInBits()),
612                          Val);
613 
614   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
615     for (unsigned i = 0; i < NumParts; i += StepSize) {
616       unsigned ThisBits = StepSize * PartBits / 2;
617       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
618       SDValue &Part0 = Parts[i];
619       SDValue &Part1 = Parts[i+StepSize/2];
620 
621       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
622                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
623       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
625 
626       if (ThisBits == PartBits && ThisVT != PartVT) {
627         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
628         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
629       }
630     }
631   }
632 
633   if (DAG.getDataLayout().isBigEndian())
634     std::reverse(Parts, Parts + OrigNumParts);
635 }
636 
637 static SDValue widenVectorToPartType(SelectionDAG &DAG,
638                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
639   if (!PartVT.isVector())
640     return SDValue();
641 
642   EVT ValueVT = Val.getValueType();
643   unsigned PartNumElts = PartVT.getVectorNumElements();
644   unsigned ValueNumElts = ValueVT.getVectorNumElements();
645   if (PartNumElts > ValueNumElts &&
646       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
647     EVT ElementVT = PartVT.getVectorElementType();
648     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
649     // undef elements.
650     SmallVector<SDValue, 16> Ops;
651     DAG.ExtractVectorElements(Val, Ops);
652     SDValue EltUndef = DAG.getUNDEF(ElementVT);
653     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
654       Ops.push_back(EltUndef);
655 
656     // FIXME: Use CONCAT for 2x -> 4x.
657     return DAG.getBuildVector(PartVT, DL, Ops);
658   }
659 
660   return SDValue();
661 }
662 
663 /// getCopyToPartsVector - Create a series of nodes that contain the specified
664 /// value split into legal parts.
665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
666                                  SDValue Val, SDValue *Parts, unsigned NumParts,
667                                  MVT PartVT, const Value *V,
668                                  Optional<CallingConv::ID> CallConv) {
669   EVT ValueVT = Val.getValueType();
670   assert(ValueVT.isVector() && "Not a vector");
671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
672   const bool IsABIRegCopy = CallConv.hasValue();
673 
674   if (NumParts == 1) {
675     EVT PartEVT = PartVT;
676     if (PartEVT == ValueVT) {
677       // Nothing to do.
678     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
679       // Bitconvert vector->vector case.
680       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
681     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
682       Val = Widened;
683     } else if (PartVT.isVector() &&
684                PartEVT.getVectorElementType().bitsGE(
685                  ValueVT.getVectorElementType()) &&
686                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
687 
688       // Promoted vector extract
689       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
690     } else {
691       if (ValueVT.getVectorNumElements() == 1) {
692         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
693                           DAG.getVectorIdxConstant(0, DL));
694       } else {
695         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
696                "lossy conversion of vector to scalar type");
697         EVT IntermediateType =
698             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
699         Val = DAG.getBitcast(IntermediateType, Val);
700         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
701       }
702     }
703 
704     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
705     Parts[0] = Val;
706     return;
707   }
708 
709   // Handle a multi-element vector.
710   EVT IntermediateVT;
711   MVT RegisterVT;
712   unsigned NumIntermediates;
713   unsigned NumRegs;
714   if (IsABIRegCopy) {
715     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
716         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
717         NumIntermediates, RegisterVT);
718   } else {
719     NumRegs =
720         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
721                                    NumIntermediates, RegisterVT);
722   }
723 
724   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
725   NumParts = NumRegs; // Silence a compiler warning.
726   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
727 
728   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
729     IntermediateVT.getVectorNumElements() : 1;
730 
731   // Convert the vector to the appropriate type if necessary.
732   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
733 
734   EVT BuiltVectorTy = EVT::getVectorVT(
735       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
736   if (ValueVT != BuiltVectorTy) {
737     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
738       Val = Widened;
739 
740     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
741   }
742 
743   // Split the vector into intermediate operands.
744   SmallVector<SDValue, 8> Ops(NumIntermediates);
745   for (unsigned i = 0; i != NumIntermediates; ++i) {
746     if (IntermediateVT.isVector()) {
747       Ops[i] =
748           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
749                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
750     } else {
751       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
752                            DAG.getVectorIdxConstant(i, DL));
753     }
754   }
755 
756   // Split the intermediate operands into legal parts.
757   if (NumParts == NumIntermediates) {
758     // If the register was not expanded, promote or copy the value,
759     // as appropriate.
760     for (unsigned i = 0; i != NumParts; ++i)
761       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
762   } else if (NumParts > 0) {
763     // If the intermediate type was expanded, split each the value into
764     // legal parts.
765     assert(NumIntermediates != 0 && "division by zero");
766     assert(NumParts % NumIntermediates == 0 &&
767            "Must expand into a divisible number of parts!");
768     unsigned Factor = NumParts / NumIntermediates;
769     for (unsigned i = 0; i != NumIntermediates; ++i)
770       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
771                      CallConv);
772   }
773 }
774 
775 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
776                            EVT valuevt, Optional<CallingConv::ID> CC)
777     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
778       RegCount(1, regs.size()), CallConv(CC) {}
779 
780 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
781                            const DataLayout &DL, unsigned Reg, Type *Ty,
782                            Optional<CallingConv::ID> CC) {
783   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
784 
785   CallConv = CC;
786 
787   for (EVT ValueVT : ValueVTs) {
788     unsigned NumRegs =
789         isABIMangled()
790             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
791             : TLI.getNumRegisters(Context, ValueVT);
792     MVT RegisterVT =
793         isABIMangled()
794             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
795             : TLI.getRegisterType(Context, ValueVT);
796     for (unsigned i = 0; i != NumRegs; ++i)
797       Regs.push_back(Reg + i);
798     RegVTs.push_back(RegisterVT);
799     RegCount.push_back(NumRegs);
800     Reg += NumRegs;
801   }
802 }
803 
804 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
805                                       FunctionLoweringInfo &FuncInfo,
806                                       const SDLoc &dl, SDValue &Chain,
807                                       SDValue *Flag, const Value *V) const {
808   // A Value with type {} or [0 x %t] needs no registers.
809   if (ValueVTs.empty())
810     return SDValue();
811 
812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
813 
814   // Assemble the legal parts into the final values.
815   SmallVector<SDValue, 4> Values(ValueVTs.size());
816   SmallVector<SDValue, 8> Parts;
817   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
818     // Copy the legal parts from the registers.
819     EVT ValueVT = ValueVTs[Value];
820     unsigned NumRegs = RegCount[Value];
821     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
822                                           *DAG.getContext(),
823                                           CallConv.getValue(), RegVTs[Value])
824                                     : RegVTs[Value];
825 
826     Parts.resize(NumRegs);
827     for (unsigned i = 0; i != NumRegs; ++i) {
828       SDValue P;
829       if (!Flag) {
830         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
831       } else {
832         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
833         *Flag = P.getValue(2);
834       }
835 
836       Chain = P.getValue(1);
837       Parts[i] = P;
838 
839       // If the source register was virtual and if we know something about it,
840       // add an assert node.
841       if (!Register::isVirtualRegister(Regs[Part + i]) ||
842           !RegisterVT.isInteger())
843         continue;
844 
845       const FunctionLoweringInfo::LiveOutInfo *LOI =
846         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
847       if (!LOI)
848         continue;
849 
850       unsigned RegSize = RegisterVT.getScalarSizeInBits();
851       unsigned NumSignBits = LOI->NumSignBits;
852       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
853 
854       if (NumZeroBits == RegSize) {
855         // The current value is a zero.
856         // Explicitly express that as it would be easier for
857         // optimizations to kick in.
858         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
859         continue;
860       }
861 
862       // FIXME: We capture more information than the dag can represent.  For
863       // now, just use the tightest assertzext/assertsext possible.
864       bool isSExt;
865       EVT FromVT(MVT::Other);
866       if (NumZeroBits) {
867         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
868         isSExt = false;
869       } else if (NumSignBits > 1) {
870         FromVT =
871             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
872         isSExt = true;
873       } else {
874         continue;
875       }
876       // Add an assertion node.
877       assert(FromVT != MVT::Other);
878       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
879                              RegisterVT, P, DAG.getValueType(FromVT));
880     }
881 
882     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
883                                      RegisterVT, ValueVT, V, CallConv);
884     Part += NumRegs;
885     Parts.clear();
886   }
887 
888   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
889 }
890 
891 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
892                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
893                                  const Value *V,
894                                  ISD::NodeType PreferredExtendType) const {
895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
896   ISD::NodeType ExtendKind = PreferredExtendType;
897 
898   // Get the list of the values's legal parts.
899   unsigned NumRegs = Regs.size();
900   SmallVector<SDValue, 8> Parts(NumRegs);
901   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
902     unsigned NumParts = RegCount[Value];
903 
904     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
905                                           *DAG.getContext(),
906                                           CallConv.getValue(), RegVTs[Value])
907                                     : RegVTs[Value];
908 
909     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
910       ExtendKind = ISD::ZERO_EXTEND;
911 
912     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
913                    NumParts, RegisterVT, V, CallConv, ExtendKind);
914     Part += NumParts;
915   }
916 
917   // Copy the parts into the registers.
918   SmallVector<SDValue, 8> Chains(NumRegs);
919   for (unsigned i = 0; i != NumRegs; ++i) {
920     SDValue Part;
921     if (!Flag) {
922       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
923     } else {
924       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
925       *Flag = Part.getValue(1);
926     }
927 
928     Chains[i] = Part.getValue(0);
929   }
930 
931   if (NumRegs == 1 || Flag)
932     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
933     // flagged to it. That is the CopyToReg nodes and the user are considered
934     // a single scheduling unit. If we create a TokenFactor and return it as
935     // chain, then the TokenFactor is both a predecessor (operand) of the
936     // user as well as a successor (the TF operands are flagged to the user).
937     // c1, f1 = CopyToReg
938     // c2, f2 = CopyToReg
939     // c3     = TokenFactor c1, c2
940     // ...
941     //        = op c3, ..., f2
942     Chain = Chains[NumRegs-1];
943   else
944     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
945 }
946 
947 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
948                                         unsigned MatchingIdx, const SDLoc &dl,
949                                         SelectionDAG &DAG,
950                                         std::vector<SDValue> &Ops) const {
951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
952 
953   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
954   if (HasMatching)
955     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
956   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
957     // Put the register class of the virtual registers in the flag word.  That
958     // way, later passes can recompute register class constraints for inline
959     // assembly as well as normal instructions.
960     // Don't do this for tied operands that can use the regclass information
961     // from the def.
962     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
963     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
964     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
965   }
966 
967   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
968   Ops.push_back(Res);
969 
970   if (Code == InlineAsm::Kind_Clobber) {
971     // Clobbers should always have a 1:1 mapping with registers, and may
972     // reference registers that have illegal (e.g. vector) types. Hence, we
973     // shouldn't try to apply any sort of splitting logic to them.
974     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
975            "No 1:1 mapping from clobbers to regs?");
976     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
977     (void)SP;
978     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
979       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
980       assert(
981           (Regs[I] != SP ||
982            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
983           "If we clobbered the stack pointer, MFI should know about it.");
984     }
985     return;
986   }
987 
988   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
989     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
990     MVT RegisterVT = RegVTs[Value];
991     for (unsigned i = 0; i != NumRegs; ++i) {
992       assert(Reg < Regs.size() && "Mismatch in # registers expected");
993       unsigned TheReg = Regs[Reg++];
994       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
995     }
996   }
997 }
998 
999 SmallVector<std::pair<unsigned, unsigned>, 4>
1000 RegsForValue::getRegsAndSizes() const {
1001   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1002   unsigned I = 0;
1003   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1004     unsigned RegCount = std::get<0>(CountAndVT);
1005     MVT RegisterVT = std::get<1>(CountAndVT);
1006     unsigned RegisterSize = RegisterVT.getSizeInBits();
1007     for (unsigned E = I + RegCount; I != E; ++I)
1008       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1009   }
1010   return OutVec;
1011 }
1012 
1013 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1014                                const TargetLibraryInfo *li) {
1015   AA = aa;
1016   GFI = gfi;
1017   LibInfo = li;
1018   DL = &DAG.getDataLayout();
1019   Context = DAG.getContext();
1020   LPadToCallSiteMap.clear();
1021   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1022 }
1023 
1024 void SelectionDAGBuilder::clear() {
1025   NodeMap.clear();
1026   UnusedArgNodeMap.clear();
1027   PendingLoads.clear();
1028   PendingExports.clear();
1029   PendingConstrainedFP.clear();
1030   PendingConstrainedFPStrict.clear();
1031   CurInst = nullptr;
1032   HasTailCall = false;
1033   SDNodeOrder = LowestSDNodeOrder;
1034   StatepointLowering.clear();
1035 }
1036 
1037 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1038   DanglingDebugInfoMap.clear();
1039 }
1040 
1041 // Update DAG root to include dependencies on Pending chains.
1042 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (Pending.empty())
1046     return Root;
1047 
1048   // Add current root to PendingChains, unless we already indirectly
1049   // depend on it.
1050   if (Root.getOpcode() != ISD::EntryToken) {
1051     unsigned i = 0, e = Pending.size();
1052     for (; i != e; ++i) {
1053       assert(Pending[i].getNode()->getNumOperands() > 1);
1054       if (Pending[i].getNode()->getOperand(0) == Root)
1055         break;  // Don't add the root if we already indirectly depend on it.
1056     }
1057 
1058     if (i == e)
1059       Pending.push_back(Root);
1060   }
1061 
1062   if (Pending.size() == 1)
1063     Root = Pending[0];
1064   else
1065     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1066 
1067   DAG.setRoot(Root);
1068   Pending.clear();
1069   return Root;
1070 }
1071 
1072 SDValue SelectionDAGBuilder::getMemoryRoot() {
1073   return updateRoot(PendingLoads);
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getRoot() {
1077   // Chain up all pending constrained intrinsics together with all
1078   // pending loads, by simply appending them to PendingLoads and
1079   // then calling getMemoryRoot().
1080   PendingLoads.reserve(PendingLoads.size() +
1081                        PendingConstrainedFP.size() +
1082                        PendingConstrainedFPStrict.size());
1083   PendingLoads.append(PendingConstrainedFP.begin(),
1084                       PendingConstrainedFP.end());
1085   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1086                       PendingConstrainedFPStrict.end());
1087   PendingConstrainedFP.clear();
1088   PendingConstrainedFPStrict.clear();
1089   return getMemoryRoot();
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getControlRoot() {
1093   // We need to emit pending fpexcept.strict constrained intrinsics,
1094   // so append them to the PendingExports list.
1095   PendingExports.append(PendingConstrainedFPStrict.begin(),
1096                         PendingConstrainedFPStrict.end());
1097   PendingConstrainedFPStrict.clear();
1098   return updateRoot(PendingExports);
1099 }
1100 
1101 void SelectionDAGBuilder::visit(const Instruction &I) {
1102   // Set up outgoing PHI node register values before emitting the terminator.
1103   if (I.isTerminator()) {
1104     HandlePHINodesInSuccessorBlocks(I.getParent());
1105   }
1106 
1107   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1108   if (!isa<DbgInfoIntrinsic>(I))
1109     ++SDNodeOrder;
1110 
1111   CurInst = &I;
1112 
1113   visit(I.getOpcode(), I);
1114 
1115   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1116     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1117     // maps to this instruction.
1118     // TODO: We could handle all flags (nsw, etc) here.
1119     // TODO: If an IR instruction maps to >1 node, only the final node will have
1120     //       flags set.
1121     if (SDNode *Node = getNodeForIRValue(&I)) {
1122       SDNodeFlags IncomingFlags;
1123       IncomingFlags.copyFMF(*FPMO);
1124       if (!Node->getFlags().isDefined())
1125         Node->setFlags(IncomingFlags);
1126       else
1127         Node->intersectFlagsWith(IncomingFlags);
1128     }
1129   }
1130   // Constrained FP intrinsics with fpexcept.ignore should also get
1131   // the NoFPExcept flag.
1132   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1133     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1134       if (SDNode *Node = getNodeForIRValue(&I)) {
1135         SDNodeFlags Flags = Node->getFlags();
1136         Flags.setNoFPExcept(true);
1137         Node->setFlags(Flags);
1138       }
1139 
1140   if (!I.isTerminator() && !HasTailCall &&
1141       !isStatepoint(&I)) // statepoints handle their exports internally
1142     CopyToExportRegsIfNeeded(&I);
1143 
1144   CurInst = nullptr;
1145 }
1146 
1147 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1148   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1149 }
1150 
1151 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1152   // Note: this doesn't use InstVisitor, because it has to work with
1153   // ConstantExpr's in addition to instructions.
1154   switch (Opcode) {
1155   default: llvm_unreachable("Unknown instruction type encountered!");
1156     // Build the switch statement using the Instruction.def file.
1157 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1158     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1159 #include "llvm/IR/Instruction.def"
1160   }
1161 }
1162 
1163 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1164                                                 const DIExpression *Expr) {
1165   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1166     const DbgValueInst *DI = DDI.getDI();
1167     DIVariable *DanglingVariable = DI->getVariable();
1168     DIExpression *DanglingExpr = DI->getExpression();
1169     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1170       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1171       return true;
1172     }
1173     return false;
1174   };
1175 
1176   for (auto &DDIMI : DanglingDebugInfoMap) {
1177     DanglingDebugInfoVector &DDIV = DDIMI.second;
1178 
1179     // If debug info is to be dropped, run it through final checks to see
1180     // whether it can be salvaged.
1181     for (auto &DDI : DDIV)
1182       if (isMatchingDbgValue(DDI))
1183         salvageUnresolvedDbgValue(DDI);
1184 
1185     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1186   }
1187 }
1188 
1189 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1190 // generate the debug data structures now that we've seen its definition.
1191 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1192                                                    SDValue Val) {
1193   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1194   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1195     return;
1196 
1197   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1198   for (auto &DDI : DDIV) {
1199     const DbgValueInst *DI = DDI.getDI();
1200     assert(DI && "Ill-formed DanglingDebugInfo");
1201     DebugLoc dl = DDI.getdl();
1202     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1203     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1204     DILocalVariable *Variable = DI->getVariable();
1205     DIExpression *Expr = DI->getExpression();
1206     assert(Variable->isValidLocationForIntrinsic(dl) &&
1207            "Expected inlined-at fields to agree");
1208     SDDbgValue *SDV;
1209     if (Val.getNode()) {
1210       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1211       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1212       // we couldn't resolve it directly when examining the DbgValue intrinsic
1213       // in the first place we should not be more successful here). Unless we
1214       // have some test case that prove this to be correct we should avoid
1215       // calling EmitFuncArgumentDbgValue here.
1216       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1217         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1218                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1219         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1220         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1221         // inserted after the definition of Val when emitting the instructions
1222         // after ISel. An alternative could be to teach
1223         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1224         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1225                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1226                    << ValSDNodeOrder << "\n");
1227         SDV = getDbgValue(Val, Variable, Expr, dl,
1228                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1229         DAG.AddDbgValue(SDV, Val.getNode(), false);
1230       } else
1231         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1232                           << "in EmitFuncArgumentDbgValue\n");
1233     } else {
1234       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1235       auto Undef =
1236           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1237       auto SDV =
1238           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1239       DAG.AddDbgValue(SDV, nullptr, false);
1240     }
1241   }
1242   DDIV.clear();
1243 }
1244 
1245 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1246   Value *V = DDI.getDI()->getValue();
1247   DILocalVariable *Var = DDI.getDI()->getVariable();
1248   DIExpression *Expr = DDI.getDI()->getExpression();
1249   DebugLoc DL = DDI.getdl();
1250   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1251   unsigned SDOrder = DDI.getSDNodeOrder();
1252 
1253   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1254   // that DW_OP_stack_value is desired.
1255   assert(isa<DbgValueInst>(DDI.getDI()));
1256   bool StackValue = true;
1257 
1258   // Can this Value can be encoded without any further work?
1259   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1260     return;
1261 
1262   // Attempt to salvage back through as many instructions as possible. Bail if
1263   // a non-instruction is seen, such as a constant expression or global
1264   // variable. FIXME: Further work could recover those too.
1265   while (isa<Instruction>(V)) {
1266     Instruction &VAsInst = *cast<Instruction>(V);
1267     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1268 
1269     // If we cannot salvage any further, and haven't yet found a suitable debug
1270     // expression, bail out.
1271     if (!NewExpr)
1272       break;
1273 
1274     // New value and expr now represent this debuginfo.
1275     V = VAsInst.getOperand(0);
1276     Expr = NewExpr;
1277 
1278     // Some kind of simplification occurred: check whether the operand of the
1279     // salvaged debug expression can be encoded in this DAG.
1280     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1281       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1282                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1283       return;
1284     }
1285   }
1286 
1287   // This was the final opportunity to salvage this debug information, and it
1288   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1289   // any earlier variable location.
1290   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1291   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1292   DAG.AddDbgValue(SDV, nullptr, false);
1293 
1294   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1295                     << "\n");
1296   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1297                     << "\n");
1298 }
1299 
1300 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1301                                            DIExpression *Expr, DebugLoc dl,
1302                                            DebugLoc InstDL, unsigned Order) {
1303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1304   SDDbgValue *SDV;
1305   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1306       isa<ConstantPointerNull>(V)) {
1307     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1308     DAG.AddDbgValue(SDV, nullptr, false);
1309     return true;
1310   }
1311 
1312   // If the Value is a frame index, we can create a FrameIndex debug value
1313   // without relying on the DAG at all.
1314   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1315     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1316     if (SI != FuncInfo.StaticAllocaMap.end()) {
1317       auto SDV =
1318           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1319                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1320       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1321       // is still available even if the SDNode gets optimized out.
1322       DAG.AddDbgValue(SDV, nullptr, false);
1323       return true;
1324     }
1325   }
1326 
1327   // Do not use getValue() in here; we don't want to generate code at
1328   // this point if it hasn't been done yet.
1329   SDValue N = NodeMap[V];
1330   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1331     N = UnusedArgNodeMap[V];
1332   if (N.getNode()) {
1333     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1334       return true;
1335     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1336     DAG.AddDbgValue(SDV, N.getNode(), false);
1337     return true;
1338   }
1339 
1340   // Special rules apply for the first dbg.values of parameter variables in a
1341   // function. Identify them by the fact they reference Argument Values, that
1342   // they're parameters, and they are parameters of the current function. We
1343   // need to let them dangle until they get an SDNode.
1344   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1345                        !InstDL.getInlinedAt();
1346   if (!IsParamOfFunc) {
1347     // The value is not used in this block yet (or it would have an SDNode).
1348     // We still want the value to appear for the user if possible -- if it has
1349     // an associated VReg, we can refer to that instead.
1350     auto VMI = FuncInfo.ValueMap.find(V);
1351     if (VMI != FuncInfo.ValueMap.end()) {
1352       unsigned Reg = VMI->second;
1353       // If this is a PHI node, it may be split up into several MI PHI nodes
1354       // (in FunctionLoweringInfo::set).
1355       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1356                        V->getType(), None);
1357       if (RFV.occupiesMultipleRegs()) {
1358         unsigned Offset = 0;
1359         unsigned BitsToDescribe = 0;
1360         if (auto VarSize = Var->getSizeInBits())
1361           BitsToDescribe = *VarSize;
1362         if (auto Fragment = Expr->getFragmentInfo())
1363           BitsToDescribe = Fragment->SizeInBits;
1364         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1365           unsigned RegisterSize = RegAndSize.second;
1366           // Bail out if all bits are described already.
1367           if (Offset >= BitsToDescribe)
1368             break;
1369           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1370               ? BitsToDescribe - Offset
1371               : RegisterSize;
1372           auto FragmentExpr = DIExpression::createFragmentExpression(
1373               Expr, Offset, FragmentSize);
1374           if (!FragmentExpr)
1375               continue;
1376           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1377                                     false, dl, SDNodeOrder);
1378           DAG.AddDbgValue(SDV, nullptr, false);
1379           Offset += RegisterSize;
1380         }
1381       } else {
1382         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1383         DAG.AddDbgValue(SDV, nullptr, false);
1384       }
1385       return true;
1386     }
1387   }
1388 
1389   return false;
1390 }
1391 
1392 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1393   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1394   for (auto &Pair : DanglingDebugInfoMap)
1395     for (auto &DDI : Pair.second)
1396       salvageUnresolvedDbgValue(DDI);
1397   clearDanglingDebugInfo();
1398 }
1399 
1400 /// getCopyFromRegs - If there was virtual register allocated for the value V
1401 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1402 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1403   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1404   SDValue Result;
1405 
1406   if (It != FuncInfo.ValueMap.end()) {
1407     unsigned InReg = It->second;
1408 
1409     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1410                      DAG.getDataLayout(), InReg, Ty,
1411                      None); // This is not an ABI copy.
1412     SDValue Chain = DAG.getEntryNode();
1413     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1414                                  V);
1415     resolveDanglingDebugInfo(V, Result);
1416   }
1417 
1418   return Result;
1419 }
1420 
1421 /// getValue - Return an SDValue for the given Value.
1422 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1423   // If we already have an SDValue for this value, use it. It's important
1424   // to do this first, so that we don't create a CopyFromReg if we already
1425   // have a regular SDValue.
1426   SDValue &N = NodeMap[V];
1427   if (N.getNode()) return N;
1428 
1429   // If there's a virtual register allocated and initialized for this
1430   // value, use it.
1431   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1432     return copyFromReg;
1433 
1434   // Otherwise create a new SDValue and remember it.
1435   SDValue Val = getValueImpl(V);
1436   NodeMap[V] = Val;
1437   resolveDanglingDebugInfo(V, Val);
1438   return Val;
1439 }
1440 
1441 // Return true if SDValue exists for the given Value
1442 bool SelectionDAGBuilder::findValue(const Value *V) const {
1443   return (NodeMap.find(V) != NodeMap.end()) ||
1444     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1445 }
1446 
1447 /// getNonRegisterValue - Return an SDValue for the given Value, but
1448 /// don't look in FuncInfo.ValueMap for a virtual register.
1449 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1450   // If we already have an SDValue for this value, use it.
1451   SDValue &N = NodeMap[V];
1452   if (N.getNode()) {
1453     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1454       // Remove the debug location from the node as the node is about to be used
1455       // in a location which may differ from the original debug location.  This
1456       // is relevant to Constant and ConstantFP nodes because they can appear
1457       // as constant expressions inside PHI nodes.
1458       N->setDebugLoc(DebugLoc());
1459     }
1460     return N;
1461   }
1462 
1463   // Otherwise create a new SDValue and remember it.
1464   SDValue Val = getValueImpl(V);
1465   NodeMap[V] = Val;
1466   resolveDanglingDebugInfo(V, Val);
1467   return Val;
1468 }
1469 
1470 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1471 /// Create an SDValue for the given value.
1472 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1474 
1475   if (const Constant *C = dyn_cast<Constant>(V)) {
1476     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1477 
1478     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1479       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1480 
1481     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1482       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1483 
1484     if (isa<ConstantPointerNull>(C)) {
1485       unsigned AS = V->getType()->getPointerAddressSpace();
1486       return DAG.getConstant(0, getCurSDLoc(),
1487                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1488     }
1489 
1490     if (match(C, m_VScale(DAG.getDataLayout())))
1491       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1492 
1493     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1494       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1495 
1496     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1497       return DAG.getUNDEF(VT);
1498 
1499     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1500       visit(CE->getOpcode(), *CE);
1501       SDValue N1 = NodeMap[V];
1502       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1503       return N1;
1504     }
1505 
1506     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1507       SmallVector<SDValue, 4> Constants;
1508       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1509            OI != OE; ++OI) {
1510         SDNode *Val = getValue(*OI).getNode();
1511         // If the operand is an empty aggregate, there are no values.
1512         if (!Val) continue;
1513         // Add each leaf value from the operand to the Constants list
1514         // to form a flattened list of all the values.
1515         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1516           Constants.push_back(SDValue(Val, i));
1517       }
1518 
1519       return DAG.getMergeValues(Constants, getCurSDLoc());
1520     }
1521 
1522     if (const ConstantDataSequential *CDS =
1523           dyn_cast<ConstantDataSequential>(C)) {
1524       SmallVector<SDValue, 4> Ops;
1525       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1526         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1527         // Add each leaf value from the operand to the Constants list
1528         // to form a flattened list of all the values.
1529         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1530           Ops.push_back(SDValue(Val, i));
1531       }
1532 
1533       if (isa<ArrayType>(CDS->getType()))
1534         return DAG.getMergeValues(Ops, getCurSDLoc());
1535       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1536     }
1537 
1538     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1539       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1540              "Unknown struct or array constant!");
1541 
1542       SmallVector<EVT, 4> ValueVTs;
1543       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1544       unsigned NumElts = ValueVTs.size();
1545       if (NumElts == 0)
1546         return SDValue(); // empty struct
1547       SmallVector<SDValue, 4> Constants(NumElts);
1548       for (unsigned i = 0; i != NumElts; ++i) {
1549         EVT EltVT = ValueVTs[i];
1550         if (isa<UndefValue>(C))
1551           Constants[i] = DAG.getUNDEF(EltVT);
1552         else if (EltVT.isFloatingPoint())
1553           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1554         else
1555           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1556       }
1557 
1558       return DAG.getMergeValues(Constants, getCurSDLoc());
1559     }
1560 
1561     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1562       return DAG.getBlockAddress(BA, VT);
1563 
1564     VectorType *VecTy = cast<VectorType>(V->getType());
1565     unsigned NumElements = VecTy->getNumElements();
1566 
1567     // Now that we know the number and type of the elements, get that number of
1568     // elements into the Ops array based on what kind of constant it is.
1569     SmallVector<SDValue, 16> Ops;
1570     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1571       for (unsigned i = 0; i != NumElements; ++i)
1572         Ops.push_back(getValue(CV->getOperand(i)));
1573     } else {
1574       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1575       EVT EltVT =
1576           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1577 
1578       SDValue Op;
1579       if (EltVT.isFloatingPoint())
1580         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1581       else
1582         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1583       Ops.assign(NumElements, Op);
1584     }
1585 
1586     // Create a BUILD_VECTOR node.
1587     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1588   }
1589 
1590   // If this is a static alloca, generate it as the frameindex instead of
1591   // computation.
1592   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1593     DenseMap<const AllocaInst*, int>::iterator SI =
1594       FuncInfo.StaticAllocaMap.find(AI);
1595     if (SI != FuncInfo.StaticAllocaMap.end())
1596       return DAG.getFrameIndex(SI->second,
1597                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1598   }
1599 
1600   // If this is an instruction which fast-isel has deferred, select it now.
1601   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1602     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1603 
1604     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1605                      Inst->getType(), getABIRegCopyCC(V));
1606     SDValue Chain = DAG.getEntryNode();
1607     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1608   }
1609 
1610   llvm_unreachable("Can't get register for value!");
1611 }
1612 
1613 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1614   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1615   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1616   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1617   bool IsSEH = isAsynchronousEHPersonality(Pers);
1618   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1619   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1620   if (!IsSEH)
1621     CatchPadMBB->setIsEHScopeEntry();
1622   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1623   if (IsMSVCCXX || IsCoreCLR)
1624     CatchPadMBB->setIsEHFuncletEntry();
1625   // Wasm does not need catchpads anymore
1626   if (!IsWasmCXX)
1627     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1628                             getControlRoot()));
1629 }
1630 
1631 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1632   // Update machine-CFG edge.
1633   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1634   FuncInfo.MBB->addSuccessor(TargetMBB);
1635 
1636   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1637   bool IsSEH = isAsynchronousEHPersonality(Pers);
1638   if (IsSEH) {
1639     // If this is not a fall-through branch or optimizations are switched off,
1640     // emit the branch.
1641     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1642         TM.getOptLevel() == CodeGenOpt::None)
1643       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1644                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1645     return;
1646   }
1647 
1648   // Figure out the funclet membership for the catchret's successor.
1649   // This will be used by the FuncletLayout pass to determine how to order the
1650   // BB's.
1651   // A 'catchret' returns to the outer scope's color.
1652   Value *ParentPad = I.getCatchSwitchParentPad();
1653   const BasicBlock *SuccessorColor;
1654   if (isa<ConstantTokenNone>(ParentPad))
1655     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1656   else
1657     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1658   assert(SuccessorColor && "No parent funclet for catchret!");
1659   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1660   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1661 
1662   // Create the terminator node.
1663   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1664                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1665                             DAG.getBasicBlock(SuccessorColorMBB));
1666   DAG.setRoot(Ret);
1667 }
1668 
1669 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1670   // Don't emit any special code for the cleanuppad instruction. It just marks
1671   // the start of an EH scope/funclet.
1672   FuncInfo.MBB->setIsEHScopeEntry();
1673   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1674   if (Pers != EHPersonality::Wasm_CXX) {
1675     FuncInfo.MBB->setIsEHFuncletEntry();
1676     FuncInfo.MBB->setIsCleanupFuncletEntry();
1677   }
1678 }
1679 
1680 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1681 // the control flow always stops at the single catch pad, as it does for a
1682 // cleanup pad. In case the exception caught is not of the types the catch pad
1683 // catches, it will be rethrown by a rethrow.
1684 static void findWasmUnwindDestinations(
1685     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1686     BranchProbability Prob,
1687     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1688         &UnwindDests) {
1689   while (EHPadBB) {
1690     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1691     if (isa<CleanupPadInst>(Pad)) {
1692       // Stop on cleanup pads.
1693       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1694       UnwindDests.back().first->setIsEHScopeEntry();
1695       break;
1696     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1697       // Add the catchpad handlers to the possible destinations. We don't
1698       // continue to the unwind destination of the catchswitch for wasm.
1699       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1700         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1701         UnwindDests.back().first->setIsEHScopeEntry();
1702       }
1703       break;
1704     } else {
1705       continue;
1706     }
1707   }
1708 }
1709 
1710 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1711 /// many places it could ultimately go. In the IR, we have a single unwind
1712 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1713 /// This function skips over imaginary basic blocks that hold catchswitch
1714 /// instructions, and finds all the "real" machine
1715 /// basic block destinations. As those destinations may not be successors of
1716 /// EHPadBB, here we also calculate the edge probability to those destinations.
1717 /// The passed-in Prob is the edge probability to EHPadBB.
1718 static void findUnwindDestinations(
1719     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1720     BranchProbability Prob,
1721     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1722         &UnwindDests) {
1723   EHPersonality Personality =
1724     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1725   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1726   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1727   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1728   bool IsSEH = isAsynchronousEHPersonality(Personality);
1729 
1730   if (IsWasmCXX) {
1731     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1732     assert(UnwindDests.size() <= 1 &&
1733            "There should be at most one unwind destination for wasm");
1734     return;
1735   }
1736 
1737   while (EHPadBB) {
1738     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1739     BasicBlock *NewEHPadBB = nullptr;
1740     if (isa<LandingPadInst>(Pad)) {
1741       // Stop on landingpads. They are not funclets.
1742       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1743       break;
1744     } else if (isa<CleanupPadInst>(Pad)) {
1745       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1746       // personalities.
1747       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1748       UnwindDests.back().first->setIsEHScopeEntry();
1749       UnwindDests.back().first->setIsEHFuncletEntry();
1750       break;
1751     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1752       // Add the catchpad handlers to the possible destinations.
1753       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1754         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1755         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1756         if (IsMSVCCXX || IsCoreCLR)
1757           UnwindDests.back().first->setIsEHFuncletEntry();
1758         if (!IsSEH)
1759           UnwindDests.back().first->setIsEHScopeEntry();
1760       }
1761       NewEHPadBB = CatchSwitch->getUnwindDest();
1762     } else {
1763       continue;
1764     }
1765 
1766     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1767     if (BPI && NewEHPadBB)
1768       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1769     EHPadBB = NewEHPadBB;
1770   }
1771 }
1772 
1773 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1774   // Update successor info.
1775   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1776   auto UnwindDest = I.getUnwindDest();
1777   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1778   BranchProbability UnwindDestProb =
1779       (BPI && UnwindDest)
1780           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1781           : BranchProbability::getZero();
1782   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1783   for (auto &UnwindDest : UnwindDests) {
1784     UnwindDest.first->setIsEHPad();
1785     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1786   }
1787   FuncInfo.MBB->normalizeSuccProbs();
1788 
1789   // Create the terminator node.
1790   SDValue Ret =
1791       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1792   DAG.setRoot(Ret);
1793 }
1794 
1795 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1796   report_fatal_error("visitCatchSwitch not yet implemented!");
1797 }
1798 
1799 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1801   auto &DL = DAG.getDataLayout();
1802   SDValue Chain = getControlRoot();
1803   SmallVector<ISD::OutputArg, 8> Outs;
1804   SmallVector<SDValue, 8> OutVals;
1805 
1806   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1807   // lower
1808   //
1809   //   %val = call <ty> @llvm.experimental.deoptimize()
1810   //   ret <ty> %val
1811   //
1812   // differently.
1813   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1814     LowerDeoptimizingReturn();
1815     return;
1816   }
1817 
1818   if (!FuncInfo.CanLowerReturn) {
1819     unsigned DemoteReg = FuncInfo.DemoteRegister;
1820     const Function *F = I.getParent()->getParent();
1821 
1822     // Emit a store of the return value through the virtual register.
1823     // Leave Outs empty so that LowerReturn won't try to load return
1824     // registers the usual way.
1825     SmallVector<EVT, 1> PtrValueVTs;
1826     ComputeValueVTs(TLI, DL,
1827                     F->getReturnType()->getPointerTo(
1828                         DAG.getDataLayout().getAllocaAddrSpace()),
1829                     PtrValueVTs);
1830 
1831     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1832                                         DemoteReg, PtrValueVTs[0]);
1833     SDValue RetOp = getValue(I.getOperand(0));
1834 
1835     SmallVector<EVT, 4> ValueVTs, MemVTs;
1836     SmallVector<uint64_t, 4> Offsets;
1837     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1838                     &Offsets);
1839     unsigned NumValues = ValueVTs.size();
1840 
1841     SmallVector<SDValue, 4> Chains(NumValues);
1842     for (unsigned i = 0; i != NumValues; ++i) {
1843       // An aggregate return value cannot wrap around the address space, so
1844       // offsets to its parts don't wrap either.
1845       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1846 
1847       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1848       if (MemVTs[i] != ValueVTs[i])
1849         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1850       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1851           // FIXME: better loc info would be nice.
1852           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1853     }
1854 
1855     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1856                         MVT::Other, Chains);
1857   } else if (I.getNumOperands() != 0) {
1858     SmallVector<EVT, 4> ValueVTs;
1859     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1860     unsigned NumValues = ValueVTs.size();
1861     if (NumValues) {
1862       SDValue RetOp = getValue(I.getOperand(0));
1863 
1864       const Function *F = I.getParent()->getParent();
1865 
1866       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1867           I.getOperand(0)->getType(), F->getCallingConv(),
1868           /*IsVarArg*/ false);
1869 
1870       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1871       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1872                                           Attribute::SExt))
1873         ExtendKind = ISD::SIGN_EXTEND;
1874       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1875                                                Attribute::ZExt))
1876         ExtendKind = ISD::ZERO_EXTEND;
1877 
1878       LLVMContext &Context = F->getContext();
1879       bool RetInReg = F->getAttributes().hasAttribute(
1880           AttributeList::ReturnIndex, Attribute::InReg);
1881 
1882       for (unsigned j = 0; j != NumValues; ++j) {
1883         EVT VT = ValueVTs[j];
1884 
1885         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1886           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1887 
1888         CallingConv::ID CC = F->getCallingConv();
1889 
1890         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1891         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1892         SmallVector<SDValue, 4> Parts(NumParts);
1893         getCopyToParts(DAG, getCurSDLoc(),
1894                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1895                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1896 
1897         // 'inreg' on function refers to return value
1898         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1899         if (RetInReg)
1900           Flags.setInReg();
1901 
1902         if (I.getOperand(0)->getType()->isPointerTy()) {
1903           Flags.setPointer();
1904           Flags.setPointerAddrSpace(
1905               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1906         }
1907 
1908         if (NeedsRegBlock) {
1909           Flags.setInConsecutiveRegs();
1910           if (j == NumValues - 1)
1911             Flags.setInConsecutiveRegsLast();
1912         }
1913 
1914         // Propagate extension type if any
1915         if (ExtendKind == ISD::SIGN_EXTEND)
1916           Flags.setSExt();
1917         else if (ExtendKind == ISD::ZERO_EXTEND)
1918           Flags.setZExt();
1919 
1920         for (unsigned i = 0; i < NumParts; ++i) {
1921           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1922                                         VT, /*isfixed=*/true, 0, 0));
1923           OutVals.push_back(Parts[i]);
1924         }
1925       }
1926     }
1927   }
1928 
1929   // Push in swifterror virtual register as the last element of Outs. This makes
1930   // sure swifterror virtual register will be returned in the swifterror
1931   // physical register.
1932   const Function *F = I.getParent()->getParent();
1933   if (TLI.supportSwiftError() &&
1934       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1935     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1936     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1937     Flags.setSwiftError();
1938     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1939                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1940                                   true /*isfixed*/, 1 /*origidx*/,
1941                                   0 /*partOffs*/));
1942     // Create SDNode for the swifterror virtual register.
1943     OutVals.push_back(
1944         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1945                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1946                         EVT(TLI.getPointerTy(DL))));
1947   }
1948 
1949   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1950   CallingConv::ID CallConv =
1951     DAG.getMachineFunction().getFunction().getCallingConv();
1952   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1953       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1954 
1955   // Verify that the target's LowerReturn behaved as expected.
1956   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1957          "LowerReturn didn't return a valid chain!");
1958 
1959   // Update the DAG with the new chain value resulting from return lowering.
1960   DAG.setRoot(Chain);
1961 }
1962 
1963 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1964 /// created for it, emit nodes to copy the value into the virtual
1965 /// registers.
1966 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1967   // Skip empty types
1968   if (V->getType()->isEmptyTy())
1969     return;
1970 
1971   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1972   if (VMI != FuncInfo.ValueMap.end()) {
1973     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1974     CopyValueToVirtualRegister(V, VMI->second);
1975   }
1976 }
1977 
1978 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1979 /// the current basic block, add it to ValueMap now so that we'll get a
1980 /// CopyTo/FromReg.
1981 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1982   // No need to export constants.
1983   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1984 
1985   // Already exported?
1986   if (FuncInfo.isExportedInst(V)) return;
1987 
1988   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1989   CopyValueToVirtualRegister(V, Reg);
1990 }
1991 
1992 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1993                                                      const BasicBlock *FromBB) {
1994   // The operands of the setcc have to be in this block.  We don't know
1995   // how to export them from some other block.
1996   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1997     // Can export from current BB.
1998     if (VI->getParent() == FromBB)
1999       return true;
2000 
2001     // Is already exported, noop.
2002     return FuncInfo.isExportedInst(V);
2003   }
2004 
2005   // If this is an argument, we can export it if the BB is the entry block or
2006   // if it is already exported.
2007   if (isa<Argument>(V)) {
2008     if (FromBB == &FromBB->getParent()->getEntryBlock())
2009       return true;
2010 
2011     // Otherwise, can only export this if it is already exported.
2012     return FuncInfo.isExportedInst(V);
2013   }
2014 
2015   // Otherwise, constants can always be exported.
2016   return true;
2017 }
2018 
2019 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2020 BranchProbability
2021 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2022                                         const MachineBasicBlock *Dst) const {
2023   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2024   const BasicBlock *SrcBB = Src->getBasicBlock();
2025   const BasicBlock *DstBB = Dst->getBasicBlock();
2026   if (!BPI) {
2027     // If BPI is not available, set the default probability as 1 / N, where N is
2028     // the number of successors.
2029     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2030     return BranchProbability(1, SuccSize);
2031   }
2032   return BPI->getEdgeProbability(SrcBB, DstBB);
2033 }
2034 
2035 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2036                                                MachineBasicBlock *Dst,
2037                                                BranchProbability Prob) {
2038   if (!FuncInfo.BPI)
2039     Src->addSuccessorWithoutProb(Dst);
2040   else {
2041     if (Prob.isUnknown())
2042       Prob = getEdgeProbability(Src, Dst);
2043     Src->addSuccessor(Dst, Prob);
2044   }
2045 }
2046 
2047 static bool InBlock(const Value *V, const BasicBlock *BB) {
2048   if (const Instruction *I = dyn_cast<Instruction>(V))
2049     return I->getParent() == BB;
2050   return true;
2051 }
2052 
2053 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2054 /// This function emits a branch and is used at the leaves of an OR or an
2055 /// AND operator tree.
2056 void
2057 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2058                                                   MachineBasicBlock *TBB,
2059                                                   MachineBasicBlock *FBB,
2060                                                   MachineBasicBlock *CurBB,
2061                                                   MachineBasicBlock *SwitchBB,
2062                                                   BranchProbability TProb,
2063                                                   BranchProbability FProb,
2064                                                   bool InvertCond) {
2065   const BasicBlock *BB = CurBB->getBasicBlock();
2066 
2067   // If the leaf of the tree is a comparison, merge the condition into
2068   // the caseblock.
2069   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2070     // The operands of the cmp have to be in this block.  We don't know
2071     // how to export them from some other block.  If this is the first block
2072     // of the sequence, no exporting is needed.
2073     if (CurBB == SwitchBB ||
2074         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2075          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2076       ISD::CondCode Condition;
2077       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2078         ICmpInst::Predicate Pred =
2079             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2080         Condition = getICmpCondCode(Pred);
2081       } else {
2082         const FCmpInst *FC = cast<FCmpInst>(Cond);
2083         FCmpInst::Predicate Pred =
2084             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2085         Condition = getFCmpCondCode(Pred);
2086         if (TM.Options.NoNaNsFPMath)
2087           Condition = getFCmpCodeWithoutNaN(Condition);
2088       }
2089 
2090       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2091                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2092       SL->SwitchCases.push_back(CB);
2093       return;
2094     }
2095   }
2096 
2097   // Create a CaseBlock record representing this branch.
2098   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2099   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2100                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2101   SL->SwitchCases.push_back(CB);
2102 }
2103 
2104 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2105                                                MachineBasicBlock *TBB,
2106                                                MachineBasicBlock *FBB,
2107                                                MachineBasicBlock *CurBB,
2108                                                MachineBasicBlock *SwitchBB,
2109                                                Instruction::BinaryOps Opc,
2110                                                BranchProbability TProb,
2111                                                BranchProbability FProb,
2112                                                bool InvertCond) {
2113   // Skip over not part of the tree and remember to invert op and operands at
2114   // next level.
2115   Value *NotCond;
2116   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2117       InBlock(NotCond, CurBB->getBasicBlock())) {
2118     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2119                          !InvertCond);
2120     return;
2121   }
2122 
2123   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2124   // Compute the effective opcode for Cond, taking into account whether it needs
2125   // to be inverted, e.g.
2126   //   and (not (or A, B)), C
2127   // gets lowered as
2128   //   and (and (not A, not B), C)
2129   unsigned BOpc = 0;
2130   if (BOp) {
2131     BOpc = BOp->getOpcode();
2132     if (InvertCond) {
2133       if (BOpc == Instruction::And)
2134         BOpc = Instruction::Or;
2135       else if (BOpc == Instruction::Or)
2136         BOpc = Instruction::And;
2137     }
2138   }
2139 
2140   // If this node is not part of the or/and tree, emit it as a branch.
2141   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2142       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2143       BOp->getParent() != CurBB->getBasicBlock() ||
2144       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2145       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2146     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2147                                  TProb, FProb, InvertCond);
2148     return;
2149   }
2150 
2151   //  Create TmpBB after CurBB.
2152   MachineFunction::iterator BBI(CurBB);
2153   MachineFunction &MF = DAG.getMachineFunction();
2154   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2155   CurBB->getParent()->insert(++BBI, TmpBB);
2156 
2157   if (Opc == Instruction::Or) {
2158     // Codegen X | Y as:
2159     // BB1:
2160     //   jmp_if_X TBB
2161     //   jmp TmpBB
2162     // TmpBB:
2163     //   jmp_if_Y TBB
2164     //   jmp FBB
2165     //
2166 
2167     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2168     // The requirement is that
2169     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2170     //     = TrueProb for original BB.
2171     // Assuming the original probabilities are A and B, one choice is to set
2172     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2173     // A/(1+B) and 2B/(1+B). This choice assumes that
2174     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2175     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2176     // TmpBB, but the math is more complicated.
2177 
2178     auto NewTrueProb = TProb / 2;
2179     auto NewFalseProb = TProb / 2 + FProb;
2180     // Emit the LHS condition.
2181     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2182                          NewTrueProb, NewFalseProb, InvertCond);
2183 
2184     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2185     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2186     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2187     // Emit the RHS condition into TmpBB.
2188     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2189                          Probs[0], Probs[1], InvertCond);
2190   } else {
2191     assert(Opc == Instruction::And && "Unknown merge op!");
2192     // Codegen X & Y as:
2193     // BB1:
2194     //   jmp_if_X TmpBB
2195     //   jmp FBB
2196     // TmpBB:
2197     //   jmp_if_Y TBB
2198     //   jmp FBB
2199     //
2200     //  This requires creation of TmpBB after CurBB.
2201 
2202     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2203     // The requirement is that
2204     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2205     //     = FalseProb for original BB.
2206     // Assuming the original probabilities are A and B, one choice is to set
2207     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2208     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2209     // TrueProb for BB1 * FalseProb for TmpBB.
2210 
2211     auto NewTrueProb = TProb + FProb / 2;
2212     auto NewFalseProb = FProb / 2;
2213     // Emit the LHS condition.
2214     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2215                          NewTrueProb, NewFalseProb, InvertCond);
2216 
2217     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2218     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2219     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2220     // Emit the RHS condition into TmpBB.
2221     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2222                          Probs[0], Probs[1], InvertCond);
2223   }
2224 }
2225 
2226 /// If the set of cases should be emitted as a series of branches, return true.
2227 /// If we should emit this as a bunch of and/or'd together conditions, return
2228 /// false.
2229 bool
2230 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2231   if (Cases.size() != 2) return true;
2232 
2233   // If this is two comparisons of the same values or'd or and'd together, they
2234   // will get folded into a single comparison, so don't emit two blocks.
2235   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2236        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2237       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2238        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2239     return false;
2240   }
2241 
2242   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2243   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2244   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2245       Cases[0].CC == Cases[1].CC &&
2246       isa<Constant>(Cases[0].CmpRHS) &&
2247       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2248     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2249       return false;
2250     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2251       return false;
2252   }
2253 
2254   return true;
2255 }
2256 
2257 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2258   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2259 
2260   // Update machine-CFG edges.
2261   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2262 
2263   if (I.isUnconditional()) {
2264     // Update machine-CFG edges.
2265     BrMBB->addSuccessor(Succ0MBB);
2266 
2267     // If this is not a fall-through branch or optimizations are switched off,
2268     // emit the branch.
2269     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2270       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2271                               MVT::Other, getControlRoot(),
2272                               DAG.getBasicBlock(Succ0MBB)));
2273 
2274     return;
2275   }
2276 
2277   // If this condition is one of the special cases we handle, do special stuff
2278   // now.
2279   const Value *CondVal = I.getCondition();
2280   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2281 
2282   // If this is a series of conditions that are or'd or and'd together, emit
2283   // this as a sequence of branches instead of setcc's with and/or operations.
2284   // As long as jumps are not expensive, this should improve performance.
2285   // For example, instead of something like:
2286   //     cmp A, B
2287   //     C = seteq
2288   //     cmp D, E
2289   //     F = setle
2290   //     or C, F
2291   //     jnz foo
2292   // Emit:
2293   //     cmp A, B
2294   //     je foo
2295   //     cmp D, E
2296   //     jle foo
2297   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2298     Instruction::BinaryOps Opcode = BOp->getOpcode();
2299     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2300         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2301         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2302       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2303                            Opcode,
2304                            getEdgeProbability(BrMBB, Succ0MBB),
2305                            getEdgeProbability(BrMBB, Succ1MBB),
2306                            /*InvertCond=*/false);
2307       // If the compares in later blocks need to use values not currently
2308       // exported from this block, export them now.  This block should always
2309       // be the first entry.
2310       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2311 
2312       // Allow some cases to be rejected.
2313       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2314         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2315           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2316           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2317         }
2318 
2319         // Emit the branch for this block.
2320         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2321         SL->SwitchCases.erase(SL->SwitchCases.begin());
2322         return;
2323       }
2324 
2325       // Okay, we decided not to do this, remove any inserted MBB's and clear
2326       // SwitchCases.
2327       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2328         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2329 
2330       SL->SwitchCases.clear();
2331     }
2332   }
2333 
2334   // Create a CaseBlock record representing this branch.
2335   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2336                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2337 
2338   // Use visitSwitchCase to actually insert the fast branch sequence for this
2339   // cond branch.
2340   visitSwitchCase(CB, BrMBB);
2341 }
2342 
2343 /// visitSwitchCase - Emits the necessary code to represent a single node in
2344 /// the binary search tree resulting from lowering a switch instruction.
2345 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2346                                           MachineBasicBlock *SwitchBB) {
2347   SDValue Cond;
2348   SDValue CondLHS = getValue(CB.CmpLHS);
2349   SDLoc dl = CB.DL;
2350 
2351   if (CB.CC == ISD::SETTRUE) {
2352     // Branch or fall through to TrueBB.
2353     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2354     SwitchBB->normalizeSuccProbs();
2355     if (CB.TrueBB != NextBlock(SwitchBB)) {
2356       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2357                               DAG.getBasicBlock(CB.TrueBB)));
2358     }
2359     return;
2360   }
2361 
2362   auto &TLI = DAG.getTargetLoweringInfo();
2363   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2364 
2365   // Build the setcc now.
2366   if (!CB.CmpMHS) {
2367     // Fold "(X == true)" to X and "(X == false)" to !X to
2368     // handle common cases produced by branch lowering.
2369     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2370         CB.CC == ISD::SETEQ)
2371       Cond = CondLHS;
2372     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2373              CB.CC == ISD::SETEQ) {
2374       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2375       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2376     } else {
2377       SDValue CondRHS = getValue(CB.CmpRHS);
2378 
2379       // If a pointer's DAG type is larger than its memory type then the DAG
2380       // values are zero-extended. This breaks signed comparisons so truncate
2381       // back to the underlying type before doing the compare.
2382       if (CondLHS.getValueType() != MemVT) {
2383         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2384         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2385       }
2386       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2387     }
2388   } else {
2389     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2390 
2391     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2392     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2393 
2394     SDValue CmpOp = getValue(CB.CmpMHS);
2395     EVT VT = CmpOp.getValueType();
2396 
2397     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2398       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2399                           ISD::SETLE);
2400     } else {
2401       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2402                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2403       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2404                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2405     }
2406   }
2407 
2408   // Update successor info
2409   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2410   // TrueBB and FalseBB are always different unless the incoming IR is
2411   // degenerate. This only happens when running llc on weird IR.
2412   if (CB.TrueBB != CB.FalseBB)
2413     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2414   SwitchBB->normalizeSuccProbs();
2415 
2416   // If the lhs block is the next block, invert the condition so that we can
2417   // fall through to the lhs instead of the rhs block.
2418   if (CB.TrueBB == NextBlock(SwitchBB)) {
2419     std::swap(CB.TrueBB, CB.FalseBB);
2420     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2421     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2422   }
2423 
2424   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2425                                MVT::Other, getControlRoot(), Cond,
2426                                DAG.getBasicBlock(CB.TrueBB));
2427 
2428   // Insert the false branch. Do this even if it's a fall through branch,
2429   // this makes it easier to do DAG optimizations which require inverting
2430   // the branch condition.
2431   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2432                        DAG.getBasicBlock(CB.FalseBB));
2433 
2434   DAG.setRoot(BrCond);
2435 }
2436 
2437 /// visitJumpTable - Emit JumpTable node in the current MBB
2438 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2439   // Emit the code for the jump table
2440   assert(JT.Reg != -1U && "Should lower JT Header first!");
2441   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2442   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2443                                      JT.Reg, PTy);
2444   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2445   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2446                                     MVT::Other, Index.getValue(1),
2447                                     Table, Index);
2448   DAG.setRoot(BrJumpTable);
2449 }
2450 
2451 /// visitJumpTableHeader - This function emits necessary code to produce index
2452 /// in the JumpTable from switch case.
2453 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2454                                                JumpTableHeader &JTH,
2455                                                MachineBasicBlock *SwitchBB) {
2456   SDLoc dl = getCurSDLoc();
2457 
2458   // Subtract the lowest switch case value from the value being switched on.
2459   SDValue SwitchOp = getValue(JTH.SValue);
2460   EVT VT = SwitchOp.getValueType();
2461   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2462                             DAG.getConstant(JTH.First, dl, VT));
2463 
2464   // The SDNode we just created, which holds the value being switched on minus
2465   // the smallest case value, needs to be copied to a virtual register so it
2466   // can be used as an index into the jump table in a subsequent basic block.
2467   // This value may be smaller or larger than the target's pointer type, and
2468   // therefore require extension or truncating.
2469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2470   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2471 
2472   unsigned JumpTableReg =
2473       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2474   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2475                                     JumpTableReg, SwitchOp);
2476   JT.Reg = JumpTableReg;
2477 
2478   if (!JTH.OmitRangeCheck) {
2479     // Emit the range check for the jump table, and branch to the default block
2480     // for the switch statement if the value being switched on exceeds the
2481     // largest case in the switch.
2482     SDValue CMP = DAG.getSetCC(
2483         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2484                                    Sub.getValueType()),
2485         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2486 
2487     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2488                                  MVT::Other, CopyTo, CMP,
2489                                  DAG.getBasicBlock(JT.Default));
2490 
2491     // Avoid emitting unnecessary branches to the next block.
2492     if (JT.MBB != NextBlock(SwitchBB))
2493       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2494                            DAG.getBasicBlock(JT.MBB));
2495 
2496     DAG.setRoot(BrCond);
2497   } else {
2498     // Avoid emitting unnecessary branches to the next block.
2499     if (JT.MBB != NextBlock(SwitchBB))
2500       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2501                               DAG.getBasicBlock(JT.MBB)));
2502     else
2503       DAG.setRoot(CopyTo);
2504   }
2505 }
2506 
2507 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2508 /// variable if there exists one.
2509 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2510                                  SDValue &Chain) {
2511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2512   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2513   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2514   MachineFunction &MF = DAG.getMachineFunction();
2515   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2516   MachineSDNode *Node =
2517       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2518   if (Global) {
2519     MachinePointerInfo MPInfo(Global);
2520     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2521                  MachineMemOperand::MODereferenceable;
2522     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2523         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2524     DAG.setNodeMemRefs(Node, {MemRef});
2525   }
2526   if (PtrTy != PtrMemTy)
2527     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2528   return SDValue(Node, 0);
2529 }
2530 
2531 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2532 /// tail spliced into a stack protector check success bb.
2533 ///
2534 /// For a high level explanation of how this fits into the stack protector
2535 /// generation see the comment on the declaration of class
2536 /// StackProtectorDescriptor.
2537 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2538                                                   MachineBasicBlock *ParentBB) {
2539 
2540   // First create the loads to the guard/stack slot for the comparison.
2541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2542   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2543   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2544 
2545   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2546   int FI = MFI.getStackProtectorIndex();
2547 
2548   SDValue Guard;
2549   SDLoc dl = getCurSDLoc();
2550   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2551   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2552   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2553 
2554   // Generate code to load the content of the guard slot.
2555   SDValue GuardVal = DAG.getLoad(
2556       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2557       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2558       MachineMemOperand::MOVolatile);
2559 
2560   if (TLI.useStackGuardXorFP())
2561     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2562 
2563   // Retrieve guard check function, nullptr if instrumentation is inlined.
2564   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2565     // The target provides a guard check function to validate the guard value.
2566     // Generate a call to that function with the content of the guard slot as
2567     // argument.
2568     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2569     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2570 
2571     TargetLowering::ArgListTy Args;
2572     TargetLowering::ArgListEntry Entry;
2573     Entry.Node = GuardVal;
2574     Entry.Ty = FnTy->getParamType(0);
2575     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2576       Entry.IsInReg = true;
2577     Args.push_back(Entry);
2578 
2579     TargetLowering::CallLoweringInfo CLI(DAG);
2580     CLI.setDebugLoc(getCurSDLoc())
2581         .setChain(DAG.getEntryNode())
2582         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2583                    getValue(GuardCheckFn), std::move(Args));
2584 
2585     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2586     DAG.setRoot(Result.second);
2587     return;
2588   }
2589 
2590   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2591   // Otherwise, emit a volatile load to retrieve the stack guard value.
2592   SDValue Chain = DAG.getEntryNode();
2593   if (TLI.useLoadStackGuardNode()) {
2594     Guard = getLoadStackGuard(DAG, dl, Chain);
2595   } else {
2596     const Value *IRGuard = TLI.getSDagStackGuard(M);
2597     SDValue GuardPtr = getValue(IRGuard);
2598 
2599     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2600                         MachinePointerInfo(IRGuard, 0), Align,
2601                         MachineMemOperand::MOVolatile);
2602   }
2603 
2604   // Perform the comparison via a subtract/getsetcc.
2605   EVT VT = Guard.getValueType();
2606   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2607 
2608   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2609                                                         *DAG.getContext(),
2610                                                         Sub.getValueType()),
2611                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2612 
2613   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2614   // branch to failure MBB.
2615   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2616                                MVT::Other, GuardVal.getOperand(0),
2617                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2618   // Otherwise branch to success MBB.
2619   SDValue Br = DAG.getNode(ISD::BR, dl,
2620                            MVT::Other, BrCond,
2621                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2622 
2623   DAG.setRoot(Br);
2624 }
2625 
2626 /// Codegen the failure basic block for a stack protector check.
2627 ///
2628 /// A failure stack protector machine basic block consists simply of a call to
2629 /// __stack_chk_fail().
2630 ///
2631 /// For a high level explanation of how this fits into the stack protector
2632 /// generation see the comment on the declaration of class
2633 /// StackProtectorDescriptor.
2634 void
2635 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2637   TargetLowering::MakeLibCallOptions CallOptions;
2638   CallOptions.setDiscardResult(true);
2639   SDValue Chain =
2640       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2641                       None, CallOptions, getCurSDLoc()).second;
2642   // On PS4, the "return address" must still be within the calling function,
2643   // even if it's at the very end, so emit an explicit TRAP here.
2644   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2645   if (TM.getTargetTriple().isPS4CPU())
2646     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2647 
2648   DAG.setRoot(Chain);
2649 }
2650 
2651 /// visitBitTestHeader - This function emits necessary code to produce value
2652 /// suitable for "bit tests"
2653 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2654                                              MachineBasicBlock *SwitchBB) {
2655   SDLoc dl = getCurSDLoc();
2656 
2657   // Subtract the minimum value.
2658   SDValue SwitchOp = getValue(B.SValue);
2659   EVT VT = SwitchOp.getValueType();
2660   SDValue RangeSub =
2661       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2662 
2663   // Determine the type of the test operands.
2664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2665   bool UsePtrType = false;
2666   if (!TLI.isTypeLegal(VT)) {
2667     UsePtrType = true;
2668   } else {
2669     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2670       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2671         // Switch table case range are encoded into series of masks.
2672         // Just use pointer type, it's guaranteed to fit.
2673         UsePtrType = true;
2674         break;
2675       }
2676   }
2677   SDValue Sub = RangeSub;
2678   if (UsePtrType) {
2679     VT = TLI.getPointerTy(DAG.getDataLayout());
2680     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2681   }
2682 
2683   B.RegVT = VT.getSimpleVT();
2684   B.Reg = FuncInfo.CreateReg(B.RegVT);
2685   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2686 
2687   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2688 
2689   if (!B.OmitRangeCheck)
2690     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2691   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2692   SwitchBB->normalizeSuccProbs();
2693 
2694   SDValue Root = CopyTo;
2695   if (!B.OmitRangeCheck) {
2696     // Conditional branch to the default block.
2697     SDValue RangeCmp = DAG.getSetCC(dl,
2698         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2699                                RangeSub.getValueType()),
2700         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2701         ISD::SETUGT);
2702 
2703     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2704                        DAG.getBasicBlock(B.Default));
2705   }
2706 
2707   // Avoid emitting unnecessary branches to the next block.
2708   if (MBB != NextBlock(SwitchBB))
2709     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2710 
2711   DAG.setRoot(Root);
2712 }
2713 
2714 /// visitBitTestCase - this function produces one "bit test"
2715 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2716                                            MachineBasicBlock* NextMBB,
2717                                            BranchProbability BranchProbToNext,
2718                                            unsigned Reg,
2719                                            BitTestCase &B,
2720                                            MachineBasicBlock *SwitchBB) {
2721   SDLoc dl = getCurSDLoc();
2722   MVT VT = BB.RegVT;
2723   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2724   SDValue Cmp;
2725   unsigned PopCount = countPopulation(B.Mask);
2726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2727   if (PopCount == 1) {
2728     // Testing for a single bit; just compare the shift count with what it
2729     // would need to be to shift a 1 bit in that position.
2730     Cmp = DAG.getSetCC(
2731         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2732         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2733         ISD::SETEQ);
2734   } else if (PopCount == BB.Range) {
2735     // There is only one zero bit in the range, test for it directly.
2736     Cmp = DAG.getSetCC(
2737         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2738         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2739         ISD::SETNE);
2740   } else {
2741     // Make desired shift
2742     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2743                                     DAG.getConstant(1, dl, VT), ShiftOp);
2744 
2745     // Emit bit tests and jumps
2746     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2747                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2748     Cmp = DAG.getSetCC(
2749         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2750         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2751   }
2752 
2753   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2754   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2755   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2756   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2757   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2758   // one as they are relative probabilities (and thus work more like weights),
2759   // and hence we need to normalize them to let the sum of them become one.
2760   SwitchBB->normalizeSuccProbs();
2761 
2762   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2763                               MVT::Other, getControlRoot(),
2764                               Cmp, DAG.getBasicBlock(B.TargetBB));
2765 
2766   // Avoid emitting unnecessary branches to the next block.
2767   if (NextMBB != NextBlock(SwitchBB))
2768     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2769                         DAG.getBasicBlock(NextMBB));
2770 
2771   DAG.setRoot(BrAnd);
2772 }
2773 
2774 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2775   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2776 
2777   // Retrieve successors. Look through artificial IR level blocks like
2778   // catchswitch for successors.
2779   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2780   const BasicBlock *EHPadBB = I.getSuccessor(1);
2781 
2782   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2783   // have to do anything here to lower funclet bundles.
2784   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2785                                         LLVMContext::OB_funclet,
2786                                         LLVMContext::OB_cfguardtarget}) &&
2787          "Cannot lower invokes with arbitrary operand bundles yet!");
2788 
2789   const Value *Callee(I.getCalledValue());
2790   const Function *Fn = dyn_cast<Function>(Callee);
2791   if (isa<InlineAsm>(Callee))
2792     visitInlineAsm(&I);
2793   else if (Fn && Fn->isIntrinsic()) {
2794     switch (Fn->getIntrinsicID()) {
2795     default:
2796       llvm_unreachable("Cannot invoke this intrinsic");
2797     case Intrinsic::donothing:
2798       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2799       break;
2800     case Intrinsic::experimental_patchpoint_void:
2801     case Intrinsic::experimental_patchpoint_i64:
2802       visitPatchpoint(&I, EHPadBB);
2803       break;
2804     case Intrinsic::experimental_gc_statepoint:
2805       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2806       break;
2807     case Intrinsic::wasm_rethrow_in_catch: {
2808       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2809       // special because it can be invoked, so we manually lower it to a DAG
2810       // node here.
2811       SmallVector<SDValue, 8> Ops;
2812       Ops.push_back(getRoot()); // inchain
2813       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2814       Ops.push_back(
2815           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2816                                 TLI.getPointerTy(DAG.getDataLayout())));
2817       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2818       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2819       break;
2820     }
2821     }
2822   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2823     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2824     // Eventually we will support lowering the @llvm.experimental.deoptimize
2825     // intrinsic, and right now there are no plans to support other intrinsics
2826     // with deopt state.
2827     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2828   } else {
2829     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2830   }
2831 
2832   // If the value of the invoke is used outside of its defining block, make it
2833   // available as a virtual register.
2834   // We already took care of the exported value for the statepoint instruction
2835   // during call to the LowerStatepoint.
2836   if (!isStatepoint(I)) {
2837     CopyToExportRegsIfNeeded(&I);
2838   }
2839 
2840   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2841   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2842   BranchProbability EHPadBBProb =
2843       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2844           : BranchProbability::getZero();
2845   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2846 
2847   // Update successor info.
2848   addSuccessorWithProb(InvokeMBB, Return);
2849   for (auto &UnwindDest : UnwindDests) {
2850     UnwindDest.first->setIsEHPad();
2851     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2852   }
2853   InvokeMBB->normalizeSuccProbs();
2854 
2855   // Drop into normal successor.
2856   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2857                           DAG.getBasicBlock(Return)));
2858 }
2859 
2860 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2861   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2862 
2863   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2864   // have to do anything here to lower funclet bundles.
2865   assert(!I.hasOperandBundlesOtherThan(
2866              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2867          "Cannot lower callbrs with arbitrary operand bundles yet!");
2868 
2869   assert(isa<InlineAsm>(I.getCalledValue()) &&
2870          "Only know how to handle inlineasm callbr");
2871   visitInlineAsm(&I);
2872 
2873   // Retrieve successors.
2874   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2875 
2876   // Update successor info.
2877   addSuccessorWithProb(CallBrMBB, Return);
2878   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2879     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2880     addSuccessorWithProb(CallBrMBB, Target);
2881   }
2882   CallBrMBB->normalizeSuccProbs();
2883 
2884   // Drop into default successor.
2885   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2886                           MVT::Other, getControlRoot(),
2887                           DAG.getBasicBlock(Return)));
2888 }
2889 
2890 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2891   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2892 }
2893 
2894 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2895   assert(FuncInfo.MBB->isEHPad() &&
2896          "Call to landingpad not in landing pad!");
2897 
2898   // If there aren't registers to copy the values into (e.g., during SjLj
2899   // exceptions), then don't bother to create these DAG nodes.
2900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2901   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2902   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2903       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2904     return;
2905 
2906   // If landingpad's return type is token type, we don't create DAG nodes
2907   // for its exception pointer and selector value. The extraction of exception
2908   // pointer or selector value from token type landingpads is not currently
2909   // supported.
2910   if (LP.getType()->isTokenTy())
2911     return;
2912 
2913   SmallVector<EVT, 2> ValueVTs;
2914   SDLoc dl = getCurSDLoc();
2915   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2916   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2917 
2918   // Get the two live-in registers as SDValues. The physregs have already been
2919   // copied into virtual registers.
2920   SDValue Ops[2];
2921   if (FuncInfo.ExceptionPointerVirtReg) {
2922     Ops[0] = DAG.getZExtOrTrunc(
2923         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2924                            FuncInfo.ExceptionPointerVirtReg,
2925                            TLI.getPointerTy(DAG.getDataLayout())),
2926         dl, ValueVTs[0]);
2927   } else {
2928     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2929   }
2930   Ops[1] = DAG.getZExtOrTrunc(
2931       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2932                          FuncInfo.ExceptionSelectorVirtReg,
2933                          TLI.getPointerTy(DAG.getDataLayout())),
2934       dl, ValueVTs[1]);
2935 
2936   // Merge into one.
2937   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2938                             DAG.getVTList(ValueVTs), Ops);
2939   setValue(&LP, Res);
2940 }
2941 
2942 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2943                                            MachineBasicBlock *Last) {
2944   // Update JTCases.
2945   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2946     if (SL->JTCases[i].first.HeaderBB == First)
2947       SL->JTCases[i].first.HeaderBB = Last;
2948 
2949   // Update BitTestCases.
2950   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2951     if (SL->BitTestCases[i].Parent == First)
2952       SL->BitTestCases[i].Parent = Last;
2953 }
2954 
2955 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2956   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2957 
2958   // Update machine-CFG edges with unique successors.
2959   SmallSet<BasicBlock*, 32> Done;
2960   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2961     BasicBlock *BB = I.getSuccessor(i);
2962     bool Inserted = Done.insert(BB).second;
2963     if (!Inserted)
2964         continue;
2965 
2966     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2967     addSuccessorWithProb(IndirectBrMBB, Succ);
2968   }
2969   IndirectBrMBB->normalizeSuccProbs();
2970 
2971   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2972                           MVT::Other, getControlRoot(),
2973                           getValue(I.getAddress())));
2974 }
2975 
2976 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2977   if (!DAG.getTarget().Options.TrapUnreachable)
2978     return;
2979 
2980   // We may be able to ignore unreachable behind a noreturn call.
2981   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2982     const BasicBlock &BB = *I.getParent();
2983     if (&I != &BB.front()) {
2984       BasicBlock::const_iterator PredI =
2985         std::prev(BasicBlock::const_iterator(&I));
2986       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2987         if (Call->doesNotReturn())
2988           return;
2989       }
2990     }
2991   }
2992 
2993   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2994 }
2995 
2996 void SelectionDAGBuilder::visitFSub(const User &I) {
2997   // -0.0 - X --> fneg
2998   Type *Ty = I.getType();
2999   if (isa<Constant>(I.getOperand(0)) &&
3000       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3001     SDValue Op2 = getValue(I.getOperand(1));
3002     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3003                              Op2.getValueType(), Op2));
3004     return;
3005   }
3006 
3007   visitBinary(I, ISD::FSUB);
3008 }
3009 
3010 /// Checks if the given instruction performs a vector reduction, in which case
3011 /// we have the freedom to alter the elements in the result as long as the
3012 /// reduction of them stays unchanged.
3013 static bool isVectorReductionOp(const User *I) {
3014   const Instruction *Inst = dyn_cast<Instruction>(I);
3015   if (!Inst || !Inst->getType()->isVectorTy())
3016     return false;
3017 
3018   auto OpCode = Inst->getOpcode();
3019   switch (OpCode) {
3020   case Instruction::Add:
3021   case Instruction::Mul:
3022   case Instruction::And:
3023   case Instruction::Or:
3024   case Instruction::Xor:
3025     break;
3026   case Instruction::FAdd:
3027   case Instruction::FMul:
3028     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3029       if (FPOp->getFastMathFlags().isFast())
3030         break;
3031     LLVM_FALLTHROUGH;
3032   default:
3033     return false;
3034   }
3035 
3036   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3037   // Ensure the reduction size is a power of 2.
3038   if (!isPowerOf2_32(ElemNum))
3039     return false;
3040 
3041   unsigned ElemNumToReduce = ElemNum;
3042 
3043   // Do DFS search on the def-use chain from the given instruction. We only
3044   // allow four kinds of operations during the search until we reach the
3045   // instruction that extracts the first element from the vector:
3046   //
3047   //   1. The reduction operation of the same opcode as the given instruction.
3048   //
3049   //   2. PHI node.
3050   //
3051   //   3. ShuffleVector instruction together with a reduction operation that
3052   //      does a partial reduction.
3053   //
3054   //   4. ExtractElement that extracts the first element from the vector, and we
3055   //      stop searching the def-use chain here.
3056   //
3057   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3058   // from 1-3 to the stack to continue the DFS. The given instruction is not
3059   // a reduction operation if we meet any other instructions other than those
3060   // listed above.
3061 
3062   SmallVector<const User *, 16> UsersToVisit{Inst};
3063   SmallPtrSet<const User *, 16> Visited;
3064   bool ReduxExtracted = false;
3065 
3066   while (!UsersToVisit.empty()) {
3067     auto User = UsersToVisit.back();
3068     UsersToVisit.pop_back();
3069     if (!Visited.insert(User).second)
3070       continue;
3071 
3072     for (const auto *U : User->users()) {
3073       auto Inst = dyn_cast<Instruction>(U);
3074       if (!Inst)
3075         return false;
3076 
3077       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3078         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3079           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3080             return false;
3081         UsersToVisit.push_back(U);
3082       } else if (const ShuffleVectorInst *ShufInst =
3083                      dyn_cast<ShuffleVectorInst>(U)) {
3084         // Detect the following pattern: A ShuffleVector instruction together
3085         // with a reduction that do partial reduction on the first and second
3086         // ElemNumToReduce / 2 elements, and store the result in
3087         // ElemNumToReduce / 2 elements in another vector.
3088 
3089         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3090         if (ResultElements < ElemNum)
3091           return false;
3092 
3093         if (ElemNumToReduce == 1)
3094           return false;
3095         if (!isa<UndefValue>(U->getOperand(1)))
3096           return false;
3097         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3098           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3099             return false;
3100         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3101           if (ShufInst->getMaskValue(i) != -1)
3102             return false;
3103 
3104         // There is only one user of this ShuffleVector instruction, which
3105         // must be a reduction operation.
3106         if (!U->hasOneUse())
3107           return false;
3108 
3109         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3110         if (!U2 || U2->getOpcode() != OpCode)
3111           return false;
3112 
3113         // Check operands of the reduction operation.
3114         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3115             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3116           UsersToVisit.push_back(U2);
3117           ElemNumToReduce /= 2;
3118         } else
3119           return false;
3120       } else if (isa<ExtractElementInst>(U)) {
3121         // At this moment we should have reduced all elements in the vector.
3122         if (ElemNumToReduce != 1)
3123           return false;
3124 
3125         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3126         if (!Val || !Val->isZero())
3127           return false;
3128 
3129         ReduxExtracted = true;
3130       } else
3131         return false;
3132     }
3133   }
3134   return ReduxExtracted;
3135 }
3136 
3137 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3138   SDNodeFlags Flags;
3139 
3140   SDValue Op = getValue(I.getOperand(0));
3141   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3142                                     Op, Flags);
3143   setValue(&I, UnNodeValue);
3144 }
3145 
3146 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3147   SDNodeFlags Flags;
3148   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3149     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3150     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3151   }
3152   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3153     Flags.setExact(ExactOp->isExact());
3154   }
3155   if (isVectorReductionOp(&I)) {
3156     Flags.setVectorReduction(true);
3157     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3158 
3159     // If no flags are set we will propagate the incoming flags, if any flags
3160     // are set, we will intersect them with the incoming flag and so we need to
3161     // copy the FMF flags here.
3162     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3163       Flags.copyFMF(*FPOp);
3164     }
3165   }
3166 
3167   SDValue Op1 = getValue(I.getOperand(0));
3168   SDValue Op2 = getValue(I.getOperand(1));
3169   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3170                                      Op1, Op2, Flags);
3171   setValue(&I, BinNodeValue);
3172 }
3173 
3174 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3175   SDValue Op1 = getValue(I.getOperand(0));
3176   SDValue Op2 = getValue(I.getOperand(1));
3177 
3178   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3179       Op1.getValueType(), DAG.getDataLayout());
3180 
3181   // Coerce the shift amount to the right type if we can.
3182   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3183     unsigned ShiftSize = ShiftTy.getSizeInBits();
3184     unsigned Op2Size = Op2.getValueSizeInBits();
3185     SDLoc DL = getCurSDLoc();
3186 
3187     // If the operand is smaller than the shift count type, promote it.
3188     if (ShiftSize > Op2Size)
3189       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3190 
3191     // If the operand is larger than the shift count type but the shift
3192     // count type has enough bits to represent any shift value, truncate
3193     // it now. This is a common case and it exposes the truncate to
3194     // optimization early.
3195     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3196       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3197     // Otherwise we'll need to temporarily settle for some other convenient
3198     // type.  Type legalization will make adjustments once the shiftee is split.
3199     else
3200       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3201   }
3202 
3203   bool nuw = false;
3204   bool nsw = false;
3205   bool exact = false;
3206 
3207   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3208 
3209     if (const OverflowingBinaryOperator *OFBinOp =
3210             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3211       nuw = OFBinOp->hasNoUnsignedWrap();
3212       nsw = OFBinOp->hasNoSignedWrap();
3213     }
3214     if (const PossiblyExactOperator *ExactOp =
3215             dyn_cast<const PossiblyExactOperator>(&I))
3216       exact = ExactOp->isExact();
3217   }
3218   SDNodeFlags Flags;
3219   Flags.setExact(exact);
3220   Flags.setNoSignedWrap(nsw);
3221   Flags.setNoUnsignedWrap(nuw);
3222   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3223                             Flags);
3224   setValue(&I, Res);
3225 }
3226 
3227 void SelectionDAGBuilder::visitSDiv(const User &I) {
3228   SDValue Op1 = getValue(I.getOperand(0));
3229   SDValue Op2 = getValue(I.getOperand(1));
3230 
3231   SDNodeFlags Flags;
3232   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3233                  cast<PossiblyExactOperator>(&I)->isExact());
3234   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3235                            Op2, Flags));
3236 }
3237 
3238 void SelectionDAGBuilder::visitICmp(const User &I) {
3239   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3240   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3241     predicate = IC->getPredicate();
3242   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3243     predicate = ICmpInst::Predicate(IC->getPredicate());
3244   SDValue Op1 = getValue(I.getOperand(0));
3245   SDValue Op2 = getValue(I.getOperand(1));
3246   ISD::CondCode Opcode = getICmpCondCode(predicate);
3247 
3248   auto &TLI = DAG.getTargetLoweringInfo();
3249   EVT MemVT =
3250       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3251 
3252   // If a pointer's DAG type is larger than its memory type then the DAG values
3253   // are zero-extended. This breaks signed comparisons so truncate back to the
3254   // underlying type before doing the compare.
3255   if (Op1.getValueType() != MemVT) {
3256     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3257     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3258   }
3259 
3260   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3261                                                         I.getType());
3262   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3263 }
3264 
3265 void SelectionDAGBuilder::visitFCmp(const User &I) {
3266   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3267   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3268     predicate = FC->getPredicate();
3269   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3270     predicate = FCmpInst::Predicate(FC->getPredicate());
3271   SDValue Op1 = getValue(I.getOperand(0));
3272   SDValue Op2 = getValue(I.getOperand(1));
3273 
3274   ISD::CondCode Condition = getFCmpCondCode(predicate);
3275   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3276   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3277     Condition = getFCmpCodeWithoutNaN(Condition);
3278 
3279   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3280                                                         I.getType());
3281   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3282 }
3283 
3284 // Check if the condition of the select has one use or two users that are both
3285 // selects with the same condition.
3286 static bool hasOnlySelectUsers(const Value *Cond) {
3287   return llvm::all_of(Cond->users(), [](const Value *V) {
3288     return isa<SelectInst>(V);
3289   });
3290 }
3291 
3292 void SelectionDAGBuilder::visitSelect(const User &I) {
3293   SmallVector<EVT, 4> ValueVTs;
3294   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3295                   ValueVTs);
3296   unsigned NumValues = ValueVTs.size();
3297   if (NumValues == 0) return;
3298 
3299   SmallVector<SDValue, 4> Values(NumValues);
3300   SDValue Cond     = getValue(I.getOperand(0));
3301   SDValue LHSVal   = getValue(I.getOperand(1));
3302   SDValue RHSVal   = getValue(I.getOperand(2));
3303   auto BaseOps = {Cond};
3304   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3305     ISD::VSELECT : ISD::SELECT;
3306 
3307   bool IsUnaryAbs = false;
3308 
3309   // Min/max matching is only viable if all output VTs are the same.
3310   if (is_splat(ValueVTs)) {
3311     EVT VT = ValueVTs[0];
3312     LLVMContext &Ctx = *DAG.getContext();
3313     auto &TLI = DAG.getTargetLoweringInfo();
3314 
3315     // We care about the legality of the operation after it has been type
3316     // legalized.
3317     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3318       VT = TLI.getTypeToTransformTo(Ctx, VT);
3319 
3320     // If the vselect is legal, assume we want to leave this as a vector setcc +
3321     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3322     // min/max is legal on the scalar type.
3323     bool UseScalarMinMax = VT.isVector() &&
3324       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3325 
3326     Value *LHS, *RHS;
3327     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3328     ISD::NodeType Opc = ISD::DELETED_NODE;
3329     switch (SPR.Flavor) {
3330     case SPF_UMAX:    Opc = ISD::UMAX; break;
3331     case SPF_UMIN:    Opc = ISD::UMIN; break;
3332     case SPF_SMAX:    Opc = ISD::SMAX; break;
3333     case SPF_SMIN:    Opc = ISD::SMIN; break;
3334     case SPF_FMINNUM:
3335       switch (SPR.NaNBehavior) {
3336       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3337       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3338       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3339       case SPNB_RETURNS_ANY: {
3340         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3341           Opc = ISD::FMINNUM;
3342         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3343           Opc = ISD::FMINIMUM;
3344         else if (UseScalarMinMax)
3345           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3346             ISD::FMINNUM : ISD::FMINIMUM;
3347         break;
3348       }
3349       }
3350       break;
3351     case SPF_FMAXNUM:
3352       switch (SPR.NaNBehavior) {
3353       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3354       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3355       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3356       case SPNB_RETURNS_ANY:
3357 
3358         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3359           Opc = ISD::FMAXNUM;
3360         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3361           Opc = ISD::FMAXIMUM;
3362         else if (UseScalarMinMax)
3363           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3364             ISD::FMAXNUM : ISD::FMAXIMUM;
3365         break;
3366       }
3367       break;
3368     case SPF_ABS:
3369       IsUnaryAbs = true;
3370       Opc = ISD::ABS;
3371       break;
3372     case SPF_NABS:
3373       // TODO: we need to produce sub(0, abs(X)).
3374     default: break;
3375     }
3376 
3377     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3378         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3379          (UseScalarMinMax &&
3380           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3381         // If the underlying comparison instruction is used by any other
3382         // instruction, the consumed instructions won't be destroyed, so it is
3383         // not profitable to convert to a min/max.
3384         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3385       OpCode = Opc;
3386       LHSVal = getValue(LHS);
3387       RHSVal = getValue(RHS);
3388       BaseOps = {};
3389     }
3390 
3391     if (IsUnaryAbs) {
3392       OpCode = Opc;
3393       LHSVal = getValue(LHS);
3394       BaseOps = {};
3395     }
3396   }
3397 
3398   if (IsUnaryAbs) {
3399     for (unsigned i = 0; i != NumValues; ++i) {
3400       Values[i] =
3401           DAG.getNode(OpCode, getCurSDLoc(),
3402                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3403                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3404     }
3405   } else {
3406     for (unsigned i = 0; i != NumValues; ++i) {
3407       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3408       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3409       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3410       Values[i] = DAG.getNode(
3411           OpCode, getCurSDLoc(),
3412           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3413     }
3414   }
3415 
3416   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3417                            DAG.getVTList(ValueVTs), Values));
3418 }
3419 
3420 void SelectionDAGBuilder::visitTrunc(const User &I) {
3421   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3422   SDValue N = getValue(I.getOperand(0));
3423   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3424                                                         I.getType());
3425   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3426 }
3427 
3428 void SelectionDAGBuilder::visitZExt(const User &I) {
3429   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3430   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3431   SDValue N = getValue(I.getOperand(0));
3432   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3433                                                         I.getType());
3434   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3435 }
3436 
3437 void SelectionDAGBuilder::visitSExt(const User &I) {
3438   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3439   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3440   SDValue N = getValue(I.getOperand(0));
3441   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3442                                                         I.getType());
3443   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3444 }
3445 
3446 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3447   // FPTrunc is never a no-op cast, no need to check
3448   SDValue N = getValue(I.getOperand(0));
3449   SDLoc dl = getCurSDLoc();
3450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3451   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3452   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3453                            DAG.getTargetConstant(
3454                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3455 }
3456 
3457 void SelectionDAGBuilder::visitFPExt(const User &I) {
3458   // FPExt is never a no-op cast, no need to check
3459   SDValue N = getValue(I.getOperand(0));
3460   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3461                                                         I.getType());
3462   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3463 }
3464 
3465 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3466   // FPToUI is never a no-op cast, no need to check
3467   SDValue N = getValue(I.getOperand(0));
3468   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3469                                                         I.getType());
3470   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3471 }
3472 
3473 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3474   // FPToSI is never a no-op cast, no need to check
3475   SDValue N = getValue(I.getOperand(0));
3476   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3477                                                         I.getType());
3478   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3479 }
3480 
3481 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3482   // UIToFP is never a no-op cast, no need to check
3483   SDValue N = getValue(I.getOperand(0));
3484   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3485                                                         I.getType());
3486   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3487 }
3488 
3489 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3490   // SIToFP is never a no-op cast, no need to check
3491   SDValue N = getValue(I.getOperand(0));
3492   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3493                                                         I.getType());
3494   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3495 }
3496 
3497 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3498   // What to do depends on the size of the integer and the size of the pointer.
3499   // We can either truncate, zero extend, or no-op, accordingly.
3500   SDValue N = getValue(I.getOperand(0));
3501   auto &TLI = DAG.getTargetLoweringInfo();
3502   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3503                                                         I.getType());
3504   EVT PtrMemVT =
3505       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3506   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3507   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3508   setValue(&I, N);
3509 }
3510 
3511 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3512   // What to do depends on the size of the integer and the size of the pointer.
3513   // We can either truncate, zero extend, or no-op, accordingly.
3514   SDValue N = getValue(I.getOperand(0));
3515   auto &TLI = DAG.getTargetLoweringInfo();
3516   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3517   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3518   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3519   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3520   setValue(&I, N);
3521 }
3522 
3523 void SelectionDAGBuilder::visitBitCast(const User &I) {
3524   SDValue N = getValue(I.getOperand(0));
3525   SDLoc dl = getCurSDLoc();
3526   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3527                                                         I.getType());
3528 
3529   // BitCast assures us that source and destination are the same size so this is
3530   // either a BITCAST or a no-op.
3531   if (DestVT != N.getValueType())
3532     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3533                              DestVT, N)); // convert types.
3534   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3535   // might fold any kind of constant expression to an integer constant and that
3536   // is not what we are looking for. Only recognize a bitcast of a genuine
3537   // constant integer as an opaque constant.
3538   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3539     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3540                                  /*isOpaque*/true));
3541   else
3542     setValue(&I, N);            // noop cast.
3543 }
3544 
3545 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3547   const Value *SV = I.getOperand(0);
3548   SDValue N = getValue(SV);
3549   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3550 
3551   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3552   unsigned DestAS = I.getType()->getPointerAddressSpace();
3553 
3554   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3555     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3556 
3557   setValue(&I, N);
3558 }
3559 
3560 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3562   SDValue InVec = getValue(I.getOperand(0));
3563   SDValue InVal = getValue(I.getOperand(1));
3564   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3565                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3566   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3567                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3568                            InVec, InVal, InIdx));
3569 }
3570 
3571 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3573   SDValue InVec = getValue(I.getOperand(0));
3574   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3575                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3576   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3577                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3578                            InVec, InIdx));
3579 }
3580 
3581 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3582   SDValue Src1 = getValue(I.getOperand(0));
3583   SDValue Src2 = getValue(I.getOperand(1));
3584   Constant *MaskV = cast<Constant>(I.getOperand(2));
3585   SDLoc DL = getCurSDLoc();
3586   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3587   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3588   EVT SrcVT = Src1.getValueType();
3589   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3590 
3591   if (MaskV->isNullValue() && VT.isScalableVector()) {
3592     // Canonical splat form of first element of first input vector.
3593     SDValue FirstElt =
3594         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3595                     DAG.getVectorIdxConstant(0, DL));
3596     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3597     return;
3598   }
3599 
3600   // For now, we only handle splats for scalable vectors.
3601   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3602   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3603   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3604 
3605   SmallVector<int, 8> Mask;
3606   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3607   unsigned MaskNumElts = Mask.size();
3608 
3609   if (SrcNumElts == MaskNumElts) {
3610     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3611     return;
3612   }
3613 
3614   // Normalize the shuffle vector since mask and vector length don't match.
3615   if (SrcNumElts < MaskNumElts) {
3616     // Mask is longer than the source vectors. We can use concatenate vector to
3617     // make the mask and vectors lengths match.
3618 
3619     if (MaskNumElts % SrcNumElts == 0) {
3620       // Mask length is a multiple of the source vector length.
3621       // Check if the shuffle is some kind of concatenation of the input
3622       // vectors.
3623       unsigned NumConcat = MaskNumElts / SrcNumElts;
3624       bool IsConcat = true;
3625       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3626       for (unsigned i = 0; i != MaskNumElts; ++i) {
3627         int Idx = Mask[i];
3628         if (Idx < 0)
3629           continue;
3630         // Ensure the indices in each SrcVT sized piece are sequential and that
3631         // the same source is used for the whole piece.
3632         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3633             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3634              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3635           IsConcat = false;
3636           break;
3637         }
3638         // Remember which source this index came from.
3639         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3640       }
3641 
3642       // The shuffle is concatenating multiple vectors together. Just emit
3643       // a CONCAT_VECTORS operation.
3644       if (IsConcat) {
3645         SmallVector<SDValue, 8> ConcatOps;
3646         for (auto Src : ConcatSrcs) {
3647           if (Src < 0)
3648             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3649           else if (Src == 0)
3650             ConcatOps.push_back(Src1);
3651           else
3652             ConcatOps.push_back(Src2);
3653         }
3654         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3655         return;
3656       }
3657     }
3658 
3659     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3660     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3661     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3662                                     PaddedMaskNumElts);
3663 
3664     // Pad both vectors with undefs to make them the same length as the mask.
3665     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3666 
3667     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3668     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3669     MOps1[0] = Src1;
3670     MOps2[0] = Src2;
3671 
3672     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3673     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3674 
3675     // Readjust mask for new input vector length.
3676     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3677     for (unsigned i = 0; i != MaskNumElts; ++i) {
3678       int Idx = Mask[i];
3679       if (Idx >= (int)SrcNumElts)
3680         Idx -= SrcNumElts - PaddedMaskNumElts;
3681       MappedOps[i] = Idx;
3682     }
3683 
3684     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3685 
3686     // If the concatenated vector was padded, extract a subvector with the
3687     // correct number of elements.
3688     if (MaskNumElts != PaddedMaskNumElts)
3689       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3690                            DAG.getVectorIdxConstant(0, DL));
3691 
3692     setValue(&I, Result);
3693     return;
3694   }
3695 
3696   if (SrcNumElts > MaskNumElts) {
3697     // Analyze the access pattern of the vector to see if we can extract
3698     // two subvectors and do the shuffle.
3699     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3700     bool CanExtract = true;
3701     for (int Idx : Mask) {
3702       unsigned Input = 0;
3703       if (Idx < 0)
3704         continue;
3705 
3706       if (Idx >= (int)SrcNumElts) {
3707         Input = 1;
3708         Idx -= SrcNumElts;
3709       }
3710 
3711       // If all the indices come from the same MaskNumElts sized portion of
3712       // the sources we can use extract. Also make sure the extract wouldn't
3713       // extract past the end of the source.
3714       int NewStartIdx = alignDown(Idx, MaskNumElts);
3715       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3716           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3717         CanExtract = false;
3718       // Make sure we always update StartIdx as we use it to track if all
3719       // elements are undef.
3720       StartIdx[Input] = NewStartIdx;
3721     }
3722 
3723     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3724       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3725       return;
3726     }
3727     if (CanExtract) {
3728       // Extract appropriate subvector and generate a vector shuffle
3729       for (unsigned Input = 0; Input < 2; ++Input) {
3730         SDValue &Src = Input == 0 ? Src1 : Src2;
3731         if (StartIdx[Input] < 0)
3732           Src = DAG.getUNDEF(VT);
3733         else {
3734           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3735                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3736         }
3737       }
3738 
3739       // Calculate new mask.
3740       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3741       for (int &Idx : MappedOps) {
3742         if (Idx >= (int)SrcNumElts)
3743           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3744         else if (Idx >= 0)
3745           Idx -= StartIdx[0];
3746       }
3747 
3748       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3749       return;
3750     }
3751   }
3752 
3753   // We can't use either concat vectors or extract subvectors so fall back to
3754   // replacing the shuffle with extract and build vector.
3755   // to insert and build vector.
3756   EVT EltVT = VT.getVectorElementType();
3757   SmallVector<SDValue,8> Ops;
3758   for (int Idx : Mask) {
3759     SDValue Res;
3760 
3761     if (Idx < 0) {
3762       Res = DAG.getUNDEF(EltVT);
3763     } else {
3764       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3765       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3766 
3767       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3768                         DAG.getVectorIdxConstant(Idx, DL));
3769     }
3770 
3771     Ops.push_back(Res);
3772   }
3773 
3774   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3775 }
3776 
3777 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3778   ArrayRef<unsigned> Indices;
3779   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3780     Indices = IV->getIndices();
3781   else
3782     Indices = cast<ConstantExpr>(&I)->getIndices();
3783 
3784   const Value *Op0 = I.getOperand(0);
3785   const Value *Op1 = I.getOperand(1);
3786   Type *AggTy = I.getType();
3787   Type *ValTy = Op1->getType();
3788   bool IntoUndef = isa<UndefValue>(Op0);
3789   bool FromUndef = isa<UndefValue>(Op1);
3790 
3791   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3792 
3793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3794   SmallVector<EVT, 4> AggValueVTs;
3795   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3796   SmallVector<EVT, 4> ValValueVTs;
3797   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3798 
3799   unsigned NumAggValues = AggValueVTs.size();
3800   unsigned NumValValues = ValValueVTs.size();
3801   SmallVector<SDValue, 4> Values(NumAggValues);
3802 
3803   // Ignore an insertvalue that produces an empty object
3804   if (!NumAggValues) {
3805     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3806     return;
3807   }
3808 
3809   SDValue Agg = getValue(Op0);
3810   unsigned i = 0;
3811   // Copy the beginning value(s) from the original aggregate.
3812   for (; i != LinearIndex; ++i)
3813     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3814                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3815   // Copy values from the inserted value(s).
3816   if (NumValValues) {
3817     SDValue Val = getValue(Op1);
3818     for (; i != LinearIndex + NumValValues; ++i)
3819       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3820                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3821   }
3822   // Copy remaining value(s) from the original aggregate.
3823   for (; i != NumAggValues; ++i)
3824     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3825                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3826 
3827   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3828                            DAG.getVTList(AggValueVTs), Values));
3829 }
3830 
3831 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3832   ArrayRef<unsigned> Indices;
3833   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3834     Indices = EV->getIndices();
3835   else
3836     Indices = cast<ConstantExpr>(&I)->getIndices();
3837 
3838   const Value *Op0 = I.getOperand(0);
3839   Type *AggTy = Op0->getType();
3840   Type *ValTy = I.getType();
3841   bool OutOfUndef = isa<UndefValue>(Op0);
3842 
3843   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3844 
3845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3846   SmallVector<EVT, 4> ValValueVTs;
3847   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3848 
3849   unsigned NumValValues = ValValueVTs.size();
3850 
3851   // Ignore a extractvalue that produces an empty object
3852   if (!NumValValues) {
3853     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3854     return;
3855   }
3856 
3857   SmallVector<SDValue, 4> Values(NumValValues);
3858 
3859   SDValue Agg = getValue(Op0);
3860   // Copy out the selected value(s).
3861   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3862     Values[i - LinearIndex] =
3863       OutOfUndef ?
3864         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3865         SDValue(Agg.getNode(), Agg.getResNo() + i);
3866 
3867   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3868                            DAG.getVTList(ValValueVTs), Values));
3869 }
3870 
3871 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3872   Value *Op0 = I.getOperand(0);
3873   // Note that the pointer operand may be a vector of pointers. Take the scalar
3874   // element which holds a pointer.
3875   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3876   SDValue N = getValue(Op0);
3877   SDLoc dl = getCurSDLoc();
3878   auto &TLI = DAG.getTargetLoweringInfo();
3879   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3880   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3881 
3882   // Normalize Vector GEP - all scalar operands should be converted to the
3883   // splat vector.
3884   unsigned VectorWidth = I.getType()->isVectorTy() ?
3885     I.getType()->getVectorNumElements() : 0;
3886 
3887   if (VectorWidth && !N.getValueType().isVector()) {
3888     LLVMContext &Context = *DAG.getContext();
3889     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3890     N = DAG.getSplatBuildVector(VT, dl, N);
3891   }
3892 
3893   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3894        GTI != E; ++GTI) {
3895     const Value *Idx = GTI.getOperand();
3896     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3897       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3898       if (Field) {
3899         // N = N + Offset
3900         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3901 
3902         // In an inbounds GEP with an offset that is nonnegative even when
3903         // interpreted as signed, assume there is no unsigned overflow.
3904         SDNodeFlags Flags;
3905         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3906           Flags.setNoUnsignedWrap(true);
3907 
3908         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3909                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3910       }
3911     } else {
3912       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3913       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3914       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3915 
3916       // If this is a scalar constant or a splat vector of constants,
3917       // handle it quickly.
3918       const auto *C = dyn_cast<Constant>(Idx);
3919       if (C && isa<VectorType>(C->getType()))
3920         C = C->getSplatValue();
3921 
3922       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3923         if (CI->isZero())
3924           continue;
3925         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3926         LLVMContext &Context = *DAG.getContext();
3927         SDValue OffsVal = VectorWidth ?
3928           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3929           DAG.getConstant(Offs, dl, IdxTy);
3930 
3931         // In an inbounds GEP with an offset that is nonnegative even when
3932         // interpreted as signed, assume there is no unsigned overflow.
3933         SDNodeFlags Flags;
3934         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3935           Flags.setNoUnsignedWrap(true);
3936 
3937         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3938 
3939         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3940         continue;
3941       }
3942 
3943       // N = N + Idx * ElementSize;
3944       SDValue IdxN = getValue(Idx);
3945 
3946       if (!IdxN.getValueType().isVector() && VectorWidth) {
3947         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3948         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3949       }
3950 
3951       // If the index is smaller or larger than intptr_t, truncate or extend
3952       // it.
3953       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3954 
3955       // If this is a multiply by a power of two, turn it into a shl
3956       // immediately.  This is a very common case.
3957       if (ElementSize != 1) {
3958         if (ElementSize.isPowerOf2()) {
3959           unsigned Amt = ElementSize.logBase2();
3960           IdxN = DAG.getNode(ISD::SHL, dl,
3961                              N.getValueType(), IdxN,
3962                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3963         } else {
3964           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3965                                           IdxN.getValueType());
3966           IdxN = DAG.getNode(ISD::MUL, dl,
3967                              N.getValueType(), IdxN, Scale);
3968         }
3969       }
3970 
3971       N = DAG.getNode(ISD::ADD, dl,
3972                       N.getValueType(), N, IdxN);
3973     }
3974   }
3975 
3976   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3977     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3978 
3979   setValue(&I, N);
3980 }
3981 
3982 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3983   // If this is a fixed sized alloca in the entry block of the function,
3984   // allocate it statically on the stack.
3985   if (FuncInfo.StaticAllocaMap.count(&I))
3986     return;   // getValue will auto-populate this.
3987 
3988   SDLoc dl = getCurSDLoc();
3989   Type *Ty = I.getAllocatedType();
3990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3991   auto &DL = DAG.getDataLayout();
3992   uint64_t TySize = DL.getTypeAllocSize(Ty);
3993   unsigned Align =
3994       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3995 
3996   SDValue AllocSize = getValue(I.getArraySize());
3997 
3998   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3999   if (AllocSize.getValueType() != IntPtr)
4000     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4001 
4002   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4003                           AllocSize,
4004                           DAG.getConstant(TySize, dl, IntPtr));
4005 
4006   // Handle alignment.  If the requested alignment is less than or equal to
4007   // the stack alignment, ignore it.  If the size is greater than or equal to
4008   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4009   unsigned StackAlign =
4010       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4011   if (Align <= StackAlign)
4012     Align = 0;
4013 
4014   // Round the size of the allocation up to the stack alignment size
4015   // by add SA-1 to the size. This doesn't overflow because we're computing
4016   // an address inside an alloca.
4017   SDNodeFlags Flags;
4018   Flags.setNoUnsignedWrap(true);
4019   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4020                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4021 
4022   // Mask out the low bits for alignment purposes.
4023   AllocSize =
4024       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4025                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4026 
4027   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4028   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4029   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4030   setValue(&I, DSA);
4031   DAG.setRoot(DSA.getValue(1));
4032 
4033   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4034 }
4035 
4036 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4037   if (I.isAtomic())
4038     return visitAtomicLoad(I);
4039 
4040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4041   const Value *SV = I.getOperand(0);
4042   if (TLI.supportSwiftError()) {
4043     // Swifterror values can come from either a function parameter with
4044     // swifterror attribute or an alloca with swifterror attribute.
4045     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4046       if (Arg->hasSwiftErrorAttr())
4047         return visitLoadFromSwiftError(I);
4048     }
4049 
4050     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4051       if (Alloca->isSwiftError())
4052         return visitLoadFromSwiftError(I);
4053     }
4054   }
4055 
4056   SDValue Ptr = getValue(SV);
4057 
4058   Type *Ty = I.getType();
4059   unsigned Alignment = I.getAlignment();
4060 
4061   AAMDNodes AAInfo;
4062   I.getAAMetadata(AAInfo);
4063   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4064 
4065   SmallVector<EVT, 4> ValueVTs, MemVTs;
4066   SmallVector<uint64_t, 4> Offsets;
4067   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4068   unsigned NumValues = ValueVTs.size();
4069   if (NumValues == 0)
4070     return;
4071 
4072   bool isVolatile = I.isVolatile();
4073 
4074   SDValue Root;
4075   bool ConstantMemory = false;
4076   if (isVolatile)
4077     // Serialize volatile loads with other side effects.
4078     Root = getRoot();
4079   else if (NumValues > MaxParallelChains)
4080     Root = getMemoryRoot();
4081   else if (AA &&
4082            AA->pointsToConstantMemory(MemoryLocation(
4083                SV,
4084                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4085                AAInfo))) {
4086     // Do not serialize (non-volatile) loads of constant memory with anything.
4087     Root = DAG.getEntryNode();
4088     ConstantMemory = true;
4089   } else {
4090     // Do not serialize non-volatile loads against each other.
4091     Root = DAG.getRoot();
4092   }
4093 
4094   SDLoc dl = getCurSDLoc();
4095 
4096   if (isVolatile)
4097     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4098 
4099   // An aggregate load cannot wrap around the address space, so offsets to its
4100   // parts don't wrap either.
4101   SDNodeFlags Flags;
4102   Flags.setNoUnsignedWrap(true);
4103 
4104   SmallVector<SDValue, 4> Values(NumValues);
4105   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4106   EVT PtrVT = Ptr.getValueType();
4107 
4108   MachineMemOperand::Flags MMOFlags
4109     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4110 
4111   unsigned ChainI = 0;
4112   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4113     // Serializing loads here may result in excessive register pressure, and
4114     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4115     // could recover a bit by hoisting nodes upward in the chain by recognizing
4116     // they are side-effect free or do not alias. The optimizer should really
4117     // avoid this case by converting large object/array copies to llvm.memcpy
4118     // (MaxParallelChains should always remain as failsafe).
4119     if (ChainI == MaxParallelChains) {
4120       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4121       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4122                                   makeArrayRef(Chains.data(), ChainI));
4123       Root = Chain;
4124       ChainI = 0;
4125     }
4126     SDValue A = DAG.getNode(ISD::ADD, dl,
4127                             PtrVT, Ptr,
4128                             DAG.getConstant(Offsets[i], dl, PtrVT),
4129                             Flags);
4130 
4131     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4132                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4133                             MMOFlags, AAInfo, Ranges);
4134     Chains[ChainI] = L.getValue(1);
4135 
4136     if (MemVTs[i] != ValueVTs[i])
4137       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4138 
4139     Values[i] = L;
4140   }
4141 
4142   if (!ConstantMemory) {
4143     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4144                                 makeArrayRef(Chains.data(), ChainI));
4145     if (isVolatile)
4146       DAG.setRoot(Chain);
4147     else
4148       PendingLoads.push_back(Chain);
4149   }
4150 
4151   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4152                            DAG.getVTList(ValueVTs), Values));
4153 }
4154 
4155 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4156   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4157          "call visitStoreToSwiftError when backend supports swifterror");
4158 
4159   SmallVector<EVT, 4> ValueVTs;
4160   SmallVector<uint64_t, 4> Offsets;
4161   const Value *SrcV = I.getOperand(0);
4162   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4163                   SrcV->getType(), ValueVTs, &Offsets);
4164   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4165          "expect a single EVT for swifterror");
4166 
4167   SDValue Src = getValue(SrcV);
4168   // Create a virtual register, then update the virtual register.
4169   Register VReg =
4170       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4171   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4172   // Chain can be getRoot or getControlRoot.
4173   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4174                                       SDValue(Src.getNode(), Src.getResNo()));
4175   DAG.setRoot(CopyNode);
4176 }
4177 
4178 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4179   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4180          "call visitLoadFromSwiftError when backend supports swifterror");
4181 
4182   assert(!I.isVolatile() &&
4183          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4184          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4185          "Support volatile, non temporal, invariant for load_from_swift_error");
4186 
4187   const Value *SV = I.getOperand(0);
4188   Type *Ty = I.getType();
4189   AAMDNodes AAInfo;
4190   I.getAAMetadata(AAInfo);
4191   assert(
4192       (!AA ||
4193        !AA->pointsToConstantMemory(MemoryLocation(
4194            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4195            AAInfo))) &&
4196       "load_from_swift_error should not be constant memory");
4197 
4198   SmallVector<EVT, 4> ValueVTs;
4199   SmallVector<uint64_t, 4> Offsets;
4200   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4201                   ValueVTs, &Offsets);
4202   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4203          "expect a single EVT for swifterror");
4204 
4205   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4206   SDValue L = DAG.getCopyFromReg(
4207       getRoot(), getCurSDLoc(),
4208       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4209 
4210   setValue(&I, L);
4211 }
4212 
4213 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4214   if (I.isAtomic())
4215     return visitAtomicStore(I);
4216 
4217   const Value *SrcV = I.getOperand(0);
4218   const Value *PtrV = I.getOperand(1);
4219 
4220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4221   if (TLI.supportSwiftError()) {
4222     // Swifterror values can come from either a function parameter with
4223     // swifterror attribute or an alloca with swifterror attribute.
4224     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4225       if (Arg->hasSwiftErrorAttr())
4226         return visitStoreToSwiftError(I);
4227     }
4228 
4229     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4230       if (Alloca->isSwiftError())
4231         return visitStoreToSwiftError(I);
4232     }
4233   }
4234 
4235   SmallVector<EVT, 4> ValueVTs, MemVTs;
4236   SmallVector<uint64_t, 4> Offsets;
4237   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4238                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4239   unsigned NumValues = ValueVTs.size();
4240   if (NumValues == 0)
4241     return;
4242 
4243   // Get the lowered operands. Note that we do this after
4244   // checking if NumResults is zero, because with zero results
4245   // the operands won't have values in the map.
4246   SDValue Src = getValue(SrcV);
4247   SDValue Ptr = getValue(PtrV);
4248 
4249   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4250   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4251   SDLoc dl = getCurSDLoc();
4252   unsigned Alignment = I.getAlignment();
4253   AAMDNodes AAInfo;
4254   I.getAAMetadata(AAInfo);
4255 
4256   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4257 
4258   // An aggregate load cannot wrap around the address space, so offsets to its
4259   // parts don't wrap either.
4260   SDNodeFlags Flags;
4261   Flags.setNoUnsignedWrap(true);
4262 
4263   unsigned ChainI = 0;
4264   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4265     // See visitLoad comments.
4266     if (ChainI == MaxParallelChains) {
4267       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4268                                   makeArrayRef(Chains.data(), ChainI));
4269       Root = Chain;
4270       ChainI = 0;
4271     }
4272     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4273     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4274     if (MemVTs[i] != ValueVTs[i])
4275       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4276     SDValue St =
4277         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4278                      Alignment, MMOFlags, AAInfo);
4279     Chains[ChainI] = St;
4280   }
4281 
4282   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4283                                   makeArrayRef(Chains.data(), ChainI));
4284   DAG.setRoot(StoreNode);
4285 }
4286 
4287 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4288                                            bool IsCompressing) {
4289   SDLoc sdl = getCurSDLoc();
4290 
4291   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4292                            unsigned& Alignment) {
4293     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4294     Src0 = I.getArgOperand(0);
4295     Ptr = I.getArgOperand(1);
4296     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4297     Mask = I.getArgOperand(3);
4298   };
4299   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4300                            unsigned& Alignment) {
4301     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4302     Src0 = I.getArgOperand(0);
4303     Ptr = I.getArgOperand(1);
4304     Mask = I.getArgOperand(2);
4305     Alignment = 0;
4306   };
4307 
4308   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4309   unsigned Alignment;
4310   if (IsCompressing)
4311     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4312   else
4313     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4314 
4315   SDValue Ptr = getValue(PtrOperand);
4316   SDValue Src0 = getValue(Src0Operand);
4317   SDValue Mask = getValue(MaskOperand);
4318   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4319 
4320   EVT VT = Src0.getValueType();
4321   if (!Alignment)
4322     Alignment = DAG.getEVTAlignment(VT);
4323 
4324   AAMDNodes AAInfo;
4325   I.getAAMetadata(AAInfo);
4326 
4327   MachineMemOperand *MMO =
4328     DAG.getMachineFunction().
4329     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4330                           MachineMemOperand::MOStore,
4331                           // TODO: Make MachineMemOperands aware of scalable
4332                           // vectors.
4333                           VT.getStoreSize().getKnownMinSize(),
4334                           Alignment, AAInfo);
4335   SDValue StoreNode =
4336       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4337                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4338   DAG.setRoot(StoreNode);
4339   setValue(&I, StoreNode);
4340 }
4341 
4342 // Get a uniform base for the Gather/Scatter intrinsic.
4343 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4344 // We try to represent it as a base pointer + vector of indices.
4345 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4346 // The first operand of the GEP may be a single pointer or a vector of pointers
4347 // Example:
4348 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4349 //  or
4350 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4351 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4352 //
4353 // When the first GEP operand is a single pointer - it is the uniform base we
4354 // are looking for. If first operand of the GEP is a splat vector - we
4355 // extract the splat value and use it as a uniform base.
4356 // In all other cases the function returns 'false'.
4357 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4358                            ISD::MemIndexType &IndexType, SDValue &Scale,
4359                            SelectionDAGBuilder *SDB) {
4360   SelectionDAG& DAG = SDB->DAG;
4361   LLVMContext &Context = *DAG.getContext();
4362 
4363   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4364   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4365   if (!GEP)
4366     return false;
4367 
4368   const Value *GEPPtr = GEP->getPointerOperand();
4369   if (!GEPPtr->getType()->isVectorTy())
4370     Ptr = GEPPtr;
4371   else if (!(Ptr = getSplatValue(GEPPtr)))
4372     return false;
4373 
4374   unsigned FinalIndex = GEP->getNumOperands() - 1;
4375   Value *IndexVal = GEP->getOperand(FinalIndex);
4376   gep_type_iterator GTI = gep_type_begin(*GEP);
4377 
4378   // Ensure all the other indices are 0.
4379   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4380     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4381     if (!C)
4382       return false;
4383     if (isa<VectorType>(C->getType()))
4384       C = C->getSplatValue();
4385     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4386     if (!CI || !CI->isZero())
4387       return false;
4388   }
4389 
4390   // The operands of the GEP may be defined in another basic block.
4391   // In this case we'll not find nodes for the operands.
4392   if (!SDB->findValue(Ptr))
4393     return false;
4394   Constant *C = dyn_cast<Constant>(IndexVal);
4395   if (!C && !SDB->findValue(IndexVal))
4396     return false;
4397 
4398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4399   const DataLayout &DL = DAG.getDataLayout();
4400   StructType *STy = GTI.getStructTypeOrNull();
4401 
4402   if (STy) {
4403     const StructLayout *SL = DL.getStructLayout(STy);
4404     if (isa<VectorType>(C->getType())) {
4405       C = C->getSplatValue();
4406       // FIXME: If getSplatValue may return nullptr for a structure?
4407       // If not, the following check can be removed.
4408       if (!C)
4409         return false;
4410     }
4411     auto *CI = cast<ConstantInt>(C);
4412     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4413     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4414                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4415   } else {
4416     Scale = DAG.getTargetConstant(
4417                 DL.getTypeAllocSize(GEP->getResultElementType()),
4418                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4419     Index = SDB->getValue(IndexVal);
4420   }
4421   Base = SDB->getValue(Ptr);
4422   IndexType = ISD::SIGNED_SCALED;
4423 
4424   if (STy || !Index.getValueType().isVector()) {
4425     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4426     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4427     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4428   }
4429   return true;
4430 }
4431 
4432 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4433   SDLoc sdl = getCurSDLoc();
4434 
4435   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4436   const Value *Ptr = I.getArgOperand(1);
4437   SDValue Src0 = getValue(I.getArgOperand(0));
4438   SDValue Mask = getValue(I.getArgOperand(3));
4439   EVT VT = Src0.getValueType();
4440   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4441   if (!Alignment)
4442     Alignment = DAG.getEVTAlignment(VT);
4443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4444 
4445   AAMDNodes AAInfo;
4446   I.getAAMetadata(AAInfo);
4447 
4448   SDValue Base;
4449   SDValue Index;
4450   ISD::MemIndexType IndexType;
4451   SDValue Scale;
4452   const Value *BasePtr = Ptr;
4453   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4454                                     this);
4455 
4456   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4457   MachineMemOperand *MMO = DAG.getMachineFunction().
4458     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4459                          MachineMemOperand::MOStore,
4460                          // TODO: Make MachineMemOperands aware of scalable
4461                          // vectors.
4462                          VT.getStoreSize().getKnownMinSize(),
4463                          Alignment, AAInfo);
4464   if (!UniformBase) {
4465     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4466     Index = getValue(Ptr);
4467     IndexType = ISD::SIGNED_SCALED;
4468     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4469   }
4470   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4471   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4472                                          Ops, MMO, IndexType);
4473   DAG.setRoot(Scatter);
4474   setValue(&I, Scatter);
4475 }
4476 
4477 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4478   SDLoc sdl = getCurSDLoc();
4479 
4480   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4481                            unsigned& Alignment) {
4482     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4483     Ptr = I.getArgOperand(0);
4484     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4485     Mask = I.getArgOperand(2);
4486     Src0 = I.getArgOperand(3);
4487   };
4488   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4489                            unsigned& Alignment) {
4490     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4491     Ptr = I.getArgOperand(0);
4492     Alignment = 0;
4493     Mask = I.getArgOperand(1);
4494     Src0 = I.getArgOperand(2);
4495   };
4496 
4497   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4498   unsigned Alignment;
4499   if (IsExpanding)
4500     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4501   else
4502     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4503 
4504   SDValue Ptr = getValue(PtrOperand);
4505   SDValue Src0 = getValue(Src0Operand);
4506   SDValue Mask = getValue(MaskOperand);
4507   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4508 
4509   EVT VT = Src0.getValueType();
4510   if (!Alignment)
4511     Alignment = DAG.getEVTAlignment(VT);
4512 
4513   AAMDNodes AAInfo;
4514   I.getAAMetadata(AAInfo);
4515   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4516 
4517   // Do not serialize masked loads of constant memory with anything.
4518   MemoryLocation ML;
4519   if (VT.isScalableVector())
4520     ML = MemoryLocation(PtrOperand);
4521   else
4522     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4523                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4524                            AAInfo);
4525   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4526 
4527   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4528 
4529   MachineMemOperand *MMO =
4530     DAG.getMachineFunction().
4531     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4532                           MachineMemOperand::MOLoad,
4533                           // TODO: Make MachineMemOperands aware of scalable
4534                           // vectors.
4535                           VT.getStoreSize().getKnownMinSize(),
4536                           Alignment, AAInfo, Ranges);
4537 
4538   SDValue Load =
4539       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4540                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4541   if (AddToChain)
4542     PendingLoads.push_back(Load.getValue(1));
4543   setValue(&I, Load);
4544 }
4545 
4546 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4547   SDLoc sdl = getCurSDLoc();
4548 
4549   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4550   const Value *Ptr = I.getArgOperand(0);
4551   SDValue Src0 = getValue(I.getArgOperand(3));
4552   SDValue Mask = getValue(I.getArgOperand(2));
4553 
4554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4555   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4556   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4557   if (!Alignment)
4558     Alignment = DAG.getEVTAlignment(VT);
4559 
4560   AAMDNodes AAInfo;
4561   I.getAAMetadata(AAInfo);
4562   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4563 
4564   SDValue Root = DAG.getRoot();
4565   SDValue Base;
4566   SDValue Index;
4567   ISD::MemIndexType IndexType;
4568   SDValue Scale;
4569   const Value *BasePtr = Ptr;
4570   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4571                                     this);
4572   bool ConstantMemory = false;
4573   if (UniformBase && AA &&
4574       AA->pointsToConstantMemory(
4575           MemoryLocation(BasePtr,
4576                          LocationSize::precise(
4577                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4578                          AAInfo))) {
4579     // Do not serialize (non-volatile) loads of constant memory with anything.
4580     Root = DAG.getEntryNode();
4581     ConstantMemory = true;
4582   }
4583 
4584   MachineMemOperand *MMO =
4585     DAG.getMachineFunction().
4586     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4587                          MachineMemOperand::MOLoad,
4588                          // TODO: Make MachineMemOperands aware of scalable
4589                          // vectors.
4590                          VT.getStoreSize().getKnownMinSize(),
4591                          Alignment, AAInfo, Ranges);
4592 
4593   if (!UniformBase) {
4594     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4595     Index = getValue(Ptr);
4596     IndexType = ISD::SIGNED_SCALED;
4597     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4598   }
4599   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4600   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4601                                        Ops, MMO, IndexType);
4602 
4603   SDValue OutChain = Gather.getValue(1);
4604   if (!ConstantMemory)
4605     PendingLoads.push_back(OutChain);
4606   setValue(&I, Gather);
4607 }
4608 
4609 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4610   SDLoc dl = getCurSDLoc();
4611   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4612   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4613   SyncScope::ID SSID = I.getSyncScopeID();
4614 
4615   SDValue InChain = getRoot();
4616 
4617   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4618   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4619 
4620   auto Alignment = DAG.getEVTAlignment(MemVT);
4621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4622   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4623 
4624   MachineFunction &MF = DAG.getMachineFunction();
4625   MachineMemOperand *MMO =
4626     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4627                             Flags, MemVT.getStoreSize(), Alignment,
4628                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4629                             FailureOrdering);
4630 
4631   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4632                                    dl, MemVT, VTs, InChain,
4633                                    getValue(I.getPointerOperand()),
4634                                    getValue(I.getCompareOperand()),
4635                                    getValue(I.getNewValOperand()), MMO);
4636 
4637   SDValue OutChain = L.getValue(2);
4638 
4639   setValue(&I, L);
4640   DAG.setRoot(OutChain);
4641 }
4642 
4643 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4644   SDLoc dl = getCurSDLoc();
4645   ISD::NodeType NT;
4646   switch (I.getOperation()) {
4647   default: llvm_unreachable("Unknown atomicrmw operation");
4648   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4649   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4650   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4651   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4652   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4653   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4654   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4655   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4656   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4657   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4658   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4659   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4660   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4661   }
4662   AtomicOrdering Ordering = I.getOrdering();
4663   SyncScope::ID SSID = I.getSyncScopeID();
4664 
4665   SDValue InChain = getRoot();
4666 
4667   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4668   auto Alignment = DAG.getEVTAlignment(MemVT);
4669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4670   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4671 
4672   MachineFunction &MF = DAG.getMachineFunction();
4673   MachineMemOperand *MMO =
4674     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4675                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4676                             nullptr, SSID, Ordering);
4677 
4678   SDValue L =
4679     DAG.getAtomic(NT, dl, MemVT, InChain,
4680                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4681                   MMO);
4682 
4683   SDValue OutChain = L.getValue(1);
4684 
4685   setValue(&I, L);
4686   DAG.setRoot(OutChain);
4687 }
4688 
4689 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4690   SDLoc dl = getCurSDLoc();
4691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4692   SDValue Ops[3];
4693   Ops[0] = getRoot();
4694   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4695                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4696   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4697                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4698   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4699 }
4700 
4701 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4702   SDLoc dl = getCurSDLoc();
4703   AtomicOrdering Order = I.getOrdering();
4704   SyncScope::ID SSID = I.getSyncScopeID();
4705 
4706   SDValue InChain = getRoot();
4707 
4708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4709   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4710   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4711 
4712   if (!TLI.supportsUnalignedAtomics() &&
4713       I.getAlignment() < MemVT.getSizeInBits() / 8)
4714     report_fatal_error("Cannot generate unaligned atomic load");
4715 
4716   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4717 
4718   MachineMemOperand *MMO =
4719       DAG.getMachineFunction().
4720       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4721                            Flags, MemVT.getStoreSize(),
4722                            I.getAlignment() ? I.getAlignment() :
4723                                               DAG.getEVTAlignment(MemVT),
4724                            AAMDNodes(), nullptr, SSID, Order);
4725 
4726   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4727 
4728   SDValue Ptr = getValue(I.getPointerOperand());
4729 
4730   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4731     // TODO: Once this is better exercised by tests, it should be merged with
4732     // the normal path for loads to prevent future divergence.
4733     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4734     if (MemVT != VT)
4735       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4736 
4737     setValue(&I, L);
4738     SDValue OutChain = L.getValue(1);
4739     if (!I.isUnordered())
4740       DAG.setRoot(OutChain);
4741     else
4742       PendingLoads.push_back(OutChain);
4743     return;
4744   }
4745 
4746   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4747                             Ptr, MMO);
4748 
4749   SDValue OutChain = L.getValue(1);
4750   if (MemVT != VT)
4751     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4752 
4753   setValue(&I, L);
4754   DAG.setRoot(OutChain);
4755 }
4756 
4757 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4758   SDLoc dl = getCurSDLoc();
4759 
4760   AtomicOrdering Ordering = I.getOrdering();
4761   SyncScope::ID SSID = I.getSyncScopeID();
4762 
4763   SDValue InChain = getRoot();
4764 
4765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4766   EVT MemVT =
4767       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4768 
4769   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4770     report_fatal_error("Cannot generate unaligned atomic store");
4771 
4772   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4773 
4774   MachineFunction &MF = DAG.getMachineFunction();
4775   MachineMemOperand *MMO =
4776     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4777                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4778                             nullptr, SSID, Ordering);
4779 
4780   SDValue Val = getValue(I.getValueOperand());
4781   if (Val.getValueType() != MemVT)
4782     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4783   SDValue Ptr = getValue(I.getPointerOperand());
4784 
4785   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4786     // TODO: Once this is better exercised by tests, it should be merged with
4787     // the normal path for stores to prevent future divergence.
4788     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4789     DAG.setRoot(S);
4790     return;
4791   }
4792   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4793                                    Ptr, Val, MMO);
4794 
4795 
4796   DAG.setRoot(OutChain);
4797 }
4798 
4799 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4800 /// node.
4801 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4802                                                unsigned Intrinsic) {
4803   // Ignore the callsite's attributes. A specific call site may be marked with
4804   // readnone, but the lowering code will expect the chain based on the
4805   // definition.
4806   const Function *F = I.getCalledFunction();
4807   bool HasChain = !F->doesNotAccessMemory();
4808   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4809 
4810   // Build the operand list.
4811   SmallVector<SDValue, 8> Ops;
4812   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4813     if (OnlyLoad) {
4814       // We don't need to serialize loads against other loads.
4815       Ops.push_back(DAG.getRoot());
4816     } else {
4817       Ops.push_back(getRoot());
4818     }
4819   }
4820 
4821   // Info is set by getTgtMemInstrinsic
4822   TargetLowering::IntrinsicInfo Info;
4823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4824   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4825                                                DAG.getMachineFunction(),
4826                                                Intrinsic);
4827 
4828   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4829   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4830       Info.opc == ISD::INTRINSIC_W_CHAIN)
4831     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4832                                         TLI.getPointerTy(DAG.getDataLayout())));
4833 
4834   // Add all operands of the call to the operand list.
4835   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4836     const Value *Arg = I.getArgOperand(i);
4837     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4838       Ops.push_back(getValue(Arg));
4839       continue;
4840     }
4841 
4842     // Use TargetConstant instead of a regular constant for immarg.
4843     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4844     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4845       assert(CI->getBitWidth() <= 64 &&
4846              "large intrinsic immediates not handled");
4847       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4848     } else {
4849       Ops.push_back(
4850           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4851     }
4852   }
4853 
4854   SmallVector<EVT, 4> ValueVTs;
4855   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4856 
4857   if (HasChain)
4858     ValueVTs.push_back(MVT::Other);
4859 
4860   SDVTList VTs = DAG.getVTList(ValueVTs);
4861 
4862   // Create the node.
4863   SDValue Result;
4864   if (IsTgtIntrinsic) {
4865     // This is target intrinsic that touches memory
4866     AAMDNodes AAInfo;
4867     I.getAAMetadata(AAInfo);
4868     Result = DAG.getMemIntrinsicNode(
4869         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4870         MachinePointerInfo(Info.ptrVal, Info.offset),
4871         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4872   } else if (!HasChain) {
4873     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4874   } else if (!I.getType()->isVoidTy()) {
4875     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4876   } else {
4877     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4878   }
4879 
4880   if (HasChain) {
4881     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4882     if (OnlyLoad)
4883       PendingLoads.push_back(Chain);
4884     else
4885       DAG.setRoot(Chain);
4886   }
4887 
4888   if (!I.getType()->isVoidTy()) {
4889     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4890       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4891       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4892     } else
4893       Result = lowerRangeToAssertZExt(DAG, I, Result);
4894 
4895     setValue(&I, Result);
4896   }
4897 }
4898 
4899 /// GetSignificand - Get the significand and build it into a floating-point
4900 /// number with exponent of 1:
4901 ///
4902 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4903 ///
4904 /// where Op is the hexadecimal representation of floating point value.
4905 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4906   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4907                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4908   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4909                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4910   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4911 }
4912 
4913 /// GetExponent - Get the exponent:
4914 ///
4915 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4916 ///
4917 /// where Op is the hexadecimal representation of floating point value.
4918 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4919                            const TargetLowering &TLI, const SDLoc &dl) {
4920   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4921                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4922   SDValue t1 = DAG.getNode(
4923       ISD::SRL, dl, MVT::i32, t0,
4924       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4925   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4926                            DAG.getConstant(127, dl, MVT::i32));
4927   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4928 }
4929 
4930 /// getF32Constant - Get 32-bit floating point constant.
4931 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4932                               const SDLoc &dl) {
4933   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4934                            MVT::f32);
4935 }
4936 
4937 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4938                                        SelectionDAG &DAG) {
4939   // TODO: What fast-math-flags should be set on the floating-point nodes?
4940 
4941   //   IntegerPartOfX = ((int32_t)(t0);
4942   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4943 
4944   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4945   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4946   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4947 
4948   //   IntegerPartOfX <<= 23;
4949   IntegerPartOfX = DAG.getNode(
4950       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4951       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4952                                   DAG.getDataLayout())));
4953 
4954   SDValue TwoToFractionalPartOfX;
4955   if (LimitFloatPrecision <= 6) {
4956     // For floating-point precision of 6:
4957     //
4958     //   TwoToFractionalPartOfX =
4959     //     0.997535578f +
4960     //       (0.735607626f + 0.252464424f * x) * x;
4961     //
4962     // error 0.0144103317, which is 6 bits
4963     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4964                              getF32Constant(DAG, 0x3e814304, dl));
4965     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4966                              getF32Constant(DAG, 0x3f3c50c8, dl));
4967     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4968     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4969                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4970   } else if (LimitFloatPrecision <= 12) {
4971     // For floating-point precision of 12:
4972     //
4973     //   TwoToFractionalPartOfX =
4974     //     0.999892986f +
4975     //       (0.696457318f +
4976     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4977     //
4978     // error 0.000107046256, which is 13 to 14 bits
4979     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4980                              getF32Constant(DAG, 0x3da235e3, dl));
4981     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4982                              getF32Constant(DAG, 0x3e65b8f3, dl));
4983     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4984     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4985                              getF32Constant(DAG, 0x3f324b07, dl));
4986     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4987     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4988                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4989   } else { // LimitFloatPrecision <= 18
4990     // For floating-point precision of 18:
4991     //
4992     //   TwoToFractionalPartOfX =
4993     //     0.999999982f +
4994     //       (0.693148872f +
4995     //         (0.240227044f +
4996     //           (0.554906021e-1f +
4997     //             (0.961591928e-2f +
4998     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4999     // error 2.47208000*10^(-7), which is better than 18 bits
5000     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5001                              getF32Constant(DAG, 0x3924b03e, dl));
5002     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5003                              getF32Constant(DAG, 0x3ab24b87, dl));
5004     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5005     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5006                              getF32Constant(DAG, 0x3c1d8c17, dl));
5007     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5008     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5009                              getF32Constant(DAG, 0x3d634a1d, dl));
5010     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5011     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5012                              getF32Constant(DAG, 0x3e75fe14, dl));
5013     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5014     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5015                               getF32Constant(DAG, 0x3f317234, dl));
5016     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5017     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5018                                          getF32Constant(DAG, 0x3f800000, dl));
5019   }
5020 
5021   // Add the exponent into the result in integer domain.
5022   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5023   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5024                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5025 }
5026 
5027 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5028 /// limited-precision mode.
5029 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5030                          const TargetLowering &TLI) {
5031   if (Op.getValueType() == MVT::f32 &&
5032       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5033 
5034     // Put the exponent in the right bit position for later addition to the
5035     // final result:
5036     //
5037     // t0 = Op * log2(e)
5038 
5039     // TODO: What fast-math-flags should be set here?
5040     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5041                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5042     return getLimitedPrecisionExp2(t0, dl, DAG);
5043   }
5044 
5045   // No special expansion.
5046   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5047 }
5048 
5049 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5050 /// limited-precision mode.
5051 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5052                          const TargetLowering &TLI) {
5053   // TODO: What fast-math-flags should be set on the floating-point nodes?
5054 
5055   if (Op.getValueType() == MVT::f32 &&
5056       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5057     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5058 
5059     // Scale the exponent by log(2).
5060     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5061     SDValue LogOfExponent =
5062         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5063                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5064 
5065     // Get the significand and build it into a floating-point number with
5066     // exponent of 1.
5067     SDValue X = GetSignificand(DAG, Op1, dl);
5068 
5069     SDValue LogOfMantissa;
5070     if (LimitFloatPrecision <= 6) {
5071       // For floating-point precision of 6:
5072       //
5073       //   LogofMantissa =
5074       //     -1.1609546f +
5075       //       (1.4034025f - 0.23903021f * x) * x;
5076       //
5077       // error 0.0034276066, which is better than 8 bits
5078       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5079                                getF32Constant(DAG, 0xbe74c456, dl));
5080       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5081                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5082       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5083       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5084                                   getF32Constant(DAG, 0x3f949a29, dl));
5085     } else if (LimitFloatPrecision <= 12) {
5086       // For floating-point precision of 12:
5087       //
5088       //   LogOfMantissa =
5089       //     -1.7417939f +
5090       //       (2.8212026f +
5091       //         (-1.4699568f +
5092       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5093       //
5094       // error 0.000061011436, which is 14 bits
5095       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5096                                getF32Constant(DAG, 0xbd67b6d6, dl));
5097       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5098                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5099       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5100       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5101                                getF32Constant(DAG, 0x3fbc278b, dl));
5102       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5103       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5104                                getF32Constant(DAG, 0x40348e95, dl));
5105       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5106       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5107                                   getF32Constant(DAG, 0x3fdef31a, dl));
5108     } else { // LimitFloatPrecision <= 18
5109       // For floating-point precision of 18:
5110       //
5111       //   LogOfMantissa =
5112       //     -2.1072184f +
5113       //       (4.2372794f +
5114       //         (-3.7029485f +
5115       //           (2.2781945f +
5116       //             (-0.87823314f +
5117       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5118       //
5119       // error 0.0000023660568, which is better than 18 bits
5120       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5121                                getF32Constant(DAG, 0xbc91e5ac, dl));
5122       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5123                                getF32Constant(DAG, 0x3e4350aa, dl));
5124       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5125       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5126                                getF32Constant(DAG, 0x3f60d3e3, dl));
5127       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5128       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5129                                getF32Constant(DAG, 0x4011cdf0, dl));
5130       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5131       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5132                                getF32Constant(DAG, 0x406cfd1c, dl));
5133       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5134       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5135                                getF32Constant(DAG, 0x408797cb, dl));
5136       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5137       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5138                                   getF32Constant(DAG, 0x4006dcab, dl));
5139     }
5140 
5141     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5142   }
5143 
5144   // No special expansion.
5145   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5146 }
5147 
5148 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5149 /// limited-precision mode.
5150 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5151                           const TargetLowering &TLI) {
5152   // TODO: What fast-math-flags should be set on the floating-point nodes?
5153 
5154   if (Op.getValueType() == MVT::f32 &&
5155       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5156     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5157 
5158     // Get the exponent.
5159     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5160 
5161     // Get the significand and build it into a floating-point number with
5162     // exponent of 1.
5163     SDValue X = GetSignificand(DAG, Op1, dl);
5164 
5165     // Different possible minimax approximations of significand in
5166     // floating-point for various degrees of accuracy over [1,2].
5167     SDValue Log2ofMantissa;
5168     if (LimitFloatPrecision <= 6) {
5169       // For floating-point precision of 6:
5170       //
5171       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5172       //
5173       // error 0.0049451742, which is more than 7 bits
5174       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5175                                getF32Constant(DAG, 0xbeb08fe0, dl));
5176       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5177                                getF32Constant(DAG, 0x40019463, dl));
5178       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5179       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5180                                    getF32Constant(DAG, 0x3fd6633d, dl));
5181     } else if (LimitFloatPrecision <= 12) {
5182       // For floating-point precision of 12:
5183       //
5184       //   Log2ofMantissa =
5185       //     -2.51285454f +
5186       //       (4.07009056f +
5187       //         (-2.12067489f +
5188       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5189       //
5190       // error 0.0000876136000, which is better than 13 bits
5191       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5192                                getF32Constant(DAG, 0xbda7262e, dl));
5193       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5194                                getF32Constant(DAG, 0x3f25280b, dl));
5195       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5196       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5197                                getF32Constant(DAG, 0x4007b923, dl));
5198       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5199       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5200                                getF32Constant(DAG, 0x40823e2f, dl));
5201       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5202       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5203                                    getF32Constant(DAG, 0x4020d29c, dl));
5204     } else { // LimitFloatPrecision <= 18
5205       // For floating-point precision of 18:
5206       //
5207       //   Log2ofMantissa =
5208       //     -3.0400495f +
5209       //       (6.1129976f +
5210       //         (-5.3420409f +
5211       //           (3.2865683f +
5212       //             (-1.2669343f +
5213       //               (0.27515199f -
5214       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5215       //
5216       // error 0.0000018516, which is better than 18 bits
5217       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5218                                getF32Constant(DAG, 0xbcd2769e, dl));
5219       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5220                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5221       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5222       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5223                                getF32Constant(DAG, 0x3fa22ae7, dl));
5224       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5225       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5226                                getF32Constant(DAG, 0x40525723, dl));
5227       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5228       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5229                                getF32Constant(DAG, 0x40aaf200, dl));
5230       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5231       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5232                                getF32Constant(DAG, 0x40c39dad, dl));
5233       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5234       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5235                                    getF32Constant(DAG, 0x4042902c, dl));
5236     }
5237 
5238     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5239   }
5240 
5241   // No special expansion.
5242   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5243 }
5244 
5245 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5246 /// limited-precision mode.
5247 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5248                            const TargetLowering &TLI) {
5249   // TODO: What fast-math-flags should be set on the floating-point nodes?
5250 
5251   if (Op.getValueType() == MVT::f32 &&
5252       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5253     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5254 
5255     // Scale the exponent by log10(2) [0.30102999f].
5256     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5257     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5258                                         getF32Constant(DAG, 0x3e9a209a, dl));
5259 
5260     // Get the significand and build it into a floating-point number with
5261     // exponent of 1.
5262     SDValue X = GetSignificand(DAG, Op1, dl);
5263 
5264     SDValue Log10ofMantissa;
5265     if (LimitFloatPrecision <= 6) {
5266       // For floating-point precision of 6:
5267       //
5268       //   Log10ofMantissa =
5269       //     -0.50419619f +
5270       //       (0.60948995f - 0.10380950f * x) * x;
5271       //
5272       // error 0.0014886165, which is 6 bits
5273       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5274                                getF32Constant(DAG, 0xbdd49a13, dl));
5275       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5276                                getF32Constant(DAG, 0x3f1c0789, dl));
5277       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5278       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5279                                     getF32Constant(DAG, 0x3f011300, dl));
5280     } else if (LimitFloatPrecision <= 12) {
5281       // For floating-point precision of 12:
5282       //
5283       //   Log10ofMantissa =
5284       //     -0.64831180f +
5285       //       (0.91751397f +
5286       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5287       //
5288       // error 0.00019228036, which is better than 12 bits
5289       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5290                                getF32Constant(DAG, 0x3d431f31, dl));
5291       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5292                                getF32Constant(DAG, 0x3ea21fb2, dl));
5293       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5294       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5295                                getF32Constant(DAG, 0x3f6ae232, dl));
5296       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5297       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5298                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5299     } else { // LimitFloatPrecision <= 18
5300       // For floating-point precision of 18:
5301       //
5302       //   Log10ofMantissa =
5303       //     -0.84299375f +
5304       //       (1.5327582f +
5305       //         (-1.0688956f +
5306       //           (0.49102474f +
5307       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5308       //
5309       // error 0.0000037995730, which is better than 18 bits
5310       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5311                                getF32Constant(DAG, 0x3c5d51ce, dl));
5312       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5313                                getF32Constant(DAG, 0x3e00685a, dl));
5314       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5315       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5316                                getF32Constant(DAG, 0x3efb6798, dl));
5317       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5318       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5319                                getF32Constant(DAG, 0x3f88d192, dl));
5320       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5321       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5322                                getF32Constant(DAG, 0x3fc4316c, dl));
5323       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5324       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5325                                     getF32Constant(DAG, 0x3f57ce70, dl));
5326     }
5327 
5328     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5329   }
5330 
5331   // No special expansion.
5332   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5333 }
5334 
5335 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5336 /// limited-precision mode.
5337 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5338                           const TargetLowering &TLI) {
5339   if (Op.getValueType() == MVT::f32 &&
5340       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5341     return getLimitedPrecisionExp2(Op, dl, DAG);
5342 
5343   // No special expansion.
5344   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5345 }
5346 
5347 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5348 /// limited-precision mode with x == 10.0f.
5349 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5350                          SelectionDAG &DAG, const TargetLowering &TLI) {
5351   bool IsExp10 = false;
5352   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5353       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5354     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5355       APFloat Ten(10.0f);
5356       IsExp10 = LHSC->isExactlyValue(Ten);
5357     }
5358   }
5359 
5360   // TODO: What fast-math-flags should be set on the FMUL node?
5361   if (IsExp10) {
5362     // Put the exponent in the right bit position for later addition to the
5363     // final result:
5364     //
5365     //   #define LOG2OF10 3.3219281f
5366     //   t0 = Op * LOG2OF10;
5367     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5368                              getF32Constant(DAG, 0x40549a78, dl));
5369     return getLimitedPrecisionExp2(t0, dl, DAG);
5370   }
5371 
5372   // No special expansion.
5373   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5374 }
5375 
5376 /// ExpandPowI - Expand a llvm.powi intrinsic.
5377 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5378                           SelectionDAG &DAG) {
5379   // If RHS is a constant, we can expand this out to a multiplication tree,
5380   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5381   // optimizing for size, we only want to do this if the expansion would produce
5382   // a small number of multiplies, otherwise we do the full expansion.
5383   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5384     // Get the exponent as a positive value.
5385     unsigned Val = RHSC->getSExtValue();
5386     if ((int)Val < 0) Val = -Val;
5387 
5388     // powi(x, 0) -> 1.0
5389     if (Val == 0)
5390       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5391 
5392     bool OptForSize = DAG.shouldOptForSize();
5393     if (!OptForSize ||
5394         // If optimizing for size, don't insert too many multiplies.
5395         // This inserts up to 5 multiplies.
5396         countPopulation(Val) + Log2_32(Val) < 7) {
5397       // We use the simple binary decomposition method to generate the multiply
5398       // sequence.  There are more optimal ways to do this (for example,
5399       // powi(x,15) generates one more multiply than it should), but this has
5400       // the benefit of being both really simple and much better than a libcall.
5401       SDValue Res;  // Logically starts equal to 1.0
5402       SDValue CurSquare = LHS;
5403       // TODO: Intrinsics should have fast-math-flags that propagate to these
5404       // nodes.
5405       while (Val) {
5406         if (Val & 1) {
5407           if (Res.getNode())
5408             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5409           else
5410             Res = CurSquare;  // 1.0*CurSquare.
5411         }
5412 
5413         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5414                                 CurSquare, CurSquare);
5415         Val >>= 1;
5416       }
5417 
5418       // If the original was negative, invert the result, producing 1/(x*x*x).
5419       if (RHSC->getSExtValue() < 0)
5420         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5421                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5422       return Res;
5423     }
5424   }
5425 
5426   // Otherwise, expand to a libcall.
5427   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5428 }
5429 
5430 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5431                             SDValue LHS, SDValue RHS, SDValue Scale,
5432                             SelectionDAG &DAG, const TargetLowering &TLI) {
5433   EVT VT = LHS.getValueType();
5434   bool Signed = Opcode == ISD::SDIVFIX;
5435   LLVMContext &Ctx = *DAG.getContext();
5436 
5437   // If the type is legal but the operation isn't, this node might survive all
5438   // the way to operation legalization. If we end up there and we do not have
5439   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5440   // node.
5441 
5442   // Coax the legalizer into expanding the node during type legalization instead
5443   // by bumping the size by one bit. This will force it to Promote, enabling the
5444   // early expansion and avoiding the need to expand later.
5445 
5446   // We don't have to do this if Scale is 0; that can always be expanded.
5447 
5448   // FIXME: We wouldn't have to do this (or any of the early
5449   // expansion/promotion) if it was possible to expand a libcall of an
5450   // illegal type during operation legalization. But it's not, so things
5451   // get a bit hacky.
5452   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5453   if (ScaleInt > 0 &&
5454       (TLI.isTypeLegal(VT) ||
5455        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5456     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5457         Opcode, VT, ScaleInt);
5458     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5459       EVT PromVT;
5460       if (VT.isScalarInteger())
5461         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5462       else if (VT.isVector()) {
5463         PromVT = VT.getVectorElementType();
5464         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5465         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5466       } else
5467         llvm_unreachable("Wrong VT for DIVFIX?");
5468       if (Signed) {
5469         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5470         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5471       } else {
5472         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5473         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5474       }
5475       // TODO: Saturation.
5476       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5477       return DAG.getZExtOrTrunc(Res, DL, VT);
5478     }
5479   }
5480 
5481   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5482 }
5483 
5484 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5485 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5486 static void
5487 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5488                      const SDValue &N) {
5489   switch (N.getOpcode()) {
5490   case ISD::CopyFromReg: {
5491     SDValue Op = N.getOperand(1);
5492     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5493                       Op.getValueType().getSizeInBits());
5494     return;
5495   }
5496   case ISD::BITCAST:
5497   case ISD::AssertZext:
5498   case ISD::AssertSext:
5499   case ISD::TRUNCATE:
5500     getUnderlyingArgRegs(Regs, N.getOperand(0));
5501     return;
5502   case ISD::BUILD_PAIR:
5503   case ISD::BUILD_VECTOR:
5504   case ISD::CONCAT_VECTORS:
5505     for (SDValue Op : N->op_values())
5506       getUnderlyingArgRegs(Regs, Op);
5507     return;
5508   default:
5509     return;
5510   }
5511 }
5512 
5513 /// If the DbgValueInst is a dbg_value of a function argument, create the
5514 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5515 /// instruction selection, they will be inserted to the entry BB.
5516 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5517     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5518     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5519   const Argument *Arg = dyn_cast<Argument>(V);
5520   if (!Arg)
5521     return false;
5522 
5523   if (!IsDbgDeclare) {
5524     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5525     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5526     // the entry block.
5527     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5528     if (!IsInEntryBlock)
5529       return false;
5530 
5531     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5532     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5533     // variable that also is a param.
5534     //
5535     // Although, if we are at the top of the entry block already, we can still
5536     // emit using ArgDbgValue. This might catch some situations when the
5537     // dbg.value refers to an argument that isn't used in the entry block, so
5538     // any CopyToReg node would be optimized out and the only way to express
5539     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5540     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5541     // we should only emit as ArgDbgValue if the Variable is an argument to the
5542     // current function, and the dbg.value intrinsic is found in the entry
5543     // block.
5544     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5545         !DL->getInlinedAt();
5546     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5547     if (!IsInPrologue && !VariableIsFunctionInputArg)
5548       return false;
5549 
5550     // Here we assume that a function argument on IR level only can be used to
5551     // describe one input parameter on source level. If we for example have
5552     // source code like this
5553     //
5554     //    struct A { long x, y; };
5555     //    void foo(struct A a, long b) {
5556     //      ...
5557     //      b = a.x;
5558     //      ...
5559     //    }
5560     //
5561     // and IR like this
5562     //
5563     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5564     //  entry:
5565     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5566     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5567     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5568     //    ...
5569     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5570     //    ...
5571     //
5572     // then the last dbg.value is describing a parameter "b" using a value that
5573     // is an argument. But since we already has used %a1 to describe a parameter
5574     // we should not handle that last dbg.value here (that would result in an
5575     // incorrect hoisting of the DBG_VALUE to the function entry).
5576     // Notice that we allow one dbg.value per IR level argument, to accommodate
5577     // for the situation with fragments above.
5578     if (VariableIsFunctionInputArg) {
5579       unsigned ArgNo = Arg->getArgNo();
5580       if (ArgNo >= FuncInfo.DescribedArgs.size())
5581         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5582       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5583         return false;
5584       FuncInfo.DescribedArgs.set(ArgNo);
5585     }
5586   }
5587 
5588   MachineFunction &MF = DAG.getMachineFunction();
5589   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5590 
5591   Optional<MachineOperand> Op;
5592   // Some arguments' frame index is recorded during argument lowering.
5593   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5594   if (FI != std::numeric_limits<int>::max())
5595     Op = MachineOperand::CreateFI(FI);
5596 
5597   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5598   if (!Op && N.getNode()) {
5599     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5600     Register Reg;
5601     if (ArgRegsAndSizes.size() == 1)
5602       Reg = ArgRegsAndSizes.front().first;
5603 
5604     if (Reg && Reg.isVirtual()) {
5605       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5606       Register PR = RegInfo.getLiveInPhysReg(Reg);
5607       if (PR)
5608         Reg = PR;
5609     }
5610     if (Reg) {
5611       Op = MachineOperand::CreateReg(Reg, false);
5612     }
5613   }
5614 
5615   if (!Op && N.getNode()) {
5616     // Check if frame index is available.
5617     SDValue LCandidate = peekThroughBitcasts(N);
5618     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5619       if (FrameIndexSDNode *FINode =
5620           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5621         Op = MachineOperand::CreateFI(FINode->getIndex());
5622   }
5623 
5624   if (!Op) {
5625     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5626     auto splitMultiRegDbgValue
5627       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5628       unsigned Offset = 0;
5629       for (auto RegAndSize : SplitRegs) {
5630         // If the expression is already a fragment, the current register
5631         // offset+size might extend beyond the fragment. In this case, only
5632         // the register bits that are inside the fragment are relevant.
5633         int RegFragmentSizeInBits = RegAndSize.second;
5634         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5635           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5636           // The register is entirely outside the expression fragment,
5637           // so is irrelevant for debug info.
5638           if (Offset >= ExprFragmentSizeInBits)
5639             break;
5640           // The register is partially outside the expression fragment, only
5641           // the low bits within the fragment are relevant for debug info.
5642           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5643             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5644           }
5645         }
5646 
5647         auto FragmentExpr = DIExpression::createFragmentExpression(
5648             Expr, Offset, RegFragmentSizeInBits);
5649         Offset += RegAndSize.second;
5650         // If a valid fragment expression cannot be created, the variable's
5651         // correct value cannot be determined and so it is set as Undef.
5652         if (!FragmentExpr) {
5653           SDDbgValue *SDV = DAG.getConstantDbgValue(
5654               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5655           DAG.AddDbgValue(SDV, nullptr, false);
5656           continue;
5657         }
5658         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5659         FuncInfo.ArgDbgValues.push_back(
5660           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5661                   RegAndSize.first, Variable, *FragmentExpr));
5662       }
5663     };
5664 
5665     // Check if ValueMap has reg number.
5666     DenseMap<const Value *, unsigned>::const_iterator
5667       VMI = FuncInfo.ValueMap.find(V);
5668     if (VMI != FuncInfo.ValueMap.end()) {
5669       const auto &TLI = DAG.getTargetLoweringInfo();
5670       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5671                        V->getType(), getABIRegCopyCC(V));
5672       if (RFV.occupiesMultipleRegs()) {
5673         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5674         return true;
5675       }
5676 
5677       Op = MachineOperand::CreateReg(VMI->second, false);
5678     } else if (ArgRegsAndSizes.size() > 1) {
5679       // This was split due to the calling convention, and no virtual register
5680       // mapping exists for the value.
5681       splitMultiRegDbgValue(ArgRegsAndSizes);
5682       return true;
5683     }
5684   }
5685 
5686   if (!Op)
5687     return false;
5688 
5689   assert(Variable->isValidLocationForIntrinsic(DL) &&
5690          "Expected inlined-at fields to agree");
5691 
5692   // If the argument arrives in a stack slot, then what the IR thought was a
5693   // normal Value is actually in memory, and we must add a deref to load it.
5694   if (Op->isFI()) {
5695     int FI = Op->getIndex();
5696     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5697     if (Expr->isImplicit()) {
5698       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5699       Expr = DIExpression::prependOpcodes(Expr, Ops);
5700     } else {
5701       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5702     }
5703   }
5704 
5705   // If this location was specified with a dbg.declare, then it and its
5706   // expression calculate the address of the variable. Append a deref to
5707   // force it to be a memory location.
5708   if (IsDbgDeclare)
5709     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5710 
5711   FuncInfo.ArgDbgValues.push_back(
5712       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5713               *Op, Variable, Expr));
5714 
5715   return true;
5716 }
5717 
5718 /// Return the appropriate SDDbgValue based on N.
5719 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5720                                              DILocalVariable *Variable,
5721                                              DIExpression *Expr,
5722                                              const DebugLoc &dl,
5723                                              unsigned DbgSDNodeOrder) {
5724   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5725     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5726     // stack slot locations.
5727     //
5728     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5729     // debug values here after optimization:
5730     //
5731     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5732     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5733     //
5734     // Both describe the direct values of their associated variables.
5735     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5736                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5737   }
5738   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5739                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5740 }
5741 
5742 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5743   switch (Intrinsic) {
5744   case Intrinsic::smul_fix:
5745     return ISD::SMULFIX;
5746   case Intrinsic::umul_fix:
5747     return ISD::UMULFIX;
5748   case Intrinsic::smul_fix_sat:
5749     return ISD::SMULFIXSAT;
5750   case Intrinsic::umul_fix_sat:
5751     return ISD::UMULFIXSAT;
5752   case Intrinsic::sdiv_fix:
5753     return ISD::SDIVFIX;
5754   case Intrinsic::udiv_fix:
5755     return ISD::UDIVFIX;
5756   default:
5757     llvm_unreachable("Unhandled fixed point intrinsic");
5758   }
5759 }
5760 
5761 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5762                                            const char *FunctionName) {
5763   assert(FunctionName && "FunctionName must not be nullptr");
5764   SDValue Callee = DAG.getExternalSymbol(
5765       FunctionName,
5766       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5767   LowerCallTo(&I, Callee, I.isTailCall());
5768 }
5769 
5770 /// Lower the call to the specified intrinsic function.
5771 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5772                                              unsigned Intrinsic) {
5773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5774   SDLoc sdl = getCurSDLoc();
5775   DebugLoc dl = getCurDebugLoc();
5776   SDValue Res;
5777 
5778   switch (Intrinsic) {
5779   default:
5780     // By default, turn this into a target intrinsic node.
5781     visitTargetIntrinsic(I, Intrinsic);
5782     return;
5783   case Intrinsic::vscale: {
5784     match(&I, m_VScale(DAG.getDataLayout()));
5785     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5786     setValue(&I,
5787              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5788     return;
5789   }
5790   case Intrinsic::vastart:  visitVAStart(I); return;
5791   case Intrinsic::vaend:    visitVAEnd(I); return;
5792   case Intrinsic::vacopy:   visitVACopy(I); return;
5793   case Intrinsic::returnaddress:
5794     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5795                              TLI.getPointerTy(DAG.getDataLayout()),
5796                              getValue(I.getArgOperand(0))));
5797     return;
5798   case Intrinsic::addressofreturnaddress:
5799     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5800                              TLI.getPointerTy(DAG.getDataLayout())));
5801     return;
5802   case Intrinsic::sponentry:
5803     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5804                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5805     return;
5806   case Intrinsic::frameaddress:
5807     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5808                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5809                              getValue(I.getArgOperand(0))));
5810     return;
5811   case Intrinsic::read_register: {
5812     Value *Reg = I.getArgOperand(0);
5813     SDValue Chain = getRoot();
5814     SDValue RegName =
5815         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5816     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5817     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5818       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5819     setValue(&I, Res);
5820     DAG.setRoot(Res.getValue(1));
5821     return;
5822   }
5823   case Intrinsic::write_register: {
5824     Value *Reg = I.getArgOperand(0);
5825     Value *RegValue = I.getArgOperand(1);
5826     SDValue Chain = getRoot();
5827     SDValue RegName =
5828         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5829     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5830                             RegName, getValue(RegValue)));
5831     return;
5832   }
5833   case Intrinsic::memcpy: {
5834     const auto &MCI = cast<MemCpyInst>(I);
5835     SDValue Op1 = getValue(I.getArgOperand(0));
5836     SDValue Op2 = getValue(I.getArgOperand(1));
5837     SDValue Op3 = getValue(I.getArgOperand(2));
5838     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5839     Align DstAlign = MCI.getDestAlign().valueOrOne();
5840     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5841     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5842     bool isVol = MCI.isVolatile();
5843     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5844     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5845     // node.
5846     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5847     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5848                                /* AlwaysInline */ false, isTC,
5849                                MachinePointerInfo(I.getArgOperand(0)),
5850                                MachinePointerInfo(I.getArgOperand(1)));
5851     updateDAGForMaybeTailCall(MC);
5852     return;
5853   }
5854   case Intrinsic::memcpy_inline: {
5855     const auto &MCI = cast<MemCpyInlineInst>(I);
5856     SDValue Dst = getValue(I.getArgOperand(0));
5857     SDValue Src = getValue(I.getArgOperand(1));
5858     SDValue Size = getValue(I.getArgOperand(2));
5859     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5860     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5861     Align DstAlign = MCI.getDestAlign().valueOrOne();
5862     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5863     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5864     bool isVol = MCI.isVolatile();
5865     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5866     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5867     // node.
5868     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5869                                /* AlwaysInline */ true, isTC,
5870                                MachinePointerInfo(I.getArgOperand(0)),
5871                                MachinePointerInfo(I.getArgOperand(1)));
5872     updateDAGForMaybeTailCall(MC);
5873     return;
5874   }
5875   case Intrinsic::memset: {
5876     const auto &MSI = cast<MemSetInst>(I);
5877     SDValue Op1 = getValue(I.getArgOperand(0));
5878     SDValue Op2 = getValue(I.getArgOperand(1));
5879     SDValue Op3 = getValue(I.getArgOperand(2));
5880     // @llvm.memset defines 0 and 1 to both mean no alignment.
5881     Align Alignment = MSI.getDestAlign().valueOrOne();
5882     bool isVol = MSI.isVolatile();
5883     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5884     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5885     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5886                                MachinePointerInfo(I.getArgOperand(0)));
5887     updateDAGForMaybeTailCall(MS);
5888     return;
5889   }
5890   case Intrinsic::memmove: {
5891     const auto &MMI = cast<MemMoveInst>(I);
5892     SDValue Op1 = getValue(I.getArgOperand(0));
5893     SDValue Op2 = getValue(I.getArgOperand(1));
5894     SDValue Op3 = getValue(I.getArgOperand(2));
5895     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5896     Align DstAlign = MMI.getDestAlign().valueOrOne();
5897     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5898     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5899     bool isVol = MMI.isVolatile();
5900     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5901     // FIXME: Support passing different dest/src alignments to the memmove DAG
5902     // node.
5903     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5904     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5905                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5906                                 MachinePointerInfo(I.getArgOperand(1)));
5907     updateDAGForMaybeTailCall(MM);
5908     return;
5909   }
5910   case Intrinsic::memcpy_element_unordered_atomic: {
5911     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5912     SDValue Dst = getValue(MI.getRawDest());
5913     SDValue Src = getValue(MI.getRawSource());
5914     SDValue Length = getValue(MI.getLength());
5915 
5916     unsigned DstAlign = MI.getDestAlignment();
5917     unsigned SrcAlign = MI.getSourceAlignment();
5918     Type *LengthTy = MI.getLength()->getType();
5919     unsigned ElemSz = MI.getElementSizeInBytes();
5920     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5921     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5922                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5923                                      MachinePointerInfo(MI.getRawDest()),
5924                                      MachinePointerInfo(MI.getRawSource()));
5925     updateDAGForMaybeTailCall(MC);
5926     return;
5927   }
5928   case Intrinsic::memmove_element_unordered_atomic: {
5929     auto &MI = cast<AtomicMemMoveInst>(I);
5930     SDValue Dst = getValue(MI.getRawDest());
5931     SDValue Src = getValue(MI.getRawSource());
5932     SDValue Length = getValue(MI.getLength());
5933 
5934     unsigned DstAlign = MI.getDestAlignment();
5935     unsigned SrcAlign = MI.getSourceAlignment();
5936     Type *LengthTy = MI.getLength()->getType();
5937     unsigned ElemSz = MI.getElementSizeInBytes();
5938     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5939     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5940                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5941                                       MachinePointerInfo(MI.getRawDest()),
5942                                       MachinePointerInfo(MI.getRawSource()));
5943     updateDAGForMaybeTailCall(MC);
5944     return;
5945   }
5946   case Intrinsic::memset_element_unordered_atomic: {
5947     auto &MI = cast<AtomicMemSetInst>(I);
5948     SDValue Dst = getValue(MI.getRawDest());
5949     SDValue Val = getValue(MI.getValue());
5950     SDValue Length = getValue(MI.getLength());
5951 
5952     unsigned DstAlign = MI.getDestAlignment();
5953     Type *LengthTy = MI.getLength()->getType();
5954     unsigned ElemSz = MI.getElementSizeInBytes();
5955     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5956     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5957                                      LengthTy, ElemSz, isTC,
5958                                      MachinePointerInfo(MI.getRawDest()));
5959     updateDAGForMaybeTailCall(MC);
5960     return;
5961   }
5962   case Intrinsic::dbg_addr:
5963   case Intrinsic::dbg_declare: {
5964     const auto &DI = cast<DbgVariableIntrinsic>(I);
5965     DILocalVariable *Variable = DI.getVariable();
5966     DIExpression *Expression = DI.getExpression();
5967     dropDanglingDebugInfo(Variable, Expression);
5968     assert(Variable && "Missing variable");
5969 
5970     // Check if address has undef value.
5971     const Value *Address = DI.getVariableLocation();
5972     if (!Address || isa<UndefValue>(Address) ||
5973         (Address->use_empty() && !isa<Argument>(Address))) {
5974       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5975       return;
5976     }
5977 
5978     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5979 
5980     // Check if this variable can be described by a frame index, typically
5981     // either as a static alloca or a byval parameter.
5982     int FI = std::numeric_limits<int>::max();
5983     if (const auto *AI =
5984             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5985       if (AI->isStaticAlloca()) {
5986         auto I = FuncInfo.StaticAllocaMap.find(AI);
5987         if (I != FuncInfo.StaticAllocaMap.end())
5988           FI = I->second;
5989       }
5990     } else if (const auto *Arg = dyn_cast<Argument>(
5991                    Address->stripInBoundsConstantOffsets())) {
5992       FI = FuncInfo.getArgumentFrameIndex(Arg);
5993     }
5994 
5995     // llvm.dbg.addr is control dependent and always generates indirect
5996     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5997     // the MachineFunction variable table.
5998     if (FI != std::numeric_limits<int>::max()) {
5999       if (Intrinsic == Intrinsic::dbg_addr) {
6000         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6001             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
6002         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
6003       }
6004       return;
6005     }
6006 
6007     SDValue &N = NodeMap[Address];
6008     if (!N.getNode() && isa<Argument>(Address))
6009       // Check unused arguments map.
6010       N = UnusedArgNodeMap[Address];
6011     SDDbgValue *SDV;
6012     if (N.getNode()) {
6013       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6014         Address = BCI->getOperand(0);
6015       // Parameters are handled specially.
6016       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6017       if (isParameter && FINode) {
6018         // Byval parameter. We have a frame index at this point.
6019         SDV =
6020             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6021                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6022       } else if (isa<Argument>(Address)) {
6023         // Address is an argument, so try to emit its dbg value using
6024         // virtual register info from the FuncInfo.ValueMap.
6025         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6026         return;
6027       } else {
6028         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6029                               true, dl, SDNodeOrder);
6030       }
6031       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
6032     } else {
6033       // If Address is an argument then try to emit its dbg value using
6034       // virtual register info from the FuncInfo.ValueMap.
6035       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6036                                     N)) {
6037         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
6038       }
6039     }
6040     return;
6041   }
6042   case Intrinsic::dbg_label: {
6043     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6044     DILabel *Label = DI.getLabel();
6045     assert(Label && "Missing label");
6046 
6047     SDDbgLabel *SDV;
6048     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6049     DAG.AddDbgLabel(SDV);
6050     return;
6051   }
6052   case Intrinsic::dbg_value: {
6053     const DbgValueInst &DI = cast<DbgValueInst>(I);
6054     assert(DI.getVariable() && "Missing variable");
6055 
6056     DILocalVariable *Variable = DI.getVariable();
6057     DIExpression *Expression = DI.getExpression();
6058     dropDanglingDebugInfo(Variable, Expression);
6059     const Value *V = DI.getValue();
6060     if (!V)
6061       return;
6062 
6063     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6064         SDNodeOrder))
6065       return;
6066 
6067     // TODO: Dangling debug info will eventually either be resolved or produce
6068     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6069     // between the original dbg.value location and its resolved DBG_VALUE, which
6070     // we should ideally fill with an extra Undef DBG_VALUE.
6071 
6072     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6073     return;
6074   }
6075 
6076   case Intrinsic::eh_typeid_for: {
6077     // Find the type id for the given typeinfo.
6078     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6079     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6080     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6081     setValue(&I, Res);
6082     return;
6083   }
6084 
6085   case Intrinsic::eh_return_i32:
6086   case Intrinsic::eh_return_i64:
6087     DAG.getMachineFunction().setCallsEHReturn(true);
6088     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6089                             MVT::Other,
6090                             getControlRoot(),
6091                             getValue(I.getArgOperand(0)),
6092                             getValue(I.getArgOperand(1))));
6093     return;
6094   case Intrinsic::eh_unwind_init:
6095     DAG.getMachineFunction().setCallsUnwindInit(true);
6096     return;
6097   case Intrinsic::eh_dwarf_cfa:
6098     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6099                              TLI.getPointerTy(DAG.getDataLayout()),
6100                              getValue(I.getArgOperand(0))));
6101     return;
6102   case Intrinsic::eh_sjlj_callsite: {
6103     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6104     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6105     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6106     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6107 
6108     MMI.setCurrentCallSite(CI->getZExtValue());
6109     return;
6110   }
6111   case Intrinsic::eh_sjlj_functioncontext: {
6112     // Get and store the index of the function context.
6113     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6114     AllocaInst *FnCtx =
6115       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6116     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6117     MFI.setFunctionContextIndex(FI);
6118     return;
6119   }
6120   case Intrinsic::eh_sjlj_setjmp: {
6121     SDValue Ops[2];
6122     Ops[0] = getRoot();
6123     Ops[1] = getValue(I.getArgOperand(0));
6124     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6125                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6126     setValue(&I, Op.getValue(0));
6127     DAG.setRoot(Op.getValue(1));
6128     return;
6129   }
6130   case Intrinsic::eh_sjlj_longjmp:
6131     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6132                             getRoot(), getValue(I.getArgOperand(0))));
6133     return;
6134   case Intrinsic::eh_sjlj_setup_dispatch:
6135     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6136                             getRoot()));
6137     return;
6138   case Intrinsic::masked_gather:
6139     visitMaskedGather(I);
6140     return;
6141   case Intrinsic::masked_load:
6142     visitMaskedLoad(I);
6143     return;
6144   case Intrinsic::masked_scatter:
6145     visitMaskedScatter(I);
6146     return;
6147   case Intrinsic::masked_store:
6148     visitMaskedStore(I);
6149     return;
6150   case Intrinsic::masked_expandload:
6151     visitMaskedLoad(I, true /* IsExpanding */);
6152     return;
6153   case Intrinsic::masked_compressstore:
6154     visitMaskedStore(I, true /* IsCompressing */);
6155     return;
6156   case Intrinsic::powi:
6157     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6158                             getValue(I.getArgOperand(1)), DAG));
6159     return;
6160   case Intrinsic::log:
6161     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6162     return;
6163   case Intrinsic::log2:
6164     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6165     return;
6166   case Intrinsic::log10:
6167     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6168     return;
6169   case Intrinsic::exp:
6170     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6171     return;
6172   case Intrinsic::exp2:
6173     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6174     return;
6175   case Intrinsic::pow:
6176     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6177                            getValue(I.getArgOperand(1)), DAG, TLI));
6178     return;
6179   case Intrinsic::sqrt:
6180   case Intrinsic::fabs:
6181   case Intrinsic::sin:
6182   case Intrinsic::cos:
6183   case Intrinsic::floor:
6184   case Intrinsic::ceil:
6185   case Intrinsic::trunc:
6186   case Intrinsic::rint:
6187   case Intrinsic::nearbyint:
6188   case Intrinsic::round:
6189   case Intrinsic::canonicalize: {
6190     unsigned Opcode;
6191     switch (Intrinsic) {
6192     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6193     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6194     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6195     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6196     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6197     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6198     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6199     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6200     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6201     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6202     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6203     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6204     }
6205 
6206     setValue(&I, DAG.getNode(Opcode, sdl,
6207                              getValue(I.getArgOperand(0)).getValueType(),
6208                              getValue(I.getArgOperand(0))));
6209     return;
6210   }
6211   case Intrinsic::lround:
6212   case Intrinsic::llround:
6213   case Intrinsic::lrint:
6214   case Intrinsic::llrint: {
6215     unsigned Opcode;
6216     switch (Intrinsic) {
6217     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6218     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6219     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6220     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6221     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6222     }
6223 
6224     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6225     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6226                              getValue(I.getArgOperand(0))));
6227     return;
6228   }
6229   case Intrinsic::minnum:
6230     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6231                              getValue(I.getArgOperand(0)).getValueType(),
6232                              getValue(I.getArgOperand(0)),
6233                              getValue(I.getArgOperand(1))));
6234     return;
6235   case Intrinsic::maxnum:
6236     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6237                              getValue(I.getArgOperand(0)).getValueType(),
6238                              getValue(I.getArgOperand(0)),
6239                              getValue(I.getArgOperand(1))));
6240     return;
6241   case Intrinsic::minimum:
6242     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6243                              getValue(I.getArgOperand(0)).getValueType(),
6244                              getValue(I.getArgOperand(0)),
6245                              getValue(I.getArgOperand(1))));
6246     return;
6247   case Intrinsic::maximum:
6248     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6249                              getValue(I.getArgOperand(0)).getValueType(),
6250                              getValue(I.getArgOperand(0)),
6251                              getValue(I.getArgOperand(1))));
6252     return;
6253   case Intrinsic::copysign:
6254     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6255                              getValue(I.getArgOperand(0)).getValueType(),
6256                              getValue(I.getArgOperand(0)),
6257                              getValue(I.getArgOperand(1))));
6258     return;
6259   case Intrinsic::fma:
6260     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6261                              getValue(I.getArgOperand(0)).getValueType(),
6262                              getValue(I.getArgOperand(0)),
6263                              getValue(I.getArgOperand(1)),
6264                              getValue(I.getArgOperand(2))));
6265     return;
6266 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6267   case Intrinsic::INTRINSIC:
6268 #include "llvm/IR/ConstrainedOps.def"
6269     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6270     return;
6271   case Intrinsic::fmuladd: {
6272     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6273     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6274         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6275       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6276                                getValue(I.getArgOperand(0)).getValueType(),
6277                                getValue(I.getArgOperand(0)),
6278                                getValue(I.getArgOperand(1)),
6279                                getValue(I.getArgOperand(2))));
6280     } else {
6281       // TODO: Intrinsic calls should have fast-math-flags.
6282       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6283                                 getValue(I.getArgOperand(0)).getValueType(),
6284                                 getValue(I.getArgOperand(0)),
6285                                 getValue(I.getArgOperand(1)));
6286       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6287                                 getValue(I.getArgOperand(0)).getValueType(),
6288                                 Mul,
6289                                 getValue(I.getArgOperand(2)));
6290       setValue(&I, Add);
6291     }
6292     return;
6293   }
6294   case Intrinsic::convert_to_fp16:
6295     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6296                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6297                                          getValue(I.getArgOperand(0)),
6298                                          DAG.getTargetConstant(0, sdl,
6299                                                                MVT::i32))));
6300     return;
6301   case Intrinsic::convert_from_fp16:
6302     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6303                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6304                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6305                                          getValue(I.getArgOperand(0)))));
6306     return;
6307   case Intrinsic::pcmarker: {
6308     SDValue Tmp = getValue(I.getArgOperand(0));
6309     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6310     return;
6311   }
6312   case Intrinsic::readcyclecounter: {
6313     SDValue Op = getRoot();
6314     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6315                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6316     setValue(&I, Res);
6317     DAG.setRoot(Res.getValue(1));
6318     return;
6319   }
6320   case Intrinsic::bitreverse:
6321     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6322                              getValue(I.getArgOperand(0)).getValueType(),
6323                              getValue(I.getArgOperand(0))));
6324     return;
6325   case Intrinsic::bswap:
6326     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6327                              getValue(I.getArgOperand(0)).getValueType(),
6328                              getValue(I.getArgOperand(0))));
6329     return;
6330   case Intrinsic::cttz: {
6331     SDValue Arg = getValue(I.getArgOperand(0));
6332     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6333     EVT Ty = Arg.getValueType();
6334     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6335                              sdl, Ty, Arg));
6336     return;
6337   }
6338   case Intrinsic::ctlz: {
6339     SDValue Arg = getValue(I.getArgOperand(0));
6340     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6341     EVT Ty = Arg.getValueType();
6342     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6343                              sdl, Ty, Arg));
6344     return;
6345   }
6346   case Intrinsic::ctpop: {
6347     SDValue Arg = getValue(I.getArgOperand(0));
6348     EVT Ty = Arg.getValueType();
6349     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6350     return;
6351   }
6352   case Intrinsic::fshl:
6353   case Intrinsic::fshr: {
6354     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6355     SDValue X = getValue(I.getArgOperand(0));
6356     SDValue Y = getValue(I.getArgOperand(1));
6357     SDValue Z = getValue(I.getArgOperand(2));
6358     EVT VT = X.getValueType();
6359     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6360     SDValue Zero = DAG.getConstant(0, sdl, VT);
6361     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6362 
6363     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6364     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6365       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6366       return;
6367     }
6368 
6369     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6370     // avoid the select that is necessary in the general case to filter out
6371     // the 0-shift possibility that leads to UB.
6372     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6373       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6374       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6375         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6376         return;
6377       }
6378 
6379       // Some targets only rotate one way. Try the opposite direction.
6380       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6381       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6382         // Negate the shift amount because it is safe to ignore the high bits.
6383         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6384         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6385         return;
6386       }
6387 
6388       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6389       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6390       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6391       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6392       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6393       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6394       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6395       return;
6396     }
6397 
6398     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6399     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6400     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6401     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6402     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6403     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6404 
6405     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6406     // and that is undefined. We must compare and select to avoid UB.
6407     EVT CCVT = MVT::i1;
6408     if (VT.isVector())
6409       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6410 
6411     // For fshl, 0-shift returns the 1st arg (X).
6412     // For fshr, 0-shift returns the 2nd arg (Y).
6413     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6414     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6415     return;
6416   }
6417   case Intrinsic::sadd_sat: {
6418     SDValue Op1 = getValue(I.getArgOperand(0));
6419     SDValue Op2 = getValue(I.getArgOperand(1));
6420     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6421     return;
6422   }
6423   case Intrinsic::uadd_sat: {
6424     SDValue Op1 = getValue(I.getArgOperand(0));
6425     SDValue Op2 = getValue(I.getArgOperand(1));
6426     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6427     return;
6428   }
6429   case Intrinsic::ssub_sat: {
6430     SDValue Op1 = getValue(I.getArgOperand(0));
6431     SDValue Op2 = getValue(I.getArgOperand(1));
6432     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6433     return;
6434   }
6435   case Intrinsic::usub_sat: {
6436     SDValue Op1 = getValue(I.getArgOperand(0));
6437     SDValue Op2 = getValue(I.getArgOperand(1));
6438     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6439     return;
6440   }
6441   case Intrinsic::smul_fix:
6442   case Intrinsic::umul_fix:
6443   case Intrinsic::smul_fix_sat:
6444   case Intrinsic::umul_fix_sat: {
6445     SDValue Op1 = getValue(I.getArgOperand(0));
6446     SDValue Op2 = getValue(I.getArgOperand(1));
6447     SDValue Op3 = getValue(I.getArgOperand(2));
6448     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6449                              Op1.getValueType(), Op1, Op2, Op3));
6450     return;
6451   }
6452   case Intrinsic::sdiv_fix:
6453   case Intrinsic::udiv_fix: {
6454     SDValue Op1 = getValue(I.getArgOperand(0));
6455     SDValue Op2 = getValue(I.getArgOperand(1));
6456     SDValue Op3 = getValue(I.getArgOperand(2));
6457     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6458                               Op1, Op2, Op3, DAG, TLI));
6459     return;
6460   }
6461   case Intrinsic::stacksave: {
6462     SDValue Op = getRoot();
6463     Res = DAG.getNode(
6464         ISD::STACKSAVE, sdl,
6465         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6466     setValue(&I, Res);
6467     DAG.setRoot(Res.getValue(1));
6468     return;
6469   }
6470   case Intrinsic::stackrestore:
6471     Res = getValue(I.getArgOperand(0));
6472     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6473     return;
6474   case Intrinsic::get_dynamic_area_offset: {
6475     SDValue Op = getRoot();
6476     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6477     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6478     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6479     // target.
6480     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6481       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6482                          " intrinsic!");
6483     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6484                       Op);
6485     DAG.setRoot(Op);
6486     setValue(&I, Res);
6487     return;
6488   }
6489   case Intrinsic::stackguard: {
6490     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6491     MachineFunction &MF = DAG.getMachineFunction();
6492     const Module &M = *MF.getFunction().getParent();
6493     SDValue Chain = getRoot();
6494     if (TLI.useLoadStackGuardNode()) {
6495       Res = getLoadStackGuard(DAG, sdl, Chain);
6496     } else {
6497       const Value *Global = TLI.getSDagStackGuard(M);
6498       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6499       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6500                         MachinePointerInfo(Global, 0), Align,
6501                         MachineMemOperand::MOVolatile);
6502     }
6503     if (TLI.useStackGuardXorFP())
6504       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6505     DAG.setRoot(Chain);
6506     setValue(&I, Res);
6507     return;
6508   }
6509   case Intrinsic::stackprotector: {
6510     // Emit code into the DAG to store the stack guard onto the stack.
6511     MachineFunction &MF = DAG.getMachineFunction();
6512     MachineFrameInfo &MFI = MF.getFrameInfo();
6513     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6514     SDValue Src, Chain = getRoot();
6515 
6516     if (TLI.useLoadStackGuardNode())
6517       Src = getLoadStackGuard(DAG, sdl, Chain);
6518     else
6519       Src = getValue(I.getArgOperand(0));   // The guard's value.
6520 
6521     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6522 
6523     int FI = FuncInfo.StaticAllocaMap[Slot];
6524     MFI.setStackProtectorIndex(FI);
6525 
6526     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6527 
6528     // Store the stack protector onto the stack.
6529     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6530                                                  DAG.getMachineFunction(), FI),
6531                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6532     setValue(&I, Res);
6533     DAG.setRoot(Res);
6534     return;
6535   }
6536   case Intrinsic::objectsize:
6537     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6538 
6539   case Intrinsic::is_constant:
6540     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6541 
6542   case Intrinsic::annotation:
6543   case Intrinsic::ptr_annotation:
6544   case Intrinsic::launder_invariant_group:
6545   case Intrinsic::strip_invariant_group:
6546     // Drop the intrinsic, but forward the value
6547     setValue(&I, getValue(I.getOperand(0)));
6548     return;
6549   case Intrinsic::assume:
6550   case Intrinsic::var_annotation:
6551   case Intrinsic::sideeffect:
6552     // Discard annotate attributes, assumptions, and artificial side-effects.
6553     return;
6554 
6555   case Intrinsic::codeview_annotation: {
6556     // Emit a label associated with this metadata.
6557     MachineFunction &MF = DAG.getMachineFunction();
6558     MCSymbol *Label =
6559         MF.getMMI().getContext().createTempSymbol("annotation", true);
6560     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6561     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6562     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6563     DAG.setRoot(Res);
6564     return;
6565   }
6566 
6567   case Intrinsic::init_trampoline: {
6568     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6569 
6570     SDValue Ops[6];
6571     Ops[0] = getRoot();
6572     Ops[1] = getValue(I.getArgOperand(0));
6573     Ops[2] = getValue(I.getArgOperand(1));
6574     Ops[3] = getValue(I.getArgOperand(2));
6575     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6576     Ops[5] = DAG.getSrcValue(F);
6577 
6578     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6579 
6580     DAG.setRoot(Res);
6581     return;
6582   }
6583   case Intrinsic::adjust_trampoline:
6584     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6585                              TLI.getPointerTy(DAG.getDataLayout()),
6586                              getValue(I.getArgOperand(0))));
6587     return;
6588   case Intrinsic::gcroot: {
6589     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6590            "only valid in functions with gc specified, enforced by Verifier");
6591     assert(GFI && "implied by previous");
6592     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6593     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6594 
6595     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6596     GFI->addStackRoot(FI->getIndex(), TypeMap);
6597     return;
6598   }
6599   case Intrinsic::gcread:
6600   case Intrinsic::gcwrite:
6601     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6602   case Intrinsic::flt_rounds:
6603     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6604     return;
6605 
6606   case Intrinsic::expect:
6607     // Just replace __builtin_expect(exp, c) with EXP.
6608     setValue(&I, getValue(I.getArgOperand(0)));
6609     return;
6610 
6611   case Intrinsic::debugtrap:
6612   case Intrinsic::trap: {
6613     StringRef TrapFuncName =
6614         I.getAttributes()
6615             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6616             .getValueAsString();
6617     if (TrapFuncName.empty()) {
6618       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6619         ISD::TRAP : ISD::DEBUGTRAP;
6620       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6621       return;
6622     }
6623     TargetLowering::ArgListTy Args;
6624 
6625     TargetLowering::CallLoweringInfo CLI(DAG);
6626     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6627         CallingConv::C, I.getType(),
6628         DAG.getExternalSymbol(TrapFuncName.data(),
6629                               TLI.getPointerTy(DAG.getDataLayout())),
6630         std::move(Args));
6631 
6632     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6633     DAG.setRoot(Result.second);
6634     return;
6635   }
6636 
6637   case Intrinsic::uadd_with_overflow:
6638   case Intrinsic::sadd_with_overflow:
6639   case Intrinsic::usub_with_overflow:
6640   case Intrinsic::ssub_with_overflow:
6641   case Intrinsic::umul_with_overflow:
6642   case Intrinsic::smul_with_overflow: {
6643     ISD::NodeType Op;
6644     switch (Intrinsic) {
6645     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6646     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6647     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6648     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6649     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6650     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6651     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6652     }
6653     SDValue Op1 = getValue(I.getArgOperand(0));
6654     SDValue Op2 = getValue(I.getArgOperand(1));
6655 
6656     EVT ResultVT = Op1.getValueType();
6657     EVT OverflowVT = MVT::i1;
6658     if (ResultVT.isVector())
6659       OverflowVT = EVT::getVectorVT(
6660           *Context, OverflowVT, ResultVT.getVectorNumElements());
6661 
6662     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6663     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6664     return;
6665   }
6666   case Intrinsic::prefetch: {
6667     SDValue Ops[5];
6668     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6669     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6670     Ops[0] = DAG.getRoot();
6671     Ops[1] = getValue(I.getArgOperand(0));
6672     Ops[2] = getValue(I.getArgOperand(1));
6673     Ops[3] = getValue(I.getArgOperand(2));
6674     Ops[4] = getValue(I.getArgOperand(3));
6675     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6676                                              DAG.getVTList(MVT::Other), Ops,
6677                                              EVT::getIntegerVT(*Context, 8),
6678                                              MachinePointerInfo(I.getArgOperand(0)),
6679                                              0, /* align */
6680                                              Flags);
6681 
6682     // Chain the prefetch in parallell with any pending loads, to stay out of
6683     // the way of later optimizations.
6684     PendingLoads.push_back(Result);
6685     Result = getRoot();
6686     DAG.setRoot(Result);
6687     return;
6688   }
6689   case Intrinsic::lifetime_start:
6690   case Intrinsic::lifetime_end: {
6691     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6692     // Stack coloring is not enabled in O0, discard region information.
6693     if (TM.getOptLevel() == CodeGenOpt::None)
6694       return;
6695 
6696     const int64_t ObjectSize =
6697         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6698     Value *const ObjectPtr = I.getArgOperand(1);
6699     SmallVector<const Value *, 4> Allocas;
6700     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6701 
6702     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6703            E = Allocas.end(); Object != E; ++Object) {
6704       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6705 
6706       // Could not find an Alloca.
6707       if (!LifetimeObject)
6708         continue;
6709 
6710       // First check that the Alloca is static, otherwise it won't have a
6711       // valid frame index.
6712       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6713       if (SI == FuncInfo.StaticAllocaMap.end())
6714         return;
6715 
6716       const int FrameIndex = SI->second;
6717       int64_t Offset;
6718       if (GetPointerBaseWithConstantOffset(
6719               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6720         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6721       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6722                                 Offset);
6723       DAG.setRoot(Res);
6724     }
6725     return;
6726   }
6727   case Intrinsic::invariant_start:
6728     // Discard region information.
6729     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6730     return;
6731   case Intrinsic::invariant_end:
6732     // Discard region information.
6733     return;
6734   case Intrinsic::clear_cache:
6735     /// FunctionName may be null.
6736     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6737       lowerCallToExternalSymbol(I, FunctionName);
6738     return;
6739   case Intrinsic::donothing:
6740     // ignore
6741     return;
6742   case Intrinsic::experimental_stackmap:
6743     visitStackmap(I);
6744     return;
6745   case Intrinsic::experimental_patchpoint_void:
6746   case Intrinsic::experimental_patchpoint_i64:
6747     visitPatchpoint(&I);
6748     return;
6749   case Intrinsic::experimental_gc_statepoint:
6750     LowerStatepoint(ImmutableStatepoint(&I));
6751     return;
6752   case Intrinsic::experimental_gc_result:
6753     visitGCResult(cast<GCResultInst>(I));
6754     return;
6755   case Intrinsic::experimental_gc_relocate:
6756     visitGCRelocate(cast<GCRelocateInst>(I));
6757     return;
6758   case Intrinsic::instrprof_increment:
6759     llvm_unreachable("instrprof failed to lower an increment");
6760   case Intrinsic::instrprof_value_profile:
6761     llvm_unreachable("instrprof failed to lower a value profiling call");
6762   case Intrinsic::localescape: {
6763     MachineFunction &MF = DAG.getMachineFunction();
6764     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6765 
6766     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6767     // is the same on all targets.
6768     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6769       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6770       if (isa<ConstantPointerNull>(Arg))
6771         continue; // Skip null pointers. They represent a hole in index space.
6772       AllocaInst *Slot = cast<AllocaInst>(Arg);
6773       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6774              "can only escape static allocas");
6775       int FI = FuncInfo.StaticAllocaMap[Slot];
6776       MCSymbol *FrameAllocSym =
6777           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6778               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6779       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6780               TII->get(TargetOpcode::LOCAL_ESCAPE))
6781           .addSym(FrameAllocSym)
6782           .addFrameIndex(FI);
6783     }
6784 
6785     return;
6786   }
6787 
6788   case Intrinsic::localrecover: {
6789     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6790     MachineFunction &MF = DAG.getMachineFunction();
6791     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6792 
6793     // Get the symbol that defines the frame offset.
6794     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6795     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6796     unsigned IdxVal =
6797         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6798     MCSymbol *FrameAllocSym =
6799         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6800             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6801 
6802     // Create a MCSymbol for the label to avoid any target lowering
6803     // that would make this PC relative.
6804     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6805     SDValue OffsetVal =
6806         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6807 
6808     // Add the offset to the FP.
6809     Value *FP = I.getArgOperand(1);
6810     SDValue FPVal = getValue(FP);
6811     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6812     setValue(&I, Add);
6813 
6814     return;
6815   }
6816 
6817   case Intrinsic::eh_exceptionpointer:
6818   case Intrinsic::eh_exceptioncode: {
6819     // Get the exception pointer vreg, copy from it, and resize it to fit.
6820     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6821     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6822     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6823     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6824     SDValue N =
6825         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6826     if (Intrinsic == Intrinsic::eh_exceptioncode)
6827       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6828     setValue(&I, N);
6829     return;
6830   }
6831   case Intrinsic::xray_customevent: {
6832     // Here we want to make sure that the intrinsic behaves as if it has a
6833     // specific calling convention, and only for x86_64.
6834     // FIXME: Support other platforms later.
6835     const auto &Triple = DAG.getTarget().getTargetTriple();
6836     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6837       return;
6838 
6839     SDLoc DL = getCurSDLoc();
6840     SmallVector<SDValue, 8> Ops;
6841 
6842     // We want to say that we always want the arguments in registers.
6843     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6844     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6845     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6846     SDValue Chain = getRoot();
6847     Ops.push_back(LogEntryVal);
6848     Ops.push_back(StrSizeVal);
6849     Ops.push_back(Chain);
6850 
6851     // We need to enforce the calling convention for the callsite, so that
6852     // argument ordering is enforced correctly, and that register allocation can
6853     // see that some registers may be assumed clobbered and have to preserve
6854     // them across calls to the intrinsic.
6855     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6856                                            DL, NodeTys, Ops);
6857     SDValue patchableNode = SDValue(MN, 0);
6858     DAG.setRoot(patchableNode);
6859     setValue(&I, patchableNode);
6860     return;
6861   }
6862   case Intrinsic::xray_typedevent: {
6863     // Here we want to make sure that the intrinsic behaves as if it has a
6864     // specific calling convention, and only for x86_64.
6865     // FIXME: Support other platforms later.
6866     const auto &Triple = DAG.getTarget().getTargetTriple();
6867     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6868       return;
6869 
6870     SDLoc DL = getCurSDLoc();
6871     SmallVector<SDValue, 8> Ops;
6872 
6873     // We want to say that we always want the arguments in registers.
6874     // It's unclear to me how manipulating the selection DAG here forces callers
6875     // to provide arguments in registers instead of on the stack.
6876     SDValue LogTypeId = getValue(I.getArgOperand(0));
6877     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6878     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6879     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6880     SDValue Chain = getRoot();
6881     Ops.push_back(LogTypeId);
6882     Ops.push_back(LogEntryVal);
6883     Ops.push_back(StrSizeVal);
6884     Ops.push_back(Chain);
6885 
6886     // We need to enforce the calling convention for the callsite, so that
6887     // argument ordering is enforced correctly, and that register allocation can
6888     // see that some registers may be assumed clobbered and have to preserve
6889     // them across calls to the intrinsic.
6890     MachineSDNode *MN = DAG.getMachineNode(
6891         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6892     SDValue patchableNode = SDValue(MN, 0);
6893     DAG.setRoot(patchableNode);
6894     setValue(&I, patchableNode);
6895     return;
6896   }
6897   case Intrinsic::experimental_deoptimize:
6898     LowerDeoptimizeCall(&I);
6899     return;
6900 
6901   case Intrinsic::experimental_vector_reduce_v2_fadd:
6902   case Intrinsic::experimental_vector_reduce_v2_fmul:
6903   case Intrinsic::experimental_vector_reduce_add:
6904   case Intrinsic::experimental_vector_reduce_mul:
6905   case Intrinsic::experimental_vector_reduce_and:
6906   case Intrinsic::experimental_vector_reduce_or:
6907   case Intrinsic::experimental_vector_reduce_xor:
6908   case Intrinsic::experimental_vector_reduce_smax:
6909   case Intrinsic::experimental_vector_reduce_smin:
6910   case Intrinsic::experimental_vector_reduce_umax:
6911   case Intrinsic::experimental_vector_reduce_umin:
6912   case Intrinsic::experimental_vector_reduce_fmax:
6913   case Intrinsic::experimental_vector_reduce_fmin:
6914     visitVectorReduce(I, Intrinsic);
6915     return;
6916 
6917   case Intrinsic::icall_branch_funnel: {
6918     SmallVector<SDValue, 16> Ops;
6919     Ops.push_back(getValue(I.getArgOperand(0)));
6920 
6921     int64_t Offset;
6922     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6923         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6924     if (!Base)
6925       report_fatal_error(
6926           "llvm.icall.branch.funnel operand must be a GlobalValue");
6927     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6928 
6929     struct BranchFunnelTarget {
6930       int64_t Offset;
6931       SDValue Target;
6932     };
6933     SmallVector<BranchFunnelTarget, 8> Targets;
6934 
6935     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6936       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6937           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6938       if (ElemBase != Base)
6939         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6940                            "to the same GlobalValue");
6941 
6942       SDValue Val = getValue(I.getArgOperand(Op + 1));
6943       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6944       if (!GA)
6945         report_fatal_error(
6946             "llvm.icall.branch.funnel operand must be a GlobalValue");
6947       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6948                                      GA->getGlobal(), getCurSDLoc(),
6949                                      Val.getValueType(), GA->getOffset())});
6950     }
6951     llvm::sort(Targets,
6952                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6953                  return T1.Offset < T2.Offset;
6954                });
6955 
6956     for (auto &T : Targets) {
6957       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6958       Ops.push_back(T.Target);
6959     }
6960 
6961     Ops.push_back(DAG.getRoot()); // Chain
6962     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6963                                  getCurSDLoc(), MVT::Other, Ops),
6964               0);
6965     DAG.setRoot(N);
6966     setValue(&I, N);
6967     HasTailCall = true;
6968     return;
6969   }
6970 
6971   case Intrinsic::wasm_landingpad_index:
6972     // Information this intrinsic contained has been transferred to
6973     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6974     // delete it now.
6975     return;
6976 
6977   case Intrinsic::aarch64_settag:
6978   case Intrinsic::aarch64_settag_zero: {
6979     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6980     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6981     SDValue Val = TSI.EmitTargetCodeForSetTag(
6982         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6983         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6984         ZeroMemory);
6985     DAG.setRoot(Val);
6986     setValue(&I, Val);
6987     return;
6988   }
6989   case Intrinsic::ptrmask: {
6990     SDValue Ptr = getValue(I.getOperand(0));
6991     SDValue Const = getValue(I.getOperand(1));
6992 
6993     EVT DestVT =
6994         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6995 
6996     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6997                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6998     return;
6999   }
7000   }
7001 }
7002 
7003 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7004     const ConstrainedFPIntrinsic &FPI) {
7005   SDLoc sdl = getCurSDLoc();
7006 
7007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7008   SmallVector<EVT, 4> ValueVTs;
7009   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7010   ValueVTs.push_back(MVT::Other); // Out chain
7011 
7012   // We do not need to serialize constrained FP intrinsics against
7013   // each other or against (nonvolatile) loads, so they can be
7014   // chained like loads.
7015   SDValue Chain = DAG.getRoot();
7016   SmallVector<SDValue, 4> Opers;
7017   Opers.push_back(Chain);
7018   if (FPI.isUnaryOp()) {
7019     Opers.push_back(getValue(FPI.getArgOperand(0)));
7020   } else if (FPI.isTernaryOp()) {
7021     Opers.push_back(getValue(FPI.getArgOperand(0)));
7022     Opers.push_back(getValue(FPI.getArgOperand(1)));
7023     Opers.push_back(getValue(FPI.getArgOperand(2)));
7024   } else {
7025     Opers.push_back(getValue(FPI.getArgOperand(0)));
7026     Opers.push_back(getValue(FPI.getArgOperand(1)));
7027   }
7028 
7029   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7030     assert(Result.getNode()->getNumValues() == 2);
7031 
7032     // Push node to the appropriate list so that future instructions can be
7033     // chained up correctly.
7034     SDValue OutChain = Result.getValue(1);
7035     switch (EB) {
7036     case fp::ExceptionBehavior::ebIgnore:
7037       // The only reason why ebIgnore nodes still need to be chained is that
7038       // they might depend on the current rounding mode, and therefore must
7039       // not be moved across instruction that may change that mode.
7040       LLVM_FALLTHROUGH;
7041     case fp::ExceptionBehavior::ebMayTrap:
7042       // These must not be moved across calls or instructions that may change
7043       // floating-point exception masks.
7044       PendingConstrainedFP.push_back(OutChain);
7045       break;
7046     case fp::ExceptionBehavior::ebStrict:
7047       // These must not be moved across calls or instructions that may change
7048       // floating-point exception masks or read floating-point exception flags.
7049       // In addition, they cannot be optimized out even if unused.
7050       PendingConstrainedFPStrict.push_back(OutChain);
7051       break;
7052     }
7053   };
7054 
7055   SDVTList VTs = DAG.getVTList(ValueVTs);
7056   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7057 
7058   unsigned Opcode;
7059   switch (FPI.getIntrinsicID()) {
7060   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7061 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7062   case Intrinsic::INTRINSIC:                                                   \
7063     Opcode = ISD::STRICT_##DAGN;                                               \
7064     break;
7065 #include "llvm/IR/ConstrainedOps.def"
7066   case Intrinsic::experimental_constrained_fmuladd: {
7067     Opcode = ISD::STRICT_FMA;
7068     // Break fmuladd into fmul and fadd.
7069     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7070         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7071                                         ValueVTs[0])) {
7072       Opers.pop_back();
7073       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers);
7074       pushOutChain(Mul, EB);
7075       Opcode = ISD::STRICT_FADD;
7076       Opers.clear();
7077       Opers.push_back(Mul.getValue(1));
7078       Opers.push_back(Mul.getValue(0));
7079       Opers.push_back(getValue(FPI.getArgOperand(2)));
7080     }
7081     break;
7082   }
7083   }
7084 
7085   // A few strict DAG nodes carry additional operands that are not
7086   // set up by the default code above.
7087   switch (Opcode) {
7088   default: break;
7089   case ISD::STRICT_FP_ROUND:
7090     Opers.push_back(
7091         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7092     break;
7093   case ISD::STRICT_FSETCC:
7094   case ISD::STRICT_FSETCCS: {
7095     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7096     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7097     break;
7098   }
7099   }
7100 
7101   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7102   pushOutChain(Result, EB);
7103 
7104   SDValue FPResult = Result.getValue(0);
7105   setValue(&FPI, FPResult);
7106 }
7107 
7108 std::pair<SDValue, SDValue>
7109 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7110                                     const BasicBlock *EHPadBB) {
7111   MachineFunction &MF = DAG.getMachineFunction();
7112   MachineModuleInfo &MMI = MF.getMMI();
7113   MCSymbol *BeginLabel = nullptr;
7114 
7115   if (EHPadBB) {
7116     // Insert a label before the invoke call to mark the try range.  This can be
7117     // used to detect deletion of the invoke via the MachineModuleInfo.
7118     BeginLabel = MMI.getContext().createTempSymbol();
7119 
7120     // For SjLj, keep track of which landing pads go with which invokes
7121     // so as to maintain the ordering of pads in the LSDA.
7122     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7123     if (CallSiteIndex) {
7124       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7125       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7126 
7127       // Now that the call site is handled, stop tracking it.
7128       MMI.setCurrentCallSite(0);
7129     }
7130 
7131     // Both PendingLoads and PendingExports must be flushed here;
7132     // this call might not return.
7133     (void)getRoot();
7134     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7135 
7136     CLI.setChain(getRoot());
7137   }
7138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7139   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7140 
7141   assert((CLI.IsTailCall || Result.second.getNode()) &&
7142          "Non-null chain expected with non-tail call!");
7143   assert((Result.second.getNode() || !Result.first.getNode()) &&
7144          "Null value expected with tail call!");
7145 
7146   if (!Result.second.getNode()) {
7147     // As a special case, a null chain means that a tail call has been emitted
7148     // and the DAG root is already updated.
7149     HasTailCall = true;
7150 
7151     // Since there's no actual continuation from this block, nothing can be
7152     // relying on us setting vregs for them.
7153     PendingExports.clear();
7154   } else {
7155     DAG.setRoot(Result.second);
7156   }
7157 
7158   if (EHPadBB) {
7159     // Insert a label at the end of the invoke call to mark the try range.  This
7160     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7161     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7162     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7163 
7164     // Inform MachineModuleInfo of range.
7165     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7166     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7167     // actually use outlined funclets and their LSDA info style.
7168     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7169       assert(CLI.CS);
7170       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7171       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7172                                 BeginLabel, EndLabel);
7173     } else if (!isScopedEHPersonality(Pers)) {
7174       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7175     }
7176   }
7177 
7178   return Result;
7179 }
7180 
7181 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7182                                       bool isTailCall,
7183                                       const BasicBlock *EHPadBB) {
7184   auto &DL = DAG.getDataLayout();
7185   FunctionType *FTy = CS.getFunctionType();
7186   Type *RetTy = CS.getType();
7187 
7188   TargetLowering::ArgListTy Args;
7189   Args.reserve(CS.arg_size());
7190 
7191   const Value *SwiftErrorVal = nullptr;
7192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7193 
7194   if (isTailCall) {
7195     // Avoid emitting tail calls in functions with the disable-tail-calls
7196     // attribute.
7197     auto *Caller = CS.getInstruction()->getParent()->getParent();
7198     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7199         "true")
7200       isTailCall = false;
7201 
7202     // We can't tail call inside a function with a swifterror argument. Lowering
7203     // does not support this yet. It would have to move into the swifterror
7204     // register before the call.
7205     if (TLI.supportSwiftError() &&
7206         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7207       isTailCall = false;
7208   }
7209 
7210   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7211        i != e; ++i) {
7212     TargetLowering::ArgListEntry Entry;
7213     const Value *V = *i;
7214 
7215     // Skip empty types
7216     if (V->getType()->isEmptyTy())
7217       continue;
7218 
7219     SDValue ArgNode = getValue(V);
7220     Entry.Node = ArgNode; Entry.Ty = V->getType();
7221 
7222     Entry.setAttributes(&CS, i - CS.arg_begin());
7223 
7224     // Use swifterror virtual register as input to the call.
7225     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7226       SwiftErrorVal = V;
7227       // We find the virtual register for the actual swifterror argument.
7228       // Instead of using the Value, we use the virtual register instead.
7229       Entry.Node = DAG.getRegister(
7230           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7231           EVT(TLI.getPointerTy(DL)));
7232     }
7233 
7234     Args.push_back(Entry);
7235 
7236     // If we have an explicit sret argument that is an Instruction, (i.e., it
7237     // might point to function-local memory), we can't meaningfully tail-call.
7238     if (Entry.IsSRet && isa<Instruction>(V))
7239       isTailCall = false;
7240   }
7241 
7242   // If call site has a cfguardtarget operand bundle, create and add an
7243   // additional ArgListEntry.
7244   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7245     TargetLowering::ArgListEntry Entry;
7246     Value *V = Bundle->Inputs[0];
7247     SDValue ArgNode = getValue(V);
7248     Entry.Node = ArgNode;
7249     Entry.Ty = V->getType();
7250     Entry.IsCFGuardTarget = true;
7251     Args.push_back(Entry);
7252   }
7253 
7254   // Check if target-independent constraints permit a tail call here.
7255   // Target-dependent constraints are checked within TLI->LowerCallTo.
7256   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7257     isTailCall = false;
7258 
7259   // Disable tail calls if there is an swifterror argument. Targets have not
7260   // been updated to support tail calls.
7261   if (TLI.supportSwiftError() && SwiftErrorVal)
7262     isTailCall = false;
7263 
7264   TargetLowering::CallLoweringInfo CLI(DAG);
7265   CLI.setDebugLoc(getCurSDLoc())
7266       .setChain(getRoot())
7267       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7268       .setTailCall(isTailCall)
7269       .setConvergent(CS.isConvergent());
7270   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7271 
7272   if (Result.first.getNode()) {
7273     const Instruction *Inst = CS.getInstruction();
7274     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7275     setValue(Inst, Result.first);
7276   }
7277 
7278   // The last element of CLI.InVals has the SDValue for swifterror return.
7279   // Here we copy it to a virtual register and update SwiftErrorMap for
7280   // book-keeping.
7281   if (SwiftErrorVal && TLI.supportSwiftError()) {
7282     // Get the last element of InVals.
7283     SDValue Src = CLI.InVals.back();
7284     Register VReg = SwiftError.getOrCreateVRegDefAt(
7285         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7286     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7287     DAG.setRoot(CopyNode);
7288   }
7289 }
7290 
7291 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7292                              SelectionDAGBuilder &Builder) {
7293   // Check to see if this load can be trivially constant folded, e.g. if the
7294   // input is from a string literal.
7295   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7296     // Cast pointer to the type we really want to load.
7297     Type *LoadTy =
7298         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7299     if (LoadVT.isVector())
7300       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7301 
7302     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7303                                          PointerType::getUnqual(LoadTy));
7304 
7305     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7306             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7307       return Builder.getValue(LoadCst);
7308   }
7309 
7310   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7311   // still constant memory, the input chain can be the entry node.
7312   SDValue Root;
7313   bool ConstantMemory = false;
7314 
7315   // Do not serialize (non-volatile) loads of constant memory with anything.
7316   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7317     Root = Builder.DAG.getEntryNode();
7318     ConstantMemory = true;
7319   } else {
7320     // Do not serialize non-volatile loads against each other.
7321     Root = Builder.DAG.getRoot();
7322   }
7323 
7324   SDValue Ptr = Builder.getValue(PtrVal);
7325   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7326                                         Ptr, MachinePointerInfo(PtrVal),
7327                                         /* Alignment = */ 1);
7328 
7329   if (!ConstantMemory)
7330     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7331   return LoadVal;
7332 }
7333 
7334 /// Record the value for an instruction that produces an integer result,
7335 /// converting the type where necessary.
7336 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7337                                                   SDValue Value,
7338                                                   bool IsSigned) {
7339   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7340                                                     I.getType(), true);
7341   if (IsSigned)
7342     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7343   else
7344     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7345   setValue(&I, Value);
7346 }
7347 
7348 /// See if we can lower a memcmp call into an optimized form. If so, return
7349 /// true and lower it. Otherwise return false, and it will be lowered like a
7350 /// normal call.
7351 /// The caller already checked that \p I calls the appropriate LibFunc with a
7352 /// correct prototype.
7353 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7354   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7355   const Value *Size = I.getArgOperand(2);
7356   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7357   if (CSize && CSize->getZExtValue() == 0) {
7358     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7359                                                           I.getType(), true);
7360     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7361     return true;
7362   }
7363 
7364   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7365   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7366       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7367       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7368   if (Res.first.getNode()) {
7369     processIntegerCallValue(I, Res.first, true);
7370     PendingLoads.push_back(Res.second);
7371     return true;
7372   }
7373 
7374   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7375   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7376   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7377     return false;
7378 
7379   // If the target has a fast compare for the given size, it will return a
7380   // preferred load type for that size. Require that the load VT is legal and
7381   // that the target supports unaligned loads of that type. Otherwise, return
7382   // INVALID.
7383   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7384     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7385     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7386     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7387       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7388       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7389       // TODO: Check alignment of src and dest ptrs.
7390       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7391       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7392       if (!TLI.isTypeLegal(LVT) ||
7393           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7394           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7395         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7396     }
7397 
7398     return LVT;
7399   };
7400 
7401   // This turns into unaligned loads. We only do this if the target natively
7402   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7403   // we'll only produce a small number of byte loads.
7404   MVT LoadVT;
7405   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7406   switch (NumBitsToCompare) {
7407   default:
7408     return false;
7409   case 16:
7410     LoadVT = MVT::i16;
7411     break;
7412   case 32:
7413     LoadVT = MVT::i32;
7414     break;
7415   case 64:
7416   case 128:
7417   case 256:
7418     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7419     break;
7420   }
7421 
7422   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7423     return false;
7424 
7425   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7426   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7427 
7428   // Bitcast to a wide integer type if the loads are vectors.
7429   if (LoadVT.isVector()) {
7430     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7431     LoadL = DAG.getBitcast(CmpVT, LoadL);
7432     LoadR = DAG.getBitcast(CmpVT, LoadR);
7433   }
7434 
7435   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7436   processIntegerCallValue(I, Cmp, false);
7437   return true;
7438 }
7439 
7440 /// See if we can lower a memchr call into an optimized form. If so, return
7441 /// true and lower it. Otherwise return false, and it will be lowered like a
7442 /// normal call.
7443 /// The caller already checked that \p I calls the appropriate LibFunc with a
7444 /// correct prototype.
7445 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7446   const Value *Src = I.getArgOperand(0);
7447   const Value *Char = I.getArgOperand(1);
7448   const Value *Length = I.getArgOperand(2);
7449 
7450   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7451   std::pair<SDValue, SDValue> Res =
7452     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7453                                 getValue(Src), getValue(Char), getValue(Length),
7454                                 MachinePointerInfo(Src));
7455   if (Res.first.getNode()) {
7456     setValue(&I, Res.first);
7457     PendingLoads.push_back(Res.second);
7458     return true;
7459   }
7460 
7461   return false;
7462 }
7463 
7464 /// See if we can lower a mempcpy call into an optimized form. If so, return
7465 /// true and lower it. Otherwise return false, and it will be lowered like a
7466 /// normal call.
7467 /// The caller already checked that \p I calls the appropriate LibFunc with a
7468 /// correct prototype.
7469 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7470   SDValue Dst = getValue(I.getArgOperand(0));
7471   SDValue Src = getValue(I.getArgOperand(1));
7472   SDValue Size = getValue(I.getArgOperand(2));
7473 
7474   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7475   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7476   // DAG::getMemcpy needs Alignment to be defined.
7477   Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign));
7478 
7479   bool isVol = false;
7480   SDLoc sdl = getCurSDLoc();
7481 
7482   // In the mempcpy context we need to pass in a false value for isTailCall
7483   // because the return pointer needs to be adjusted by the size of
7484   // the copied memory.
7485   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7486   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7487                              /*isTailCall=*/false,
7488                              MachinePointerInfo(I.getArgOperand(0)),
7489                              MachinePointerInfo(I.getArgOperand(1)));
7490   assert(MC.getNode() != nullptr &&
7491          "** memcpy should not be lowered as TailCall in mempcpy context **");
7492   DAG.setRoot(MC);
7493 
7494   // Check if Size needs to be truncated or extended.
7495   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7496 
7497   // Adjust return pointer to point just past the last dst byte.
7498   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7499                                     Dst, Size);
7500   setValue(&I, DstPlusSize);
7501   return true;
7502 }
7503 
7504 /// See if we can lower a strcpy call into an optimized form.  If so, return
7505 /// true and lower it, otherwise return false and it will be lowered like a
7506 /// normal call.
7507 /// The caller already checked that \p I calls the appropriate LibFunc with a
7508 /// correct prototype.
7509 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7510   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7511 
7512   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7513   std::pair<SDValue, SDValue> Res =
7514     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7515                                 getValue(Arg0), getValue(Arg1),
7516                                 MachinePointerInfo(Arg0),
7517                                 MachinePointerInfo(Arg1), isStpcpy);
7518   if (Res.first.getNode()) {
7519     setValue(&I, Res.first);
7520     DAG.setRoot(Res.second);
7521     return true;
7522   }
7523 
7524   return false;
7525 }
7526 
7527 /// See if we can lower a strcmp call into an optimized form.  If so, return
7528 /// true and lower it, otherwise return false and it will be lowered like a
7529 /// normal call.
7530 /// The caller already checked that \p I calls the appropriate LibFunc with a
7531 /// correct prototype.
7532 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7533   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7534 
7535   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7536   std::pair<SDValue, SDValue> Res =
7537     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7538                                 getValue(Arg0), getValue(Arg1),
7539                                 MachinePointerInfo(Arg0),
7540                                 MachinePointerInfo(Arg1));
7541   if (Res.first.getNode()) {
7542     processIntegerCallValue(I, Res.first, true);
7543     PendingLoads.push_back(Res.second);
7544     return true;
7545   }
7546 
7547   return false;
7548 }
7549 
7550 /// See if we can lower a strlen call into an optimized form.  If so, return
7551 /// true and lower it, otherwise return false and it will be lowered like a
7552 /// normal call.
7553 /// The caller already checked that \p I calls the appropriate LibFunc with a
7554 /// correct prototype.
7555 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7556   const Value *Arg0 = I.getArgOperand(0);
7557 
7558   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7559   std::pair<SDValue, SDValue> Res =
7560     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7561                                 getValue(Arg0), MachinePointerInfo(Arg0));
7562   if (Res.first.getNode()) {
7563     processIntegerCallValue(I, Res.first, false);
7564     PendingLoads.push_back(Res.second);
7565     return true;
7566   }
7567 
7568   return false;
7569 }
7570 
7571 /// See if we can lower a strnlen call into an optimized form.  If so, return
7572 /// true and lower it, otherwise return false and it will be lowered like a
7573 /// normal call.
7574 /// The caller already checked that \p I calls the appropriate LibFunc with a
7575 /// correct prototype.
7576 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7577   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7578 
7579   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7580   std::pair<SDValue, SDValue> Res =
7581     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7582                                  getValue(Arg0), getValue(Arg1),
7583                                  MachinePointerInfo(Arg0));
7584   if (Res.first.getNode()) {
7585     processIntegerCallValue(I, Res.first, false);
7586     PendingLoads.push_back(Res.second);
7587     return true;
7588   }
7589 
7590   return false;
7591 }
7592 
7593 /// See if we can lower a unary floating-point operation into an SDNode with
7594 /// the specified Opcode.  If so, return true and lower it, otherwise return
7595 /// false and it will be lowered like a normal call.
7596 /// The caller already checked that \p I calls the appropriate LibFunc with a
7597 /// correct prototype.
7598 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7599                                               unsigned Opcode) {
7600   // We already checked this call's prototype; verify it doesn't modify errno.
7601   if (!I.onlyReadsMemory())
7602     return false;
7603 
7604   SDValue Tmp = getValue(I.getArgOperand(0));
7605   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7606   return true;
7607 }
7608 
7609 /// See if we can lower a binary floating-point operation into an SDNode with
7610 /// the specified Opcode. If so, return true and lower it. Otherwise return
7611 /// false, and it will be lowered like a normal call.
7612 /// The caller already checked that \p I calls the appropriate LibFunc with a
7613 /// correct prototype.
7614 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7615                                                unsigned Opcode) {
7616   // We already checked this call's prototype; verify it doesn't modify errno.
7617   if (!I.onlyReadsMemory())
7618     return false;
7619 
7620   SDValue Tmp0 = getValue(I.getArgOperand(0));
7621   SDValue Tmp1 = getValue(I.getArgOperand(1));
7622   EVT VT = Tmp0.getValueType();
7623   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7624   return true;
7625 }
7626 
7627 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7628   // Handle inline assembly differently.
7629   if (isa<InlineAsm>(I.getCalledValue())) {
7630     visitInlineAsm(&I);
7631     return;
7632   }
7633 
7634   if (Function *F = I.getCalledFunction()) {
7635     if (F->isDeclaration()) {
7636       // Is this an LLVM intrinsic or a target-specific intrinsic?
7637       unsigned IID = F->getIntrinsicID();
7638       if (!IID)
7639         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7640           IID = II->getIntrinsicID(F);
7641 
7642       if (IID) {
7643         visitIntrinsicCall(I, IID);
7644         return;
7645       }
7646     }
7647 
7648     // Check for well-known libc/libm calls.  If the function is internal, it
7649     // can't be a library call.  Don't do the check if marked as nobuiltin for
7650     // some reason or the call site requires strict floating point semantics.
7651     LibFunc Func;
7652     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7653         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7654         LibInfo->hasOptimizedCodeGen(Func)) {
7655       switch (Func) {
7656       default: break;
7657       case LibFunc_copysign:
7658       case LibFunc_copysignf:
7659       case LibFunc_copysignl:
7660         // We already checked this call's prototype; verify it doesn't modify
7661         // errno.
7662         if (I.onlyReadsMemory()) {
7663           SDValue LHS = getValue(I.getArgOperand(0));
7664           SDValue RHS = getValue(I.getArgOperand(1));
7665           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7666                                    LHS.getValueType(), LHS, RHS));
7667           return;
7668         }
7669         break;
7670       case LibFunc_fabs:
7671       case LibFunc_fabsf:
7672       case LibFunc_fabsl:
7673         if (visitUnaryFloatCall(I, ISD::FABS))
7674           return;
7675         break;
7676       case LibFunc_fmin:
7677       case LibFunc_fminf:
7678       case LibFunc_fminl:
7679         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7680           return;
7681         break;
7682       case LibFunc_fmax:
7683       case LibFunc_fmaxf:
7684       case LibFunc_fmaxl:
7685         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7686           return;
7687         break;
7688       case LibFunc_sin:
7689       case LibFunc_sinf:
7690       case LibFunc_sinl:
7691         if (visitUnaryFloatCall(I, ISD::FSIN))
7692           return;
7693         break;
7694       case LibFunc_cos:
7695       case LibFunc_cosf:
7696       case LibFunc_cosl:
7697         if (visitUnaryFloatCall(I, ISD::FCOS))
7698           return;
7699         break;
7700       case LibFunc_sqrt:
7701       case LibFunc_sqrtf:
7702       case LibFunc_sqrtl:
7703       case LibFunc_sqrt_finite:
7704       case LibFunc_sqrtf_finite:
7705       case LibFunc_sqrtl_finite:
7706         if (visitUnaryFloatCall(I, ISD::FSQRT))
7707           return;
7708         break;
7709       case LibFunc_floor:
7710       case LibFunc_floorf:
7711       case LibFunc_floorl:
7712         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7713           return;
7714         break;
7715       case LibFunc_nearbyint:
7716       case LibFunc_nearbyintf:
7717       case LibFunc_nearbyintl:
7718         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7719           return;
7720         break;
7721       case LibFunc_ceil:
7722       case LibFunc_ceilf:
7723       case LibFunc_ceill:
7724         if (visitUnaryFloatCall(I, ISD::FCEIL))
7725           return;
7726         break;
7727       case LibFunc_rint:
7728       case LibFunc_rintf:
7729       case LibFunc_rintl:
7730         if (visitUnaryFloatCall(I, ISD::FRINT))
7731           return;
7732         break;
7733       case LibFunc_round:
7734       case LibFunc_roundf:
7735       case LibFunc_roundl:
7736         if (visitUnaryFloatCall(I, ISD::FROUND))
7737           return;
7738         break;
7739       case LibFunc_trunc:
7740       case LibFunc_truncf:
7741       case LibFunc_truncl:
7742         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7743           return;
7744         break;
7745       case LibFunc_log2:
7746       case LibFunc_log2f:
7747       case LibFunc_log2l:
7748         if (visitUnaryFloatCall(I, ISD::FLOG2))
7749           return;
7750         break;
7751       case LibFunc_exp2:
7752       case LibFunc_exp2f:
7753       case LibFunc_exp2l:
7754         if (visitUnaryFloatCall(I, ISD::FEXP2))
7755           return;
7756         break;
7757       case LibFunc_memcmp:
7758         if (visitMemCmpCall(I))
7759           return;
7760         break;
7761       case LibFunc_mempcpy:
7762         if (visitMemPCpyCall(I))
7763           return;
7764         break;
7765       case LibFunc_memchr:
7766         if (visitMemChrCall(I))
7767           return;
7768         break;
7769       case LibFunc_strcpy:
7770         if (visitStrCpyCall(I, false))
7771           return;
7772         break;
7773       case LibFunc_stpcpy:
7774         if (visitStrCpyCall(I, true))
7775           return;
7776         break;
7777       case LibFunc_strcmp:
7778         if (visitStrCmpCall(I))
7779           return;
7780         break;
7781       case LibFunc_strlen:
7782         if (visitStrLenCall(I))
7783           return;
7784         break;
7785       case LibFunc_strnlen:
7786         if (visitStrNLenCall(I))
7787           return;
7788         break;
7789       }
7790     }
7791   }
7792 
7793   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7794   // have to do anything here to lower funclet bundles.
7795   // CFGuardTarget bundles are lowered in LowerCallTo.
7796   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7797                                         LLVMContext::OB_funclet,
7798                                         LLVMContext::OB_cfguardtarget}) &&
7799          "Cannot lower calls with arbitrary operand bundles!");
7800 
7801   SDValue Callee = getValue(I.getCalledValue());
7802 
7803   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7804     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7805   else
7806     // Check if we can potentially perform a tail call. More detailed checking
7807     // is be done within LowerCallTo, after more information about the call is
7808     // known.
7809     LowerCallTo(&I, Callee, I.isTailCall());
7810 }
7811 
7812 namespace {
7813 
7814 /// AsmOperandInfo - This contains information for each constraint that we are
7815 /// lowering.
7816 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7817 public:
7818   /// CallOperand - If this is the result output operand or a clobber
7819   /// this is null, otherwise it is the incoming operand to the CallInst.
7820   /// This gets modified as the asm is processed.
7821   SDValue CallOperand;
7822 
7823   /// AssignedRegs - If this is a register or register class operand, this
7824   /// contains the set of register corresponding to the operand.
7825   RegsForValue AssignedRegs;
7826 
7827   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7828     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7829   }
7830 
7831   /// Whether or not this operand accesses memory
7832   bool hasMemory(const TargetLowering &TLI) const {
7833     // Indirect operand accesses access memory.
7834     if (isIndirect)
7835       return true;
7836 
7837     for (const auto &Code : Codes)
7838       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7839         return true;
7840 
7841     return false;
7842   }
7843 
7844   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7845   /// corresponds to.  If there is no Value* for this operand, it returns
7846   /// MVT::Other.
7847   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7848                            const DataLayout &DL) const {
7849     if (!CallOperandVal) return MVT::Other;
7850 
7851     if (isa<BasicBlock>(CallOperandVal))
7852       return TLI.getPointerTy(DL);
7853 
7854     llvm::Type *OpTy = CallOperandVal->getType();
7855 
7856     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7857     // If this is an indirect operand, the operand is a pointer to the
7858     // accessed type.
7859     if (isIndirect) {
7860       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7861       if (!PtrTy)
7862         report_fatal_error("Indirect operand for inline asm not a pointer!");
7863       OpTy = PtrTy->getElementType();
7864     }
7865 
7866     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7867     if (StructType *STy = dyn_cast<StructType>(OpTy))
7868       if (STy->getNumElements() == 1)
7869         OpTy = STy->getElementType(0);
7870 
7871     // If OpTy is not a single value, it may be a struct/union that we
7872     // can tile with integers.
7873     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7874       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7875       switch (BitSize) {
7876       default: break;
7877       case 1:
7878       case 8:
7879       case 16:
7880       case 32:
7881       case 64:
7882       case 128:
7883         OpTy = IntegerType::get(Context, BitSize);
7884         break;
7885       }
7886     }
7887 
7888     return TLI.getValueType(DL, OpTy, true);
7889   }
7890 };
7891 
7892 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7893 
7894 } // end anonymous namespace
7895 
7896 /// Make sure that the output operand \p OpInfo and its corresponding input
7897 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7898 /// out).
7899 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7900                                SDISelAsmOperandInfo &MatchingOpInfo,
7901                                SelectionDAG &DAG) {
7902   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7903     return;
7904 
7905   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7906   const auto &TLI = DAG.getTargetLoweringInfo();
7907 
7908   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7909       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7910                                        OpInfo.ConstraintVT);
7911   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7912       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7913                                        MatchingOpInfo.ConstraintVT);
7914   if ((OpInfo.ConstraintVT.isInteger() !=
7915        MatchingOpInfo.ConstraintVT.isInteger()) ||
7916       (MatchRC.second != InputRC.second)) {
7917     // FIXME: error out in a more elegant fashion
7918     report_fatal_error("Unsupported asm: input constraint"
7919                        " with a matching output constraint of"
7920                        " incompatible type!");
7921   }
7922   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7923 }
7924 
7925 /// Get a direct memory input to behave well as an indirect operand.
7926 /// This may introduce stores, hence the need for a \p Chain.
7927 /// \return The (possibly updated) chain.
7928 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7929                                         SDISelAsmOperandInfo &OpInfo,
7930                                         SelectionDAG &DAG) {
7931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7932 
7933   // If we don't have an indirect input, put it in the constpool if we can,
7934   // otherwise spill it to a stack slot.
7935   // TODO: This isn't quite right. We need to handle these according to
7936   // the addressing mode that the constraint wants. Also, this may take
7937   // an additional register for the computation and we don't want that
7938   // either.
7939 
7940   // If the operand is a float, integer, or vector constant, spill to a
7941   // constant pool entry to get its address.
7942   const Value *OpVal = OpInfo.CallOperandVal;
7943   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7944       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7945     OpInfo.CallOperand = DAG.getConstantPool(
7946         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7947     return Chain;
7948   }
7949 
7950   // Otherwise, create a stack slot and emit a store to it before the asm.
7951   Type *Ty = OpVal->getType();
7952   auto &DL = DAG.getDataLayout();
7953   uint64_t TySize = DL.getTypeAllocSize(Ty);
7954   unsigned Align = DL.getPrefTypeAlignment(Ty);
7955   MachineFunction &MF = DAG.getMachineFunction();
7956   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7957   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7958   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7959                             MachinePointerInfo::getFixedStack(MF, SSFI),
7960                             TLI.getMemValueType(DL, Ty));
7961   OpInfo.CallOperand = StackSlot;
7962 
7963   return Chain;
7964 }
7965 
7966 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7967 /// specified operand.  We prefer to assign virtual registers, to allow the
7968 /// register allocator to handle the assignment process.  However, if the asm
7969 /// uses features that we can't model on machineinstrs, we have SDISel do the
7970 /// allocation.  This produces generally horrible, but correct, code.
7971 ///
7972 ///   OpInfo describes the operand
7973 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7974 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7975                                  SDISelAsmOperandInfo &OpInfo,
7976                                  SDISelAsmOperandInfo &RefOpInfo) {
7977   LLVMContext &Context = *DAG.getContext();
7978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7979 
7980   MachineFunction &MF = DAG.getMachineFunction();
7981   SmallVector<unsigned, 4> Regs;
7982   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7983 
7984   // No work to do for memory operations.
7985   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7986     return;
7987 
7988   // If this is a constraint for a single physreg, or a constraint for a
7989   // register class, find it.
7990   unsigned AssignedReg;
7991   const TargetRegisterClass *RC;
7992   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7993       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7994   // RC is unset only on failure. Return immediately.
7995   if (!RC)
7996     return;
7997 
7998   // Get the actual register value type.  This is important, because the user
7999   // may have asked for (e.g.) the AX register in i32 type.  We need to
8000   // remember that AX is actually i16 to get the right extension.
8001   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8002 
8003   if (OpInfo.ConstraintVT != MVT::Other) {
8004     // If this is an FP operand in an integer register (or visa versa), or more
8005     // generally if the operand value disagrees with the register class we plan
8006     // to stick it in, fix the operand type.
8007     //
8008     // If this is an input value, the bitcast to the new type is done now.
8009     // Bitcast for output value is done at the end of visitInlineAsm().
8010     if ((OpInfo.Type == InlineAsm::isOutput ||
8011          OpInfo.Type == InlineAsm::isInput) &&
8012         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8013       // Try to convert to the first EVT that the reg class contains.  If the
8014       // types are identical size, use a bitcast to convert (e.g. two differing
8015       // vector types).  Note: output bitcast is done at the end of
8016       // visitInlineAsm().
8017       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8018         // Exclude indirect inputs while they are unsupported because the code
8019         // to perform the load is missing and thus OpInfo.CallOperand still
8020         // refers to the input address rather than the pointed-to value.
8021         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8022           OpInfo.CallOperand =
8023               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8024         OpInfo.ConstraintVT = RegVT;
8025         // If the operand is an FP value and we want it in integer registers,
8026         // use the corresponding integer type. This turns an f64 value into
8027         // i64, which can be passed with two i32 values on a 32-bit machine.
8028       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8029         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8030         if (OpInfo.Type == InlineAsm::isInput)
8031           OpInfo.CallOperand =
8032               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8033         OpInfo.ConstraintVT = VT;
8034       }
8035     }
8036   }
8037 
8038   // No need to allocate a matching input constraint since the constraint it's
8039   // matching to has already been allocated.
8040   if (OpInfo.isMatchingInputConstraint())
8041     return;
8042 
8043   EVT ValueVT = OpInfo.ConstraintVT;
8044   if (OpInfo.ConstraintVT == MVT::Other)
8045     ValueVT = RegVT;
8046 
8047   // Initialize NumRegs.
8048   unsigned NumRegs = 1;
8049   if (OpInfo.ConstraintVT != MVT::Other)
8050     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8051 
8052   // If this is a constraint for a specific physical register, like {r17},
8053   // assign it now.
8054 
8055   // If this associated to a specific register, initialize iterator to correct
8056   // place. If virtual, make sure we have enough registers
8057 
8058   // Initialize iterator if necessary
8059   TargetRegisterClass::iterator I = RC->begin();
8060   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8061 
8062   // Do not check for single registers.
8063   if (AssignedReg) {
8064       for (; *I != AssignedReg; ++I)
8065         assert(I != RC->end() && "AssignedReg should be member of RC");
8066   }
8067 
8068   for (; NumRegs; --NumRegs, ++I) {
8069     assert(I != RC->end() && "Ran out of registers to allocate!");
8070     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8071     Regs.push_back(R);
8072   }
8073 
8074   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8075 }
8076 
8077 static unsigned
8078 findMatchingInlineAsmOperand(unsigned OperandNo,
8079                              const std::vector<SDValue> &AsmNodeOperands) {
8080   // Scan until we find the definition we already emitted of this operand.
8081   unsigned CurOp = InlineAsm::Op_FirstOperand;
8082   for (; OperandNo; --OperandNo) {
8083     // Advance to the next operand.
8084     unsigned OpFlag =
8085         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8086     assert((InlineAsm::isRegDefKind(OpFlag) ||
8087             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8088             InlineAsm::isMemKind(OpFlag)) &&
8089            "Skipped past definitions?");
8090     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8091   }
8092   return CurOp;
8093 }
8094 
8095 namespace {
8096 
8097 class ExtraFlags {
8098   unsigned Flags = 0;
8099 
8100 public:
8101   explicit ExtraFlags(ImmutableCallSite CS) {
8102     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8103     if (IA->hasSideEffects())
8104       Flags |= InlineAsm::Extra_HasSideEffects;
8105     if (IA->isAlignStack())
8106       Flags |= InlineAsm::Extra_IsAlignStack;
8107     if (CS.isConvergent())
8108       Flags |= InlineAsm::Extra_IsConvergent;
8109     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8110   }
8111 
8112   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8113     // Ideally, we would only check against memory constraints.  However, the
8114     // meaning of an Other constraint can be target-specific and we can't easily
8115     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8116     // for Other constraints as well.
8117     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8118         OpInfo.ConstraintType == TargetLowering::C_Other) {
8119       if (OpInfo.Type == InlineAsm::isInput)
8120         Flags |= InlineAsm::Extra_MayLoad;
8121       else if (OpInfo.Type == InlineAsm::isOutput)
8122         Flags |= InlineAsm::Extra_MayStore;
8123       else if (OpInfo.Type == InlineAsm::isClobber)
8124         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8125     }
8126   }
8127 
8128   unsigned get() const { return Flags; }
8129 };
8130 
8131 } // end anonymous namespace
8132 
8133 /// visitInlineAsm - Handle a call to an InlineAsm object.
8134 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8135   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8136 
8137   /// ConstraintOperands - Information about all of the constraints.
8138   SDISelAsmOperandInfoVector ConstraintOperands;
8139 
8140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8141   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8142       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8143 
8144   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8145   // AsmDialect, MayLoad, MayStore).
8146   bool HasSideEffect = IA->hasSideEffects();
8147   ExtraFlags ExtraInfo(CS);
8148 
8149   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8150   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8151   for (auto &T : TargetConstraints) {
8152     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8153     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8154 
8155     // Compute the value type for each operand.
8156     if (OpInfo.Type == InlineAsm::isInput ||
8157         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8158       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8159 
8160       // Process the call argument. BasicBlocks are labels, currently appearing
8161       // only in asm's.
8162       const Instruction *I = CS.getInstruction();
8163       if (isa<CallBrInst>(I) &&
8164           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8165                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8166         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8167         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8168         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8169       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8170         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8171       } else {
8172         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8173       }
8174 
8175       OpInfo.ConstraintVT =
8176           OpInfo
8177               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8178               .getSimpleVT();
8179     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8180       // The return value of the call is this value.  As such, there is no
8181       // corresponding argument.
8182       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8183       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8184         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8185             DAG.getDataLayout(), STy->getElementType(ResNo));
8186       } else {
8187         assert(ResNo == 0 && "Asm only has one result!");
8188         OpInfo.ConstraintVT =
8189             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8190       }
8191       ++ResNo;
8192     } else {
8193       OpInfo.ConstraintVT = MVT::Other;
8194     }
8195 
8196     if (!HasSideEffect)
8197       HasSideEffect = OpInfo.hasMemory(TLI);
8198 
8199     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8200     // FIXME: Could we compute this on OpInfo rather than T?
8201 
8202     // Compute the constraint code and ConstraintType to use.
8203     TLI.ComputeConstraintToUse(T, SDValue());
8204 
8205     if (T.ConstraintType == TargetLowering::C_Immediate &&
8206         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8207       // We've delayed emitting a diagnostic like the "n" constraint because
8208       // inlining could cause an integer showing up.
8209       return emitInlineAsmError(
8210           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8211                   "integer constant expression");
8212 
8213     ExtraInfo.update(T);
8214   }
8215 
8216 
8217   // We won't need to flush pending loads if this asm doesn't touch
8218   // memory and is nonvolatile.
8219   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8220 
8221   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8222   if (IsCallBr) {
8223     // If this is a callbr we need to flush pending exports since inlineasm_br
8224     // is a terminator. We need to do this before nodes are glued to
8225     // the inlineasm_br node.
8226     Chain = getControlRoot();
8227   }
8228 
8229   // Second pass over the constraints: compute which constraint option to use.
8230   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8231     // If this is an output operand with a matching input operand, look up the
8232     // matching input. If their types mismatch, e.g. one is an integer, the
8233     // other is floating point, or their sizes are different, flag it as an
8234     // error.
8235     if (OpInfo.hasMatchingInput()) {
8236       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8237       patchMatchingInput(OpInfo, Input, DAG);
8238     }
8239 
8240     // Compute the constraint code and ConstraintType to use.
8241     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8242 
8243     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8244         OpInfo.Type == InlineAsm::isClobber)
8245       continue;
8246 
8247     // If this is a memory input, and if the operand is not indirect, do what we
8248     // need to provide an address for the memory input.
8249     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8250         !OpInfo.isIndirect) {
8251       assert((OpInfo.isMultipleAlternative ||
8252               (OpInfo.Type == InlineAsm::isInput)) &&
8253              "Can only indirectify direct input operands!");
8254 
8255       // Memory operands really want the address of the value.
8256       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8257 
8258       // There is no longer a Value* corresponding to this operand.
8259       OpInfo.CallOperandVal = nullptr;
8260 
8261       // It is now an indirect operand.
8262       OpInfo.isIndirect = true;
8263     }
8264 
8265   }
8266 
8267   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8268   std::vector<SDValue> AsmNodeOperands;
8269   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8270   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8271       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8272 
8273   // If we have a !srcloc metadata node associated with it, we want to attach
8274   // this to the ultimately generated inline asm machineinstr.  To do this, we
8275   // pass in the third operand as this (potentially null) inline asm MDNode.
8276   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8277   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8278 
8279   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8280   // bits as operand 3.
8281   AsmNodeOperands.push_back(DAG.getTargetConstant(
8282       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8283 
8284   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8285   // this, assign virtual and physical registers for inputs and otput.
8286   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8287     // Assign Registers.
8288     SDISelAsmOperandInfo &RefOpInfo =
8289         OpInfo.isMatchingInputConstraint()
8290             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8291             : OpInfo;
8292     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8293 
8294     switch (OpInfo.Type) {
8295     case InlineAsm::isOutput:
8296       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8297         unsigned ConstraintID =
8298             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8299         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8300                "Failed to convert memory constraint code to constraint id.");
8301 
8302         // Add information to the INLINEASM node to know about this output.
8303         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8304         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8305         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8306                                                         MVT::i32));
8307         AsmNodeOperands.push_back(OpInfo.CallOperand);
8308       } else {
8309         // Otherwise, this outputs to a register (directly for C_Register /
8310         // C_RegisterClass, and a target-defined fashion for
8311         // C_Immediate/C_Other). Find a register that we can use.
8312         if (OpInfo.AssignedRegs.Regs.empty()) {
8313           emitInlineAsmError(
8314               CS, "couldn't allocate output register for constraint '" +
8315                       Twine(OpInfo.ConstraintCode) + "'");
8316           return;
8317         }
8318 
8319         // Add information to the INLINEASM node to know that this register is
8320         // set.
8321         OpInfo.AssignedRegs.AddInlineAsmOperands(
8322             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8323                                   : InlineAsm::Kind_RegDef,
8324             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8325       }
8326       break;
8327 
8328     case InlineAsm::isInput: {
8329       SDValue InOperandVal = OpInfo.CallOperand;
8330 
8331       if (OpInfo.isMatchingInputConstraint()) {
8332         // If this is required to match an output register we have already set,
8333         // just use its register.
8334         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8335                                                   AsmNodeOperands);
8336         unsigned OpFlag =
8337           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8338         if (InlineAsm::isRegDefKind(OpFlag) ||
8339             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8340           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8341           if (OpInfo.isIndirect) {
8342             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8343             emitInlineAsmError(CS, "inline asm not supported yet:"
8344                                    " don't know how to handle tied "
8345                                    "indirect register inputs");
8346             return;
8347           }
8348 
8349           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8350           SmallVector<unsigned, 4> Regs;
8351 
8352           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8353             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8354             MachineRegisterInfo &RegInfo =
8355                 DAG.getMachineFunction().getRegInfo();
8356             for (unsigned i = 0; i != NumRegs; ++i)
8357               Regs.push_back(RegInfo.createVirtualRegister(RC));
8358           } else {
8359             emitInlineAsmError(CS, "inline asm error: This value type register "
8360                                    "class is not natively supported!");
8361             return;
8362           }
8363 
8364           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8365 
8366           SDLoc dl = getCurSDLoc();
8367           // Use the produced MatchedRegs object to
8368           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8369                                     CS.getInstruction());
8370           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8371                                            true, OpInfo.getMatchedOperand(), dl,
8372                                            DAG, AsmNodeOperands);
8373           break;
8374         }
8375 
8376         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8377         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8378                "Unexpected number of operands");
8379         // Add information to the INLINEASM node to know about this input.
8380         // See InlineAsm.h isUseOperandTiedToDef.
8381         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8382         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8383                                                     OpInfo.getMatchedOperand());
8384         AsmNodeOperands.push_back(DAG.getTargetConstant(
8385             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8386         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8387         break;
8388       }
8389 
8390       // Treat indirect 'X' constraint as memory.
8391       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8392           OpInfo.isIndirect)
8393         OpInfo.ConstraintType = TargetLowering::C_Memory;
8394 
8395       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8396           OpInfo.ConstraintType == TargetLowering::C_Other) {
8397         std::vector<SDValue> Ops;
8398         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8399                                           Ops, DAG);
8400         if (Ops.empty()) {
8401           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8402             if (isa<ConstantSDNode>(InOperandVal)) {
8403               emitInlineAsmError(CS, "value out of range for constraint '" +
8404                                  Twine(OpInfo.ConstraintCode) + "'");
8405               return;
8406             }
8407 
8408           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8409                                      Twine(OpInfo.ConstraintCode) + "'");
8410           return;
8411         }
8412 
8413         // Add information to the INLINEASM node to know about this input.
8414         unsigned ResOpType =
8415           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8416         AsmNodeOperands.push_back(DAG.getTargetConstant(
8417             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8418         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8419         break;
8420       }
8421 
8422       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8423         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8424         assert(InOperandVal.getValueType() ==
8425                    TLI.getPointerTy(DAG.getDataLayout()) &&
8426                "Memory operands expect pointer values");
8427 
8428         unsigned ConstraintID =
8429             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8430         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8431                "Failed to convert memory constraint code to constraint id.");
8432 
8433         // Add information to the INLINEASM node to know about this input.
8434         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8435         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8436         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8437                                                         getCurSDLoc(),
8438                                                         MVT::i32));
8439         AsmNodeOperands.push_back(InOperandVal);
8440         break;
8441       }
8442 
8443       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8444               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8445              "Unknown constraint type!");
8446 
8447       // TODO: Support this.
8448       if (OpInfo.isIndirect) {
8449         emitInlineAsmError(
8450             CS, "Don't know how to handle indirect register inputs yet "
8451                 "for constraint '" +
8452                     Twine(OpInfo.ConstraintCode) + "'");
8453         return;
8454       }
8455 
8456       // Copy the input into the appropriate registers.
8457       if (OpInfo.AssignedRegs.Regs.empty()) {
8458         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8459                                    Twine(OpInfo.ConstraintCode) + "'");
8460         return;
8461       }
8462 
8463       SDLoc dl = getCurSDLoc();
8464 
8465       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8466                                         Chain, &Flag, CS.getInstruction());
8467 
8468       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8469                                                dl, DAG, AsmNodeOperands);
8470       break;
8471     }
8472     case InlineAsm::isClobber:
8473       // Add the clobbered value to the operand list, so that the register
8474       // allocator is aware that the physreg got clobbered.
8475       if (!OpInfo.AssignedRegs.Regs.empty())
8476         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8477                                                  false, 0, getCurSDLoc(), DAG,
8478                                                  AsmNodeOperands);
8479       break;
8480     }
8481   }
8482 
8483   // Finish up input operands.  Set the input chain and add the flag last.
8484   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8485   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8486 
8487   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8488   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8489                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8490   Flag = Chain.getValue(1);
8491 
8492   // Do additional work to generate outputs.
8493 
8494   SmallVector<EVT, 1> ResultVTs;
8495   SmallVector<SDValue, 1> ResultValues;
8496   SmallVector<SDValue, 8> OutChains;
8497 
8498   llvm::Type *CSResultType = CS.getType();
8499   ArrayRef<Type *> ResultTypes;
8500   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8501     ResultTypes = StructResult->elements();
8502   else if (!CSResultType->isVoidTy())
8503     ResultTypes = makeArrayRef(CSResultType);
8504 
8505   auto CurResultType = ResultTypes.begin();
8506   auto handleRegAssign = [&](SDValue V) {
8507     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8508     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8509     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8510     ++CurResultType;
8511     // If the type of the inline asm call site return value is different but has
8512     // same size as the type of the asm output bitcast it.  One example of this
8513     // is for vectors with different width / number of elements.  This can
8514     // happen for register classes that can contain multiple different value
8515     // types.  The preg or vreg allocated may not have the same VT as was
8516     // expected.
8517     //
8518     // This can also happen for a return value that disagrees with the register
8519     // class it is put in, eg. a double in a general-purpose register on a
8520     // 32-bit machine.
8521     if (ResultVT != V.getValueType() &&
8522         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8523       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8524     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8525              V.getValueType().isInteger()) {
8526       // If a result value was tied to an input value, the computed result
8527       // may have a wider width than the expected result.  Extract the
8528       // relevant portion.
8529       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8530     }
8531     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8532     ResultVTs.push_back(ResultVT);
8533     ResultValues.push_back(V);
8534   };
8535 
8536   // Deal with output operands.
8537   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8538     if (OpInfo.Type == InlineAsm::isOutput) {
8539       SDValue Val;
8540       // Skip trivial output operands.
8541       if (OpInfo.AssignedRegs.Regs.empty())
8542         continue;
8543 
8544       switch (OpInfo.ConstraintType) {
8545       case TargetLowering::C_Register:
8546       case TargetLowering::C_RegisterClass:
8547         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8548             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8549         break;
8550       case TargetLowering::C_Immediate:
8551       case TargetLowering::C_Other:
8552         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8553                                               OpInfo, DAG);
8554         break;
8555       case TargetLowering::C_Memory:
8556         break; // Already handled.
8557       case TargetLowering::C_Unknown:
8558         assert(false && "Unexpected unknown constraint");
8559       }
8560 
8561       // Indirect output manifest as stores. Record output chains.
8562       if (OpInfo.isIndirect) {
8563         const Value *Ptr = OpInfo.CallOperandVal;
8564         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8565         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8566                                      MachinePointerInfo(Ptr));
8567         OutChains.push_back(Store);
8568       } else {
8569         // generate CopyFromRegs to associated registers.
8570         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8571         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8572           for (const SDValue &V : Val->op_values())
8573             handleRegAssign(V);
8574         } else
8575           handleRegAssign(Val);
8576       }
8577     }
8578   }
8579 
8580   // Set results.
8581   if (!ResultValues.empty()) {
8582     assert(CurResultType == ResultTypes.end() &&
8583            "Mismatch in number of ResultTypes");
8584     assert(ResultValues.size() == ResultTypes.size() &&
8585            "Mismatch in number of output operands in asm result");
8586 
8587     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8588                             DAG.getVTList(ResultVTs), ResultValues);
8589     setValue(CS.getInstruction(), V);
8590   }
8591 
8592   // Collect store chains.
8593   if (!OutChains.empty())
8594     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8595 
8596   // Only Update Root if inline assembly has a memory effect.
8597   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8598     DAG.setRoot(Chain);
8599 }
8600 
8601 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8602                                              const Twine &Message) {
8603   LLVMContext &Ctx = *DAG.getContext();
8604   Ctx.emitError(CS.getInstruction(), Message);
8605 
8606   // Make sure we leave the DAG in a valid state
8607   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8608   SmallVector<EVT, 1> ValueVTs;
8609   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8610 
8611   if (ValueVTs.empty())
8612     return;
8613 
8614   SmallVector<SDValue, 1> Ops;
8615   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8616     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8617 
8618   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8619 }
8620 
8621 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8622   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8623                           MVT::Other, getRoot(),
8624                           getValue(I.getArgOperand(0)),
8625                           DAG.getSrcValue(I.getArgOperand(0))));
8626 }
8627 
8628 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8630   const DataLayout &DL = DAG.getDataLayout();
8631   SDValue V = DAG.getVAArg(
8632       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8633       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8634       DL.getABITypeAlignment(I.getType()));
8635   DAG.setRoot(V.getValue(1));
8636 
8637   if (I.getType()->isPointerTy())
8638     V = DAG.getPtrExtOrTrunc(
8639         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8640   setValue(&I, V);
8641 }
8642 
8643 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8644   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8645                           MVT::Other, getRoot(),
8646                           getValue(I.getArgOperand(0)),
8647                           DAG.getSrcValue(I.getArgOperand(0))));
8648 }
8649 
8650 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8651   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8652                           MVT::Other, getRoot(),
8653                           getValue(I.getArgOperand(0)),
8654                           getValue(I.getArgOperand(1)),
8655                           DAG.getSrcValue(I.getArgOperand(0)),
8656                           DAG.getSrcValue(I.getArgOperand(1))));
8657 }
8658 
8659 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8660                                                     const Instruction &I,
8661                                                     SDValue Op) {
8662   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8663   if (!Range)
8664     return Op;
8665 
8666   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8667   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8668     return Op;
8669 
8670   APInt Lo = CR.getUnsignedMin();
8671   if (!Lo.isMinValue())
8672     return Op;
8673 
8674   APInt Hi = CR.getUnsignedMax();
8675   unsigned Bits = std::max(Hi.getActiveBits(),
8676                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8677 
8678   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8679 
8680   SDLoc SL = getCurSDLoc();
8681 
8682   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8683                              DAG.getValueType(SmallVT));
8684   unsigned NumVals = Op.getNode()->getNumValues();
8685   if (NumVals == 1)
8686     return ZExt;
8687 
8688   SmallVector<SDValue, 4> Ops;
8689 
8690   Ops.push_back(ZExt);
8691   for (unsigned I = 1; I != NumVals; ++I)
8692     Ops.push_back(Op.getValue(I));
8693 
8694   return DAG.getMergeValues(Ops, SL);
8695 }
8696 
8697 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8698 /// the call being lowered.
8699 ///
8700 /// This is a helper for lowering intrinsics that follow a target calling
8701 /// convention or require stack pointer adjustment. Only a subset of the
8702 /// intrinsic's operands need to participate in the calling convention.
8703 void SelectionDAGBuilder::populateCallLoweringInfo(
8704     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8705     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8706     bool IsPatchPoint) {
8707   TargetLowering::ArgListTy Args;
8708   Args.reserve(NumArgs);
8709 
8710   // Populate the argument list.
8711   // Attributes for args start at offset 1, after the return attribute.
8712   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8713        ArgI != ArgE; ++ArgI) {
8714     const Value *V = Call->getOperand(ArgI);
8715 
8716     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8717 
8718     TargetLowering::ArgListEntry Entry;
8719     Entry.Node = getValue(V);
8720     Entry.Ty = V->getType();
8721     Entry.setAttributes(Call, ArgI);
8722     Args.push_back(Entry);
8723   }
8724 
8725   CLI.setDebugLoc(getCurSDLoc())
8726       .setChain(getRoot())
8727       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8728       .setDiscardResult(Call->use_empty())
8729       .setIsPatchPoint(IsPatchPoint);
8730 }
8731 
8732 /// Add a stack map intrinsic call's live variable operands to a stackmap
8733 /// or patchpoint target node's operand list.
8734 ///
8735 /// Constants are converted to TargetConstants purely as an optimization to
8736 /// avoid constant materialization and register allocation.
8737 ///
8738 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8739 /// generate addess computation nodes, and so FinalizeISel can convert the
8740 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8741 /// address materialization and register allocation, but may also be required
8742 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8743 /// alloca in the entry block, then the runtime may assume that the alloca's
8744 /// StackMap location can be read immediately after compilation and that the
8745 /// location is valid at any point during execution (this is similar to the
8746 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8747 /// only available in a register, then the runtime would need to trap when
8748 /// execution reaches the StackMap in order to read the alloca's location.
8749 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8750                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8751                                 SelectionDAGBuilder &Builder) {
8752   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8753     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8754     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8755       Ops.push_back(
8756         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8757       Ops.push_back(
8758         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8759     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8760       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8761       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8762           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8763     } else
8764       Ops.push_back(OpVal);
8765   }
8766 }
8767 
8768 /// Lower llvm.experimental.stackmap directly to its target opcode.
8769 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8770   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8771   //                                  [live variables...])
8772 
8773   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8774 
8775   SDValue Chain, InFlag, Callee, NullPtr;
8776   SmallVector<SDValue, 32> Ops;
8777 
8778   SDLoc DL = getCurSDLoc();
8779   Callee = getValue(CI.getCalledValue());
8780   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8781 
8782   // The stackmap intrinsic only records the live variables (the arguments
8783   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8784   // intrinsic, this won't be lowered to a function call. This means we don't
8785   // have to worry about calling conventions and target specific lowering code.
8786   // Instead we perform the call lowering right here.
8787   //
8788   // chain, flag = CALLSEQ_START(chain, 0, 0)
8789   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8790   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8791   //
8792   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8793   InFlag = Chain.getValue(1);
8794 
8795   // Add the <id> and <numBytes> constants.
8796   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8797   Ops.push_back(DAG.getTargetConstant(
8798                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8799   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8800   Ops.push_back(DAG.getTargetConstant(
8801                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8802                   MVT::i32));
8803 
8804   // Push live variables for the stack map.
8805   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8806 
8807   // We are not pushing any register mask info here on the operands list,
8808   // because the stackmap doesn't clobber anything.
8809 
8810   // Push the chain and the glue flag.
8811   Ops.push_back(Chain);
8812   Ops.push_back(InFlag);
8813 
8814   // Create the STACKMAP node.
8815   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8816   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8817   Chain = SDValue(SM, 0);
8818   InFlag = Chain.getValue(1);
8819 
8820   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8821 
8822   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8823 
8824   // Set the root to the target-lowered call chain.
8825   DAG.setRoot(Chain);
8826 
8827   // Inform the Frame Information that we have a stackmap in this function.
8828   FuncInfo.MF->getFrameInfo().setHasStackMap();
8829 }
8830 
8831 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8832 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8833                                           const BasicBlock *EHPadBB) {
8834   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8835   //                                                 i32 <numBytes>,
8836   //                                                 i8* <target>,
8837   //                                                 i32 <numArgs>,
8838   //                                                 [Args...],
8839   //                                                 [live variables...])
8840 
8841   CallingConv::ID CC = CS.getCallingConv();
8842   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8843   bool HasDef = !CS->getType()->isVoidTy();
8844   SDLoc dl = getCurSDLoc();
8845   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8846 
8847   // Handle immediate and symbolic callees.
8848   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8849     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8850                                    /*isTarget=*/true);
8851   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8852     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8853                                          SDLoc(SymbolicCallee),
8854                                          SymbolicCallee->getValueType(0));
8855 
8856   // Get the real number of arguments participating in the call <numArgs>
8857   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8858   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8859 
8860   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8861   // Intrinsics include all meta-operands up to but not including CC.
8862   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8863   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8864          "Not enough arguments provided to the patchpoint intrinsic");
8865 
8866   // For AnyRegCC the arguments are lowered later on manually.
8867   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8868   Type *ReturnTy =
8869     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8870 
8871   TargetLowering::CallLoweringInfo CLI(DAG);
8872   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8873                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8874   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8875 
8876   SDNode *CallEnd = Result.second.getNode();
8877   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8878     CallEnd = CallEnd->getOperand(0).getNode();
8879 
8880   /// Get a call instruction from the call sequence chain.
8881   /// Tail calls are not allowed.
8882   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8883          "Expected a callseq node.");
8884   SDNode *Call = CallEnd->getOperand(0).getNode();
8885   bool HasGlue = Call->getGluedNode();
8886 
8887   // Replace the target specific call node with the patchable intrinsic.
8888   SmallVector<SDValue, 8> Ops;
8889 
8890   // Add the <id> and <numBytes> constants.
8891   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8892   Ops.push_back(DAG.getTargetConstant(
8893                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8894   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8895   Ops.push_back(DAG.getTargetConstant(
8896                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8897                   MVT::i32));
8898 
8899   // Add the callee.
8900   Ops.push_back(Callee);
8901 
8902   // Adjust <numArgs> to account for any arguments that have been passed on the
8903   // stack instead.
8904   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8905   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8906   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8907   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8908 
8909   // Add the calling convention
8910   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8911 
8912   // Add the arguments we omitted previously. The register allocator should
8913   // place these in any free register.
8914   if (IsAnyRegCC)
8915     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8916       Ops.push_back(getValue(CS.getArgument(i)));
8917 
8918   // Push the arguments from the call instruction up to the register mask.
8919   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8920   Ops.append(Call->op_begin() + 2, e);
8921 
8922   // Push live variables for the stack map.
8923   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8924 
8925   // Push the register mask info.
8926   if (HasGlue)
8927     Ops.push_back(*(Call->op_end()-2));
8928   else
8929     Ops.push_back(*(Call->op_end()-1));
8930 
8931   // Push the chain (this is originally the first operand of the call, but
8932   // becomes now the last or second to last operand).
8933   Ops.push_back(*(Call->op_begin()));
8934 
8935   // Push the glue flag (last operand).
8936   if (HasGlue)
8937     Ops.push_back(*(Call->op_end()-1));
8938 
8939   SDVTList NodeTys;
8940   if (IsAnyRegCC && HasDef) {
8941     // Create the return types based on the intrinsic definition
8942     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8943     SmallVector<EVT, 3> ValueVTs;
8944     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8945     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8946 
8947     // There is always a chain and a glue type at the end
8948     ValueVTs.push_back(MVT::Other);
8949     ValueVTs.push_back(MVT::Glue);
8950     NodeTys = DAG.getVTList(ValueVTs);
8951   } else
8952     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8953 
8954   // Replace the target specific call node with a PATCHPOINT node.
8955   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8956                                          dl, NodeTys, Ops);
8957 
8958   // Update the NodeMap.
8959   if (HasDef) {
8960     if (IsAnyRegCC)
8961       setValue(CS.getInstruction(), SDValue(MN, 0));
8962     else
8963       setValue(CS.getInstruction(), Result.first);
8964   }
8965 
8966   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8967   // call sequence. Furthermore the location of the chain and glue can change
8968   // when the AnyReg calling convention is used and the intrinsic returns a
8969   // value.
8970   if (IsAnyRegCC && HasDef) {
8971     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8972     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8973     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8974   } else
8975     DAG.ReplaceAllUsesWith(Call, MN);
8976   DAG.DeleteNode(Call);
8977 
8978   // Inform the Frame Information that we have a patchpoint in this function.
8979   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8980 }
8981 
8982 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8983                                             unsigned Intrinsic) {
8984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8985   SDValue Op1 = getValue(I.getArgOperand(0));
8986   SDValue Op2;
8987   if (I.getNumArgOperands() > 1)
8988     Op2 = getValue(I.getArgOperand(1));
8989   SDLoc dl = getCurSDLoc();
8990   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8991   SDValue Res;
8992   FastMathFlags FMF;
8993   if (isa<FPMathOperator>(I))
8994     FMF = I.getFastMathFlags();
8995 
8996   switch (Intrinsic) {
8997   case Intrinsic::experimental_vector_reduce_v2_fadd:
8998     if (FMF.allowReassoc())
8999       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9000                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
9001     else
9002       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
9003     break;
9004   case Intrinsic::experimental_vector_reduce_v2_fmul:
9005     if (FMF.allowReassoc())
9006       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9007                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
9008     else
9009       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
9010     break;
9011   case Intrinsic::experimental_vector_reduce_add:
9012     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9013     break;
9014   case Intrinsic::experimental_vector_reduce_mul:
9015     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9016     break;
9017   case Intrinsic::experimental_vector_reduce_and:
9018     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9019     break;
9020   case Intrinsic::experimental_vector_reduce_or:
9021     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9022     break;
9023   case Intrinsic::experimental_vector_reduce_xor:
9024     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9025     break;
9026   case Intrinsic::experimental_vector_reduce_smax:
9027     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9028     break;
9029   case Intrinsic::experimental_vector_reduce_smin:
9030     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9031     break;
9032   case Intrinsic::experimental_vector_reduce_umax:
9033     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9034     break;
9035   case Intrinsic::experimental_vector_reduce_umin:
9036     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9037     break;
9038   case Intrinsic::experimental_vector_reduce_fmax:
9039     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9040     break;
9041   case Intrinsic::experimental_vector_reduce_fmin:
9042     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9043     break;
9044   default:
9045     llvm_unreachable("Unhandled vector reduce intrinsic");
9046   }
9047   setValue(&I, Res);
9048 }
9049 
9050 /// Returns an AttributeList representing the attributes applied to the return
9051 /// value of the given call.
9052 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9053   SmallVector<Attribute::AttrKind, 2> Attrs;
9054   if (CLI.RetSExt)
9055     Attrs.push_back(Attribute::SExt);
9056   if (CLI.RetZExt)
9057     Attrs.push_back(Attribute::ZExt);
9058   if (CLI.IsInReg)
9059     Attrs.push_back(Attribute::InReg);
9060 
9061   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9062                             Attrs);
9063 }
9064 
9065 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9066 /// implementation, which just calls LowerCall.
9067 /// FIXME: When all targets are
9068 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9069 std::pair<SDValue, SDValue>
9070 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9071   // Handle the incoming return values from the call.
9072   CLI.Ins.clear();
9073   Type *OrigRetTy = CLI.RetTy;
9074   SmallVector<EVT, 4> RetTys;
9075   SmallVector<uint64_t, 4> Offsets;
9076   auto &DL = CLI.DAG.getDataLayout();
9077   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9078 
9079   if (CLI.IsPostTypeLegalization) {
9080     // If we are lowering a libcall after legalization, split the return type.
9081     SmallVector<EVT, 4> OldRetTys;
9082     SmallVector<uint64_t, 4> OldOffsets;
9083     RetTys.swap(OldRetTys);
9084     Offsets.swap(OldOffsets);
9085 
9086     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9087       EVT RetVT = OldRetTys[i];
9088       uint64_t Offset = OldOffsets[i];
9089       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9090       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9091       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9092       RetTys.append(NumRegs, RegisterVT);
9093       for (unsigned j = 0; j != NumRegs; ++j)
9094         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9095     }
9096   }
9097 
9098   SmallVector<ISD::OutputArg, 4> Outs;
9099   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9100 
9101   bool CanLowerReturn =
9102       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9103                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9104 
9105   SDValue DemoteStackSlot;
9106   int DemoteStackIdx = -100;
9107   if (!CanLowerReturn) {
9108     // FIXME: equivalent assert?
9109     // assert(!CS.hasInAllocaArgument() &&
9110     //        "sret demotion is incompatible with inalloca");
9111     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9112     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9113     MachineFunction &MF = CLI.DAG.getMachineFunction();
9114     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9115     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9116                                               DL.getAllocaAddrSpace());
9117 
9118     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9119     ArgListEntry Entry;
9120     Entry.Node = DemoteStackSlot;
9121     Entry.Ty = StackSlotPtrType;
9122     Entry.IsSExt = false;
9123     Entry.IsZExt = false;
9124     Entry.IsInReg = false;
9125     Entry.IsSRet = true;
9126     Entry.IsNest = false;
9127     Entry.IsByVal = false;
9128     Entry.IsReturned = false;
9129     Entry.IsSwiftSelf = false;
9130     Entry.IsSwiftError = false;
9131     Entry.IsCFGuardTarget = false;
9132     Entry.Alignment = Align;
9133     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9134     CLI.NumFixedArgs += 1;
9135     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9136 
9137     // sret demotion isn't compatible with tail-calls, since the sret argument
9138     // points into the callers stack frame.
9139     CLI.IsTailCall = false;
9140   } else {
9141     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9142         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9143     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9144       ISD::ArgFlagsTy Flags;
9145       if (NeedsRegBlock) {
9146         Flags.setInConsecutiveRegs();
9147         if (I == RetTys.size() - 1)
9148           Flags.setInConsecutiveRegsLast();
9149       }
9150       EVT VT = RetTys[I];
9151       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9152                                                      CLI.CallConv, VT);
9153       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9154                                                        CLI.CallConv, VT);
9155       for (unsigned i = 0; i != NumRegs; ++i) {
9156         ISD::InputArg MyFlags;
9157         MyFlags.Flags = Flags;
9158         MyFlags.VT = RegisterVT;
9159         MyFlags.ArgVT = VT;
9160         MyFlags.Used = CLI.IsReturnValueUsed;
9161         if (CLI.RetTy->isPointerTy()) {
9162           MyFlags.Flags.setPointer();
9163           MyFlags.Flags.setPointerAddrSpace(
9164               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9165         }
9166         if (CLI.RetSExt)
9167           MyFlags.Flags.setSExt();
9168         if (CLI.RetZExt)
9169           MyFlags.Flags.setZExt();
9170         if (CLI.IsInReg)
9171           MyFlags.Flags.setInReg();
9172         CLI.Ins.push_back(MyFlags);
9173       }
9174     }
9175   }
9176 
9177   // We push in swifterror return as the last element of CLI.Ins.
9178   ArgListTy &Args = CLI.getArgs();
9179   if (supportSwiftError()) {
9180     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9181       if (Args[i].IsSwiftError) {
9182         ISD::InputArg MyFlags;
9183         MyFlags.VT = getPointerTy(DL);
9184         MyFlags.ArgVT = EVT(getPointerTy(DL));
9185         MyFlags.Flags.setSwiftError();
9186         CLI.Ins.push_back(MyFlags);
9187       }
9188     }
9189   }
9190 
9191   // Handle all of the outgoing arguments.
9192   CLI.Outs.clear();
9193   CLI.OutVals.clear();
9194   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9195     SmallVector<EVT, 4> ValueVTs;
9196     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9197     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9198     Type *FinalType = Args[i].Ty;
9199     if (Args[i].IsByVal)
9200       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9201     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9202         FinalType, CLI.CallConv, CLI.IsVarArg);
9203     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9204          ++Value) {
9205       EVT VT = ValueVTs[Value];
9206       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9207       SDValue Op = SDValue(Args[i].Node.getNode(),
9208                            Args[i].Node.getResNo() + Value);
9209       ISD::ArgFlagsTy Flags;
9210 
9211       // Certain targets (such as MIPS), may have a different ABI alignment
9212       // for a type depending on the context. Give the target a chance to
9213       // specify the alignment it wants.
9214       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9215 
9216       if (Args[i].Ty->isPointerTy()) {
9217         Flags.setPointer();
9218         Flags.setPointerAddrSpace(
9219             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9220       }
9221       if (Args[i].IsZExt)
9222         Flags.setZExt();
9223       if (Args[i].IsSExt)
9224         Flags.setSExt();
9225       if (Args[i].IsInReg) {
9226         // If we are using vectorcall calling convention, a structure that is
9227         // passed InReg - is surely an HVA
9228         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9229             isa<StructType>(FinalType)) {
9230           // The first value of a structure is marked
9231           if (0 == Value)
9232             Flags.setHvaStart();
9233           Flags.setHva();
9234         }
9235         // Set InReg Flag
9236         Flags.setInReg();
9237       }
9238       if (Args[i].IsSRet)
9239         Flags.setSRet();
9240       if (Args[i].IsSwiftSelf)
9241         Flags.setSwiftSelf();
9242       if (Args[i].IsSwiftError)
9243         Flags.setSwiftError();
9244       if (Args[i].IsCFGuardTarget)
9245         Flags.setCFGuardTarget();
9246       if (Args[i].IsByVal)
9247         Flags.setByVal();
9248       if (Args[i].IsInAlloca) {
9249         Flags.setInAlloca();
9250         // Set the byval flag for CCAssignFn callbacks that don't know about
9251         // inalloca.  This way we can know how many bytes we should've allocated
9252         // and how many bytes a callee cleanup function will pop.  If we port
9253         // inalloca to more targets, we'll have to add custom inalloca handling
9254         // in the various CC lowering callbacks.
9255         Flags.setByVal();
9256       }
9257       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9258         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9259         Type *ElementTy = Ty->getElementType();
9260 
9261         unsigned FrameSize = DL.getTypeAllocSize(
9262             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9263         Flags.setByValSize(FrameSize);
9264 
9265         // info is not there but there are cases it cannot get right.
9266         unsigned FrameAlign;
9267         if (Args[i].Alignment)
9268           FrameAlign = Args[i].Alignment;
9269         else
9270           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9271         Flags.setByValAlign(Align(FrameAlign));
9272       }
9273       if (Args[i].IsNest)
9274         Flags.setNest();
9275       if (NeedsRegBlock)
9276         Flags.setInConsecutiveRegs();
9277       Flags.setOrigAlign(OriginalAlignment);
9278 
9279       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9280                                                  CLI.CallConv, VT);
9281       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9282                                                         CLI.CallConv, VT);
9283       SmallVector<SDValue, 4> Parts(NumParts);
9284       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9285 
9286       if (Args[i].IsSExt)
9287         ExtendKind = ISD::SIGN_EXTEND;
9288       else if (Args[i].IsZExt)
9289         ExtendKind = ISD::ZERO_EXTEND;
9290 
9291       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9292       // for now.
9293       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9294           CanLowerReturn) {
9295         assert((CLI.RetTy == Args[i].Ty ||
9296                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9297                  CLI.RetTy->getPointerAddressSpace() ==
9298                      Args[i].Ty->getPointerAddressSpace())) &&
9299                RetTys.size() == NumValues && "unexpected use of 'returned'");
9300         // Before passing 'returned' to the target lowering code, ensure that
9301         // either the register MVT and the actual EVT are the same size or that
9302         // the return value and argument are extended in the same way; in these
9303         // cases it's safe to pass the argument register value unchanged as the
9304         // return register value (although it's at the target's option whether
9305         // to do so)
9306         // TODO: allow code generation to take advantage of partially preserved
9307         // registers rather than clobbering the entire register when the
9308         // parameter extension method is not compatible with the return
9309         // extension method
9310         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9311             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9312              CLI.RetZExt == Args[i].IsZExt))
9313           Flags.setReturned();
9314       }
9315 
9316       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9317                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9318 
9319       for (unsigned j = 0; j != NumParts; ++j) {
9320         // if it isn't first piece, alignment must be 1
9321         // For scalable vectors the scalable part is currently handled
9322         // by individual targets, so we just use the known minimum size here.
9323         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9324                     i < CLI.NumFixedArgs, i,
9325                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9326         if (NumParts > 1 && j == 0)
9327           MyFlags.Flags.setSplit();
9328         else if (j != 0) {
9329           MyFlags.Flags.setOrigAlign(Align(1));
9330           if (j == NumParts - 1)
9331             MyFlags.Flags.setSplitEnd();
9332         }
9333 
9334         CLI.Outs.push_back(MyFlags);
9335         CLI.OutVals.push_back(Parts[j]);
9336       }
9337 
9338       if (NeedsRegBlock && Value == NumValues - 1)
9339         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9340     }
9341   }
9342 
9343   SmallVector<SDValue, 4> InVals;
9344   CLI.Chain = LowerCall(CLI, InVals);
9345 
9346   // Update CLI.InVals to use outside of this function.
9347   CLI.InVals = InVals;
9348 
9349   // Verify that the target's LowerCall behaved as expected.
9350   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9351          "LowerCall didn't return a valid chain!");
9352   assert((!CLI.IsTailCall || InVals.empty()) &&
9353          "LowerCall emitted a return value for a tail call!");
9354   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9355          "LowerCall didn't emit the correct number of values!");
9356 
9357   // For a tail call, the return value is merely live-out and there aren't
9358   // any nodes in the DAG representing it. Return a special value to
9359   // indicate that a tail call has been emitted and no more Instructions
9360   // should be processed in the current block.
9361   if (CLI.IsTailCall) {
9362     CLI.DAG.setRoot(CLI.Chain);
9363     return std::make_pair(SDValue(), SDValue());
9364   }
9365 
9366 #ifndef NDEBUG
9367   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9368     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9369     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9370            "LowerCall emitted a value with the wrong type!");
9371   }
9372 #endif
9373 
9374   SmallVector<SDValue, 4> ReturnValues;
9375   if (!CanLowerReturn) {
9376     // The instruction result is the result of loading from the
9377     // hidden sret parameter.
9378     SmallVector<EVT, 1> PVTs;
9379     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9380 
9381     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9382     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9383     EVT PtrVT = PVTs[0];
9384 
9385     unsigned NumValues = RetTys.size();
9386     ReturnValues.resize(NumValues);
9387     SmallVector<SDValue, 4> Chains(NumValues);
9388 
9389     // An aggregate return value cannot wrap around the address space, so
9390     // offsets to its parts don't wrap either.
9391     SDNodeFlags Flags;
9392     Flags.setNoUnsignedWrap(true);
9393 
9394     for (unsigned i = 0; i < NumValues; ++i) {
9395       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9396                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9397                                                         PtrVT), Flags);
9398       SDValue L = CLI.DAG.getLoad(
9399           RetTys[i], CLI.DL, CLI.Chain, Add,
9400           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9401                                             DemoteStackIdx, Offsets[i]),
9402           /* Alignment = */ 1);
9403       ReturnValues[i] = L;
9404       Chains[i] = L.getValue(1);
9405     }
9406 
9407     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9408   } else {
9409     // Collect the legal value parts into potentially illegal values
9410     // that correspond to the original function's return values.
9411     Optional<ISD::NodeType> AssertOp;
9412     if (CLI.RetSExt)
9413       AssertOp = ISD::AssertSext;
9414     else if (CLI.RetZExt)
9415       AssertOp = ISD::AssertZext;
9416     unsigned CurReg = 0;
9417     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9418       EVT VT = RetTys[I];
9419       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9420                                                      CLI.CallConv, VT);
9421       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9422                                                        CLI.CallConv, VT);
9423 
9424       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9425                                               NumRegs, RegisterVT, VT, nullptr,
9426                                               CLI.CallConv, AssertOp));
9427       CurReg += NumRegs;
9428     }
9429 
9430     // For a function returning void, there is no return value. We can't create
9431     // such a node, so we just return a null return value in that case. In
9432     // that case, nothing will actually look at the value.
9433     if (ReturnValues.empty())
9434       return std::make_pair(SDValue(), CLI.Chain);
9435   }
9436 
9437   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9438                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9439   return std::make_pair(Res, CLI.Chain);
9440 }
9441 
9442 void TargetLowering::LowerOperationWrapper(SDNode *N,
9443                                            SmallVectorImpl<SDValue> &Results,
9444                                            SelectionDAG &DAG) const {
9445   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9446     Results.push_back(Res);
9447 }
9448 
9449 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9450   llvm_unreachable("LowerOperation not implemented for this target!");
9451 }
9452 
9453 void
9454 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9455   SDValue Op = getNonRegisterValue(V);
9456   assert((Op.getOpcode() != ISD::CopyFromReg ||
9457           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9458          "Copy from a reg to the same reg!");
9459   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9460 
9461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9462   // If this is an InlineAsm we have to match the registers required, not the
9463   // notional registers required by the type.
9464 
9465   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9466                    None); // This is not an ABI copy.
9467   SDValue Chain = DAG.getEntryNode();
9468 
9469   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9470                               FuncInfo.PreferredExtendType.end())
9471                                  ? ISD::ANY_EXTEND
9472                                  : FuncInfo.PreferredExtendType[V];
9473   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9474   PendingExports.push_back(Chain);
9475 }
9476 
9477 #include "llvm/CodeGen/SelectionDAGISel.h"
9478 
9479 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9480 /// entry block, return true.  This includes arguments used by switches, since
9481 /// the switch may expand into multiple basic blocks.
9482 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9483   // With FastISel active, we may be splitting blocks, so force creation
9484   // of virtual registers for all non-dead arguments.
9485   if (FastISel)
9486     return A->use_empty();
9487 
9488   const BasicBlock &Entry = A->getParent()->front();
9489   for (const User *U : A->users())
9490     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9491       return false;  // Use not in entry block.
9492 
9493   return true;
9494 }
9495 
9496 using ArgCopyElisionMapTy =
9497     DenseMap<const Argument *,
9498              std::pair<const AllocaInst *, const StoreInst *>>;
9499 
9500 /// Scan the entry block of the function in FuncInfo for arguments that look
9501 /// like copies into a local alloca. Record any copied arguments in
9502 /// ArgCopyElisionCandidates.
9503 static void
9504 findArgumentCopyElisionCandidates(const DataLayout &DL,
9505                                   FunctionLoweringInfo *FuncInfo,
9506                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9507   // Record the state of every static alloca used in the entry block. Argument
9508   // allocas are all used in the entry block, so we need approximately as many
9509   // entries as we have arguments.
9510   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9511   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9512   unsigned NumArgs = FuncInfo->Fn->arg_size();
9513   StaticAllocas.reserve(NumArgs * 2);
9514 
9515   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9516     if (!V)
9517       return nullptr;
9518     V = V->stripPointerCasts();
9519     const auto *AI = dyn_cast<AllocaInst>(V);
9520     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9521       return nullptr;
9522     auto Iter = StaticAllocas.insert({AI, Unknown});
9523     return &Iter.first->second;
9524   };
9525 
9526   // Look for stores of arguments to static allocas. Look through bitcasts and
9527   // GEPs to handle type coercions, as long as the alloca is fully initialized
9528   // by the store. Any non-store use of an alloca escapes it and any subsequent
9529   // unanalyzed store might write it.
9530   // FIXME: Handle structs initialized with multiple stores.
9531   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9532     // Look for stores, and handle non-store uses conservatively.
9533     const auto *SI = dyn_cast<StoreInst>(&I);
9534     if (!SI) {
9535       // We will look through cast uses, so ignore them completely.
9536       if (I.isCast())
9537         continue;
9538       // Ignore debug info intrinsics, they don't escape or store to allocas.
9539       if (isa<DbgInfoIntrinsic>(I))
9540         continue;
9541       // This is an unknown instruction. Assume it escapes or writes to all
9542       // static alloca operands.
9543       for (const Use &U : I.operands()) {
9544         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9545           *Info = StaticAllocaInfo::Clobbered;
9546       }
9547       continue;
9548     }
9549 
9550     // If the stored value is a static alloca, mark it as escaped.
9551     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9552       *Info = StaticAllocaInfo::Clobbered;
9553 
9554     // Check if the destination is a static alloca.
9555     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9556     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9557     if (!Info)
9558       continue;
9559     const AllocaInst *AI = cast<AllocaInst>(Dst);
9560 
9561     // Skip allocas that have been initialized or clobbered.
9562     if (*Info != StaticAllocaInfo::Unknown)
9563       continue;
9564 
9565     // Check if the stored value is an argument, and that this store fully
9566     // initializes the alloca. Don't elide copies from the same argument twice.
9567     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9568     const auto *Arg = dyn_cast<Argument>(Val);
9569     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9570         Arg->getType()->isEmptyTy() ||
9571         DL.getTypeStoreSize(Arg->getType()) !=
9572             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9573         ArgCopyElisionCandidates.count(Arg)) {
9574       *Info = StaticAllocaInfo::Clobbered;
9575       continue;
9576     }
9577 
9578     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9579                       << '\n');
9580 
9581     // Mark this alloca and store for argument copy elision.
9582     *Info = StaticAllocaInfo::Elidable;
9583     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9584 
9585     // Stop scanning if we've seen all arguments. This will happen early in -O0
9586     // builds, which is useful, because -O0 builds have large entry blocks and
9587     // many allocas.
9588     if (ArgCopyElisionCandidates.size() == NumArgs)
9589       break;
9590   }
9591 }
9592 
9593 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9594 /// ArgVal is a load from a suitable fixed stack object.
9595 static void tryToElideArgumentCopy(
9596     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9597     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9598     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9599     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9600     SDValue ArgVal, bool &ArgHasUses) {
9601   // Check if this is a load from a fixed stack object.
9602   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9603   if (!LNode)
9604     return;
9605   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9606   if (!FINode)
9607     return;
9608 
9609   // Check that the fixed stack object is the right size and alignment.
9610   // Look at the alignment that the user wrote on the alloca instead of looking
9611   // at the stack object.
9612   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9613   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9614   const AllocaInst *AI = ArgCopyIter->second.first;
9615   int FixedIndex = FINode->getIndex();
9616   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9617   int OldIndex = AllocaIndex;
9618   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9619   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9620     LLVM_DEBUG(
9621         dbgs() << "  argument copy elision failed due to bad fixed stack "
9622                   "object size\n");
9623     return;
9624   }
9625   unsigned RequiredAlignment = AI->getAlignment();
9626   if (!RequiredAlignment) {
9627     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9628         AI->getAllocatedType());
9629   }
9630   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9631     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9632                          "greater than stack argument alignment ("
9633                       << RequiredAlignment << " vs "
9634                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9635     return;
9636   }
9637 
9638   // Perform the elision. Delete the old stack object and replace its only use
9639   // in the variable info map. Mark the stack object as mutable.
9640   LLVM_DEBUG({
9641     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9642            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9643            << '\n';
9644   });
9645   MFI.RemoveStackObject(OldIndex);
9646   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9647   AllocaIndex = FixedIndex;
9648   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9649   Chains.push_back(ArgVal.getValue(1));
9650 
9651   // Avoid emitting code for the store implementing the copy.
9652   const StoreInst *SI = ArgCopyIter->second.second;
9653   ElidedArgCopyInstrs.insert(SI);
9654 
9655   // Check for uses of the argument again so that we can avoid exporting ArgVal
9656   // if it is't used by anything other than the store.
9657   for (const Value *U : Arg.users()) {
9658     if (U != SI) {
9659       ArgHasUses = true;
9660       break;
9661     }
9662   }
9663 }
9664 
9665 void SelectionDAGISel::LowerArguments(const Function &F) {
9666   SelectionDAG &DAG = SDB->DAG;
9667   SDLoc dl = SDB->getCurSDLoc();
9668   const DataLayout &DL = DAG.getDataLayout();
9669   SmallVector<ISD::InputArg, 16> Ins;
9670 
9671   if (!FuncInfo->CanLowerReturn) {
9672     // Put in an sret pointer parameter before all the other parameters.
9673     SmallVector<EVT, 1> ValueVTs;
9674     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9675                     F.getReturnType()->getPointerTo(
9676                         DAG.getDataLayout().getAllocaAddrSpace()),
9677                     ValueVTs);
9678 
9679     // NOTE: Assuming that a pointer will never break down to more than one VT
9680     // or one register.
9681     ISD::ArgFlagsTy Flags;
9682     Flags.setSRet();
9683     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9684     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9685                          ISD::InputArg::NoArgIndex, 0);
9686     Ins.push_back(RetArg);
9687   }
9688 
9689   // Look for stores of arguments to static allocas. Mark such arguments with a
9690   // flag to ask the target to give us the memory location of that argument if
9691   // available.
9692   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9693   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9694                                     ArgCopyElisionCandidates);
9695 
9696   // Set up the incoming argument description vector.
9697   for (const Argument &Arg : F.args()) {
9698     unsigned ArgNo = Arg.getArgNo();
9699     SmallVector<EVT, 4> ValueVTs;
9700     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9701     bool isArgValueUsed = !Arg.use_empty();
9702     unsigned PartBase = 0;
9703     Type *FinalType = Arg.getType();
9704     if (Arg.hasAttribute(Attribute::ByVal))
9705       FinalType = Arg.getParamByValType();
9706     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9707         FinalType, F.getCallingConv(), F.isVarArg());
9708     for (unsigned Value = 0, NumValues = ValueVTs.size();
9709          Value != NumValues; ++Value) {
9710       EVT VT = ValueVTs[Value];
9711       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9712       ISD::ArgFlagsTy Flags;
9713 
9714       // Certain targets (such as MIPS), may have a different ABI alignment
9715       // for a type depending on the context. Give the target a chance to
9716       // specify the alignment it wants.
9717       const Align OriginalAlignment(
9718           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9719 
9720       if (Arg.getType()->isPointerTy()) {
9721         Flags.setPointer();
9722         Flags.setPointerAddrSpace(
9723             cast<PointerType>(Arg.getType())->getAddressSpace());
9724       }
9725       if (Arg.hasAttribute(Attribute::ZExt))
9726         Flags.setZExt();
9727       if (Arg.hasAttribute(Attribute::SExt))
9728         Flags.setSExt();
9729       if (Arg.hasAttribute(Attribute::InReg)) {
9730         // If we are using vectorcall calling convention, a structure that is
9731         // passed InReg - is surely an HVA
9732         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9733             isa<StructType>(Arg.getType())) {
9734           // The first value of a structure is marked
9735           if (0 == Value)
9736             Flags.setHvaStart();
9737           Flags.setHva();
9738         }
9739         // Set InReg Flag
9740         Flags.setInReg();
9741       }
9742       if (Arg.hasAttribute(Attribute::StructRet))
9743         Flags.setSRet();
9744       if (Arg.hasAttribute(Attribute::SwiftSelf))
9745         Flags.setSwiftSelf();
9746       if (Arg.hasAttribute(Attribute::SwiftError))
9747         Flags.setSwiftError();
9748       if (Arg.hasAttribute(Attribute::ByVal))
9749         Flags.setByVal();
9750       if (Arg.hasAttribute(Attribute::InAlloca)) {
9751         Flags.setInAlloca();
9752         // Set the byval flag for CCAssignFn callbacks that don't know about
9753         // inalloca.  This way we can know how many bytes we should've allocated
9754         // and how many bytes a callee cleanup function will pop.  If we port
9755         // inalloca to more targets, we'll have to add custom inalloca handling
9756         // in the various CC lowering callbacks.
9757         Flags.setByVal();
9758       }
9759       if (F.getCallingConv() == CallingConv::X86_INTR) {
9760         // IA Interrupt passes frame (1st parameter) by value in the stack.
9761         if (ArgNo == 0)
9762           Flags.setByVal();
9763       }
9764       if (Flags.isByVal() || Flags.isInAlloca()) {
9765         Type *ElementTy = Arg.getParamByValType();
9766 
9767         // For ByVal, size and alignment should be passed from FE.  BE will
9768         // guess if this info is not there but there are cases it cannot get
9769         // right.
9770         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9771         Flags.setByValSize(FrameSize);
9772 
9773         unsigned FrameAlign;
9774         if (Arg.getParamAlignment())
9775           FrameAlign = Arg.getParamAlignment();
9776         else
9777           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9778         Flags.setByValAlign(Align(FrameAlign));
9779       }
9780       if (Arg.hasAttribute(Attribute::Nest))
9781         Flags.setNest();
9782       if (NeedsRegBlock)
9783         Flags.setInConsecutiveRegs();
9784       Flags.setOrigAlign(OriginalAlignment);
9785       if (ArgCopyElisionCandidates.count(&Arg))
9786         Flags.setCopyElisionCandidate();
9787       if (Arg.hasAttribute(Attribute::Returned))
9788         Flags.setReturned();
9789 
9790       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9791           *CurDAG->getContext(), F.getCallingConv(), VT);
9792       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9793           *CurDAG->getContext(), F.getCallingConv(), VT);
9794       for (unsigned i = 0; i != NumRegs; ++i) {
9795         // For scalable vectors, use the minimum size; individual targets
9796         // are responsible for handling scalable vector arguments and
9797         // return values.
9798         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9799                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9800         if (NumRegs > 1 && i == 0)
9801           MyFlags.Flags.setSplit();
9802         // if it isn't first piece, alignment must be 1
9803         else if (i > 0) {
9804           MyFlags.Flags.setOrigAlign(Align(1));
9805           if (i == NumRegs - 1)
9806             MyFlags.Flags.setSplitEnd();
9807         }
9808         Ins.push_back(MyFlags);
9809       }
9810       if (NeedsRegBlock && Value == NumValues - 1)
9811         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9812       PartBase += VT.getStoreSize().getKnownMinSize();
9813     }
9814   }
9815 
9816   // Call the target to set up the argument values.
9817   SmallVector<SDValue, 8> InVals;
9818   SDValue NewRoot = TLI->LowerFormalArguments(
9819       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9820 
9821   // Verify that the target's LowerFormalArguments behaved as expected.
9822   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9823          "LowerFormalArguments didn't return a valid chain!");
9824   assert(InVals.size() == Ins.size() &&
9825          "LowerFormalArguments didn't emit the correct number of values!");
9826   LLVM_DEBUG({
9827     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9828       assert(InVals[i].getNode() &&
9829              "LowerFormalArguments emitted a null value!");
9830       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9831              "LowerFormalArguments emitted a value with the wrong type!");
9832     }
9833   });
9834 
9835   // Update the DAG with the new chain value resulting from argument lowering.
9836   DAG.setRoot(NewRoot);
9837 
9838   // Set up the argument values.
9839   unsigned i = 0;
9840   if (!FuncInfo->CanLowerReturn) {
9841     // Create a virtual register for the sret pointer, and put in a copy
9842     // from the sret argument into it.
9843     SmallVector<EVT, 1> ValueVTs;
9844     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9845                     F.getReturnType()->getPointerTo(
9846                         DAG.getDataLayout().getAllocaAddrSpace()),
9847                     ValueVTs);
9848     MVT VT = ValueVTs[0].getSimpleVT();
9849     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9850     Optional<ISD::NodeType> AssertOp = None;
9851     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9852                                         nullptr, F.getCallingConv(), AssertOp);
9853 
9854     MachineFunction& MF = SDB->DAG.getMachineFunction();
9855     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9856     Register SRetReg =
9857         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9858     FuncInfo->DemoteRegister = SRetReg;
9859     NewRoot =
9860         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9861     DAG.setRoot(NewRoot);
9862 
9863     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9864     ++i;
9865   }
9866 
9867   SmallVector<SDValue, 4> Chains;
9868   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9869   for (const Argument &Arg : F.args()) {
9870     SmallVector<SDValue, 4> ArgValues;
9871     SmallVector<EVT, 4> ValueVTs;
9872     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9873     unsigned NumValues = ValueVTs.size();
9874     if (NumValues == 0)
9875       continue;
9876 
9877     bool ArgHasUses = !Arg.use_empty();
9878 
9879     // Elide the copying store if the target loaded this argument from a
9880     // suitable fixed stack object.
9881     if (Ins[i].Flags.isCopyElisionCandidate()) {
9882       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9883                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9884                              InVals[i], ArgHasUses);
9885     }
9886 
9887     // If this argument is unused then remember its value. It is used to generate
9888     // debugging information.
9889     bool isSwiftErrorArg =
9890         TLI->supportSwiftError() &&
9891         Arg.hasAttribute(Attribute::SwiftError);
9892     if (!ArgHasUses && !isSwiftErrorArg) {
9893       SDB->setUnusedArgValue(&Arg, InVals[i]);
9894 
9895       // Also remember any frame index for use in FastISel.
9896       if (FrameIndexSDNode *FI =
9897           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9898         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9899     }
9900 
9901     for (unsigned Val = 0; Val != NumValues; ++Val) {
9902       EVT VT = ValueVTs[Val];
9903       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9904                                                       F.getCallingConv(), VT);
9905       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9906           *CurDAG->getContext(), F.getCallingConv(), VT);
9907 
9908       // Even an apparent 'unused' swifterror argument needs to be returned. So
9909       // we do generate a copy for it that can be used on return from the
9910       // function.
9911       if (ArgHasUses || isSwiftErrorArg) {
9912         Optional<ISD::NodeType> AssertOp;
9913         if (Arg.hasAttribute(Attribute::SExt))
9914           AssertOp = ISD::AssertSext;
9915         else if (Arg.hasAttribute(Attribute::ZExt))
9916           AssertOp = ISD::AssertZext;
9917 
9918         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9919                                              PartVT, VT, nullptr,
9920                                              F.getCallingConv(), AssertOp));
9921       }
9922 
9923       i += NumParts;
9924     }
9925 
9926     // We don't need to do anything else for unused arguments.
9927     if (ArgValues.empty())
9928       continue;
9929 
9930     // Note down frame index.
9931     if (FrameIndexSDNode *FI =
9932         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9933       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9934 
9935     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9936                                      SDB->getCurSDLoc());
9937 
9938     SDB->setValue(&Arg, Res);
9939     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9940       // We want to associate the argument with the frame index, among
9941       // involved operands, that correspond to the lowest address. The
9942       // getCopyFromParts function, called earlier, is swapping the order of
9943       // the operands to BUILD_PAIR depending on endianness. The result of
9944       // that swapping is that the least significant bits of the argument will
9945       // be in the first operand of the BUILD_PAIR node, and the most
9946       // significant bits will be in the second operand.
9947       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9948       if (LoadSDNode *LNode =
9949           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9950         if (FrameIndexSDNode *FI =
9951             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9952           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9953     }
9954 
9955     // Analyses past this point are naive and don't expect an assertion.
9956     if (Res.getOpcode() == ISD::AssertZext)
9957       Res = Res.getOperand(0);
9958 
9959     // Update the SwiftErrorVRegDefMap.
9960     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9961       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9962       if (Register::isVirtualRegister(Reg))
9963         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9964                                    Reg);
9965     }
9966 
9967     // If this argument is live outside of the entry block, insert a copy from
9968     // wherever we got it to the vreg that other BB's will reference it as.
9969     if (Res.getOpcode() == ISD::CopyFromReg) {
9970       // If we can, though, try to skip creating an unnecessary vreg.
9971       // FIXME: This isn't very clean... it would be nice to make this more
9972       // general.
9973       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9974       if (Register::isVirtualRegister(Reg)) {
9975         FuncInfo->ValueMap[&Arg] = Reg;
9976         continue;
9977       }
9978     }
9979     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9980       FuncInfo->InitializeRegForValue(&Arg);
9981       SDB->CopyToExportRegsIfNeeded(&Arg);
9982     }
9983   }
9984 
9985   if (!Chains.empty()) {
9986     Chains.push_back(NewRoot);
9987     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9988   }
9989 
9990   DAG.setRoot(NewRoot);
9991 
9992   assert(i == InVals.size() && "Argument register count mismatch!");
9993 
9994   // If any argument copy elisions occurred and we have debug info, update the
9995   // stale frame indices used in the dbg.declare variable info table.
9996   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9997   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9998     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9999       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10000       if (I != ArgCopyElisionFrameIndexMap.end())
10001         VI.Slot = I->second;
10002     }
10003   }
10004 
10005   // Finally, if the target has anything special to do, allow it to do so.
10006   EmitFunctionEntryCode();
10007 }
10008 
10009 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10010 /// ensure constants are generated when needed.  Remember the virtual registers
10011 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10012 /// directly add them, because expansion might result in multiple MBB's for one
10013 /// BB.  As such, the start of the BB might correspond to a different MBB than
10014 /// the end.
10015 void
10016 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10017   const Instruction *TI = LLVMBB->getTerminator();
10018 
10019   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10020 
10021   // Check PHI nodes in successors that expect a value to be available from this
10022   // block.
10023   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10024     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10025     if (!isa<PHINode>(SuccBB->begin())) continue;
10026     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10027 
10028     // If this terminator has multiple identical successors (common for
10029     // switches), only handle each succ once.
10030     if (!SuccsHandled.insert(SuccMBB).second)
10031       continue;
10032 
10033     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10034 
10035     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10036     // nodes and Machine PHI nodes, but the incoming operands have not been
10037     // emitted yet.
10038     for (const PHINode &PN : SuccBB->phis()) {
10039       // Ignore dead phi's.
10040       if (PN.use_empty())
10041         continue;
10042 
10043       // Skip empty types
10044       if (PN.getType()->isEmptyTy())
10045         continue;
10046 
10047       unsigned Reg;
10048       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10049 
10050       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10051         unsigned &RegOut = ConstantsOut[C];
10052         if (RegOut == 0) {
10053           RegOut = FuncInfo.CreateRegs(C);
10054           CopyValueToVirtualRegister(C, RegOut);
10055         }
10056         Reg = RegOut;
10057       } else {
10058         DenseMap<const Value *, unsigned>::iterator I =
10059           FuncInfo.ValueMap.find(PHIOp);
10060         if (I != FuncInfo.ValueMap.end())
10061           Reg = I->second;
10062         else {
10063           assert(isa<AllocaInst>(PHIOp) &&
10064                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10065                  "Didn't codegen value into a register!??");
10066           Reg = FuncInfo.CreateRegs(PHIOp);
10067           CopyValueToVirtualRegister(PHIOp, Reg);
10068         }
10069       }
10070 
10071       // Remember that this register needs to added to the machine PHI node as
10072       // the input for this MBB.
10073       SmallVector<EVT, 4> ValueVTs;
10074       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10075       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10076       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10077         EVT VT = ValueVTs[vti];
10078         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10079         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10080           FuncInfo.PHINodesToUpdate.push_back(
10081               std::make_pair(&*MBBI++, Reg + i));
10082         Reg += NumRegisters;
10083       }
10084     }
10085   }
10086 
10087   ConstantsOut.clear();
10088 }
10089 
10090 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10091 /// is 0.
10092 MachineBasicBlock *
10093 SelectionDAGBuilder::StackProtectorDescriptor::
10094 AddSuccessorMBB(const BasicBlock *BB,
10095                 MachineBasicBlock *ParentMBB,
10096                 bool IsLikely,
10097                 MachineBasicBlock *SuccMBB) {
10098   // If SuccBB has not been created yet, create it.
10099   if (!SuccMBB) {
10100     MachineFunction *MF = ParentMBB->getParent();
10101     MachineFunction::iterator BBI(ParentMBB);
10102     SuccMBB = MF->CreateMachineBasicBlock(BB);
10103     MF->insert(++BBI, SuccMBB);
10104   }
10105   // Add it as a successor of ParentMBB.
10106   ParentMBB->addSuccessor(
10107       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10108   return SuccMBB;
10109 }
10110 
10111 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10112   MachineFunction::iterator I(MBB);
10113   if (++I == FuncInfo.MF->end())
10114     return nullptr;
10115   return &*I;
10116 }
10117 
10118 /// During lowering new call nodes can be created (such as memset, etc.).
10119 /// Those will become new roots of the current DAG, but complications arise
10120 /// when they are tail calls. In such cases, the call lowering will update
10121 /// the root, but the builder still needs to know that a tail call has been
10122 /// lowered in order to avoid generating an additional return.
10123 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10124   // If the node is null, we do have a tail call.
10125   if (MaybeTC.getNode() != nullptr)
10126     DAG.setRoot(MaybeTC);
10127   else
10128     HasTailCall = true;
10129 }
10130 
10131 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10132                                         MachineBasicBlock *SwitchMBB,
10133                                         MachineBasicBlock *DefaultMBB) {
10134   MachineFunction *CurMF = FuncInfo.MF;
10135   MachineBasicBlock *NextMBB = nullptr;
10136   MachineFunction::iterator BBI(W.MBB);
10137   if (++BBI != FuncInfo.MF->end())
10138     NextMBB = &*BBI;
10139 
10140   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10141 
10142   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10143 
10144   if (Size == 2 && W.MBB == SwitchMBB) {
10145     // If any two of the cases has the same destination, and if one value
10146     // is the same as the other, but has one bit unset that the other has set,
10147     // use bit manipulation to do two compares at once.  For example:
10148     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10149     // TODO: This could be extended to merge any 2 cases in switches with 3
10150     // cases.
10151     // TODO: Handle cases where W.CaseBB != SwitchBB.
10152     CaseCluster &Small = *W.FirstCluster;
10153     CaseCluster &Big = *W.LastCluster;
10154 
10155     if (Small.Low == Small.High && Big.Low == Big.High &&
10156         Small.MBB == Big.MBB) {
10157       const APInt &SmallValue = Small.Low->getValue();
10158       const APInt &BigValue = Big.Low->getValue();
10159 
10160       // Check that there is only one bit different.
10161       APInt CommonBit = BigValue ^ SmallValue;
10162       if (CommonBit.isPowerOf2()) {
10163         SDValue CondLHS = getValue(Cond);
10164         EVT VT = CondLHS.getValueType();
10165         SDLoc DL = getCurSDLoc();
10166 
10167         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10168                                  DAG.getConstant(CommonBit, DL, VT));
10169         SDValue Cond = DAG.getSetCC(
10170             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10171             ISD::SETEQ);
10172 
10173         // Update successor info.
10174         // Both Small and Big will jump to Small.BB, so we sum up the
10175         // probabilities.
10176         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10177         if (BPI)
10178           addSuccessorWithProb(
10179               SwitchMBB, DefaultMBB,
10180               // The default destination is the first successor in IR.
10181               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10182         else
10183           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10184 
10185         // Insert the true branch.
10186         SDValue BrCond =
10187             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10188                         DAG.getBasicBlock(Small.MBB));
10189         // Insert the false branch.
10190         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10191                              DAG.getBasicBlock(DefaultMBB));
10192 
10193         DAG.setRoot(BrCond);
10194         return;
10195       }
10196     }
10197   }
10198 
10199   if (TM.getOptLevel() != CodeGenOpt::None) {
10200     // Here, we order cases by probability so the most likely case will be
10201     // checked first. However, two clusters can have the same probability in
10202     // which case their relative ordering is non-deterministic. So we use Low
10203     // as a tie-breaker as clusters are guaranteed to never overlap.
10204     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10205                [](const CaseCluster &a, const CaseCluster &b) {
10206       return a.Prob != b.Prob ?
10207              a.Prob > b.Prob :
10208              a.Low->getValue().slt(b.Low->getValue());
10209     });
10210 
10211     // Rearrange the case blocks so that the last one falls through if possible
10212     // without changing the order of probabilities.
10213     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10214       --I;
10215       if (I->Prob > W.LastCluster->Prob)
10216         break;
10217       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10218         std::swap(*I, *W.LastCluster);
10219         break;
10220       }
10221     }
10222   }
10223 
10224   // Compute total probability.
10225   BranchProbability DefaultProb = W.DefaultProb;
10226   BranchProbability UnhandledProbs = DefaultProb;
10227   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10228     UnhandledProbs += I->Prob;
10229 
10230   MachineBasicBlock *CurMBB = W.MBB;
10231   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10232     bool FallthroughUnreachable = false;
10233     MachineBasicBlock *Fallthrough;
10234     if (I == W.LastCluster) {
10235       // For the last cluster, fall through to the default destination.
10236       Fallthrough = DefaultMBB;
10237       FallthroughUnreachable = isa<UnreachableInst>(
10238           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10239     } else {
10240       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10241       CurMF->insert(BBI, Fallthrough);
10242       // Put Cond in a virtual register to make it available from the new blocks.
10243       ExportFromCurrentBlock(Cond);
10244     }
10245     UnhandledProbs -= I->Prob;
10246 
10247     switch (I->Kind) {
10248       case CC_JumpTable: {
10249         // FIXME: Optimize away range check based on pivot comparisons.
10250         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10251         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10252 
10253         // The jump block hasn't been inserted yet; insert it here.
10254         MachineBasicBlock *JumpMBB = JT->MBB;
10255         CurMF->insert(BBI, JumpMBB);
10256 
10257         auto JumpProb = I->Prob;
10258         auto FallthroughProb = UnhandledProbs;
10259 
10260         // If the default statement is a target of the jump table, we evenly
10261         // distribute the default probability to successors of CurMBB. Also
10262         // update the probability on the edge from JumpMBB to Fallthrough.
10263         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10264                                               SE = JumpMBB->succ_end();
10265              SI != SE; ++SI) {
10266           if (*SI == DefaultMBB) {
10267             JumpProb += DefaultProb / 2;
10268             FallthroughProb -= DefaultProb / 2;
10269             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10270             JumpMBB->normalizeSuccProbs();
10271             break;
10272           }
10273         }
10274 
10275         if (FallthroughUnreachable) {
10276           // Skip the range check if the fallthrough block is unreachable.
10277           JTH->OmitRangeCheck = true;
10278         }
10279 
10280         if (!JTH->OmitRangeCheck)
10281           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10282         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10283         CurMBB->normalizeSuccProbs();
10284 
10285         // The jump table header will be inserted in our current block, do the
10286         // range check, and fall through to our fallthrough block.
10287         JTH->HeaderBB = CurMBB;
10288         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10289 
10290         // If we're in the right place, emit the jump table header right now.
10291         if (CurMBB == SwitchMBB) {
10292           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10293           JTH->Emitted = true;
10294         }
10295         break;
10296       }
10297       case CC_BitTests: {
10298         // FIXME: Optimize away range check based on pivot comparisons.
10299         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10300 
10301         // The bit test blocks haven't been inserted yet; insert them here.
10302         for (BitTestCase &BTC : BTB->Cases)
10303           CurMF->insert(BBI, BTC.ThisBB);
10304 
10305         // Fill in fields of the BitTestBlock.
10306         BTB->Parent = CurMBB;
10307         BTB->Default = Fallthrough;
10308 
10309         BTB->DefaultProb = UnhandledProbs;
10310         // If the cases in bit test don't form a contiguous range, we evenly
10311         // distribute the probability on the edge to Fallthrough to two
10312         // successors of CurMBB.
10313         if (!BTB->ContiguousRange) {
10314           BTB->Prob += DefaultProb / 2;
10315           BTB->DefaultProb -= DefaultProb / 2;
10316         }
10317 
10318         if (FallthroughUnreachable) {
10319           // Skip the range check if the fallthrough block is unreachable.
10320           BTB->OmitRangeCheck = true;
10321         }
10322 
10323         // If we're in the right place, emit the bit test header right now.
10324         if (CurMBB == SwitchMBB) {
10325           visitBitTestHeader(*BTB, SwitchMBB);
10326           BTB->Emitted = true;
10327         }
10328         break;
10329       }
10330       case CC_Range: {
10331         const Value *RHS, *LHS, *MHS;
10332         ISD::CondCode CC;
10333         if (I->Low == I->High) {
10334           // Check Cond == I->Low.
10335           CC = ISD::SETEQ;
10336           LHS = Cond;
10337           RHS=I->Low;
10338           MHS = nullptr;
10339         } else {
10340           // Check I->Low <= Cond <= I->High.
10341           CC = ISD::SETLE;
10342           LHS = I->Low;
10343           MHS = Cond;
10344           RHS = I->High;
10345         }
10346 
10347         // If Fallthrough is unreachable, fold away the comparison.
10348         if (FallthroughUnreachable)
10349           CC = ISD::SETTRUE;
10350 
10351         // The false probability is the sum of all unhandled cases.
10352         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10353                      getCurSDLoc(), I->Prob, UnhandledProbs);
10354 
10355         if (CurMBB == SwitchMBB)
10356           visitSwitchCase(CB, SwitchMBB);
10357         else
10358           SL->SwitchCases.push_back(CB);
10359 
10360         break;
10361       }
10362     }
10363     CurMBB = Fallthrough;
10364   }
10365 }
10366 
10367 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10368                                               CaseClusterIt First,
10369                                               CaseClusterIt Last) {
10370   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10371     if (X.Prob != CC.Prob)
10372       return X.Prob > CC.Prob;
10373 
10374     // Ties are broken by comparing the case value.
10375     return X.Low->getValue().slt(CC.Low->getValue());
10376   });
10377 }
10378 
10379 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10380                                         const SwitchWorkListItem &W,
10381                                         Value *Cond,
10382                                         MachineBasicBlock *SwitchMBB) {
10383   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10384          "Clusters not sorted?");
10385 
10386   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10387 
10388   // Balance the tree based on branch probabilities to create a near-optimal (in
10389   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10390   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10391   CaseClusterIt LastLeft = W.FirstCluster;
10392   CaseClusterIt FirstRight = W.LastCluster;
10393   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10394   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10395 
10396   // Move LastLeft and FirstRight towards each other from opposite directions to
10397   // find a partitioning of the clusters which balances the probability on both
10398   // sides. If LeftProb and RightProb are equal, alternate which side is
10399   // taken to ensure 0-probability nodes are distributed evenly.
10400   unsigned I = 0;
10401   while (LastLeft + 1 < FirstRight) {
10402     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10403       LeftProb += (++LastLeft)->Prob;
10404     else
10405       RightProb += (--FirstRight)->Prob;
10406     I++;
10407   }
10408 
10409   while (true) {
10410     // Our binary search tree differs from a typical BST in that ours can have up
10411     // to three values in each leaf. The pivot selection above doesn't take that
10412     // into account, which means the tree might require more nodes and be less
10413     // efficient. We compensate for this here.
10414 
10415     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10416     unsigned NumRight = W.LastCluster - FirstRight + 1;
10417 
10418     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10419       // If one side has less than 3 clusters, and the other has more than 3,
10420       // consider taking a cluster from the other side.
10421 
10422       if (NumLeft < NumRight) {
10423         // Consider moving the first cluster on the right to the left side.
10424         CaseCluster &CC = *FirstRight;
10425         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10426         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10427         if (LeftSideRank <= RightSideRank) {
10428           // Moving the cluster to the left does not demote it.
10429           ++LastLeft;
10430           ++FirstRight;
10431           continue;
10432         }
10433       } else {
10434         assert(NumRight < NumLeft);
10435         // Consider moving the last element on the left to the right side.
10436         CaseCluster &CC = *LastLeft;
10437         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10438         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10439         if (RightSideRank <= LeftSideRank) {
10440           // Moving the cluster to the right does not demot it.
10441           --LastLeft;
10442           --FirstRight;
10443           continue;
10444         }
10445       }
10446     }
10447     break;
10448   }
10449 
10450   assert(LastLeft + 1 == FirstRight);
10451   assert(LastLeft >= W.FirstCluster);
10452   assert(FirstRight <= W.LastCluster);
10453 
10454   // Use the first element on the right as pivot since we will make less-than
10455   // comparisons against it.
10456   CaseClusterIt PivotCluster = FirstRight;
10457   assert(PivotCluster > W.FirstCluster);
10458   assert(PivotCluster <= W.LastCluster);
10459 
10460   CaseClusterIt FirstLeft = W.FirstCluster;
10461   CaseClusterIt LastRight = W.LastCluster;
10462 
10463   const ConstantInt *Pivot = PivotCluster->Low;
10464 
10465   // New blocks will be inserted immediately after the current one.
10466   MachineFunction::iterator BBI(W.MBB);
10467   ++BBI;
10468 
10469   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10470   // we can branch to its destination directly if it's squeezed exactly in
10471   // between the known lower bound and Pivot - 1.
10472   MachineBasicBlock *LeftMBB;
10473   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10474       FirstLeft->Low == W.GE &&
10475       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10476     LeftMBB = FirstLeft->MBB;
10477   } else {
10478     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10479     FuncInfo.MF->insert(BBI, LeftMBB);
10480     WorkList.push_back(
10481         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10482     // Put Cond in a virtual register to make it available from the new blocks.
10483     ExportFromCurrentBlock(Cond);
10484   }
10485 
10486   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10487   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10488   // directly if RHS.High equals the current upper bound.
10489   MachineBasicBlock *RightMBB;
10490   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10491       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10492     RightMBB = FirstRight->MBB;
10493   } else {
10494     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10495     FuncInfo.MF->insert(BBI, RightMBB);
10496     WorkList.push_back(
10497         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10498     // Put Cond in a virtual register to make it available from the new blocks.
10499     ExportFromCurrentBlock(Cond);
10500   }
10501 
10502   // Create the CaseBlock record that will be used to lower the branch.
10503   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10504                getCurSDLoc(), LeftProb, RightProb);
10505 
10506   if (W.MBB == SwitchMBB)
10507     visitSwitchCase(CB, SwitchMBB);
10508   else
10509     SL->SwitchCases.push_back(CB);
10510 }
10511 
10512 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10513 // from the swith statement.
10514 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10515                                             BranchProbability PeeledCaseProb) {
10516   if (PeeledCaseProb == BranchProbability::getOne())
10517     return BranchProbability::getZero();
10518   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10519 
10520   uint32_t Numerator = CaseProb.getNumerator();
10521   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10522   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10523 }
10524 
10525 // Try to peel the top probability case if it exceeds the threshold.
10526 // Return current MachineBasicBlock for the switch statement if the peeling
10527 // does not occur.
10528 // If the peeling is performed, return the newly created MachineBasicBlock
10529 // for the peeled switch statement. Also update Clusters to remove the peeled
10530 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10531 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10532     const SwitchInst &SI, CaseClusterVector &Clusters,
10533     BranchProbability &PeeledCaseProb) {
10534   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10535   // Don't perform if there is only one cluster or optimizing for size.
10536   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10537       TM.getOptLevel() == CodeGenOpt::None ||
10538       SwitchMBB->getParent()->getFunction().hasMinSize())
10539     return SwitchMBB;
10540 
10541   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10542   unsigned PeeledCaseIndex = 0;
10543   bool SwitchPeeled = false;
10544   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10545     CaseCluster &CC = Clusters[Index];
10546     if (CC.Prob < TopCaseProb)
10547       continue;
10548     TopCaseProb = CC.Prob;
10549     PeeledCaseIndex = Index;
10550     SwitchPeeled = true;
10551   }
10552   if (!SwitchPeeled)
10553     return SwitchMBB;
10554 
10555   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10556                     << TopCaseProb << "\n");
10557 
10558   // Record the MBB for the peeled switch statement.
10559   MachineFunction::iterator BBI(SwitchMBB);
10560   ++BBI;
10561   MachineBasicBlock *PeeledSwitchMBB =
10562       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10563   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10564 
10565   ExportFromCurrentBlock(SI.getCondition());
10566   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10567   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10568                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10569   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10570 
10571   Clusters.erase(PeeledCaseIt);
10572   for (CaseCluster &CC : Clusters) {
10573     LLVM_DEBUG(
10574         dbgs() << "Scale the probablity for one cluster, before scaling: "
10575                << CC.Prob << "\n");
10576     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10577     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10578   }
10579   PeeledCaseProb = TopCaseProb;
10580   return PeeledSwitchMBB;
10581 }
10582 
10583 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10584   // Extract cases from the switch.
10585   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10586   CaseClusterVector Clusters;
10587   Clusters.reserve(SI.getNumCases());
10588   for (auto I : SI.cases()) {
10589     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10590     const ConstantInt *CaseVal = I.getCaseValue();
10591     BranchProbability Prob =
10592         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10593             : BranchProbability(1, SI.getNumCases() + 1);
10594     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10595   }
10596 
10597   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10598 
10599   // Cluster adjacent cases with the same destination. We do this at all
10600   // optimization levels because it's cheap to do and will make codegen faster
10601   // if there are many clusters.
10602   sortAndRangeify(Clusters);
10603 
10604   // The branch probablity of the peeled case.
10605   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10606   MachineBasicBlock *PeeledSwitchMBB =
10607       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10608 
10609   // If there is only the default destination, jump there directly.
10610   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10611   if (Clusters.empty()) {
10612     assert(PeeledSwitchMBB == SwitchMBB);
10613     SwitchMBB->addSuccessor(DefaultMBB);
10614     if (DefaultMBB != NextBlock(SwitchMBB)) {
10615       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10616                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10617     }
10618     return;
10619   }
10620 
10621   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10622   SL->findBitTestClusters(Clusters, &SI);
10623 
10624   LLVM_DEBUG({
10625     dbgs() << "Case clusters: ";
10626     for (const CaseCluster &C : Clusters) {
10627       if (C.Kind == CC_JumpTable)
10628         dbgs() << "JT:";
10629       if (C.Kind == CC_BitTests)
10630         dbgs() << "BT:";
10631 
10632       C.Low->getValue().print(dbgs(), true);
10633       if (C.Low != C.High) {
10634         dbgs() << '-';
10635         C.High->getValue().print(dbgs(), true);
10636       }
10637       dbgs() << ' ';
10638     }
10639     dbgs() << '\n';
10640   });
10641 
10642   assert(!Clusters.empty());
10643   SwitchWorkList WorkList;
10644   CaseClusterIt First = Clusters.begin();
10645   CaseClusterIt Last = Clusters.end() - 1;
10646   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10647   // Scale the branchprobability for DefaultMBB if the peel occurs and
10648   // DefaultMBB is not replaced.
10649   if (PeeledCaseProb != BranchProbability::getZero() &&
10650       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10651     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10652   WorkList.push_back(
10653       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10654 
10655   while (!WorkList.empty()) {
10656     SwitchWorkListItem W = WorkList.back();
10657     WorkList.pop_back();
10658     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10659 
10660     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10661         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10662       // For optimized builds, lower large range as a balanced binary tree.
10663       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10664       continue;
10665     }
10666 
10667     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10668   }
10669 }
10670 
10671 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10672   SDValue N = getValue(I.getOperand(0));
10673   setValue(&I, N);
10674 }
10675