xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4b0aa5724feaa89a9538dcab97e018110b0e4bc3)
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/CallingConv.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DebugInfoMetadata.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GetElementPtrTypeIterator.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/IntrinsicsAArch64.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/Metadata.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/Operator.h"
94 #include "llvm/IR/PatternMatch.h"
95 #include "llvm/IR/Statepoint.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/MC/MCContext.h"
100 #include "llvm/MC/MCSymbol.h"
101 #include "llvm/Support/AtomicOrdering.h"
102 #include "llvm/Support/BranchProbability.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CodeGen.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/MachineValueType.h"
110 #include "llvm/Support/MathExtras.h"
111 #include "llvm/Support/raw_ostream.h"
112 #include "llvm/Target/TargetIntrinsicInfo.h"
113 #include "llvm/Target/TargetMachine.h"
114 #include "llvm/Target/TargetOptions.h"
115 #include "llvm/Transforms/Utils/Local.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cstddef>
119 #include <cstdint>
120 #include <cstring>
121 #include <iterator>
122 #include <limits>
123 #include <numeric>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 using namespace llvm;
129 using namespace PatternMatch;
130 using namespace SwitchCG;
131 
132 #define DEBUG_TYPE "isel"
133 
134 /// LimitFloatPrecision - Generate low-precision inline sequences for
135 /// some float libcalls (6, 8 or 12 bits).
136 static unsigned LimitFloatPrecision;
137 
138 static cl::opt<bool>
139     InsertAssertAlign("insert-assert-align", cl::init(true),
140                       cl::desc("Insert the experimental `assertalign` node."),
141                       cl::ReallyHidden);
142 
143 static cl::opt<unsigned, true>
144     LimitFPPrecision("limit-float-precision",
145                      cl::desc("Generate low-precision inline sequences "
146                               "for some float libcalls"),
147                      cl::location(LimitFloatPrecision), cl::Hidden,
148                      cl::init(0));
149 
150 static cl::opt<unsigned> SwitchPeelThreshold(
151     "switch-peel-threshold", cl::Hidden, cl::init(66),
152     cl::desc("Set the case probability threshold for peeling the case from a "
153              "switch statement. A value greater than 100 will void this "
154              "optimization"));
155 
156 // Limit the width of DAG chains. This is important in general to prevent
157 // DAG-based analysis from blowing up. For example, alias analysis and
158 // load clustering may not complete in reasonable time. It is difficult to
159 // recognize and avoid this situation within each individual analysis, and
160 // future analyses are likely to have the same behavior. Limiting DAG width is
161 // the safe approach and will be especially important with global DAGs.
162 //
163 // MaxParallelChains default is arbitrarily high to avoid affecting
164 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
165 // sequence over this should have been converted to llvm.memcpy by the
166 // frontend. It is easy to induce this behavior with .ll code such as:
167 // %buffer = alloca [4096 x i8]
168 // %data = load [4096 x i8]* %argPtr
169 // store [4096 x i8] %data, [4096 x i8]* %buffer
170 static const unsigned MaxParallelChains = 64;
171 
172 // Return the calling convention if the Value passed requires ABI mangling as it
173 // is a parameter to a function or a return value from a function which is not
174 // an intrinsic.
175 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
176   if (auto *R = dyn_cast<ReturnInst>(V))
177     return R->getParent()->getParent()->getCallingConv();
178 
179   if (auto *CI = dyn_cast<CallInst>(V)) {
180     const bool IsInlineAsm = CI->isInlineAsm();
181     const bool IsIndirectFunctionCall =
182         !IsInlineAsm && !CI->getCalledFunction();
183 
184     // It is possible that the call instruction is an inline asm statement or an
185     // indirect function call in which case the return value of
186     // getCalledFunction() would be nullptr.
187     const bool IsInstrinsicCall =
188         !IsInlineAsm && !IsIndirectFunctionCall &&
189         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
190 
191     if (!IsInlineAsm && !IsInstrinsicCall)
192       return CI->getCallingConv();
193   }
194 
195   return None;
196 }
197 
198 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
199                                       const SDValue *Parts, unsigned NumParts,
200                                       MVT PartVT, EVT ValueVT, const Value *V,
201                                       Optional<CallingConv::ID> CC);
202 
203 /// getCopyFromParts - Create a value that contains the specified legal parts
204 /// combined into the value they represent.  If the parts combine to a type
205 /// larger than ValueVT then AssertOp can be used to specify whether the extra
206 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
207 /// (ISD::AssertSext).
208 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
209                                 const SDValue *Parts, unsigned NumParts,
210                                 MVT PartVT, EVT ValueVT, const Value *V,
211                                 Optional<CallingConv::ID> CC = None,
212                                 Optional<ISD::NodeType> AssertOp = None) {
213   // Let the target assemble the parts if it wants to
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
216                                                    PartVT, ValueVT, CC))
217     return Val;
218 
219   if (ValueVT.isVector())
220     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
221                                   CC);
222 
223   assert(NumParts > 0 && "No parts to assemble!");
224   SDValue Val = Parts[0];
225 
226   if (NumParts > 1) {
227     // Assemble the value from multiple parts.
228     if (ValueVT.isInteger()) {
229       unsigned PartBits = PartVT.getSizeInBits();
230       unsigned ValueBits = ValueVT.getSizeInBits();
231 
232       // Assemble the power of 2 part.
233       unsigned RoundParts =
234           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
235       unsigned RoundBits = PartBits * RoundParts;
236       EVT RoundVT = RoundBits == ValueBits ?
237         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
238       SDValue Lo, Hi;
239 
240       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
241 
242       if (RoundParts > 2) {
243         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
244                               PartVT, HalfVT, V);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
246                               RoundParts / 2, PartVT, HalfVT, V);
247       } else {
248         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
249         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
250       }
251 
252       if (DAG.getDataLayout().isBigEndian())
253         std::swap(Lo, Hi);
254 
255       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
256 
257       if (RoundParts < NumParts) {
258         // Assemble the trailing non-power-of-2 part.
259         unsigned OddParts = NumParts - RoundParts;
260         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
261         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
262                               OddVT, V, CC);
263 
264         // Combine the round and odd parts.
265         Lo = Val;
266         if (DAG.getDataLayout().isBigEndian())
267           std::swap(Lo, Hi);
268         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
269         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
270         Hi =
271             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
272                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
273                                         TLI.getPointerTy(DAG.getDataLayout())));
274         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
275         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
276       }
277     } else if (PartVT.isFloatingPoint()) {
278       // FP split into multiple FP parts (for ppcf128)
279       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
280              "Unexpected split");
281       SDValue Lo, Hi;
282       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
283       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
284       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
285         std::swap(Lo, Hi);
286       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
287     } else {
288       // FP split into integer parts (soft fp)
289       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
290              !PartVT.isVector() && "Unexpected split");
291       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
292       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
293     }
294   }
295 
296   // There is now one part, held in Val.  Correct it to match ValueVT.
297   // PartEVT is the type of the register class that holds the value.
298   // ValueVT is the type of the inline asm operation.
299   EVT PartEVT = Val.getValueType();
300 
301   if (PartEVT == ValueVT)
302     return Val;
303 
304   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
305       ValueVT.bitsLT(PartEVT)) {
306     // For an FP value in an integer part, we need to truncate to the right
307     // width first.
308     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
309     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
310   }
311 
312   // Handle types that have the same size.
313   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
314     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
315 
316   // Handle types with different sizes.
317   if (PartEVT.isInteger() && ValueVT.isInteger()) {
318     if (ValueVT.bitsLT(PartEVT)) {
319       // For a truncate, see if we have any information to
320       // indicate whether the truncated bits will always be
321       // zero or sign-extension.
322       if (AssertOp.hasValue())
323         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
324                           DAG.getValueType(ValueVT));
325       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
326     }
327     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
328   }
329 
330   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
331     // FP_ROUND's are always exact here.
332     if (ValueVT.bitsLT(Val.getValueType()))
333       return DAG.getNode(
334           ISD::FP_ROUND, DL, ValueVT, Val,
335           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
336 
337     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
338   }
339 
340   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
341   // then truncating.
342   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
343       ValueVT.bitsLT(PartEVT)) {
344     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
345     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
346   }
347 
348   report_fatal_error("Unknown mismatch in getCopyFromParts!");
349 }
350 
351 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
352                                               const Twine &ErrMsg) {
353   const Instruction *I = dyn_cast_or_null<Instruction>(V);
354   if (!V)
355     return Ctx.emitError(ErrMsg);
356 
357   const char *AsmError = ", possible invalid constraint for vector type";
358   if (const CallInst *CI = dyn_cast<CallInst>(I))
359     if (CI->isInlineAsm())
360       return Ctx.emitError(I, ErrMsg + AsmError);
361 
362   return Ctx.emitError(I, ErrMsg);
363 }
364 
365 /// getCopyFromPartsVector - Create a value that contains the specified legal
366 /// parts combined into the value they represent.  If the parts combine to a
367 /// type larger than ValueVT then AssertOp can be used to specify whether the
368 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
369 /// ValueVT (ISD::AssertSext).
370 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
371                                       const SDValue *Parts, unsigned NumParts,
372                                       MVT PartVT, EVT ValueVT, const Value *V,
373                                       Optional<CallingConv::ID> CallConv) {
374   assert(ValueVT.isVector() && "Not a vector value");
375   assert(NumParts > 0 && "No parts to assemble!");
376   const bool IsABIRegCopy = CallConv.hasValue();
377 
378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
379   SDValue Val = Parts[0];
380 
381   // Handle a multi-element vector.
382   if (NumParts > 1) {
383     EVT IntermediateVT;
384     MVT RegisterVT;
385     unsigned NumIntermediates;
386     unsigned NumRegs;
387 
388     if (IsABIRegCopy) {
389       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
390           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
391           NumIntermediates, RegisterVT);
392     } else {
393       NumRegs =
394           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
395                                      NumIntermediates, RegisterVT);
396     }
397 
398     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
399     NumParts = NumRegs; // Silence a compiler warning.
400     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
401     assert(RegisterVT.getSizeInBits() ==
402            Parts[0].getSimpleValueType().getSizeInBits() &&
403            "Part type sizes don't match!");
404 
405     // Assemble the parts into intermediate operands.
406     SmallVector<SDValue, 8> Ops(NumIntermediates);
407     if (NumIntermediates == NumParts) {
408       // If the register was not expanded, truncate or copy the value,
409       // as appropriate.
410       for (unsigned i = 0; i != NumParts; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
412                                   PartVT, IntermediateVT, V);
413     } else if (NumParts > 0) {
414       // If the intermediate type was expanded, build the intermediate
415       // operands from the parts.
416       assert(NumParts % NumIntermediates == 0 &&
417              "Must expand into a divisible number of parts!");
418       unsigned Factor = NumParts / NumIntermediates;
419       for (unsigned i = 0; i != NumIntermediates; ++i)
420         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
421                                   PartVT, IntermediateVT, V);
422     }
423 
424     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
425     // intermediate operands.
426     EVT BuiltVectorTy =
427         IntermediateVT.isVector()
428             ? EVT::getVectorVT(
429                   *DAG.getContext(), IntermediateVT.getScalarType(),
430                   IntermediateVT.getVectorElementCount() * NumParts)
431             : EVT::getVectorVT(*DAG.getContext(),
432                                IntermediateVT.getScalarType(),
433                                NumIntermediates);
434     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
435                                                 : ISD::BUILD_VECTOR,
436                       DL, BuiltVectorTy, Ops);
437   }
438 
439   // There is now one part, held in Val.  Correct it to match ValueVT.
440   EVT PartEVT = Val.getValueType();
441 
442   if (PartEVT == ValueVT)
443     return Val;
444 
445   if (PartEVT.isVector()) {
446     // If the element type of the source/dest vectors are the same, but the
447     // parts vector has more elements than the value vector, then we have a
448     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
449     // elements we want.
450     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
451       assert((PartEVT.getVectorElementCount().Min >
452               ValueVT.getVectorElementCount().Min) &&
453              (PartEVT.getVectorElementCount().Scalable ==
454               ValueVT.getVectorElementCount().Scalable) &&
455              "Cannot narrow, it would be a lossy transformation");
456       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
457                          DAG.getVectorIdxConstant(0, DL));
458     }
459 
460     // Vector/Vector bitcast.
461     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
462       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
463 
464     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
465       "Cannot handle this kind of promotion");
466     // Promoted vector extract
467     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
468 
469   }
470 
471   // Trivial bitcast if the types are the same size and the destination
472   // vector type is legal.
473   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
474       TLI.isTypeLegal(ValueVT))
475     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
476 
477   if (ValueVT.getVectorNumElements() != 1) {
478      // Certain ABIs require that vectors are passed as integers. For vectors
479      // are the same size, this is an obvious bitcast.
480      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
481        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
482      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
483        // Bitcast Val back the original type and extract the corresponding
484        // vector we want.
485        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
486        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
487                                            ValueVT.getVectorElementType(), Elts);
488        Val = DAG.getBitcast(WiderVecType, Val);
489        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
490                           DAG.getVectorIdxConstant(0, DL));
491      }
492 
493      diagnosePossiblyInvalidConstraint(
494          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
495      return DAG.getUNDEF(ValueVT);
496   }
497 
498   // Handle cases such as i8 -> <1 x i1>
499   EVT ValueSVT = ValueVT.getVectorElementType();
500   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
501     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
502       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
503     else
504       Val = ValueVT.isFloatingPoint()
505                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
506                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
507   }
508 
509   return DAG.getBuildVector(ValueVT, DL, Val);
510 }
511 
512 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
513                                  SDValue Val, SDValue *Parts, unsigned NumParts,
514                                  MVT PartVT, const Value *V,
515                                  Optional<CallingConv::ID> CallConv);
516 
517 /// getCopyToParts - Create a series of nodes that contain the specified value
518 /// split into legal parts.  If the parts contain more bits than Val, then, for
519 /// integers, ExtendKind can be used to specify how to generate the extra bits.
520 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
521                            SDValue *Parts, unsigned NumParts, MVT PartVT,
522                            const Value *V,
523                            Optional<CallingConv::ID> CallConv = None,
524                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
525   // Let the target split the parts if it wants to
526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
527   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
528                                       CallConv))
529     return;
530   EVT ValueVT = Val.getValueType();
531 
532   // Handle the vector case separately.
533   if (ValueVT.isVector())
534     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
535                                 CallConv);
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   unsigned OrigNumParts = NumParts;
539   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
540          "Copying to an illegal type!");
541 
542   if (NumParts == 0)
543     return;
544 
545   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
546   EVT PartEVT = PartVT;
547   if (PartEVT == ValueVT) {
548     assert(NumParts == 1 && "No-op copy with multiple parts!");
549     Parts[0] = Val;
550     return;
551   }
552 
553   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
554     // If the parts cover more bits than the value has, promote the value.
555     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
556       assert(NumParts == 1 && "Do not know what to promote to!");
557       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
558     } else {
559       if (ValueVT.isFloatingPoint()) {
560         // FP values need to be bitcast, then extended if they are being put
561         // into a larger container.
562         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
563         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
564       }
565       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566              ValueVT.isInteger() &&
567              "Unknown mismatch!");
568       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
570       if (PartVT == MVT::x86mmx)
571         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572     }
573   } else if (PartBits == ValueVT.getSizeInBits()) {
574     // Different types of the same size.
575     assert(NumParts == 1 && PartEVT != ValueVT);
576     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
577   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
578     // If the parts cover less bits than value has, truncate the value.
579     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
580            ValueVT.isInteger() &&
581            "Unknown mismatch!");
582     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
583     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
584     if (PartVT == MVT::x86mmx)
585       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
586   }
587 
588   // The value may have changed - recompute ValueVT.
589   ValueVT = Val.getValueType();
590   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
591          "Failed to tile the value with PartVT!");
592 
593   if (NumParts == 1) {
594     if (PartEVT != ValueVT) {
595       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
596                                         "scalar-to-vector conversion failed");
597       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
598     }
599 
600     Parts[0] = Val;
601     return;
602   }
603 
604   // Expand the value into multiple parts.
605   if (NumParts & (NumParts - 1)) {
606     // The number of parts is not a power of 2.  Split off and copy the tail.
607     assert(PartVT.isInteger() && ValueVT.isInteger() &&
608            "Do not know what to expand to!");
609     unsigned RoundParts = 1 << Log2_32(NumParts);
610     unsigned RoundBits = RoundParts * PartBits;
611     unsigned OddParts = NumParts - RoundParts;
612     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
613       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
614 
615     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
616                    CallConv);
617 
618     if (DAG.getDataLayout().isBigEndian())
619       // The odd parts were reversed by getCopyToParts - unreverse them.
620       std::reverse(Parts + RoundParts, Parts + NumParts);
621 
622     NumParts = RoundParts;
623     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
624     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
625   }
626 
627   // The number of parts is a power of 2.  Repeatedly bisect the value using
628   // EXTRACT_ELEMENT.
629   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
630                          EVT::getIntegerVT(*DAG.getContext(),
631                                            ValueVT.getSizeInBits()),
632                          Val);
633 
634   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
635     for (unsigned i = 0; i < NumParts; i += StepSize) {
636       unsigned ThisBits = StepSize * PartBits / 2;
637       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
638       SDValue &Part0 = Parts[i];
639       SDValue &Part1 = Parts[i+StepSize/2];
640 
641       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
642                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
643       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
644                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
645 
646       if (ThisBits == PartBits && ThisVT != PartVT) {
647         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
648         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
649       }
650     }
651   }
652 
653   if (DAG.getDataLayout().isBigEndian())
654     std::reverse(Parts, Parts + OrigNumParts);
655 }
656 
657 static SDValue widenVectorToPartType(SelectionDAG &DAG,
658                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
659   if (!PartVT.isVector())
660     return SDValue();
661 
662   EVT ValueVT = Val.getValueType();
663   unsigned PartNumElts = PartVT.getVectorNumElements();
664   unsigned ValueNumElts = ValueVT.getVectorNumElements();
665   if (PartNumElts > ValueNumElts &&
666       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
667     EVT ElementVT = PartVT.getVectorElementType();
668     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
669     // undef elements.
670     SmallVector<SDValue, 16> Ops;
671     DAG.ExtractVectorElements(Val, Ops);
672     SDValue EltUndef = DAG.getUNDEF(ElementVT);
673     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
674       Ops.push_back(EltUndef);
675 
676     // FIXME: Use CONCAT for 2x -> 4x.
677     return DAG.getBuildVector(PartVT, DL, Ops);
678   }
679 
680   return SDValue();
681 }
682 
683 /// getCopyToPartsVector - Create a series of nodes that contain the specified
684 /// value split into legal parts.
685 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
686                                  SDValue Val, SDValue *Parts, unsigned NumParts,
687                                  MVT PartVT, const Value *V,
688                                  Optional<CallingConv::ID> CallConv) {
689   EVT ValueVT = Val.getValueType();
690   assert(ValueVT.isVector() && "Not a vector");
691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
692   const bool IsABIRegCopy = CallConv.hasValue();
693 
694   if (NumParts == 1) {
695     EVT PartEVT = PartVT;
696     if (PartEVT == ValueVT) {
697       // Nothing to do.
698     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
699       // Bitconvert vector->vector case.
700       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
701     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
702       Val = Widened;
703     } else if (PartVT.isVector() &&
704                PartEVT.getVectorElementType().bitsGE(
705                  ValueVT.getVectorElementType()) &&
706                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
707 
708       // Promoted vector extract
709       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
710     } else {
711       if (ValueVT.getVectorNumElements() == 1) {
712         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
713                           DAG.getVectorIdxConstant(0, DL));
714       } else {
715         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
716                "lossy conversion of vector to scalar type");
717         EVT IntermediateType =
718             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
719         Val = DAG.getBitcast(IntermediateType, Val);
720         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
721       }
722     }
723 
724     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
725     Parts[0] = Val;
726     return;
727   }
728 
729   // Handle a multi-element vector.
730   EVT IntermediateVT;
731   MVT RegisterVT;
732   unsigned NumIntermediates;
733   unsigned NumRegs;
734   if (IsABIRegCopy) {
735     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
736         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
737         NumIntermediates, RegisterVT);
738   } else {
739     NumRegs =
740         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
741                                    NumIntermediates, RegisterVT);
742   }
743 
744   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
745   NumParts = NumRegs; // Silence a compiler warning.
746   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
747 
748   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
749     IntermediateVT.getVectorNumElements() : 1;
750 
751   // Convert the vector to the appropriate type if necessary.
752   auto DestEltCnt = ElementCount(NumIntermediates * IntermediateNumElts,
753                                  ValueVT.isScalableVector());
754   EVT BuiltVectorTy = EVT::getVectorVT(
755       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt);
756   if (ValueVT != BuiltVectorTy) {
757     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
758       Val = Widened;
759 
760     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
761   }
762 
763   // Split the vector into intermediate operands.
764   SmallVector<SDValue, 8> Ops(NumIntermediates);
765   for (unsigned i = 0; i != NumIntermediates; ++i) {
766     if (IntermediateVT.isVector()) {
767       Ops[i] =
768           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770     } else {
771       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772                            DAG.getVectorIdxConstant(i, DL));
773     }
774   }
775 
776   // Split the intermediate operands into legal parts.
777   if (NumParts == NumIntermediates) {
778     // If the register was not expanded, promote or copy the value,
779     // as appropriate.
780     for (unsigned i = 0; i != NumParts; ++i)
781       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782   } else if (NumParts > 0) {
783     // If the intermediate type was expanded, split each the value into
784     // legal parts.
785     assert(NumIntermediates != 0 && "division by zero");
786     assert(NumParts % NumIntermediates == 0 &&
787            "Must expand into a divisible number of parts!");
788     unsigned Factor = NumParts / NumIntermediates;
789     for (unsigned i = 0; i != NumIntermediates; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791                      CallConv);
792   }
793 }
794 
795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
796                            EVT valuevt, Optional<CallingConv::ID> CC)
797     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798       RegCount(1, regs.size()), CallConv(CC) {}
799 
800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
801                            const DataLayout &DL, unsigned Reg, Type *Ty,
802                            Optional<CallingConv::ID> CC) {
803   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805   CallConv = CC;
806 
807   for (EVT ValueVT : ValueVTs) {
808     unsigned NumRegs =
809         isABIMangled()
810             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811             : TLI.getNumRegisters(Context, ValueVT);
812     MVT RegisterVT =
813         isABIMangled()
814             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815             : TLI.getRegisterType(Context, ValueVT);
816     for (unsigned i = 0; i != NumRegs; ++i)
817       Regs.push_back(Reg + i);
818     RegVTs.push_back(RegisterVT);
819     RegCount.push_back(NumRegs);
820     Reg += NumRegs;
821   }
822 }
823 
824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
825                                       FunctionLoweringInfo &FuncInfo,
826                                       const SDLoc &dl, SDValue &Chain,
827                                       SDValue *Flag, const Value *V) const {
828   // A Value with type {} or [0 x %t] needs no registers.
829   if (ValueVTs.empty())
830     return SDValue();
831 
832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834   // Assemble the legal parts into the final values.
835   SmallVector<SDValue, 4> Values(ValueVTs.size());
836   SmallVector<SDValue, 8> Parts;
837   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838     // Copy the legal parts from the registers.
839     EVT ValueVT = ValueVTs[Value];
840     unsigned NumRegs = RegCount[Value];
841     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842                                           *DAG.getContext(),
843                                           CallConv.getValue(), RegVTs[Value])
844                                     : RegVTs[Value];
845 
846     Parts.resize(NumRegs);
847     for (unsigned i = 0; i != NumRegs; ++i) {
848       SDValue P;
849       if (!Flag) {
850         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851       } else {
852         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853         *Flag = P.getValue(2);
854       }
855 
856       Chain = P.getValue(1);
857       Parts[i] = P;
858 
859       // If the source register was virtual and if we know something about it,
860       // add an assert node.
861       if (!Register::isVirtualRegister(Regs[Part + i]) ||
862           !RegisterVT.isInteger())
863         continue;
864 
865       const FunctionLoweringInfo::LiveOutInfo *LOI =
866         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867       if (!LOI)
868         continue;
869 
870       unsigned RegSize = RegisterVT.getScalarSizeInBits();
871       unsigned NumSignBits = LOI->NumSignBits;
872       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874       if (NumZeroBits == RegSize) {
875         // The current value is a zero.
876         // Explicitly express that as it would be easier for
877         // optimizations to kick in.
878         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879         continue;
880       }
881 
882       // FIXME: We capture more information than the dag can represent.  For
883       // now, just use the tightest assertzext/assertsext possible.
884       bool isSExt;
885       EVT FromVT(MVT::Other);
886       if (NumZeroBits) {
887         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888         isSExt = false;
889       } else if (NumSignBits > 1) {
890         FromVT =
891             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892         isSExt = true;
893       } else {
894         continue;
895       }
896       // Add an assertion node.
897       assert(FromVT != MVT::Other);
898       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899                              RegisterVT, P, DAG.getValueType(FromVT));
900     }
901 
902     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903                                      RegisterVT, ValueVT, V, CallConv);
904     Part += NumRegs;
905     Parts.clear();
906   }
907 
908   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
912                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913                                  const Value *V,
914                                  ISD::NodeType PreferredExtendType) const {
915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916   ISD::NodeType ExtendKind = PreferredExtendType;
917 
918   // Get the list of the values's legal parts.
919   unsigned NumRegs = Regs.size();
920   SmallVector<SDValue, 8> Parts(NumRegs);
921   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922     unsigned NumParts = RegCount[Value];
923 
924     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925                                           *DAG.getContext(),
926                                           CallConv.getValue(), RegVTs[Value])
927                                     : RegVTs[Value];
928 
929     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
930       ExtendKind = ISD::ZERO_EXTEND;
931 
932     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
933                    NumParts, RegisterVT, V, CallConv, ExtendKind);
934     Part += NumParts;
935   }
936 
937   // Copy the parts into the registers.
938   SmallVector<SDValue, 8> Chains(NumRegs);
939   for (unsigned i = 0; i != NumRegs; ++i) {
940     SDValue Part;
941     if (!Flag) {
942       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
943     } else {
944       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
945       *Flag = Part.getValue(1);
946     }
947 
948     Chains[i] = Part.getValue(0);
949   }
950 
951   if (NumRegs == 1 || Flag)
952     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
953     // flagged to it. That is the CopyToReg nodes and the user are considered
954     // a single scheduling unit. If we create a TokenFactor and return it as
955     // chain, then the TokenFactor is both a predecessor (operand) of the
956     // user as well as a successor (the TF operands are flagged to the user).
957     // c1, f1 = CopyToReg
958     // c2, f2 = CopyToReg
959     // c3     = TokenFactor c1, c2
960     // ...
961     //        = op c3, ..., f2
962     Chain = Chains[NumRegs-1];
963   else
964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
965 }
966 
967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
968                                         unsigned MatchingIdx, const SDLoc &dl,
969                                         SelectionDAG &DAG,
970                                         std::vector<SDValue> &Ops) const {
971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
972 
973   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
974   if (HasMatching)
975     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
976   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
977     // Put the register class of the virtual registers in the flag word.  That
978     // way, later passes can recompute register class constraints for inline
979     // assembly as well as normal instructions.
980     // Don't do this for tied operands that can use the regclass information
981     // from the def.
982     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
983     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
984     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
985   }
986 
987   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
988   Ops.push_back(Res);
989 
990   if (Code == InlineAsm::Kind_Clobber) {
991     // Clobbers should always have a 1:1 mapping with registers, and may
992     // reference registers that have illegal (e.g. vector) types. Hence, we
993     // shouldn't try to apply any sort of splitting logic to them.
994     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
995            "No 1:1 mapping from clobbers to regs?");
996     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
997     (void)SP;
998     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
999       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1000       assert(
1001           (Regs[I] != SP ||
1002            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1003           "If we clobbered the stack pointer, MFI should know about it.");
1004     }
1005     return;
1006   }
1007 
1008   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1009     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
1010     MVT RegisterVT = RegVTs[Value];
1011     for (unsigned i = 0; i != NumRegs; ++i) {
1012       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1013       unsigned TheReg = Regs[Reg++];
1014       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1015     }
1016   }
1017 }
1018 
1019 SmallVector<std::pair<unsigned, unsigned>, 4>
1020 RegsForValue::getRegsAndSizes() const {
1021   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1022   unsigned I = 0;
1023   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1024     unsigned RegCount = std::get<0>(CountAndVT);
1025     MVT RegisterVT = std::get<1>(CountAndVT);
1026     unsigned RegisterSize = RegisterVT.getSizeInBits();
1027     for (unsigned E = I + RegCount; I != E; ++I)
1028       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1029   }
1030   return OutVec;
1031 }
1032 
1033 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1034                                const TargetLibraryInfo *li) {
1035   AA = aa;
1036   GFI = gfi;
1037   LibInfo = li;
1038   DL = &DAG.getDataLayout();
1039   Context = DAG.getContext();
1040   LPadToCallSiteMap.clear();
1041   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1042 }
1043 
1044 void SelectionDAGBuilder::clear() {
1045   NodeMap.clear();
1046   UnusedArgNodeMap.clear();
1047   PendingLoads.clear();
1048   PendingExports.clear();
1049   PendingConstrainedFP.clear();
1050   PendingConstrainedFPStrict.clear();
1051   CurInst = nullptr;
1052   HasTailCall = false;
1053   SDNodeOrder = LowestSDNodeOrder;
1054   StatepointLowering.clear();
1055 }
1056 
1057 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1058   DanglingDebugInfoMap.clear();
1059 }
1060 
1061 // Update DAG root to include dependencies on Pending chains.
1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1063   SDValue Root = DAG.getRoot();
1064 
1065   if (Pending.empty())
1066     return Root;
1067 
1068   // Add current root to PendingChains, unless we already indirectly
1069   // depend on it.
1070   if (Root.getOpcode() != ISD::EntryToken) {
1071     unsigned i = 0, e = Pending.size();
1072     for (; i != e; ++i) {
1073       assert(Pending[i].getNode()->getNumOperands() > 1);
1074       if (Pending[i].getNode()->getOperand(0) == Root)
1075         break;  // Don't add the root if we already indirectly depend on it.
1076     }
1077 
1078     if (i == e)
1079       Pending.push_back(Root);
1080   }
1081 
1082   if (Pending.size() == 1)
1083     Root = Pending[0];
1084   else
1085     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1086 
1087   DAG.setRoot(Root);
1088   Pending.clear();
1089   return Root;
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getMemoryRoot() {
1093   return updateRoot(PendingLoads);
1094 }
1095 
1096 SDValue SelectionDAGBuilder::getRoot() {
1097   // Chain up all pending constrained intrinsics together with all
1098   // pending loads, by simply appending them to PendingLoads and
1099   // then calling getMemoryRoot().
1100   PendingLoads.reserve(PendingLoads.size() +
1101                        PendingConstrainedFP.size() +
1102                        PendingConstrainedFPStrict.size());
1103   PendingLoads.append(PendingConstrainedFP.begin(),
1104                       PendingConstrainedFP.end());
1105   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1106                       PendingConstrainedFPStrict.end());
1107   PendingConstrainedFP.clear();
1108   PendingConstrainedFPStrict.clear();
1109   return getMemoryRoot();
1110 }
1111 
1112 SDValue SelectionDAGBuilder::getControlRoot() {
1113   // We need to emit pending fpexcept.strict constrained intrinsics,
1114   // so append them to the PendingExports list.
1115   PendingExports.append(PendingConstrainedFPStrict.begin(),
1116                         PendingConstrainedFPStrict.end());
1117   PendingConstrainedFPStrict.clear();
1118   return updateRoot(PendingExports);
1119 }
1120 
1121 void SelectionDAGBuilder::visit(const Instruction &I) {
1122   // Set up outgoing PHI node register values before emitting the terminator.
1123   if (I.isTerminator()) {
1124     HandlePHINodesInSuccessorBlocks(I.getParent());
1125   }
1126 
1127   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1128   if (!isa<DbgInfoIntrinsic>(I))
1129     ++SDNodeOrder;
1130 
1131   CurInst = &I;
1132 
1133   visit(I.getOpcode(), I);
1134 
1135   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1136     // ConstrainedFPIntrinsics handle their own FMF.
1137     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1138       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1139       // maps to this instruction.
1140       // TODO: We could handle all flags (nsw, etc) here.
1141       // TODO: If an IR instruction maps to >1 node, only the final node will have
1142       //       flags set.
1143       if (SDNode *Node = getNodeForIRValue(&I)) {
1144         SDNodeFlags IncomingFlags;
1145         IncomingFlags.copyFMF(*FPMO);
1146         if (!Node->getFlags().isDefined())
1147           Node->setFlags(IncomingFlags);
1148         else
1149           Node->intersectFlagsWith(IncomingFlags);
1150       }
1151     }
1152   }
1153 
1154   if (!I.isTerminator() && !HasTailCall &&
1155       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1156     CopyToExportRegsIfNeeded(&I);
1157 
1158   CurInst = nullptr;
1159 }
1160 
1161 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1162   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1163 }
1164 
1165 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1166   // Note: this doesn't use InstVisitor, because it has to work with
1167   // ConstantExpr's in addition to instructions.
1168   switch (Opcode) {
1169   default: llvm_unreachable("Unknown instruction type encountered!");
1170     // Build the switch statement using the Instruction.def file.
1171 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1172     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1173 #include "llvm/IR/Instruction.def"
1174   }
1175 }
1176 
1177 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1178                                                 const DIExpression *Expr) {
1179   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1180     const DbgValueInst *DI = DDI.getDI();
1181     DIVariable *DanglingVariable = DI->getVariable();
1182     DIExpression *DanglingExpr = DI->getExpression();
1183     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1184       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1185       return true;
1186     }
1187     return false;
1188   };
1189 
1190   for (auto &DDIMI : DanglingDebugInfoMap) {
1191     DanglingDebugInfoVector &DDIV = DDIMI.second;
1192 
1193     // If debug info is to be dropped, run it through final checks to see
1194     // whether it can be salvaged.
1195     for (auto &DDI : DDIV)
1196       if (isMatchingDbgValue(DDI))
1197         salvageUnresolvedDbgValue(DDI);
1198 
1199     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1200   }
1201 }
1202 
1203 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1204 // generate the debug data structures now that we've seen its definition.
1205 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1206                                                    SDValue Val) {
1207   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1208   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1209     return;
1210 
1211   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1212   for (auto &DDI : DDIV) {
1213     const DbgValueInst *DI = DDI.getDI();
1214     assert(DI && "Ill-formed DanglingDebugInfo");
1215     DebugLoc dl = DDI.getdl();
1216     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1217     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1218     DILocalVariable *Variable = DI->getVariable();
1219     DIExpression *Expr = DI->getExpression();
1220     assert(Variable->isValidLocationForIntrinsic(dl) &&
1221            "Expected inlined-at fields to agree");
1222     SDDbgValue *SDV;
1223     if (Val.getNode()) {
1224       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1225       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1226       // we couldn't resolve it directly when examining the DbgValue intrinsic
1227       // in the first place we should not be more successful here). Unless we
1228       // have some test case that prove this to be correct we should avoid
1229       // calling EmitFuncArgumentDbgValue here.
1230       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1231         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1232                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1233         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1234         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1235         // inserted after the definition of Val when emitting the instructions
1236         // after ISel. An alternative could be to teach
1237         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1238         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1239                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1240                    << ValSDNodeOrder << "\n");
1241         SDV = getDbgValue(Val, Variable, Expr, dl,
1242                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1243         DAG.AddDbgValue(SDV, Val.getNode(), false);
1244       } else
1245         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1246                           << "in EmitFuncArgumentDbgValue\n");
1247     } else {
1248       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1249       auto Undef =
1250           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1251       auto SDV =
1252           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1253       DAG.AddDbgValue(SDV, nullptr, false);
1254     }
1255   }
1256   DDIV.clear();
1257 }
1258 
1259 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1260   Value *V = DDI.getDI()->getValue();
1261   DILocalVariable *Var = DDI.getDI()->getVariable();
1262   DIExpression *Expr = DDI.getDI()->getExpression();
1263   DebugLoc DL = DDI.getdl();
1264   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1265   unsigned SDOrder = DDI.getSDNodeOrder();
1266 
1267   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1268   // that DW_OP_stack_value is desired.
1269   assert(isa<DbgValueInst>(DDI.getDI()));
1270   bool StackValue = true;
1271 
1272   // Can this Value can be encoded without any further work?
1273   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1274     return;
1275 
1276   // Attempt to salvage back through as many instructions as possible. Bail if
1277   // a non-instruction is seen, such as a constant expression or global
1278   // variable. FIXME: Further work could recover those too.
1279   while (isa<Instruction>(V)) {
1280     Instruction &VAsInst = *cast<Instruction>(V);
1281     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1282 
1283     // If we cannot salvage any further, and haven't yet found a suitable debug
1284     // expression, bail out.
1285     if (!NewExpr)
1286       break;
1287 
1288     // New value and expr now represent this debuginfo.
1289     V = VAsInst.getOperand(0);
1290     Expr = NewExpr;
1291 
1292     // Some kind of simplification occurred: check whether the operand of the
1293     // salvaged debug expression can be encoded in this DAG.
1294     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1295       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1296                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1297       return;
1298     }
1299   }
1300 
1301   // This was the final opportunity to salvage this debug information, and it
1302   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1303   // any earlier variable location.
1304   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1305   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1306   DAG.AddDbgValue(SDV, nullptr, false);
1307 
1308   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1309                     << "\n");
1310   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1311                     << "\n");
1312 }
1313 
1314 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1315                                            DIExpression *Expr, DebugLoc dl,
1316                                            DebugLoc InstDL, unsigned Order) {
1317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1318   SDDbgValue *SDV;
1319   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1320       isa<ConstantPointerNull>(V)) {
1321     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1322     DAG.AddDbgValue(SDV, nullptr, false);
1323     return true;
1324   }
1325 
1326   // If the Value is a frame index, we can create a FrameIndex debug value
1327   // without relying on the DAG at all.
1328   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1329     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1330     if (SI != FuncInfo.StaticAllocaMap.end()) {
1331       auto SDV =
1332           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1333                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1334       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1335       // is still available even if the SDNode gets optimized out.
1336       DAG.AddDbgValue(SDV, nullptr, false);
1337       return true;
1338     }
1339   }
1340 
1341   // Do not use getValue() in here; we don't want to generate code at
1342   // this point if it hasn't been done yet.
1343   SDValue N = NodeMap[V];
1344   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1345     N = UnusedArgNodeMap[V];
1346   if (N.getNode()) {
1347     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1348       return true;
1349     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1350     DAG.AddDbgValue(SDV, N.getNode(), false);
1351     return true;
1352   }
1353 
1354   // Special rules apply for the first dbg.values of parameter variables in a
1355   // function. Identify them by the fact they reference Argument Values, that
1356   // they're parameters, and they are parameters of the current function. We
1357   // need to let them dangle until they get an SDNode.
1358   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1359                        !InstDL.getInlinedAt();
1360   if (!IsParamOfFunc) {
1361     // The value is not used in this block yet (or it would have an SDNode).
1362     // We still want the value to appear for the user if possible -- if it has
1363     // an associated VReg, we can refer to that instead.
1364     auto VMI = FuncInfo.ValueMap.find(V);
1365     if (VMI != FuncInfo.ValueMap.end()) {
1366       unsigned Reg = VMI->second;
1367       // If this is a PHI node, it may be split up into several MI PHI nodes
1368       // (in FunctionLoweringInfo::set).
1369       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1370                        V->getType(), None);
1371       if (RFV.occupiesMultipleRegs()) {
1372         unsigned Offset = 0;
1373         unsigned BitsToDescribe = 0;
1374         if (auto VarSize = Var->getSizeInBits())
1375           BitsToDescribe = *VarSize;
1376         if (auto Fragment = Expr->getFragmentInfo())
1377           BitsToDescribe = Fragment->SizeInBits;
1378         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1379           unsigned RegisterSize = RegAndSize.second;
1380           // Bail out if all bits are described already.
1381           if (Offset >= BitsToDescribe)
1382             break;
1383           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1384               ? BitsToDescribe - Offset
1385               : RegisterSize;
1386           auto FragmentExpr = DIExpression::createFragmentExpression(
1387               Expr, Offset, FragmentSize);
1388           if (!FragmentExpr)
1389               continue;
1390           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1391                                     false, dl, SDNodeOrder);
1392           DAG.AddDbgValue(SDV, nullptr, false);
1393           Offset += RegisterSize;
1394         }
1395       } else {
1396         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1397         DAG.AddDbgValue(SDV, nullptr, false);
1398       }
1399       return true;
1400     }
1401   }
1402 
1403   return false;
1404 }
1405 
1406 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1407   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1408   for (auto &Pair : DanglingDebugInfoMap)
1409     for (auto &DDI : Pair.second)
1410       salvageUnresolvedDbgValue(DDI);
1411   clearDanglingDebugInfo();
1412 }
1413 
1414 /// getCopyFromRegs - If there was virtual register allocated for the value V
1415 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1416 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1417   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1418   SDValue Result;
1419 
1420   if (It != FuncInfo.ValueMap.end()) {
1421     Register InReg = It->second;
1422 
1423     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1424                      DAG.getDataLayout(), InReg, Ty,
1425                      None); // This is not an ABI copy.
1426     SDValue Chain = DAG.getEntryNode();
1427     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1428                                  V);
1429     resolveDanglingDebugInfo(V, Result);
1430   }
1431 
1432   return Result;
1433 }
1434 
1435 /// getValue - Return an SDValue for the given Value.
1436 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1437   // If we already have an SDValue for this value, use it. It's important
1438   // to do this first, so that we don't create a CopyFromReg if we already
1439   // have a regular SDValue.
1440   SDValue &N = NodeMap[V];
1441   if (N.getNode()) return N;
1442 
1443   // If there's a virtual register allocated and initialized for this
1444   // value, use it.
1445   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1446     return copyFromReg;
1447 
1448   // Otherwise create a new SDValue and remember it.
1449   SDValue Val = getValueImpl(V);
1450   NodeMap[V] = Val;
1451   resolveDanglingDebugInfo(V, Val);
1452   return Val;
1453 }
1454 
1455 /// getNonRegisterValue - Return an SDValue for the given Value, but
1456 /// don't look in FuncInfo.ValueMap for a virtual register.
1457 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1458   // If we already have an SDValue for this value, use it.
1459   SDValue &N = NodeMap[V];
1460   if (N.getNode()) {
1461     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1462       // Remove the debug location from the node as the node is about to be used
1463       // in a location which may differ from the original debug location.  This
1464       // is relevant to Constant and ConstantFP nodes because they can appear
1465       // as constant expressions inside PHI nodes.
1466       N->setDebugLoc(DebugLoc());
1467     }
1468     return N;
1469   }
1470 
1471   // Otherwise create a new SDValue and remember it.
1472   SDValue Val = getValueImpl(V);
1473   NodeMap[V] = Val;
1474   resolveDanglingDebugInfo(V, Val);
1475   return Val;
1476 }
1477 
1478 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1479 /// Create an SDValue for the given value.
1480 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1482 
1483   if (const Constant *C = dyn_cast<Constant>(V)) {
1484     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1485 
1486     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1487       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1488 
1489     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1490       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1491 
1492     if (isa<ConstantPointerNull>(C)) {
1493       unsigned AS = V->getType()->getPointerAddressSpace();
1494       return DAG.getConstant(0, getCurSDLoc(),
1495                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1496     }
1497 
1498     if (match(C, m_VScale(DAG.getDataLayout())))
1499       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1500 
1501     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1502       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1503 
1504     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1505       return DAG.getUNDEF(VT);
1506 
1507     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1508       visit(CE->getOpcode(), *CE);
1509       SDValue N1 = NodeMap[V];
1510       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1511       return N1;
1512     }
1513 
1514     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1515       SmallVector<SDValue, 4> Constants;
1516       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1517            OI != OE; ++OI) {
1518         SDNode *Val = getValue(*OI).getNode();
1519         // If the operand is an empty aggregate, there are no values.
1520         if (!Val) continue;
1521         // Add each leaf value from the operand to the Constants list
1522         // to form a flattened list of all the values.
1523         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1524           Constants.push_back(SDValue(Val, i));
1525       }
1526 
1527       return DAG.getMergeValues(Constants, getCurSDLoc());
1528     }
1529 
1530     if (const ConstantDataSequential *CDS =
1531           dyn_cast<ConstantDataSequential>(C)) {
1532       SmallVector<SDValue, 4> Ops;
1533       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1534         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1535         // Add each leaf value from the operand to the Constants list
1536         // to form a flattened list of all the values.
1537         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1538           Ops.push_back(SDValue(Val, i));
1539       }
1540 
1541       if (isa<ArrayType>(CDS->getType()))
1542         return DAG.getMergeValues(Ops, getCurSDLoc());
1543       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1544     }
1545 
1546     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1547       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1548              "Unknown struct or array constant!");
1549 
1550       SmallVector<EVT, 4> ValueVTs;
1551       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1552       unsigned NumElts = ValueVTs.size();
1553       if (NumElts == 0)
1554         return SDValue(); // empty struct
1555       SmallVector<SDValue, 4> Constants(NumElts);
1556       for (unsigned i = 0; i != NumElts; ++i) {
1557         EVT EltVT = ValueVTs[i];
1558         if (isa<UndefValue>(C))
1559           Constants[i] = DAG.getUNDEF(EltVT);
1560         else if (EltVT.isFloatingPoint())
1561           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1562         else
1563           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1564       }
1565 
1566       return DAG.getMergeValues(Constants, getCurSDLoc());
1567     }
1568 
1569     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1570       return DAG.getBlockAddress(BA, VT);
1571 
1572     VectorType *VecTy = cast<VectorType>(V->getType());
1573 
1574     // Now that we know the number and type of the elements, get that number of
1575     // elements into the Ops array based on what kind of constant it is.
1576     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1577       SmallVector<SDValue, 16> Ops;
1578       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1579       for (unsigned i = 0; i != NumElements; ++i)
1580         Ops.push_back(getValue(CV->getOperand(i)));
1581 
1582       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1583     } else if (isa<ConstantAggregateZero>(C)) {
1584       EVT EltVT =
1585           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1586 
1587       SDValue Op;
1588       if (EltVT.isFloatingPoint())
1589         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1590       else
1591         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1592 
1593       if (isa<ScalableVectorType>(VecTy))
1594         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1595       else {
1596         SmallVector<SDValue, 16> Ops;
1597         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1598         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1599       }
1600     }
1601     llvm_unreachable("Unknown vector constant");
1602   }
1603 
1604   // If this is a static alloca, generate it as the frameindex instead of
1605   // computation.
1606   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1607     DenseMap<const AllocaInst*, int>::iterator SI =
1608       FuncInfo.StaticAllocaMap.find(AI);
1609     if (SI != FuncInfo.StaticAllocaMap.end())
1610       return DAG.getFrameIndex(SI->second,
1611                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1612   }
1613 
1614   // If this is an instruction which fast-isel has deferred, select it now.
1615   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1616     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1617 
1618     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1619                      Inst->getType(), getABIRegCopyCC(V));
1620     SDValue Chain = DAG.getEntryNode();
1621     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1622   }
1623 
1624   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1625     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1626   }
1627   llvm_unreachable("Can't get register for value!");
1628 }
1629 
1630 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1631   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1632   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1633   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1634   bool IsSEH = isAsynchronousEHPersonality(Pers);
1635   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1636   if (!IsSEH)
1637     CatchPadMBB->setIsEHScopeEntry();
1638   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1639   if (IsMSVCCXX || IsCoreCLR)
1640     CatchPadMBB->setIsEHFuncletEntry();
1641 }
1642 
1643 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1644   // Update machine-CFG edge.
1645   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1646   FuncInfo.MBB->addSuccessor(TargetMBB);
1647 
1648   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1649   bool IsSEH = isAsynchronousEHPersonality(Pers);
1650   if (IsSEH) {
1651     // If this is not a fall-through branch or optimizations are switched off,
1652     // emit the branch.
1653     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1654         TM.getOptLevel() == CodeGenOpt::None)
1655       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1656                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1657     return;
1658   }
1659 
1660   // Figure out the funclet membership for the catchret's successor.
1661   // This will be used by the FuncletLayout pass to determine how to order the
1662   // BB's.
1663   // A 'catchret' returns to the outer scope's color.
1664   Value *ParentPad = I.getCatchSwitchParentPad();
1665   const BasicBlock *SuccessorColor;
1666   if (isa<ConstantTokenNone>(ParentPad))
1667     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1668   else
1669     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1670   assert(SuccessorColor && "No parent funclet for catchret!");
1671   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1672   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1673 
1674   // Create the terminator node.
1675   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1676                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1677                             DAG.getBasicBlock(SuccessorColorMBB));
1678   DAG.setRoot(Ret);
1679 }
1680 
1681 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1682   // Don't emit any special code for the cleanuppad instruction. It just marks
1683   // the start of an EH scope/funclet.
1684   FuncInfo.MBB->setIsEHScopeEntry();
1685   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1686   if (Pers != EHPersonality::Wasm_CXX) {
1687     FuncInfo.MBB->setIsEHFuncletEntry();
1688     FuncInfo.MBB->setIsCleanupFuncletEntry();
1689   }
1690 }
1691 
1692 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1693 // the control flow always stops at the single catch pad, as it does for a
1694 // cleanup pad. In case the exception caught is not of the types the catch pad
1695 // catches, it will be rethrown by a rethrow.
1696 static void findWasmUnwindDestinations(
1697     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1698     BranchProbability Prob,
1699     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1700         &UnwindDests) {
1701   while (EHPadBB) {
1702     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1703     if (isa<CleanupPadInst>(Pad)) {
1704       // Stop on cleanup pads.
1705       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1706       UnwindDests.back().first->setIsEHScopeEntry();
1707       break;
1708     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1709       // Add the catchpad handlers to the possible destinations. We don't
1710       // continue to the unwind destination of the catchswitch for wasm.
1711       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1712         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1713         UnwindDests.back().first->setIsEHScopeEntry();
1714       }
1715       break;
1716     } else {
1717       continue;
1718     }
1719   }
1720 }
1721 
1722 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1723 /// many places it could ultimately go. In the IR, we have a single unwind
1724 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1725 /// This function skips over imaginary basic blocks that hold catchswitch
1726 /// instructions, and finds all the "real" machine
1727 /// basic block destinations. As those destinations may not be successors of
1728 /// EHPadBB, here we also calculate the edge probability to those destinations.
1729 /// The passed-in Prob is the edge probability to EHPadBB.
1730 static void findUnwindDestinations(
1731     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1732     BranchProbability Prob,
1733     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1734         &UnwindDests) {
1735   EHPersonality Personality =
1736     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1737   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1738   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1739   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1740   bool IsSEH = isAsynchronousEHPersonality(Personality);
1741 
1742   if (IsWasmCXX) {
1743     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1744     assert(UnwindDests.size() <= 1 &&
1745            "There should be at most one unwind destination for wasm");
1746     return;
1747   }
1748 
1749   while (EHPadBB) {
1750     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1751     BasicBlock *NewEHPadBB = nullptr;
1752     if (isa<LandingPadInst>(Pad)) {
1753       // Stop on landingpads. They are not funclets.
1754       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1755       break;
1756     } else if (isa<CleanupPadInst>(Pad)) {
1757       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1758       // personalities.
1759       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1760       UnwindDests.back().first->setIsEHScopeEntry();
1761       UnwindDests.back().first->setIsEHFuncletEntry();
1762       break;
1763     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1764       // Add the catchpad handlers to the possible destinations.
1765       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1766         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1767         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1768         if (IsMSVCCXX || IsCoreCLR)
1769           UnwindDests.back().first->setIsEHFuncletEntry();
1770         if (!IsSEH)
1771           UnwindDests.back().first->setIsEHScopeEntry();
1772       }
1773       NewEHPadBB = CatchSwitch->getUnwindDest();
1774     } else {
1775       continue;
1776     }
1777 
1778     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1779     if (BPI && NewEHPadBB)
1780       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1781     EHPadBB = NewEHPadBB;
1782   }
1783 }
1784 
1785 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1786   // Update successor info.
1787   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1788   auto UnwindDest = I.getUnwindDest();
1789   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1790   BranchProbability UnwindDestProb =
1791       (BPI && UnwindDest)
1792           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1793           : BranchProbability::getZero();
1794   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1795   for (auto &UnwindDest : UnwindDests) {
1796     UnwindDest.first->setIsEHPad();
1797     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1798   }
1799   FuncInfo.MBB->normalizeSuccProbs();
1800 
1801   // Create the terminator node.
1802   SDValue Ret =
1803       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1804   DAG.setRoot(Ret);
1805 }
1806 
1807 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1808   report_fatal_error("visitCatchSwitch not yet implemented!");
1809 }
1810 
1811 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1813   auto &DL = DAG.getDataLayout();
1814   SDValue Chain = getControlRoot();
1815   SmallVector<ISD::OutputArg, 8> Outs;
1816   SmallVector<SDValue, 8> OutVals;
1817 
1818   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1819   // lower
1820   //
1821   //   %val = call <ty> @llvm.experimental.deoptimize()
1822   //   ret <ty> %val
1823   //
1824   // differently.
1825   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1826     LowerDeoptimizingReturn();
1827     return;
1828   }
1829 
1830   if (!FuncInfo.CanLowerReturn) {
1831     unsigned DemoteReg = FuncInfo.DemoteRegister;
1832     const Function *F = I.getParent()->getParent();
1833 
1834     // Emit a store of the return value through the virtual register.
1835     // Leave Outs empty so that LowerReturn won't try to load return
1836     // registers the usual way.
1837     SmallVector<EVT, 1> PtrValueVTs;
1838     ComputeValueVTs(TLI, DL,
1839                     F->getReturnType()->getPointerTo(
1840                         DAG.getDataLayout().getAllocaAddrSpace()),
1841                     PtrValueVTs);
1842 
1843     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1844                                         DemoteReg, PtrValueVTs[0]);
1845     SDValue RetOp = getValue(I.getOperand(0));
1846 
1847     SmallVector<EVT, 4> ValueVTs, MemVTs;
1848     SmallVector<uint64_t, 4> Offsets;
1849     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1850                     &Offsets);
1851     unsigned NumValues = ValueVTs.size();
1852 
1853     SmallVector<SDValue, 4> Chains(NumValues);
1854     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1855     for (unsigned i = 0; i != NumValues; ++i) {
1856       // An aggregate return value cannot wrap around the address space, so
1857       // offsets to its parts don't wrap either.
1858       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1859 
1860       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1861       if (MemVTs[i] != ValueVTs[i])
1862         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1863       Chains[i] = DAG.getStore(
1864           Chain, getCurSDLoc(), Val,
1865           // FIXME: better loc info would be nice.
1866           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1867           commonAlignment(BaseAlign, Offsets[i]));
1868     }
1869 
1870     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1871                         MVT::Other, Chains);
1872   } else if (I.getNumOperands() != 0) {
1873     SmallVector<EVT, 4> ValueVTs;
1874     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1875     unsigned NumValues = ValueVTs.size();
1876     if (NumValues) {
1877       SDValue RetOp = getValue(I.getOperand(0));
1878 
1879       const Function *F = I.getParent()->getParent();
1880 
1881       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1882           I.getOperand(0)->getType(), F->getCallingConv(),
1883           /*IsVarArg*/ false);
1884 
1885       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1886       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1887                                           Attribute::SExt))
1888         ExtendKind = ISD::SIGN_EXTEND;
1889       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1890                                                Attribute::ZExt))
1891         ExtendKind = ISD::ZERO_EXTEND;
1892 
1893       LLVMContext &Context = F->getContext();
1894       bool RetInReg = F->getAttributes().hasAttribute(
1895           AttributeList::ReturnIndex, Attribute::InReg);
1896 
1897       for (unsigned j = 0; j != NumValues; ++j) {
1898         EVT VT = ValueVTs[j];
1899 
1900         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1901           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1902 
1903         CallingConv::ID CC = F->getCallingConv();
1904 
1905         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1906         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1907         SmallVector<SDValue, 4> Parts(NumParts);
1908         getCopyToParts(DAG, getCurSDLoc(),
1909                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1910                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1911 
1912         // 'inreg' on function refers to return value
1913         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1914         if (RetInReg)
1915           Flags.setInReg();
1916 
1917         if (I.getOperand(0)->getType()->isPointerTy()) {
1918           Flags.setPointer();
1919           Flags.setPointerAddrSpace(
1920               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1921         }
1922 
1923         if (NeedsRegBlock) {
1924           Flags.setInConsecutiveRegs();
1925           if (j == NumValues - 1)
1926             Flags.setInConsecutiveRegsLast();
1927         }
1928 
1929         // Propagate extension type if any
1930         if (ExtendKind == ISD::SIGN_EXTEND)
1931           Flags.setSExt();
1932         else if (ExtendKind == ISD::ZERO_EXTEND)
1933           Flags.setZExt();
1934 
1935         for (unsigned i = 0; i < NumParts; ++i) {
1936           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1937                                         VT, /*isfixed=*/true, 0, 0));
1938           OutVals.push_back(Parts[i]);
1939         }
1940       }
1941     }
1942   }
1943 
1944   // Push in swifterror virtual register as the last element of Outs. This makes
1945   // sure swifterror virtual register will be returned in the swifterror
1946   // physical register.
1947   const Function *F = I.getParent()->getParent();
1948   if (TLI.supportSwiftError() &&
1949       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1950     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1951     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1952     Flags.setSwiftError();
1953     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1954                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1955                                   true /*isfixed*/, 1 /*origidx*/,
1956                                   0 /*partOffs*/));
1957     // Create SDNode for the swifterror virtual register.
1958     OutVals.push_back(
1959         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1960                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1961                         EVT(TLI.getPointerTy(DL))));
1962   }
1963 
1964   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1965   CallingConv::ID CallConv =
1966     DAG.getMachineFunction().getFunction().getCallingConv();
1967   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1968       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1969 
1970   // Verify that the target's LowerReturn behaved as expected.
1971   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1972          "LowerReturn didn't return a valid chain!");
1973 
1974   // Update the DAG with the new chain value resulting from return lowering.
1975   DAG.setRoot(Chain);
1976 }
1977 
1978 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1979 /// created for it, emit nodes to copy the value into the virtual
1980 /// registers.
1981 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1982   // Skip empty types
1983   if (V->getType()->isEmptyTy())
1984     return;
1985 
1986   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1987   if (VMI != FuncInfo.ValueMap.end()) {
1988     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1989     CopyValueToVirtualRegister(V, VMI->second);
1990   }
1991 }
1992 
1993 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1994 /// the current basic block, add it to ValueMap now so that we'll get a
1995 /// CopyTo/FromReg.
1996 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1997   // No need to export constants.
1998   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1999 
2000   // Already exported?
2001   if (FuncInfo.isExportedInst(V)) return;
2002 
2003   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2004   CopyValueToVirtualRegister(V, Reg);
2005 }
2006 
2007 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2008                                                      const BasicBlock *FromBB) {
2009   // The operands of the setcc have to be in this block.  We don't know
2010   // how to export them from some other block.
2011   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2012     // Can export from current BB.
2013     if (VI->getParent() == FromBB)
2014       return true;
2015 
2016     // Is already exported, noop.
2017     return FuncInfo.isExportedInst(V);
2018   }
2019 
2020   // If this is an argument, we can export it if the BB is the entry block or
2021   // if it is already exported.
2022   if (isa<Argument>(V)) {
2023     if (FromBB == &FromBB->getParent()->getEntryBlock())
2024       return true;
2025 
2026     // Otherwise, can only export this if it is already exported.
2027     return FuncInfo.isExportedInst(V);
2028   }
2029 
2030   // Otherwise, constants can always be exported.
2031   return true;
2032 }
2033 
2034 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2035 BranchProbability
2036 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2037                                         const MachineBasicBlock *Dst) const {
2038   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2039   const BasicBlock *SrcBB = Src->getBasicBlock();
2040   const BasicBlock *DstBB = Dst->getBasicBlock();
2041   if (!BPI) {
2042     // If BPI is not available, set the default probability as 1 / N, where N is
2043     // the number of successors.
2044     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2045     return BranchProbability(1, SuccSize);
2046   }
2047   return BPI->getEdgeProbability(SrcBB, DstBB);
2048 }
2049 
2050 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2051                                                MachineBasicBlock *Dst,
2052                                                BranchProbability Prob) {
2053   if (!FuncInfo.BPI)
2054     Src->addSuccessorWithoutProb(Dst);
2055   else {
2056     if (Prob.isUnknown())
2057       Prob = getEdgeProbability(Src, Dst);
2058     Src->addSuccessor(Dst, Prob);
2059   }
2060 }
2061 
2062 static bool InBlock(const Value *V, const BasicBlock *BB) {
2063   if (const Instruction *I = dyn_cast<Instruction>(V))
2064     return I->getParent() == BB;
2065   return true;
2066 }
2067 
2068 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2069 /// This function emits a branch and is used at the leaves of an OR or an
2070 /// AND operator tree.
2071 void
2072 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2073                                                   MachineBasicBlock *TBB,
2074                                                   MachineBasicBlock *FBB,
2075                                                   MachineBasicBlock *CurBB,
2076                                                   MachineBasicBlock *SwitchBB,
2077                                                   BranchProbability TProb,
2078                                                   BranchProbability FProb,
2079                                                   bool InvertCond) {
2080   const BasicBlock *BB = CurBB->getBasicBlock();
2081 
2082   // If the leaf of the tree is a comparison, merge the condition into
2083   // the caseblock.
2084   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2085     // The operands of the cmp have to be in this block.  We don't know
2086     // how to export them from some other block.  If this is the first block
2087     // of the sequence, no exporting is needed.
2088     if (CurBB == SwitchBB ||
2089         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2090          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2091       ISD::CondCode Condition;
2092       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2093         ICmpInst::Predicate Pred =
2094             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2095         Condition = getICmpCondCode(Pred);
2096       } else {
2097         const FCmpInst *FC = cast<FCmpInst>(Cond);
2098         FCmpInst::Predicate Pred =
2099             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2100         Condition = getFCmpCondCode(Pred);
2101         if (TM.Options.NoNaNsFPMath)
2102           Condition = getFCmpCodeWithoutNaN(Condition);
2103       }
2104 
2105       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2106                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2107       SL->SwitchCases.push_back(CB);
2108       return;
2109     }
2110   }
2111 
2112   // Create a CaseBlock record representing this branch.
2113   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2114   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2115                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2116   SL->SwitchCases.push_back(CB);
2117 }
2118 
2119 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2120                                                MachineBasicBlock *TBB,
2121                                                MachineBasicBlock *FBB,
2122                                                MachineBasicBlock *CurBB,
2123                                                MachineBasicBlock *SwitchBB,
2124                                                Instruction::BinaryOps Opc,
2125                                                BranchProbability TProb,
2126                                                BranchProbability FProb,
2127                                                bool InvertCond) {
2128   // Skip over not part of the tree and remember to invert op and operands at
2129   // next level.
2130   Value *NotCond;
2131   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2132       InBlock(NotCond, CurBB->getBasicBlock())) {
2133     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2134                          !InvertCond);
2135     return;
2136   }
2137 
2138   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2139   // Compute the effective opcode for Cond, taking into account whether it needs
2140   // to be inverted, e.g.
2141   //   and (not (or A, B)), C
2142   // gets lowered as
2143   //   and (and (not A, not B), C)
2144   unsigned BOpc = 0;
2145   if (BOp) {
2146     BOpc = BOp->getOpcode();
2147     if (InvertCond) {
2148       if (BOpc == Instruction::And)
2149         BOpc = Instruction::Or;
2150       else if (BOpc == Instruction::Or)
2151         BOpc = Instruction::And;
2152     }
2153   }
2154 
2155   // If this node is not part of the or/and tree, emit it as a branch.
2156   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2157       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2158       BOp->getParent() != CurBB->getBasicBlock() ||
2159       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2160       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2161     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2162                                  TProb, FProb, InvertCond);
2163     return;
2164   }
2165 
2166   //  Create TmpBB after CurBB.
2167   MachineFunction::iterator BBI(CurBB);
2168   MachineFunction &MF = DAG.getMachineFunction();
2169   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2170   CurBB->getParent()->insert(++BBI, TmpBB);
2171 
2172   if (Opc == Instruction::Or) {
2173     // Codegen X | Y as:
2174     // BB1:
2175     //   jmp_if_X TBB
2176     //   jmp TmpBB
2177     // TmpBB:
2178     //   jmp_if_Y TBB
2179     //   jmp FBB
2180     //
2181 
2182     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2183     // The requirement is that
2184     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2185     //     = TrueProb for original BB.
2186     // Assuming the original probabilities are A and B, one choice is to set
2187     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2188     // A/(1+B) and 2B/(1+B). This choice assumes that
2189     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2190     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2191     // TmpBB, but the math is more complicated.
2192 
2193     auto NewTrueProb = TProb / 2;
2194     auto NewFalseProb = TProb / 2 + FProb;
2195     // Emit the LHS condition.
2196     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2197                          NewTrueProb, NewFalseProb, InvertCond);
2198 
2199     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2200     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2201     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2202     // Emit the RHS condition into TmpBB.
2203     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2204                          Probs[0], Probs[1], InvertCond);
2205   } else {
2206     assert(Opc == Instruction::And && "Unknown merge op!");
2207     // Codegen X & Y as:
2208     // BB1:
2209     //   jmp_if_X TmpBB
2210     //   jmp FBB
2211     // TmpBB:
2212     //   jmp_if_Y TBB
2213     //   jmp FBB
2214     //
2215     //  This requires creation of TmpBB after CurBB.
2216 
2217     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2218     // The requirement is that
2219     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2220     //     = FalseProb for original BB.
2221     // Assuming the original probabilities are A and B, one choice is to set
2222     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2223     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2224     // TrueProb for BB1 * FalseProb for TmpBB.
2225 
2226     auto NewTrueProb = TProb + FProb / 2;
2227     auto NewFalseProb = FProb / 2;
2228     // Emit the LHS condition.
2229     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2230                          NewTrueProb, NewFalseProb, InvertCond);
2231 
2232     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2233     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2234     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2235     // Emit the RHS condition into TmpBB.
2236     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2237                          Probs[0], Probs[1], InvertCond);
2238   }
2239 }
2240 
2241 /// If the set of cases should be emitted as a series of branches, return true.
2242 /// If we should emit this as a bunch of and/or'd together conditions, return
2243 /// false.
2244 bool
2245 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2246   if (Cases.size() != 2) return true;
2247 
2248   // If this is two comparisons of the same values or'd or and'd together, they
2249   // will get folded into a single comparison, so don't emit two blocks.
2250   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2251        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2252       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2253        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2254     return false;
2255   }
2256 
2257   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2258   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2259   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2260       Cases[0].CC == Cases[1].CC &&
2261       isa<Constant>(Cases[0].CmpRHS) &&
2262       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2263     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2264       return false;
2265     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2266       return false;
2267   }
2268 
2269   return true;
2270 }
2271 
2272 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2273   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2274 
2275   // Update machine-CFG edges.
2276   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2277 
2278   if (I.isUnconditional()) {
2279     // Update machine-CFG edges.
2280     BrMBB->addSuccessor(Succ0MBB);
2281 
2282     // If this is not a fall-through branch or optimizations are switched off,
2283     // emit the branch.
2284     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2285       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2286                               MVT::Other, getControlRoot(),
2287                               DAG.getBasicBlock(Succ0MBB)));
2288 
2289     return;
2290   }
2291 
2292   // If this condition is one of the special cases we handle, do special stuff
2293   // now.
2294   const Value *CondVal = I.getCondition();
2295   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2296 
2297   // If this is a series of conditions that are or'd or and'd together, emit
2298   // this as a sequence of branches instead of setcc's with and/or operations.
2299   // As long as jumps are not expensive, this should improve performance.
2300   // For example, instead of something like:
2301   //     cmp A, B
2302   //     C = seteq
2303   //     cmp D, E
2304   //     F = setle
2305   //     or C, F
2306   //     jnz foo
2307   // Emit:
2308   //     cmp A, B
2309   //     je foo
2310   //     cmp D, E
2311   //     jle foo
2312   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2313     Instruction::BinaryOps Opcode = BOp->getOpcode();
2314     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2315         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2316         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2317       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2318                            Opcode,
2319                            getEdgeProbability(BrMBB, Succ0MBB),
2320                            getEdgeProbability(BrMBB, Succ1MBB),
2321                            /*InvertCond=*/false);
2322       // If the compares in later blocks need to use values not currently
2323       // exported from this block, export them now.  This block should always
2324       // be the first entry.
2325       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2326 
2327       // Allow some cases to be rejected.
2328       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2329         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2330           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2331           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2332         }
2333 
2334         // Emit the branch for this block.
2335         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2336         SL->SwitchCases.erase(SL->SwitchCases.begin());
2337         return;
2338       }
2339 
2340       // Okay, we decided not to do this, remove any inserted MBB's and clear
2341       // SwitchCases.
2342       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2343         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2344 
2345       SL->SwitchCases.clear();
2346     }
2347   }
2348 
2349   // Create a CaseBlock record representing this branch.
2350   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2351                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2352 
2353   // Use visitSwitchCase to actually insert the fast branch sequence for this
2354   // cond branch.
2355   visitSwitchCase(CB, BrMBB);
2356 }
2357 
2358 /// visitSwitchCase - Emits the necessary code to represent a single node in
2359 /// the binary search tree resulting from lowering a switch instruction.
2360 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2361                                           MachineBasicBlock *SwitchBB) {
2362   SDValue Cond;
2363   SDValue CondLHS = getValue(CB.CmpLHS);
2364   SDLoc dl = CB.DL;
2365 
2366   if (CB.CC == ISD::SETTRUE) {
2367     // Branch or fall through to TrueBB.
2368     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2369     SwitchBB->normalizeSuccProbs();
2370     if (CB.TrueBB != NextBlock(SwitchBB)) {
2371       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2372                               DAG.getBasicBlock(CB.TrueBB)));
2373     }
2374     return;
2375   }
2376 
2377   auto &TLI = DAG.getTargetLoweringInfo();
2378   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2379 
2380   // Build the setcc now.
2381   if (!CB.CmpMHS) {
2382     // Fold "(X == true)" to X and "(X == false)" to !X to
2383     // handle common cases produced by branch lowering.
2384     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2385         CB.CC == ISD::SETEQ)
2386       Cond = CondLHS;
2387     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2388              CB.CC == ISD::SETEQ) {
2389       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2390       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2391     } else {
2392       SDValue CondRHS = getValue(CB.CmpRHS);
2393 
2394       // If a pointer's DAG type is larger than its memory type then the DAG
2395       // values are zero-extended. This breaks signed comparisons so truncate
2396       // back to the underlying type before doing the compare.
2397       if (CondLHS.getValueType() != MemVT) {
2398         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2399         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2400       }
2401       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2402     }
2403   } else {
2404     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2405 
2406     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2407     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2408 
2409     SDValue CmpOp = getValue(CB.CmpMHS);
2410     EVT VT = CmpOp.getValueType();
2411 
2412     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2413       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2414                           ISD::SETLE);
2415     } else {
2416       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2417                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2418       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2419                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2420     }
2421   }
2422 
2423   // Update successor info
2424   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2425   // TrueBB and FalseBB are always different unless the incoming IR is
2426   // degenerate. This only happens when running llc on weird IR.
2427   if (CB.TrueBB != CB.FalseBB)
2428     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2429   SwitchBB->normalizeSuccProbs();
2430 
2431   // If the lhs block is the next block, invert the condition so that we can
2432   // fall through to the lhs instead of the rhs block.
2433   if (CB.TrueBB == NextBlock(SwitchBB)) {
2434     std::swap(CB.TrueBB, CB.FalseBB);
2435     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2436     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2437   }
2438 
2439   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2440                                MVT::Other, getControlRoot(), Cond,
2441                                DAG.getBasicBlock(CB.TrueBB));
2442 
2443   // Insert the false branch. Do this even if it's a fall through branch,
2444   // this makes it easier to do DAG optimizations which require inverting
2445   // the branch condition.
2446   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2447                        DAG.getBasicBlock(CB.FalseBB));
2448 
2449   DAG.setRoot(BrCond);
2450 }
2451 
2452 /// visitJumpTable - Emit JumpTable node in the current MBB
2453 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2454   // Emit the code for the jump table
2455   assert(JT.Reg != -1U && "Should lower JT Header first!");
2456   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2457   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2458                                      JT.Reg, PTy);
2459   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2460   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2461                                     MVT::Other, Index.getValue(1),
2462                                     Table, Index);
2463   DAG.setRoot(BrJumpTable);
2464 }
2465 
2466 /// visitJumpTableHeader - This function emits necessary code to produce index
2467 /// in the JumpTable from switch case.
2468 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2469                                                JumpTableHeader &JTH,
2470                                                MachineBasicBlock *SwitchBB) {
2471   SDLoc dl = getCurSDLoc();
2472 
2473   // Subtract the lowest switch case value from the value being switched on.
2474   SDValue SwitchOp = getValue(JTH.SValue);
2475   EVT VT = SwitchOp.getValueType();
2476   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2477                             DAG.getConstant(JTH.First, dl, VT));
2478 
2479   // The SDNode we just created, which holds the value being switched on minus
2480   // the smallest case value, needs to be copied to a virtual register so it
2481   // can be used as an index into the jump table in a subsequent basic block.
2482   // This value may be smaller or larger than the target's pointer type, and
2483   // therefore require extension or truncating.
2484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2485   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2486 
2487   unsigned JumpTableReg =
2488       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2489   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2490                                     JumpTableReg, SwitchOp);
2491   JT.Reg = JumpTableReg;
2492 
2493   if (!JTH.OmitRangeCheck) {
2494     // Emit the range check for the jump table, and branch to the default block
2495     // for the switch statement if the value being switched on exceeds the
2496     // largest case in the switch.
2497     SDValue CMP = DAG.getSetCC(
2498         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2499                                    Sub.getValueType()),
2500         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2501 
2502     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2503                                  MVT::Other, CopyTo, CMP,
2504                                  DAG.getBasicBlock(JT.Default));
2505 
2506     // Avoid emitting unnecessary branches to the next block.
2507     if (JT.MBB != NextBlock(SwitchBB))
2508       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2509                            DAG.getBasicBlock(JT.MBB));
2510 
2511     DAG.setRoot(BrCond);
2512   } else {
2513     // Avoid emitting unnecessary branches to the next block.
2514     if (JT.MBB != NextBlock(SwitchBB))
2515       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2516                               DAG.getBasicBlock(JT.MBB)));
2517     else
2518       DAG.setRoot(CopyTo);
2519   }
2520 }
2521 
2522 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2523 /// variable if there exists one.
2524 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2525                                  SDValue &Chain) {
2526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2527   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2528   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2529   MachineFunction &MF = DAG.getMachineFunction();
2530   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2531   MachineSDNode *Node =
2532       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2533   if (Global) {
2534     MachinePointerInfo MPInfo(Global);
2535     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2536                  MachineMemOperand::MODereferenceable;
2537     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2538         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2539     DAG.setNodeMemRefs(Node, {MemRef});
2540   }
2541   if (PtrTy != PtrMemTy)
2542     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2543   return SDValue(Node, 0);
2544 }
2545 
2546 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2547 /// tail spliced into a stack protector check success bb.
2548 ///
2549 /// For a high level explanation of how this fits into the stack protector
2550 /// generation see the comment on the declaration of class
2551 /// StackProtectorDescriptor.
2552 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2553                                                   MachineBasicBlock *ParentBB) {
2554 
2555   // First create the loads to the guard/stack slot for the comparison.
2556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2557   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2558   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2559 
2560   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2561   int FI = MFI.getStackProtectorIndex();
2562 
2563   SDValue Guard;
2564   SDLoc dl = getCurSDLoc();
2565   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2566   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2567   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2568 
2569   // Generate code to load the content of the guard slot.
2570   SDValue GuardVal = DAG.getLoad(
2571       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2572       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2573       MachineMemOperand::MOVolatile);
2574 
2575   if (TLI.useStackGuardXorFP())
2576     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2577 
2578   // Retrieve guard check function, nullptr if instrumentation is inlined.
2579   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2580     // The target provides a guard check function to validate the guard value.
2581     // Generate a call to that function with the content of the guard slot as
2582     // argument.
2583     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2584     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2585 
2586     TargetLowering::ArgListTy Args;
2587     TargetLowering::ArgListEntry Entry;
2588     Entry.Node = GuardVal;
2589     Entry.Ty = FnTy->getParamType(0);
2590     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2591       Entry.IsInReg = true;
2592     Args.push_back(Entry);
2593 
2594     TargetLowering::CallLoweringInfo CLI(DAG);
2595     CLI.setDebugLoc(getCurSDLoc())
2596         .setChain(DAG.getEntryNode())
2597         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2598                    getValue(GuardCheckFn), std::move(Args));
2599 
2600     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2601     DAG.setRoot(Result.second);
2602     return;
2603   }
2604 
2605   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2606   // Otherwise, emit a volatile load to retrieve the stack guard value.
2607   SDValue Chain = DAG.getEntryNode();
2608   if (TLI.useLoadStackGuardNode()) {
2609     Guard = getLoadStackGuard(DAG, dl, Chain);
2610   } else {
2611     const Value *IRGuard = TLI.getSDagStackGuard(M);
2612     SDValue GuardPtr = getValue(IRGuard);
2613 
2614     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2615                         MachinePointerInfo(IRGuard, 0), Align,
2616                         MachineMemOperand::MOVolatile);
2617   }
2618 
2619   // Perform the comparison via a getsetcc.
2620   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2621                                                         *DAG.getContext(),
2622                                                         Guard.getValueType()),
2623                              Guard, GuardVal, ISD::SETNE);
2624 
2625   // If the guard/stackslot do not equal, branch to failure MBB.
2626   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2627                                MVT::Other, GuardVal.getOperand(0),
2628                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2629   // Otherwise branch to success MBB.
2630   SDValue Br = DAG.getNode(ISD::BR, dl,
2631                            MVT::Other, BrCond,
2632                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2633 
2634   DAG.setRoot(Br);
2635 }
2636 
2637 /// Codegen the failure basic block for a stack protector check.
2638 ///
2639 /// A failure stack protector machine basic block consists simply of a call to
2640 /// __stack_chk_fail().
2641 ///
2642 /// For a high level explanation of how this fits into the stack protector
2643 /// generation see the comment on the declaration of class
2644 /// StackProtectorDescriptor.
2645 void
2646 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2648   TargetLowering::MakeLibCallOptions CallOptions;
2649   CallOptions.setDiscardResult(true);
2650   SDValue Chain =
2651       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2652                       None, CallOptions, getCurSDLoc()).second;
2653   // On PS4, the "return address" must still be within the calling function,
2654   // even if it's at the very end, so emit an explicit TRAP here.
2655   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2656   if (TM.getTargetTriple().isPS4CPU())
2657     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2658 
2659   DAG.setRoot(Chain);
2660 }
2661 
2662 /// visitBitTestHeader - This function emits necessary code to produce value
2663 /// suitable for "bit tests"
2664 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2665                                              MachineBasicBlock *SwitchBB) {
2666   SDLoc dl = getCurSDLoc();
2667 
2668   // Subtract the minimum value.
2669   SDValue SwitchOp = getValue(B.SValue);
2670   EVT VT = SwitchOp.getValueType();
2671   SDValue RangeSub =
2672       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2673 
2674   // Determine the type of the test operands.
2675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2676   bool UsePtrType = false;
2677   if (!TLI.isTypeLegal(VT)) {
2678     UsePtrType = true;
2679   } else {
2680     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2681       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2682         // Switch table case range are encoded into series of masks.
2683         // Just use pointer type, it's guaranteed to fit.
2684         UsePtrType = true;
2685         break;
2686       }
2687   }
2688   SDValue Sub = RangeSub;
2689   if (UsePtrType) {
2690     VT = TLI.getPointerTy(DAG.getDataLayout());
2691     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2692   }
2693 
2694   B.RegVT = VT.getSimpleVT();
2695   B.Reg = FuncInfo.CreateReg(B.RegVT);
2696   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2697 
2698   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2699 
2700   if (!B.OmitRangeCheck)
2701     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2702   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2703   SwitchBB->normalizeSuccProbs();
2704 
2705   SDValue Root = CopyTo;
2706   if (!B.OmitRangeCheck) {
2707     // Conditional branch to the default block.
2708     SDValue RangeCmp = DAG.getSetCC(dl,
2709         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2710                                RangeSub.getValueType()),
2711         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2712         ISD::SETUGT);
2713 
2714     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2715                        DAG.getBasicBlock(B.Default));
2716   }
2717 
2718   // Avoid emitting unnecessary branches to the next block.
2719   if (MBB != NextBlock(SwitchBB))
2720     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2721 
2722   DAG.setRoot(Root);
2723 }
2724 
2725 /// visitBitTestCase - this function produces one "bit test"
2726 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2727                                            MachineBasicBlock* NextMBB,
2728                                            BranchProbability BranchProbToNext,
2729                                            unsigned Reg,
2730                                            BitTestCase &B,
2731                                            MachineBasicBlock *SwitchBB) {
2732   SDLoc dl = getCurSDLoc();
2733   MVT VT = BB.RegVT;
2734   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2735   SDValue Cmp;
2736   unsigned PopCount = countPopulation(B.Mask);
2737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2738   if (PopCount == 1) {
2739     // Testing for a single bit; just compare the shift count with what it
2740     // would need to be to shift a 1 bit in that position.
2741     Cmp = DAG.getSetCC(
2742         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2743         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2744         ISD::SETEQ);
2745   } else if (PopCount == BB.Range) {
2746     // There is only one zero bit in the range, test for it directly.
2747     Cmp = DAG.getSetCC(
2748         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2749         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2750         ISD::SETNE);
2751   } else {
2752     // Make desired shift
2753     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2754                                     DAG.getConstant(1, dl, VT), ShiftOp);
2755 
2756     // Emit bit tests and jumps
2757     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2758                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2759     Cmp = DAG.getSetCC(
2760         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2761         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2762   }
2763 
2764   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2765   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2766   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2767   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2768   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2769   // one as they are relative probabilities (and thus work more like weights),
2770   // and hence we need to normalize them to let the sum of them become one.
2771   SwitchBB->normalizeSuccProbs();
2772 
2773   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2774                               MVT::Other, getControlRoot(),
2775                               Cmp, DAG.getBasicBlock(B.TargetBB));
2776 
2777   // Avoid emitting unnecessary branches to the next block.
2778   if (NextMBB != NextBlock(SwitchBB))
2779     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2780                         DAG.getBasicBlock(NextMBB));
2781 
2782   DAG.setRoot(BrAnd);
2783 }
2784 
2785 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2786   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2787 
2788   // Retrieve successors. Look through artificial IR level blocks like
2789   // catchswitch for successors.
2790   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2791   const BasicBlock *EHPadBB = I.getSuccessor(1);
2792 
2793   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2794   // have to do anything here to lower funclet bundles.
2795   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2796                                         LLVMContext::OB_gc_transition,
2797                                         LLVMContext::OB_gc_live,
2798                                         LLVMContext::OB_funclet,
2799                                         LLVMContext::OB_cfguardtarget}) &&
2800          "Cannot lower invokes with arbitrary operand bundles yet!");
2801 
2802   const Value *Callee(I.getCalledOperand());
2803   const Function *Fn = dyn_cast<Function>(Callee);
2804   if (isa<InlineAsm>(Callee))
2805     visitInlineAsm(I);
2806   else if (Fn && Fn->isIntrinsic()) {
2807     switch (Fn->getIntrinsicID()) {
2808     default:
2809       llvm_unreachable("Cannot invoke this intrinsic");
2810     case Intrinsic::donothing:
2811       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2812       break;
2813     case Intrinsic::experimental_patchpoint_void:
2814     case Intrinsic::experimental_patchpoint_i64:
2815       visitPatchpoint(I, EHPadBB);
2816       break;
2817     case Intrinsic::experimental_gc_statepoint:
2818       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2819       break;
2820     case Intrinsic::wasm_rethrow_in_catch: {
2821       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2822       // special because it can be invoked, so we manually lower it to a DAG
2823       // node here.
2824       SmallVector<SDValue, 8> Ops;
2825       Ops.push_back(getRoot()); // inchain
2826       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2827       Ops.push_back(
2828           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2829                                 TLI.getPointerTy(DAG.getDataLayout())));
2830       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2831       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2832       break;
2833     }
2834     }
2835   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2836     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2837     // Eventually we will support lowering the @llvm.experimental.deoptimize
2838     // intrinsic, and right now there are no plans to support other intrinsics
2839     // with deopt state.
2840     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2841   } else {
2842     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2843   }
2844 
2845   // If the value of the invoke is used outside of its defining block, make it
2846   // available as a virtual register.
2847   // We already took care of the exported value for the statepoint instruction
2848   // during call to the LowerStatepoint.
2849   if (!isa<GCStatepointInst>(I)) {
2850     CopyToExportRegsIfNeeded(&I);
2851   }
2852 
2853   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2854   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2855   BranchProbability EHPadBBProb =
2856       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2857           : BranchProbability::getZero();
2858   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2859 
2860   // Update successor info.
2861   addSuccessorWithProb(InvokeMBB, Return);
2862   for (auto &UnwindDest : UnwindDests) {
2863     UnwindDest.first->setIsEHPad();
2864     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2865   }
2866   InvokeMBB->normalizeSuccProbs();
2867 
2868   // Drop into normal successor.
2869   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2870                           DAG.getBasicBlock(Return)));
2871 }
2872 
2873 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2874   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2875 
2876   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2877   // have to do anything here to lower funclet bundles.
2878   assert(!I.hasOperandBundlesOtherThan(
2879              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2880          "Cannot lower callbrs with arbitrary operand bundles yet!");
2881 
2882   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2883   visitInlineAsm(I);
2884   CopyToExportRegsIfNeeded(&I);
2885 
2886   // Retrieve successors.
2887   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2888 
2889   // Update successor info.
2890   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2891   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2892     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2893     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2894     Target->setIsInlineAsmBrIndirectTarget();
2895   }
2896   CallBrMBB->normalizeSuccProbs();
2897 
2898   // Drop into default successor.
2899   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2900                           MVT::Other, getControlRoot(),
2901                           DAG.getBasicBlock(Return)));
2902 }
2903 
2904 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2905   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2906 }
2907 
2908 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2909   assert(FuncInfo.MBB->isEHPad() &&
2910          "Call to landingpad not in landing pad!");
2911 
2912   // If there aren't registers to copy the values into (e.g., during SjLj
2913   // exceptions), then don't bother to create these DAG nodes.
2914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2915   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2916   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2917       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2918     return;
2919 
2920   // If landingpad's return type is token type, we don't create DAG nodes
2921   // for its exception pointer and selector value. The extraction of exception
2922   // pointer or selector value from token type landingpads is not currently
2923   // supported.
2924   if (LP.getType()->isTokenTy())
2925     return;
2926 
2927   SmallVector<EVT, 2> ValueVTs;
2928   SDLoc dl = getCurSDLoc();
2929   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2930   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2931 
2932   // Get the two live-in registers as SDValues. The physregs have already been
2933   // copied into virtual registers.
2934   SDValue Ops[2];
2935   if (FuncInfo.ExceptionPointerVirtReg) {
2936     Ops[0] = DAG.getZExtOrTrunc(
2937         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2938                            FuncInfo.ExceptionPointerVirtReg,
2939                            TLI.getPointerTy(DAG.getDataLayout())),
2940         dl, ValueVTs[0]);
2941   } else {
2942     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2943   }
2944   Ops[1] = DAG.getZExtOrTrunc(
2945       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2946                          FuncInfo.ExceptionSelectorVirtReg,
2947                          TLI.getPointerTy(DAG.getDataLayout())),
2948       dl, ValueVTs[1]);
2949 
2950   // Merge into one.
2951   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2952                             DAG.getVTList(ValueVTs), Ops);
2953   setValue(&LP, Res);
2954 }
2955 
2956 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2957                                            MachineBasicBlock *Last) {
2958   // Update JTCases.
2959   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2960     if (SL->JTCases[i].first.HeaderBB == First)
2961       SL->JTCases[i].first.HeaderBB = Last;
2962 
2963   // Update BitTestCases.
2964   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2965     if (SL->BitTestCases[i].Parent == First)
2966       SL->BitTestCases[i].Parent = Last;
2967 }
2968 
2969 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2970   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2971 
2972   // Update machine-CFG edges with unique successors.
2973   SmallSet<BasicBlock*, 32> Done;
2974   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2975     BasicBlock *BB = I.getSuccessor(i);
2976     bool Inserted = Done.insert(BB).second;
2977     if (!Inserted)
2978         continue;
2979 
2980     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2981     addSuccessorWithProb(IndirectBrMBB, Succ);
2982   }
2983   IndirectBrMBB->normalizeSuccProbs();
2984 
2985   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2986                           MVT::Other, getControlRoot(),
2987                           getValue(I.getAddress())));
2988 }
2989 
2990 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2991   if (!DAG.getTarget().Options.TrapUnreachable)
2992     return;
2993 
2994   // We may be able to ignore unreachable behind a noreturn call.
2995   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2996     const BasicBlock &BB = *I.getParent();
2997     if (&I != &BB.front()) {
2998       BasicBlock::const_iterator PredI =
2999         std::prev(BasicBlock::const_iterator(&I));
3000       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3001         if (Call->doesNotReturn())
3002           return;
3003       }
3004     }
3005   }
3006 
3007   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3008 }
3009 
3010 void SelectionDAGBuilder::visitFSub(const User &I) {
3011   // -0.0 - X --> fneg
3012   Type *Ty = I.getType();
3013   if (isa<Constant>(I.getOperand(0)) &&
3014       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3015     SDValue Op2 = getValue(I.getOperand(1));
3016     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3017                              Op2.getValueType(), Op2));
3018     return;
3019   }
3020 
3021   visitBinary(I, ISD::FSUB);
3022 }
3023 
3024 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3025   SDNodeFlags Flags;
3026 
3027   SDValue Op = getValue(I.getOperand(0));
3028   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3029                                     Op, Flags);
3030   setValue(&I, UnNodeValue);
3031 }
3032 
3033 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3034   SDNodeFlags Flags;
3035   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3036     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3037     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3038   }
3039   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3040     Flags.setExact(ExactOp->isExact());
3041   }
3042 
3043   SDValue Op1 = getValue(I.getOperand(0));
3044   SDValue Op2 = getValue(I.getOperand(1));
3045   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3046                                      Op1, Op2, Flags);
3047   setValue(&I, BinNodeValue);
3048 }
3049 
3050 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3051   SDValue Op1 = getValue(I.getOperand(0));
3052   SDValue Op2 = getValue(I.getOperand(1));
3053 
3054   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3055       Op1.getValueType(), DAG.getDataLayout());
3056 
3057   // Coerce the shift amount to the right type if we can.
3058   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3059     unsigned ShiftSize = ShiftTy.getSizeInBits();
3060     unsigned Op2Size = Op2.getValueSizeInBits();
3061     SDLoc DL = getCurSDLoc();
3062 
3063     // If the operand is smaller than the shift count type, promote it.
3064     if (ShiftSize > Op2Size)
3065       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3066 
3067     // If the operand is larger than the shift count type but the shift
3068     // count type has enough bits to represent any shift value, truncate
3069     // it now. This is a common case and it exposes the truncate to
3070     // optimization early.
3071     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3072       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3073     // Otherwise we'll need to temporarily settle for some other convenient
3074     // type.  Type legalization will make adjustments once the shiftee is split.
3075     else
3076       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3077   }
3078 
3079   bool nuw = false;
3080   bool nsw = false;
3081   bool exact = false;
3082 
3083   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3084 
3085     if (const OverflowingBinaryOperator *OFBinOp =
3086             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3087       nuw = OFBinOp->hasNoUnsignedWrap();
3088       nsw = OFBinOp->hasNoSignedWrap();
3089     }
3090     if (const PossiblyExactOperator *ExactOp =
3091             dyn_cast<const PossiblyExactOperator>(&I))
3092       exact = ExactOp->isExact();
3093   }
3094   SDNodeFlags Flags;
3095   Flags.setExact(exact);
3096   Flags.setNoSignedWrap(nsw);
3097   Flags.setNoUnsignedWrap(nuw);
3098   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3099                             Flags);
3100   setValue(&I, Res);
3101 }
3102 
3103 void SelectionDAGBuilder::visitSDiv(const User &I) {
3104   SDValue Op1 = getValue(I.getOperand(0));
3105   SDValue Op2 = getValue(I.getOperand(1));
3106 
3107   SDNodeFlags Flags;
3108   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3109                  cast<PossiblyExactOperator>(&I)->isExact());
3110   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3111                            Op2, Flags));
3112 }
3113 
3114 void SelectionDAGBuilder::visitICmp(const User &I) {
3115   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3116   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3117     predicate = IC->getPredicate();
3118   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3119     predicate = ICmpInst::Predicate(IC->getPredicate());
3120   SDValue Op1 = getValue(I.getOperand(0));
3121   SDValue Op2 = getValue(I.getOperand(1));
3122   ISD::CondCode Opcode = getICmpCondCode(predicate);
3123 
3124   auto &TLI = DAG.getTargetLoweringInfo();
3125   EVT MemVT =
3126       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3127 
3128   // If a pointer's DAG type is larger than its memory type then the DAG values
3129   // are zero-extended. This breaks signed comparisons so truncate back to the
3130   // underlying type before doing the compare.
3131   if (Op1.getValueType() != MemVT) {
3132     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3133     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3134   }
3135 
3136   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3137                                                         I.getType());
3138   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3139 }
3140 
3141 void SelectionDAGBuilder::visitFCmp(const User &I) {
3142   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3143   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3144     predicate = FC->getPredicate();
3145   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3146     predicate = FCmpInst::Predicate(FC->getPredicate());
3147   SDValue Op1 = getValue(I.getOperand(0));
3148   SDValue Op2 = getValue(I.getOperand(1));
3149 
3150   ISD::CondCode Condition = getFCmpCondCode(predicate);
3151   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3152   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3153     Condition = getFCmpCodeWithoutNaN(Condition);
3154 
3155   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3156                                                         I.getType());
3157   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3158 }
3159 
3160 // Check if the condition of the select has one use or two users that are both
3161 // selects with the same condition.
3162 static bool hasOnlySelectUsers(const Value *Cond) {
3163   return llvm::all_of(Cond->users(), [](const Value *V) {
3164     return isa<SelectInst>(V);
3165   });
3166 }
3167 
3168 void SelectionDAGBuilder::visitSelect(const User &I) {
3169   SmallVector<EVT, 4> ValueVTs;
3170   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3171                   ValueVTs);
3172   unsigned NumValues = ValueVTs.size();
3173   if (NumValues == 0) return;
3174 
3175   SmallVector<SDValue, 4> Values(NumValues);
3176   SDValue Cond     = getValue(I.getOperand(0));
3177   SDValue LHSVal   = getValue(I.getOperand(1));
3178   SDValue RHSVal   = getValue(I.getOperand(2));
3179   SmallVector<SDValue, 1> BaseOps(1, Cond);
3180   ISD::NodeType OpCode =
3181       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3182 
3183   bool IsUnaryAbs = false;
3184 
3185   // Min/max matching is only viable if all output VTs are the same.
3186   if (is_splat(ValueVTs)) {
3187     EVT VT = ValueVTs[0];
3188     LLVMContext &Ctx = *DAG.getContext();
3189     auto &TLI = DAG.getTargetLoweringInfo();
3190 
3191     // We care about the legality of the operation after it has been type
3192     // legalized.
3193     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3194       VT = TLI.getTypeToTransformTo(Ctx, VT);
3195 
3196     // If the vselect is legal, assume we want to leave this as a vector setcc +
3197     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3198     // min/max is legal on the scalar type.
3199     bool UseScalarMinMax = VT.isVector() &&
3200       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3201 
3202     Value *LHS, *RHS;
3203     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3204     ISD::NodeType Opc = ISD::DELETED_NODE;
3205     switch (SPR.Flavor) {
3206     case SPF_UMAX:    Opc = ISD::UMAX; break;
3207     case SPF_UMIN:    Opc = ISD::UMIN; break;
3208     case SPF_SMAX:    Opc = ISD::SMAX; break;
3209     case SPF_SMIN:    Opc = ISD::SMIN; break;
3210     case SPF_FMINNUM:
3211       switch (SPR.NaNBehavior) {
3212       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3213       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3214       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3215       case SPNB_RETURNS_ANY: {
3216         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3217           Opc = ISD::FMINNUM;
3218         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3219           Opc = ISD::FMINIMUM;
3220         else if (UseScalarMinMax)
3221           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3222             ISD::FMINNUM : ISD::FMINIMUM;
3223         break;
3224       }
3225       }
3226       break;
3227     case SPF_FMAXNUM:
3228       switch (SPR.NaNBehavior) {
3229       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3230       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3231       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3232       case SPNB_RETURNS_ANY:
3233 
3234         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3235           Opc = ISD::FMAXNUM;
3236         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3237           Opc = ISD::FMAXIMUM;
3238         else if (UseScalarMinMax)
3239           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3240             ISD::FMAXNUM : ISD::FMAXIMUM;
3241         break;
3242       }
3243       break;
3244     case SPF_ABS:
3245       IsUnaryAbs = true;
3246       Opc = ISD::ABS;
3247       break;
3248     case SPF_NABS:
3249       // TODO: we need to produce sub(0, abs(X)).
3250     default: break;
3251     }
3252 
3253     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3254         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3255          (UseScalarMinMax &&
3256           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3257         // If the underlying comparison instruction is used by any other
3258         // instruction, the consumed instructions won't be destroyed, so it is
3259         // not profitable to convert to a min/max.
3260         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3261       OpCode = Opc;
3262       LHSVal = getValue(LHS);
3263       RHSVal = getValue(RHS);
3264       BaseOps.clear();
3265     }
3266 
3267     if (IsUnaryAbs) {
3268       OpCode = Opc;
3269       LHSVal = getValue(LHS);
3270       BaseOps.clear();
3271     }
3272   }
3273 
3274   if (IsUnaryAbs) {
3275     for (unsigned i = 0; i != NumValues; ++i) {
3276       Values[i] =
3277           DAG.getNode(OpCode, getCurSDLoc(),
3278                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3279                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3280     }
3281   } else {
3282     for (unsigned i = 0; i != NumValues; ++i) {
3283       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3284       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3285       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3286       Values[i] = DAG.getNode(
3287           OpCode, getCurSDLoc(),
3288           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3289     }
3290   }
3291 
3292   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3293                            DAG.getVTList(ValueVTs), Values));
3294 }
3295 
3296 void SelectionDAGBuilder::visitTrunc(const User &I) {
3297   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3298   SDValue N = getValue(I.getOperand(0));
3299   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3300                                                         I.getType());
3301   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3302 }
3303 
3304 void SelectionDAGBuilder::visitZExt(const User &I) {
3305   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3306   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3307   SDValue N = getValue(I.getOperand(0));
3308   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3309                                                         I.getType());
3310   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3311 }
3312 
3313 void SelectionDAGBuilder::visitSExt(const User &I) {
3314   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3315   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3316   SDValue N = getValue(I.getOperand(0));
3317   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3318                                                         I.getType());
3319   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3320 }
3321 
3322 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3323   // FPTrunc is never a no-op cast, no need to check
3324   SDValue N = getValue(I.getOperand(0));
3325   SDLoc dl = getCurSDLoc();
3326   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3327   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3328   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3329                            DAG.getTargetConstant(
3330                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3331 }
3332 
3333 void SelectionDAGBuilder::visitFPExt(const User &I) {
3334   // FPExt is never a no-op cast, no need to check
3335   SDValue N = getValue(I.getOperand(0));
3336   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3337                                                         I.getType());
3338   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3339 }
3340 
3341 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3342   // FPToUI is never a no-op cast, no need to check
3343   SDValue N = getValue(I.getOperand(0));
3344   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3345                                                         I.getType());
3346   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3347 }
3348 
3349 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3350   // FPToSI is never a no-op cast, no need to check
3351   SDValue N = getValue(I.getOperand(0));
3352   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3353                                                         I.getType());
3354   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3355 }
3356 
3357 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3358   // UIToFP is never a no-op cast, no need to check
3359   SDValue N = getValue(I.getOperand(0));
3360   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3361                                                         I.getType());
3362   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3363 }
3364 
3365 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3366   // SIToFP is never a no-op cast, no need to check
3367   SDValue N = getValue(I.getOperand(0));
3368   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3369                                                         I.getType());
3370   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3371 }
3372 
3373 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3374   // What to do depends on the size of the integer and the size of the pointer.
3375   // We can either truncate, zero extend, or no-op, accordingly.
3376   SDValue N = getValue(I.getOperand(0));
3377   auto &TLI = DAG.getTargetLoweringInfo();
3378   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3379                                                         I.getType());
3380   EVT PtrMemVT =
3381       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3382   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3383   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3384   setValue(&I, N);
3385 }
3386 
3387 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3388   // What to do depends on the size of the integer and the size of the pointer.
3389   // We can either truncate, zero extend, or no-op, accordingly.
3390   SDValue N = getValue(I.getOperand(0));
3391   auto &TLI = DAG.getTargetLoweringInfo();
3392   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3393   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3394   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3395   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3396   setValue(&I, N);
3397 }
3398 
3399 void SelectionDAGBuilder::visitBitCast(const User &I) {
3400   SDValue N = getValue(I.getOperand(0));
3401   SDLoc dl = getCurSDLoc();
3402   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3403                                                         I.getType());
3404 
3405   // BitCast assures us that source and destination are the same size so this is
3406   // either a BITCAST or a no-op.
3407   if (DestVT != N.getValueType())
3408     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3409                              DestVT, N)); // convert types.
3410   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3411   // might fold any kind of constant expression to an integer constant and that
3412   // is not what we are looking for. Only recognize a bitcast of a genuine
3413   // constant integer as an opaque constant.
3414   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3415     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3416                                  /*isOpaque*/true));
3417   else
3418     setValue(&I, N);            // noop cast.
3419 }
3420 
3421 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3423   const Value *SV = I.getOperand(0);
3424   SDValue N = getValue(SV);
3425   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3426 
3427   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3428   unsigned DestAS = I.getType()->getPointerAddressSpace();
3429 
3430   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3431     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3432 
3433   setValue(&I, N);
3434 }
3435 
3436 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3438   SDValue InVec = getValue(I.getOperand(0));
3439   SDValue InVal = getValue(I.getOperand(1));
3440   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3441                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3442   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3443                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3444                            InVec, InVal, InIdx));
3445 }
3446 
3447 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3449   SDValue InVec = getValue(I.getOperand(0));
3450   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3451                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3452   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3453                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3454                            InVec, InIdx));
3455 }
3456 
3457 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3458   SDValue Src1 = getValue(I.getOperand(0));
3459   SDValue Src2 = getValue(I.getOperand(1));
3460   ArrayRef<int> Mask;
3461   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3462     Mask = SVI->getShuffleMask();
3463   else
3464     Mask = cast<ConstantExpr>(I).getShuffleMask();
3465   SDLoc DL = getCurSDLoc();
3466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3467   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3468   EVT SrcVT = Src1.getValueType();
3469 
3470   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3471       VT.isScalableVector()) {
3472     // Canonical splat form of first element of first input vector.
3473     SDValue FirstElt =
3474         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3475                     DAG.getVectorIdxConstant(0, DL));
3476     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3477     return;
3478   }
3479 
3480   // For now, we only handle splats for scalable vectors.
3481   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3482   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3483   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3484 
3485   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3486   unsigned MaskNumElts = Mask.size();
3487 
3488   if (SrcNumElts == MaskNumElts) {
3489     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3490     return;
3491   }
3492 
3493   // Normalize the shuffle vector since mask and vector length don't match.
3494   if (SrcNumElts < MaskNumElts) {
3495     // Mask is longer than the source vectors. We can use concatenate vector to
3496     // make the mask and vectors lengths match.
3497 
3498     if (MaskNumElts % SrcNumElts == 0) {
3499       // Mask length is a multiple of the source vector length.
3500       // Check if the shuffle is some kind of concatenation of the input
3501       // vectors.
3502       unsigned NumConcat = MaskNumElts / SrcNumElts;
3503       bool IsConcat = true;
3504       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3505       for (unsigned i = 0; i != MaskNumElts; ++i) {
3506         int Idx = Mask[i];
3507         if (Idx < 0)
3508           continue;
3509         // Ensure the indices in each SrcVT sized piece are sequential and that
3510         // the same source is used for the whole piece.
3511         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3512             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3513              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3514           IsConcat = false;
3515           break;
3516         }
3517         // Remember which source this index came from.
3518         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3519       }
3520 
3521       // The shuffle is concatenating multiple vectors together. Just emit
3522       // a CONCAT_VECTORS operation.
3523       if (IsConcat) {
3524         SmallVector<SDValue, 8> ConcatOps;
3525         for (auto Src : ConcatSrcs) {
3526           if (Src < 0)
3527             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3528           else if (Src == 0)
3529             ConcatOps.push_back(Src1);
3530           else
3531             ConcatOps.push_back(Src2);
3532         }
3533         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3534         return;
3535       }
3536     }
3537 
3538     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3539     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3540     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3541                                     PaddedMaskNumElts);
3542 
3543     // Pad both vectors with undefs to make them the same length as the mask.
3544     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3545 
3546     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3547     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3548     MOps1[0] = Src1;
3549     MOps2[0] = Src2;
3550 
3551     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3552     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3553 
3554     // Readjust mask for new input vector length.
3555     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3556     for (unsigned i = 0; i != MaskNumElts; ++i) {
3557       int Idx = Mask[i];
3558       if (Idx >= (int)SrcNumElts)
3559         Idx -= SrcNumElts - PaddedMaskNumElts;
3560       MappedOps[i] = Idx;
3561     }
3562 
3563     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3564 
3565     // If the concatenated vector was padded, extract a subvector with the
3566     // correct number of elements.
3567     if (MaskNumElts != PaddedMaskNumElts)
3568       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3569                            DAG.getVectorIdxConstant(0, DL));
3570 
3571     setValue(&I, Result);
3572     return;
3573   }
3574 
3575   if (SrcNumElts > MaskNumElts) {
3576     // Analyze the access pattern of the vector to see if we can extract
3577     // two subvectors and do the shuffle.
3578     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3579     bool CanExtract = true;
3580     for (int Idx : Mask) {
3581       unsigned Input = 0;
3582       if (Idx < 0)
3583         continue;
3584 
3585       if (Idx >= (int)SrcNumElts) {
3586         Input = 1;
3587         Idx -= SrcNumElts;
3588       }
3589 
3590       // If all the indices come from the same MaskNumElts sized portion of
3591       // the sources we can use extract. Also make sure the extract wouldn't
3592       // extract past the end of the source.
3593       int NewStartIdx = alignDown(Idx, MaskNumElts);
3594       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3595           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3596         CanExtract = false;
3597       // Make sure we always update StartIdx as we use it to track if all
3598       // elements are undef.
3599       StartIdx[Input] = NewStartIdx;
3600     }
3601 
3602     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3603       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3604       return;
3605     }
3606     if (CanExtract) {
3607       // Extract appropriate subvector and generate a vector shuffle
3608       for (unsigned Input = 0; Input < 2; ++Input) {
3609         SDValue &Src = Input == 0 ? Src1 : Src2;
3610         if (StartIdx[Input] < 0)
3611           Src = DAG.getUNDEF(VT);
3612         else {
3613           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3614                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3615         }
3616       }
3617 
3618       // Calculate new mask.
3619       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3620       for (int &Idx : MappedOps) {
3621         if (Idx >= (int)SrcNumElts)
3622           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3623         else if (Idx >= 0)
3624           Idx -= StartIdx[0];
3625       }
3626 
3627       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3628       return;
3629     }
3630   }
3631 
3632   // We can't use either concat vectors or extract subvectors so fall back to
3633   // replacing the shuffle with extract and build vector.
3634   // to insert and build vector.
3635   EVT EltVT = VT.getVectorElementType();
3636   SmallVector<SDValue,8> Ops;
3637   for (int Idx : Mask) {
3638     SDValue Res;
3639 
3640     if (Idx < 0) {
3641       Res = DAG.getUNDEF(EltVT);
3642     } else {
3643       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3644       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3645 
3646       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3647                         DAG.getVectorIdxConstant(Idx, DL));
3648     }
3649 
3650     Ops.push_back(Res);
3651   }
3652 
3653   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3654 }
3655 
3656 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3657   ArrayRef<unsigned> Indices;
3658   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3659     Indices = IV->getIndices();
3660   else
3661     Indices = cast<ConstantExpr>(&I)->getIndices();
3662 
3663   const Value *Op0 = I.getOperand(0);
3664   const Value *Op1 = I.getOperand(1);
3665   Type *AggTy = I.getType();
3666   Type *ValTy = Op1->getType();
3667   bool IntoUndef = isa<UndefValue>(Op0);
3668   bool FromUndef = isa<UndefValue>(Op1);
3669 
3670   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3671 
3672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3673   SmallVector<EVT, 4> AggValueVTs;
3674   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3675   SmallVector<EVT, 4> ValValueVTs;
3676   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3677 
3678   unsigned NumAggValues = AggValueVTs.size();
3679   unsigned NumValValues = ValValueVTs.size();
3680   SmallVector<SDValue, 4> Values(NumAggValues);
3681 
3682   // Ignore an insertvalue that produces an empty object
3683   if (!NumAggValues) {
3684     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3685     return;
3686   }
3687 
3688   SDValue Agg = getValue(Op0);
3689   unsigned i = 0;
3690   // Copy the beginning value(s) from the original aggregate.
3691   for (; i != LinearIndex; ++i)
3692     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3693                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3694   // Copy values from the inserted value(s).
3695   if (NumValValues) {
3696     SDValue Val = getValue(Op1);
3697     for (; i != LinearIndex + NumValValues; ++i)
3698       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3699                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3700   }
3701   // Copy remaining value(s) from the original aggregate.
3702   for (; i != NumAggValues; ++i)
3703     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3704                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3705 
3706   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3707                            DAG.getVTList(AggValueVTs), Values));
3708 }
3709 
3710 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3711   ArrayRef<unsigned> Indices;
3712   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3713     Indices = EV->getIndices();
3714   else
3715     Indices = cast<ConstantExpr>(&I)->getIndices();
3716 
3717   const Value *Op0 = I.getOperand(0);
3718   Type *AggTy = Op0->getType();
3719   Type *ValTy = I.getType();
3720   bool OutOfUndef = isa<UndefValue>(Op0);
3721 
3722   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3723 
3724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3725   SmallVector<EVT, 4> ValValueVTs;
3726   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3727 
3728   unsigned NumValValues = ValValueVTs.size();
3729 
3730   // Ignore a extractvalue that produces an empty object
3731   if (!NumValValues) {
3732     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3733     return;
3734   }
3735 
3736   SmallVector<SDValue, 4> Values(NumValValues);
3737 
3738   SDValue Agg = getValue(Op0);
3739   // Copy out the selected value(s).
3740   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3741     Values[i - LinearIndex] =
3742       OutOfUndef ?
3743         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3744         SDValue(Agg.getNode(), Agg.getResNo() + i);
3745 
3746   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3747                            DAG.getVTList(ValValueVTs), Values));
3748 }
3749 
3750 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3751   Value *Op0 = I.getOperand(0);
3752   // Note that the pointer operand may be a vector of pointers. Take the scalar
3753   // element which holds a pointer.
3754   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3755   SDValue N = getValue(Op0);
3756   SDLoc dl = getCurSDLoc();
3757   auto &TLI = DAG.getTargetLoweringInfo();
3758   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3759   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3760 
3761   // Normalize Vector GEP - all scalar operands should be converted to the
3762   // splat vector.
3763   bool IsVectorGEP = I.getType()->isVectorTy();
3764   ElementCount VectorElementCount =
3765       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3766                   : ElementCount(0, false);
3767 
3768   if (IsVectorGEP && !N.getValueType().isVector()) {
3769     LLVMContext &Context = *DAG.getContext();
3770     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3771     if (VectorElementCount.Scalable)
3772       N = DAG.getSplatVector(VT, dl, N);
3773     else
3774       N = DAG.getSplatBuildVector(VT, dl, N);
3775   }
3776 
3777   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3778        GTI != E; ++GTI) {
3779     const Value *Idx = GTI.getOperand();
3780     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3781       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3782       if (Field) {
3783         // N = N + Offset
3784         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3785 
3786         // In an inbounds GEP with an offset that is nonnegative even when
3787         // interpreted as signed, assume there is no unsigned overflow.
3788         SDNodeFlags Flags;
3789         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3790           Flags.setNoUnsignedWrap(true);
3791 
3792         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3793                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3794       }
3795     } else {
3796       // IdxSize is the width of the arithmetic according to IR semantics.
3797       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3798       // (and fix up the result later).
3799       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3800       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3801       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3802       // We intentionally mask away the high bits here; ElementSize may not
3803       // fit in IdxTy.
3804       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3805       bool ElementScalable = ElementSize.isScalable();
3806 
3807       // If this is a scalar constant or a splat vector of constants,
3808       // handle it quickly.
3809       const auto *C = dyn_cast<Constant>(Idx);
3810       if (C && isa<VectorType>(C->getType()))
3811         C = C->getSplatValue();
3812 
3813       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3814       if (CI && CI->isZero())
3815         continue;
3816       if (CI && !ElementScalable) {
3817         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3818         LLVMContext &Context = *DAG.getContext();
3819         SDValue OffsVal;
3820         if (IsVectorGEP)
3821           OffsVal = DAG.getConstant(
3822               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3823         else
3824           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3825 
3826         // In an inbounds GEP with an offset that is nonnegative even when
3827         // interpreted as signed, assume there is no unsigned overflow.
3828         SDNodeFlags Flags;
3829         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3830           Flags.setNoUnsignedWrap(true);
3831 
3832         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3833 
3834         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3835         continue;
3836       }
3837 
3838       // N = N + Idx * ElementMul;
3839       SDValue IdxN = getValue(Idx);
3840 
3841       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3842         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3843                                   VectorElementCount);
3844         if (VectorElementCount.Scalable)
3845           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3846         else
3847           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3848       }
3849 
3850       // If the index is smaller or larger than intptr_t, truncate or extend
3851       // it.
3852       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3853 
3854       if (ElementScalable) {
3855         EVT VScaleTy = N.getValueType().getScalarType();
3856         SDValue VScale = DAG.getNode(
3857             ISD::VSCALE, dl, VScaleTy,
3858             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3859         if (IsVectorGEP)
3860           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3861         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3862       } else {
3863         // If this is a multiply by a power of two, turn it into a shl
3864         // immediately.  This is a very common case.
3865         if (ElementMul != 1) {
3866           if (ElementMul.isPowerOf2()) {
3867             unsigned Amt = ElementMul.logBase2();
3868             IdxN = DAG.getNode(ISD::SHL, dl,
3869                                N.getValueType(), IdxN,
3870                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3871           } else {
3872             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3873                                             IdxN.getValueType());
3874             IdxN = DAG.getNode(ISD::MUL, dl,
3875                                N.getValueType(), IdxN, Scale);
3876           }
3877         }
3878       }
3879 
3880       N = DAG.getNode(ISD::ADD, dl,
3881                       N.getValueType(), N, IdxN);
3882     }
3883   }
3884 
3885   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3886     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3887 
3888   setValue(&I, N);
3889 }
3890 
3891 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3892   // If this is a fixed sized alloca in the entry block of the function,
3893   // allocate it statically on the stack.
3894   if (FuncInfo.StaticAllocaMap.count(&I))
3895     return;   // getValue will auto-populate this.
3896 
3897   SDLoc dl = getCurSDLoc();
3898   Type *Ty = I.getAllocatedType();
3899   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3900   auto &DL = DAG.getDataLayout();
3901   uint64_t TySize = DL.getTypeAllocSize(Ty);
3902   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3903 
3904   SDValue AllocSize = getValue(I.getArraySize());
3905 
3906   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3907   if (AllocSize.getValueType() != IntPtr)
3908     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3909 
3910   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3911                           AllocSize,
3912                           DAG.getConstant(TySize, dl, IntPtr));
3913 
3914   // Handle alignment.  If the requested alignment is less than or equal to
3915   // the stack alignment, ignore it.  If the size is greater than or equal to
3916   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3917   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3918   if (*Alignment <= StackAlign)
3919     Alignment = None;
3920 
3921   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3922   // Round the size of the allocation up to the stack alignment size
3923   // by add SA-1 to the size. This doesn't overflow because we're computing
3924   // an address inside an alloca.
3925   SDNodeFlags Flags;
3926   Flags.setNoUnsignedWrap(true);
3927   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3928                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3929 
3930   // Mask out the low bits for alignment purposes.
3931   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3932                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3933 
3934   SDValue Ops[] = {
3935       getRoot(), AllocSize,
3936       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3937   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3938   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3939   setValue(&I, DSA);
3940   DAG.setRoot(DSA.getValue(1));
3941 
3942   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3943 }
3944 
3945 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3946   if (I.isAtomic())
3947     return visitAtomicLoad(I);
3948 
3949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3950   const Value *SV = I.getOperand(0);
3951   if (TLI.supportSwiftError()) {
3952     // Swifterror values can come from either a function parameter with
3953     // swifterror attribute or an alloca with swifterror attribute.
3954     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3955       if (Arg->hasSwiftErrorAttr())
3956         return visitLoadFromSwiftError(I);
3957     }
3958 
3959     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3960       if (Alloca->isSwiftError())
3961         return visitLoadFromSwiftError(I);
3962     }
3963   }
3964 
3965   SDValue Ptr = getValue(SV);
3966 
3967   Type *Ty = I.getType();
3968   Align Alignment = I.getAlign();
3969 
3970   AAMDNodes AAInfo;
3971   I.getAAMetadata(AAInfo);
3972   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3973 
3974   SmallVector<EVT, 4> ValueVTs, MemVTs;
3975   SmallVector<uint64_t, 4> Offsets;
3976   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3977   unsigned NumValues = ValueVTs.size();
3978   if (NumValues == 0)
3979     return;
3980 
3981   bool isVolatile = I.isVolatile();
3982 
3983   SDValue Root;
3984   bool ConstantMemory = false;
3985   if (isVolatile)
3986     // Serialize volatile loads with other side effects.
3987     Root = getRoot();
3988   else if (NumValues > MaxParallelChains)
3989     Root = getMemoryRoot();
3990   else if (AA &&
3991            AA->pointsToConstantMemory(MemoryLocation(
3992                SV,
3993                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3994                AAInfo))) {
3995     // Do not serialize (non-volatile) loads of constant memory with anything.
3996     Root = DAG.getEntryNode();
3997     ConstantMemory = true;
3998   } else {
3999     // Do not serialize non-volatile loads against each other.
4000     Root = DAG.getRoot();
4001   }
4002 
4003   SDLoc dl = getCurSDLoc();
4004 
4005   if (isVolatile)
4006     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4007 
4008   // An aggregate load cannot wrap around the address space, so offsets to its
4009   // parts don't wrap either.
4010   SDNodeFlags Flags;
4011   Flags.setNoUnsignedWrap(true);
4012 
4013   SmallVector<SDValue, 4> Values(NumValues);
4014   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4015   EVT PtrVT = Ptr.getValueType();
4016 
4017   MachineMemOperand::Flags MMOFlags
4018     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4019 
4020   unsigned ChainI = 0;
4021   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4022     // Serializing loads here may result in excessive register pressure, and
4023     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4024     // could recover a bit by hoisting nodes upward in the chain by recognizing
4025     // they are side-effect free or do not alias. The optimizer should really
4026     // avoid this case by converting large object/array copies to llvm.memcpy
4027     // (MaxParallelChains should always remain as failsafe).
4028     if (ChainI == MaxParallelChains) {
4029       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4030       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4031                                   makeArrayRef(Chains.data(), ChainI));
4032       Root = Chain;
4033       ChainI = 0;
4034     }
4035     SDValue A = DAG.getNode(ISD::ADD, dl,
4036                             PtrVT, Ptr,
4037                             DAG.getConstant(Offsets[i], dl, PtrVT),
4038                             Flags);
4039 
4040     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4041                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4042                             MMOFlags, AAInfo, Ranges);
4043     Chains[ChainI] = L.getValue(1);
4044 
4045     if (MemVTs[i] != ValueVTs[i])
4046       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4047 
4048     Values[i] = L;
4049   }
4050 
4051   if (!ConstantMemory) {
4052     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4053                                 makeArrayRef(Chains.data(), ChainI));
4054     if (isVolatile)
4055       DAG.setRoot(Chain);
4056     else
4057       PendingLoads.push_back(Chain);
4058   }
4059 
4060   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4061                            DAG.getVTList(ValueVTs), Values));
4062 }
4063 
4064 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4065   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4066          "call visitStoreToSwiftError when backend supports swifterror");
4067 
4068   SmallVector<EVT, 4> ValueVTs;
4069   SmallVector<uint64_t, 4> Offsets;
4070   const Value *SrcV = I.getOperand(0);
4071   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4072                   SrcV->getType(), ValueVTs, &Offsets);
4073   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4074          "expect a single EVT for swifterror");
4075 
4076   SDValue Src = getValue(SrcV);
4077   // Create a virtual register, then update the virtual register.
4078   Register VReg =
4079       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4080   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4081   // Chain can be getRoot or getControlRoot.
4082   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4083                                       SDValue(Src.getNode(), Src.getResNo()));
4084   DAG.setRoot(CopyNode);
4085 }
4086 
4087 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4088   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4089          "call visitLoadFromSwiftError when backend supports swifterror");
4090 
4091   assert(!I.isVolatile() &&
4092          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4093          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4094          "Support volatile, non temporal, invariant for load_from_swift_error");
4095 
4096   const Value *SV = I.getOperand(0);
4097   Type *Ty = I.getType();
4098   AAMDNodes AAInfo;
4099   I.getAAMetadata(AAInfo);
4100   assert(
4101       (!AA ||
4102        !AA->pointsToConstantMemory(MemoryLocation(
4103            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4104            AAInfo))) &&
4105       "load_from_swift_error should not be constant memory");
4106 
4107   SmallVector<EVT, 4> ValueVTs;
4108   SmallVector<uint64_t, 4> Offsets;
4109   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4110                   ValueVTs, &Offsets);
4111   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4112          "expect a single EVT for swifterror");
4113 
4114   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4115   SDValue L = DAG.getCopyFromReg(
4116       getRoot(), getCurSDLoc(),
4117       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4118 
4119   setValue(&I, L);
4120 }
4121 
4122 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4123   if (I.isAtomic())
4124     return visitAtomicStore(I);
4125 
4126   const Value *SrcV = I.getOperand(0);
4127   const Value *PtrV = I.getOperand(1);
4128 
4129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4130   if (TLI.supportSwiftError()) {
4131     // Swifterror values can come from either a function parameter with
4132     // swifterror attribute or an alloca with swifterror attribute.
4133     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4134       if (Arg->hasSwiftErrorAttr())
4135         return visitStoreToSwiftError(I);
4136     }
4137 
4138     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4139       if (Alloca->isSwiftError())
4140         return visitStoreToSwiftError(I);
4141     }
4142   }
4143 
4144   SmallVector<EVT, 4> ValueVTs, MemVTs;
4145   SmallVector<uint64_t, 4> Offsets;
4146   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4147                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4148   unsigned NumValues = ValueVTs.size();
4149   if (NumValues == 0)
4150     return;
4151 
4152   // Get the lowered operands. Note that we do this after
4153   // checking if NumResults is zero, because with zero results
4154   // the operands won't have values in the map.
4155   SDValue Src = getValue(SrcV);
4156   SDValue Ptr = getValue(PtrV);
4157 
4158   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4159   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4160   SDLoc dl = getCurSDLoc();
4161   Align Alignment = I.getAlign();
4162   AAMDNodes AAInfo;
4163   I.getAAMetadata(AAInfo);
4164 
4165   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4166 
4167   // An aggregate load cannot wrap around the address space, so offsets to its
4168   // parts don't wrap either.
4169   SDNodeFlags Flags;
4170   Flags.setNoUnsignedWrap(true);
4171 
4172   unsigned ChainI = 0;
4173   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4174     // See visitLoad comments.
4175     if (ChainI == MaxParallelChains) {
4176       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4177                                   makeArrayRef(Chains.data(), ChainI));
4178       Root = Chain;
4179       ChainI = 0;
4180     }
4181     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4182     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4183     if (MemVTs[i] != ValueVTs[i])
4184       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4185     SDValue St =
4186         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4187                      Alignment, MMOFlags, AAInfo);
4188     Chains[ChainI] = St;
4189   }
4190 
4191   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4192                                   makeArrayRef(Chains.data(), ChainI));
4193   DAG.setRoot(StoreNode);
4194 }
4195 
4196 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4197                                            bool IsCompressing) {
4198   SDLoc sdl = getCurSDLoc();
4199 
4200   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4201                                MaybeAlign &Alignment) {
4202     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4203     Src0 = I.getArgOperand(0);
4204     Ptr = I.getArgOperand(1);
4205     Alignment =
4206         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4207     Mask = I.getArgOperand(3);
4208   };
4209   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4210                                     MaybeAlign &Alignment) {
4211     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4212     Src0 = I.getArgOperand(0);
4213     Ptr = I.getArgOperand(1);
4214     Mask = I.getArgOperand(2);
4215     Alignment = None;
4216   };
4217 
4218   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4219   MaybeAlign Alignment;
4220   if (IsCompressing)
4221     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4222   else
4223     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4224 
4225   SDValue Ptr = getValue(PtrOperand);
4226   SDValue Src0 = getValue(Src0Operand);
4227   SDValue Mask = getValue(MaskOperand);
4228   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4229 
4230   EVT VT = Src0.getValueType();
4231   if (!Alignment)
4232     Alignment = DAG.getEVTAlign(VT);
4233 
4234   AAMDNodes AAInfo;
4235   I.getAAMetadata(AAInfo);
4236 
4237   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4238       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4239       // TODO: Make MachineMemOperands aware of scalable
4240       // vectors.
4241       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4242   SDValue StoreNode =
4243       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4244                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4245   DAG.setRoot(StoreNode);
4246   setValue(&I, StoreNode);
4247 }
4248 
4249 // Get a uniform base for the Gather/Scatter intrinsic.
4250 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4251 // We try to represent it as a base pointer + vector of indices.
4252 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4253 // The first operand of the GEP may be a single pointer or a vector of pointers
4254 // Example:
4255 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4256 //  or
4257 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4258 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4259 //
4260 // When the first GEP operand is a single pointer - it is the uniform base we
4261 // are looking for. If first operand of the GEP is a splat vector - we
4262 // extract the splat value and use it as a uniform base.
4263 // In all other cases the function returns 'false'.
4264 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4265                            ISD::MemIndexType &IndexType, SDValue &Scale,
4266                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4267   SelectionDAG& DAG = SDB->DAG;
4268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4269   const DataLayout &DL = DAG.getDataLayout();
4270 
4271   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4272 
4273   // Handle splat constant pointer.
4274   if (auto *C = dyn_cast<Constant>(Ptr)) {
4275     C = C->getSplatValue();
4276     if (!C)
4277       return false;
4278 
4279     Base = SDB->getValue(C);
4280 
4281     unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements();
4282     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4283     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4284     IndexType = ISD::SIGNED_SCALED;
4285     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4286     return true;
4287   }
4288 
4289   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4290   if (!GEP || GEP->getParent() != CurBB)
4291     return false;
4292 
4293   if (GEP->getNumOperands() != 2)
4294     return false;
4295 
4296   const Value *BasePtr = GEP->getPointerOperand();
4297   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4298 
4299   // Make sure the base is scalar and the index is a vector.
4300   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4301     return false;
4302 
4303   Base = SDB->getValue(BasePtr);
4304   Index = SDB->getValue(IndexVal);
4305   IndexType = ISD::SIGNED_SCALED;
4306   Scale = DAG.getTargetConstant(
4307               DL.getTypeAllocSize(GEP->getResultElementType()),
4308               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4309   return true;
4310 }
4311 
4312 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4313   SDLoc sdl = getCurSDLoc();
4314 
4315   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4316   const Value *Ptr = I.getArgOperand(1);
4317   SDValue Src0 = getValue(I.getArgOperand(0));
4318   SDValue Mask = getValue(I.getArgOperand(3));
4319   EVT VT = Src0.getValueType();
4320   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4321   if (!Alignment)
4322     Alignment = DAG.getEVTAlign(VT);
4323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4324 
4325   AAMDNodes AAInfo;
4326   I.getAAMetadata(AAInfo);
4327 
4328   SDValue Base;
4329   SDValue Index;
4330   ISD::MemIndexType IndexType;
4331   SDValue Scale;
4332   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4333                                     I.getParent());
4334 
4335   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4336   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4337       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4338       // TODO: Make MachineMemOperands aware of scalable
4339       // vectors.
4340       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4341   if (!UniformBase) {
4342     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4343     Index = getValue(Ptr);
4344     IndexType = ISD::SIGNED_SCALED;
4345     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4346   }
4347   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4348   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4349                                          Ops, MMO, IndexType);
4350   DAG.setRoot(Scatter);
4351   setValue(&I, Scatter);
4352 }
4353 
4354 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4355   SDLoc sdl = getCurSDLoc();
4356 
4357   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4358                               MaybeAlign &Alignment) {
4359     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4360     Ptr = I.getArgOperand(0);
4361     Alignment =
4362         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4363     Mask = I.getArgOperand(2);
4364     Src0 = I.getArgOperand(3);
4365   };
4366   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4367                                  MaybeAlign &Alignment) {
4368     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4369     Ptr = I.getArgOperand(0);
4370     Alignment = None;
4371     Mask = I.getArgOperand(1);
4372     Src0 = I.getArgOperand(2);
4373   };
4374 
4375   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4376   MaybeAlign Alignment;
4377   if (IsExpanding)
4378     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4379   else
4380     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4381 
4382   SDValue Ptr = getValue(PtrOperand);
4383   SDValue Src0 = getValue(Src0Operand);
4384   SDValue Mask = getValue(MaskOperand);
4385   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4386 
4387   EVT VT = Src0.getValueType();
4388   if (!Alignment)
4389     Alignment = DAG.getEVTAlign(VT);
4390 
4391   AAMDNodes AAInfo;
4392   I.getAAMetadata(AAInfo);
4393   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4394 
4395   // Do not serialize masked loads of constant memory with anything.
4396   MemoryLocation ML;
4397   if (VT.isScalableVector())
4398     ML = MemoryLocation(PtrOperand);
4399   else
4400     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4401                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4402                            AAInfo);
4403   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4404 
4405   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4406 
4407   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4408       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4409       // TODO: Make MachineMemOperands aware of scalable
4410       // vectors.
4411       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4412 
4413   SDValue Load =
4414       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4415                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4416   if (AddToChain)
4417     PendingLoads.push_back(Load.getValue(1));
4418   setValue(&I, Load);
4419 }
4420 
4421 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4422   SDLoc sdl = getCurSDLoc();
4423 
4424   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4425   const Value *Ptr = I.getArgOperand(0);
4426   SDValue Src0 = getValue(I.getArgOperand(3));
4427   SDValue Mask = getValue(I.getArgOperand(2));
4428 
4429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4430   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4431   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4432   if (!Alignment)
4433     Alignment = DAG.getEVTAlign(VT);
4434 
4435   AAMDNodes AAInfo;
4436   I.getAAMetadata(AAInfo);
4437   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4438 
4439   SDValue Root = DAG.getRoot();
4440   SDValue Base;
4441   SDValue Index;
4442   ISD::MemIndexType IndexType;
4443   SDValue Scale;
4444   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4445                                     I.getParent());
4446   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4447   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4448       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4449       // TODO: Make MachineMemOperands aware of scalable
4450       // vectors.
4451       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4452 
4453   if (!UniformBase) {
4454     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4455     Index = getValue(Ptr);
4456     IndexType = ISD::SIGNED_SCALED;
4457     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4458   }
4459   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4460   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4461                                        Ops, MMO, IndexType);
4462 
4463   PendingLoads.push_back(Gather.getValue(1));
4464   setValue(&I, Gather);
4465 }
4466 
4467 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4468   SDLoc dl = getCurSDLoc();
4469   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4470   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4471   SyncScope::ID SSID = I.getSyncScopeID();
4472 
4473   SDValue InChain = getRoot();
4474 
4475   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4476   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4477 
4478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4479   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4480 
4481   MachineFunction &MF = DAG.getMachineFunction();
4482   MachineMemOperand *MMO = MF.getMachineMemOperand(
4483       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4484       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4485       FailureOrdering);
4486 
4487   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4488                                    dl, MemVT, VTs, InChain,
4489                                    getValue(I.getPointerOperand()),
4490                                    getValue(I.getCompareOperand()),
4491                                    getValue(I.getNewValOperand()), MMO);
4492 
4493   SDValue OutChain = L.getValue(2);
4494 
4495   setValue(&I, L);
4496   DAG.setRoot(OutChain);
4497 }
4498 
4499 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4500   SDLoc dl = getCurSDLoc();
4501   ISD::NodeType NT;
4502   switch (I.getOperation()) {
4503   default: llvm_unreachable("Unknown atomicrmw operation");
4504   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4505   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4506   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4507   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4508   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4509   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4510   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4511   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4512   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4513   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4514   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4515   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4516   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4517   }
4518   AtomicOrdering Ordering = I.getOrdering();
4519   SyncScope::ID SSID = I.getSyncScopeID();
4520 
4521   SDValue InChain = getRoot();
4522 
4523   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4525   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4526 
4527   MachineFunction &MF = DAG.getMachineFunction();
4528   MachineMemOperand *MMO = MF.getMachineMemOperand(
4529       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4530       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4531 
4532   SDValue L =
4533     DAG.getAtomic(NT, dl, MemVT, InChain,
4534                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4535                   MMO);
4536 
4537   SDValue OutChain = L.getValue(1);
4538 
4539   setValue(&I, L);
4540   DAG.setRoot(OutChain);
4541 }
4542 
4543 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4544   SDLoc dl = getCurSDLoc();
4545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4546   SDValue Ops[3];
4547   Ops[0] = getRoot();
4548   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4549                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4550   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4551                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4552   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4553 }
4554 
4555 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4556   SDLoc dl = getCurSDLoc();
4557   AtomicOrdering Order = I.getOrdering();
4558   SyncScope::ID SSID = I.getSyncScopeID();
4559 
4560   SDValue InChain = getRoot();
4561 
4562   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4563   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4564   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4565 
4566   if (!TLI.supportsUnalignedAtomics() &&
4567       I.getAlignment() < MemVT.getSizeInBits() / 8)
4568     report_fatal_error("Cannot generate unaligned atomic load");
4569 
4570   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4571 
4572   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4573       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4574       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4575 
4576   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4577 
4578   SDValue Ptr = getValue(I.getPointerOperand());
4579 
4580   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4581     // TODO: Once this is better exercised by tests, it should be merged with
4582     // the normal path for loads to prevent future divergence.
4583     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4584     if (MemVT != VT)
4585       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4586 
4587     setValue(&I, L);
4588     SDValue OutChain = L.getValue(1);
4589     if (!I.isUnordered())
4590       DAG.setRoot(OutChain);
4591     else
4592       PendingLoads.push_back(OutChain);
4593     return;
4594   }
4595 
4596   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4597                             Ptr, MMO);
4598 
4599   SDValue OutChain = L.getValue(1);
4600   if (MemVT != VT)
4601     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4602 
4603   setValue(&I, L);
4604   DAG.setRoot(OutChain);
4605 }
4606 
4607 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4608   SDLoc dl = getCurSDLoc();
4609 
4610   AtomicOrdering Ordering = I.getOrdering();
4611   SyncScope::ID SSID = I.getSyncScopeID();
4612 
4613   SDValue InChain = getRoot();
4614 
4615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4616   EVT MemVT =
4617       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4618 
4619   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4620     report_fatal_error("Cannot generate unaligned atomic store");
4621 
4622   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4623 
4624   MachineFunction &MF = DAG.getMachineFunction();
4625   MachineMemOperand *MMO = MF.getMachineMemOperand(
4626       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4627       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4628 
4629   SDValue Val = getValue(I.getValueOperand());
4630   if (Val.getValueType() != MemVT)
4631     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4632   SDValue Ptr = getValue(I.getPointerOperand());
4633 
4634   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4635     // TODO: Once this is better exercised by tests, it should be merged with
4636     // the normal path for stores to prevent future divergence.
4637     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4638     DAG.setRoot(S);
4639     return;
4640   }
4641   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4642                                    Ptr, Val, MMO);
4643 
4644 
4645   DAG.setRoot(OutChain);
4646 }
4647 
4648 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4649 /// node.
4650 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4651                                                unsigned Intrinsic) {
4652   // Ignore the callsite's attributes. A specific call site may be marked with
4653   // readnone, but the lowering code will expect the chain based on the
4654   // definition.
4655   const Function *F = I.getCalledFunction();
4656   bool HasChain = !F->doesNotAccessMemory();
4657   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4658 
4659   // Build the operand list.
4660   SmallVector<SDValue, 8> Ops;
4661   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4662     if (OnlyLoad) {
4663       // We don't need to serialize loads against other loads.
4664       Ops.push_back(DAG.getRoot());
4665     } else {
4666       Ops.push_back(getRoot());
4667     }
4668   }
4669 
4670   // Info is set by getTgtMemInstrinsic
4671   TargetLowering::IntrinsicInfo Info;
4672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4673   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4674                                                DAG.getMachineFunction(),
4675                                                Intrinsic);
4676 
4677   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4678   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4679       Info.opc == ISD::INTRINSIC_W_CHAIN)
4680     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4681                                         TLI.getPointerTy(DAG.getDataLayout())));
4682 
4683   // Add all operands of the call to the operand list.
4684   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4685     const Value *Arg = I.getArgOperand(i);
4686     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4687       Ops.push_back(getValue(Arg));
4688       continue;
4689     }
4690 
4691     // Use TargetConstant instead of a regular constant for immarg.
4692     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4693     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4694       assert(CI->getBitWidth() <= 64 &&
4695              "large intrinsic immediates not handled");
4696       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4697     } else {
4698       Ops.push_back(
4699           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4700     }
4701   }
4702 
4703   SmallVector<EVT, 4> ValueVTs;
4704   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4705 
4706   if (HasChain)
4707     ValueVTs.push_back(MVT::Other);
4708 
4709   SDVTList VTs = DAG.getVTList(ValueVTs);
4710 
4711   // Create the node.
4712   SDValue Result;
4713   if (IsTgtIntrinsic) {
4714     // This is target intrinsic that touches memory
4715     AAMDNodes AAInfo;
4716     I.getAAMetadata(AAInfo);
4717     Result =
4718         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4719                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4720                                 Info.align, Info.flags, Info.size, AAInfo);
4721   } else if (!HasChain) {
4722     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4723   } else if (!I.getType()->isVoidTy()) {
4724     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4725   } else {
4726     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4727   }
4728 
4729   if (HasChain) {
4730     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4731     if (OnlyLoad)
4732       PendingLoads.push_back(Chain);
4733     else
4734       DAG.setRoot(Chain);
4735   }
4736 
4737   if (!I.getType()->isVoidTy()) {
4738     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4739       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4740       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4741     } else
4742       Result = lowerRangeToAssertZExt(DAG, I, Result);
4743 
4744     MaybeAlign Alignment = I.getRetAlign();
4745     if (!Alignment)
4746       Alignment = F->getAttributes().getRetAlignment();
4747     // Insert `assertalign` node if there's an alignment.
4748     if (InsertAssertAlign && Alignment) {
4749       Result =
4750           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4751     }
4752 
4753     setValue(&I, Result);
4754   }
4755 }
4756 
4757 /// GetSignificand - Get the significand and build it into a floating-point
4758 /// number with exponent of 1:
4759 ///
4760 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4761 ///
4762 /// where Op is the hexadecimal representation of floating point value.
4763 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4764   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4765                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4766   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4767                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4768   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4769 }
4770 
4771 /// GetExponent - Get the exponent:
4772 ///
4773 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4774 ///
4775 /// where Op is the hexadecimal representation of floating point value.
4776 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4777                            const TargetLowering &TLI, const SDLoc &dl) {
4778   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4779                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4780   SDValue t1 = DAG.getNode(
4781       ISD::SRL, dl, MVT::i32, t0,
4782       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4783   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4784                            DAG.getConstant(127, dl, MVT::i32));
4785   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4786 }
4787 
4788 /// getF32Constant - Get 32-bit floating point constant.
4789 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4790                               const SDLoc &dl) {
4791   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4792                            MVT::f32);
4793 }
4794 
4795 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4796                                        SelectionDAG &DAG) {
4797   // TODO: What fast-math-flags should be set on the floating-point nodes?
4798 
4799   //   IntegerPartOfX = ((int32_t)(t0);
4800   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4801 
4802   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4803   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4804   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4805 
4806   //   IntegerPartOfX <<= 23;
4807   IntegerPartOfX = DAG.getNode(
4808       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4809       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4810                                   DAG.getDataLayout())));
4811 
4812   SDValue TwoToFractionalPartOfX;
4813   if (LimitFloatPrecision <= 6) {
4814     // For floating-point precision of 6:
4815     //
4816     //   TwoToFractionalPartOfX =
4817     //     0.997535578f +
4818     //       (0.735607626f + 0.252464424f * x) * x;
4819     //
4820     // error 0.0144103317, which is 6 bits
4821     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4822                              getF32Constant(DAG, 0x3e814304, dl));
4823     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4824                              getF32Constant(DAG, 0x3f3c50c8, dl));
4825     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4826     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4827                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4828   } else if (LimitFloatPrecision <= 12) {
4829     // For floating-point precision of 12:
4830     //
4831     //   TwoToFractionalPartOfX =
4832     //     0.999892986f +
4833     //       (0.696457318f +
4834     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4835     //
4836     // error 0.000107046256, which is 13 to 14 bits
4837     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4838                              getF32Constant(DAG, 0x3da235e3, dl));
4839     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4840                              getF32Constant(DAG, 0x3e65b8f3, dl));
4841     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4842     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4843                              getF32Constant(DAG, 0x3f324b07, dl));
4844     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4845     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4846                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4847   } else { // LimitFloatPrecision <= 18
4848     // For floating-point precision of 18:
4849     //
4850     //   TwoToFractionalPartOfX =
4851     //     0.999999982f +
4852     //       (0.693148872f +
4853     //         (0.240227044f +
4854     //           (0.554906021e-1f +
4855     //             (0.961591928e-2f +
4856     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4857     // error 2.47208000*10^(-7), which is better than 18 bits
4858     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4859                              getF32Constant(DAG, 0x3924b03e, dl));
4860     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4861                              getF32Constant(DAG, 0x3ab24b87, dl));
4862     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4863     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4864                              getF32Constant(DAG, 0x3c1d8c17, dl));
4865     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4866     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4867                              getF32Constant(DAG, 0x3d634a1d, dl));
4868     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4869     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4870                              getF32Constant(DAG, 0x3e75fe14, dl));
4871     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4872     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4873                               getF32Constant(DAG, 0x3f317234, dl));
4874     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4875     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4876                                          getF32Constant(DAG, 0x3f800000, dl));
4877   }
4878 
4879   // Add the exponent into the result in integer domain.
4880   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4881   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4882                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4883 }
4884 
4885 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4886 /// limited-precision mode.
4887 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4888                          const TargetLowering &TLI) {
4889   if (Op.getValueType() == MVT::f32 &&
4890       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4891 
4892     // Put the exponent in the right bit position for later addition to the
4893     // final result:
4894     //
4895     // t0 = Op * log2(e)
4896 
4897     // TODO: What fast-math-flags should be set here?
4898     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4899                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4900     return getLimitedPrecisionExp2(t0, dl, DAG);
4901   }
4902 
4903   // No special expansion.
4904   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4905 }
4906 
4907 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4908 /// limited-precision mode.
4909 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4910                          const TargetLowering &TLI) {
4911   // TODO: What fast-math-flags should be set on the floating-point nodes?
4912 
4913   if (Op.getValueType() == MVT::f32 &&
4914       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4915     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4916 
4917     // Scale the exponent by log(2).
4918     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4919     SDValue LogOfExponent =
4920         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4921                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4922 
4923     // Get the significand and build it into a floating-point number with
4924     // exponent of 1.
4925     SDValue X = GetSignificand(DAG, Op1, dl);
4926 
4927     SDValue LogOfMantissa;
4928     if (LimitFloatPrecision <= 6) {
4929       // For floating-point precision of 6:
4930       //
4931       //   LogofMantissa =
4932       //     -1.1609546f +
4933       //       (1.4034025f - 0.23903021f * x) * x;
4934       //
4935       // error 0.0034276066, which is better than 8 bits
4936       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4937                                getF32Constant(DAG, 0xbe74c456, dl));
4938       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4939                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4940       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4941       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4942                                   getF32Constant(DAG, 0x3f949a29, dl));
4943     } else if (LimitFloatPrecision <= 12) {
4944       // For floating-point precision of 12:
4945       //
4946       //   LogOfMantissa =
4947       //     -1.7417939f +
4948       //       (2.8212026f +
4949       //         (-1.4699568f +
4950       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4951       //
4952       // error 0.000061011436, which is 14 bits
4953       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4954                                getF32Constant(DAG, 0xbd67b6d6, dl));
4955       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4956                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4957       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4958       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4959                                getF32Constant(DAG, 0x3fbc278b, dl));
4960       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4961       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4962                                getF32Constant(DAG, 0x40348e95, dl));
4963       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4964       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4965                                   getF32Constant(DAG, 0x3fdef31a, dl));
4966     } else { // LimitFloatPrecision <= 18
4967       // For floating-point precision of 18:
4968       //
4969       //   LogOfMantissa =
4970       //     -2.1072184f +
4971       //       (4.2372794f +
4972       //         (-3.7029485f +
4973       //           (2.2781945f +
4974       //             (-0.87823314f +
4975       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4976       //
4977       // error 0.0000023660568, which is better than 18 bits
4978       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4979                                getF32Constant(DAG, 0xbc91e5ac, dl));
4980       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4981                                getF32Constant(DAG, 0x3e4350aa, dl));
4982       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4983       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4984                                getF32Constant(DAG, 0x3f60d3e3, dl));
4985       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4986       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4987                                getF32Constant(DAG, 0x4011cdf0, dl));
4988       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4989       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4990                                getF32Constant(DAG, 0x406cfd1c, dl));
4991       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4992       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4993                                getF32Constant(DAG, 0x408797cb, dl));
4994       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4995       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4996                                   getF32Constant(DAG, 0x4006dcab, dl));
4997     }
4998 
4999     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5000   }
5001 
5002   // No special expansion.
5003   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5004 }
5005 
5006 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5007 /// limited-precision mode.
5008 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5009                           const TargetLowering &TLI) {
5010   // TODO: What fast-math-flags should be set on the floating-point nodes?
5011 
5012   if (Op.getValueType() == MVT::f32 &&
5013       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5014     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5015 
5016     // Get the exponent.
5017     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5018 
5019     // Get the significand and build it into a floating-point number with
5020     // exponent of 1.
5021     SDValue X = GetSignificand(DAG, Op1, dl);
5022 
5023     // Different possible minimax approximations of significand in
5024     // floating-point for various degrees of accuracy over [1,2].
5025     SDValue Log2ofMantissa;
5026     if (LimitFloatPrecision <= 6) {
5027       // For floating-point precision of 6:
5028       //
5029       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5030       //
5031       // error 0.0049451742, which is more than 7 bits
5032       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5033                                getF32Constant(DAG, 0xbeb08fe0, dl));
5034       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5035                                getF32Constant(DAG, 0x40019463, dl));
5036       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5037       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5038                                    getF32Constant(DAG, 0x3fd6633d, dl));
5039     } else if (LimitFloatPrecision <= 12) {
5040       // For floating-point precision of 12:
5041       //
5042       //   Log2ofMantissa =
5043       //     -2.51285454f +
5044       //       (4.07009056f +
5045       //         (-2.12067489f +
5046       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5047       //
5048       // error 0.0000876136000, which is better than 13 bits
5049       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5050                                getF32Constant(DAG, 0xbda7262e, dl));
5051       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5052                                getF32Constant(DAG, 0x3f25280b, dl));
5053       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5054       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5055                                getF32Constant(DAG, 0x4007b923, dl));
5056       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5057       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5058                                getF32Constant(DAG, 0x40823e2f, dl));
5059       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5060       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5061                                    getF32Constant(DAG, 0x4020d29c, dl));
5062     } else { // LimitFloatPrecision <= 18
5063       // For floating-point precision of 18:
5064       //
5065       //   Log2ofMantissa =
5066       //     -3.0400495f +
5067       //       (6.1129976f +
5068       //         (-5.3420409f +
5069       //           (3.2865683f +
5070       //             (-1.2669343f +
5071       //               (0.27515199f -
5072       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5073       //
5074       // error 0.0000018516, which is better than 18 bits
5075       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5076                                getF32Constant(DAG, 0xbcd2769e, dl));
5077       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5078                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5079       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5080       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5081                                getF32Constant(DAG, 0x3fa22ae7, dl));
5082       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5083       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5084                                getF32Constant(DAG, 0x40525723, dl));
5085       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5086       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5087                                getF32Constant(DAG, 0x40aaf200, dl));
5088       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5089       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5090                                getF32Constant(DAG, 0x40c39dad, dl));
5091       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5092       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5093                                    getF32Constant(DAG, 0x4042902c, dl));
5094     }
5095 
5096     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5097   }
5098 
5099   // No special expansion.
5100   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5101 }
5102 
5103 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5104 /// limited-precision mode.
5105 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5106                            const TargetLowering &TLI) {
5107   // TODO: What fast-math-flags should be set on the floating-point nodes?
5108 
5109   if (Op.getValueType() == MVT::f32 &&
5110       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5111     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5112 
5113     // Scale the exponent by log10(2) [0.30102999f].
5114     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5115     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5116                                         getF32Constant(DAG, 0x3e9a209a, dl));
5117 
5118     // Get the significand and build it into a floating-point number with
5119     // exponent of 1.
5120     SDValue X = GetSignificand(DAG, Op1, dl);
5121 
5122     SDValue Log10ofMantissa;
5123     if (LimitFloatPrecision <= 6) {
5124       // For floating-point precision of 6:
5125       //
5126       //   Log10ofMantissa =
5127       //     -0.50419619f +
5128       //       (0.60948995f - 0.10380950f * x) * x;
5129       //
5130       // error 0.0014886165, which is 6 bits
5131       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5132                                getF32Constant(DAG, 0xbdd49a13, dl));
5133       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5134                                getF32Constant(DAG, 0x3f1c0789, dl));
5135       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5136       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5137                                     getF32Constant(DAG, 0x3f011300, dl));
5138     } else if (LimitFloatPrecision <= 12) {
5139       // For floating-point precision of 12:
5140       //
5141       //   Log10ofMantissa =
5142       //     -0.64831180f +
5143       //       (0.91751397f +
5144       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5145       //
5146       // error 0.00019228036, which is better than 12 bits
5147       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5148                                getF32Constant(DAG, 0x3d431f31, dl));
5149       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5150                                getF32Constant(DAG, 0x3ea21fb2, dl));
5151       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5152       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5153                                getF32Constant(DAG, 0x3f6ae232, dl));
5154       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5155       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5156                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5157     } else { // LimitFloatPrecision <= 18
5158       // For floating-point precision of 18:
5159       //
5160       //   Log10ofMantissa =
5161       //     -0.84299375f +
5162       //       (1.5327582f +
5163       //         (-1.0688956f +
5164       //           (0.49102474f +
5165       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5166       //
5167       // error 0.0000037995730, which is better than 18 bits
5168       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5169                                getF32Constant(DAG, 0x3c5d51ce, dl));
5170       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5171                                getF32Constant(DAG, 0x3e00685a, dl));
5172       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5173       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5174                                getF32Constant(DAG, 0x3efb6798, dl));
5175       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5176       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5177                                getF32Constant(DAG, 0x3f88d192, dl));
5178       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5179       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5180                                getF32Constant(DAG, 0x3fc4316c, dl));
5181       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5182       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5183                                     getF32Constant(DAG, 0x3f57ce70, dl));
5184     }
5185 
5186     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5187   }
5188 
5189   // No special expansion.
5190   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5191 }
5192 
5193 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5194 /// limited-precision mode.
5195 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5196                           const TargetLowering &TLI) {
5197   if (Op.getValueType() == MVT::f32 &&
5198       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5199     return getLimitedPrecisionExp2(Op, dl, DAG);
5200 
5201   // No special expansion.
5202   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5203 }
5204 
5205 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5206 /// limited-precision mode with x == 10.0f.
5207 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5208                          SelectionDAG &DAG, const TargetLowering &TLI) {
5209   bool IsExp10 = false;
5210   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5211       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5212     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5213       APFloat Ten(10.0f);
5214       IsExp10 = LHSC->isExactlyValue(Ten);
5215     }
5216   }
5217 
5218   // TODO: What fast-math-flags should be set on the FMUL node?
5219   if (IsExp10) {
5220     // Put the exponent in the right bit position for later addition to the
5221     // final result:
5222     //
5223     //   #define LOG2OF10 3.3219281f
5224     //   t0 = Op * LOG2OF10;
5225     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5226                              getF32Constant(DAG, 0x40549a78, dl));
5227     return getLimitedPrecisionExp2(t0, dl, DAG);
5228   }
5229 
5230   // No special expansion.
5231   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5232 }
5233 
5234 /// ExpandPowI - Expand a llvm.powi intrinsic.
5235 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5236                           SelectionDAG &DAG) {
5237   // If RHS is a constant, we can expand this out to a multiplication tree,
5238   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5239   // optimizing for size, we only want to do this if the expansion would produce
5240   // a small number of multiplies, otherwise we do the full expansion.
5241   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5242     // Get the exponent as a positive value.
5243     unsigned Val = RHSC->getSExtValue();
5244     if ((int)Val < 0) Val = -Val;
5245 
5246     // powi(x, 0) -> 1.0
5247     if (Val == 0)
5248       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5249 
5250     bool OptForSize = DAG.shouldOptForSize();
5251     if (!OptForSize ||
5252         // If optimizing for size, don't insert too many multiplies.
5253         // This inserts up to 5 multiplies.
5254         countPopulation(Val) + Log2_32(Val) < 7) {
5255       // We use the simple binary decomposition method to generate the multiply
5256       // sequence.  There are more optimal ways to do this (for example,
5257       // powi(x,15) generates one more multiply than it should), but this has
5258       // the benefit of being both really simple and much better than a libcall.
5259       SDValue Res;  // Logically starts equal to 1.0
5260       SDValue CurSquare = LHS;
5261       // TODO: Intrinsics should have fast-math-flags that propagate to these
5262       // nodes.
5263       while (Val) {
5264         if (Val & 1) {
5265           if (Res.getNode())
5266             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5267           else
5268             Res = CurSquare;  // 1.0*CurSquare.
5269         }
5270 
5271         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5272                                 CurSquare, CurSquare);
5273         Val >>= 1;
5274       }
5275 
5276       // If the original was negative, invert the result, producing 1/(x*x*x).
5277       if (RHSC->getSExtValue() < 0)
5278         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5279                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5280       return Res;
5281     }
5282   }
5283 
5284   // Otherwise, expand to a libcall.
5285   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5286 }
5287 
5288 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5289                             SDValue LHS, SDValue RHS, SDValue Scale,
5290                             SelectionDAG &DAG, const TargetLowering &TLI) {
5291   EVT VT = LHS.getValueType();
5292   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5293   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5294   LLVMContext &Ctx = *DAG.getContext();
5295 
5296   // If the type is legal but the operation isn't, this node might survive all
5297   // the way to operation legalization. If we end up there and we do not have
5298   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5299   // node.
5300 
5301   // Coax the legalizer into expanding the node during type legalization instead
5302   // by bumping the size by one bit. This will force it to Promote, enabling the
5303   // early expansion and avoiding the need to expand later.
5304 
5305   // We don't have to do this if Scale is 0; that can always be expanded, unless
5306   // it's a saturating signed operation. Those can experience true integer
5307   // division overflow, a case which we must avoid.
5308 
5309   // FIXME: We wouldn't have to do this (or any of the early
5310   // expansion/promotion) if it was possible to expand a libcall of an
5311   // illegal type during operation legalization. But it's not, so things
5312   // get a bit hacky.
5313   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5314   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5315       (TLI.isTypeLegal(VT) ||
5316        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5317     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5318         Opcode, VT, ScaleInt);
5319     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5320       EVT PromVT;
5321       if (VT.isScalarInteger())
5322         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5323       else if (VT.isVector()) {
5324         PromVT = VT.getVectorElementType();
5325         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5326         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5327       } else
5328         llvm_unreachable("Wrong VT for DIVFIX?");
5329       if (Signed) {
5330         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5331         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5332       } else {
5333         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5334         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5335       }
5336       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5337       // For saturating operations, we need to shift up the LHS to get the
5338       // proper saturation width, and then shift down again afterwards.
5339       if (Saturating)
5340         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5341                           DAG.getConstant(1, DL, ShiftTy));
5342       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5343       if (Saturating)
5344         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5345                           DAG.getConstant(1, DL, ShiftTy));
5346       return DAG.getZExtOrTrunc(Res, DL, VT);
5347     }
5348   }
5349 
5350   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5351 }
5352 
5353 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5354 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5355 static void
5356 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5357                      const SDValue &N) {
5358   switch (N.getOpcode()) {
5359   case ISD::CopyFromReg: {
5360     SDValue Op = N.getOperand(1);
5361     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5362                       Op.getValueType().getSizeInBits());
5363     return;
5364   }
5365   case ISD::BITCAST:
5366   case ISD::AssertZext:
5367   case ISD::AssertSext:
5368   case ISD::TRUNCATE:
5369     getUnderlyingArgRegs(Regs, N.getOperand(0));
5370     return;
5371   case ISD::BUILD_PAIR:
5372   case ISD::BUILD_VECTOR:
5373   case ISD::CONCAT_VECTORS:
5374     for (SDValue Op : N->op_values())
5375       getUnderlyingArgRegs(Regs, Op);
5376     return;
5377   default:
5378     return;
5379   }
5380 }
5381 
5382 /// If the DbgValueInst is a dbg_value of a function argument, create the
5383 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5384 /// instruction selection, they will be inserted to the entry BB.
5385 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5386     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5387     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5388   const Argument *Arg = dyn_cast<Argument>(V);
5389   if (!Arg)
5390     return false;
5391 
5392   if (!IsDbgDeclare) {
5393     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5394     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5395     // the entry block.
5396     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5397     if (!IsInEntryBlock)
5398       return false;
5399 
5400     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5401     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5402     // variable that also is a param.
5403     //
5404     // Although, if we are at the top of the entry block already, we can still
5405     // emit using ArgDbgValue. This might catch some situations when the
5406     // dbg.value refers to an argument that isn't used in the entry block, so
5407     // any CopyToReg node would be optimized out and the only way to express
5408     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5409     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5410     // we should only emit as ArgDbgValue if the Variable is an argument to the
5411     // current function, and the dbg.value intrinsic is found in the entry
5412     // block.
5413     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5414         !DL->getInlinedAt();
5415     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5416     if (!IsInPrologue && !VariableIsFunctionInputArg)
5417       return false;
5418 
5419     // Here we assume that a function argument on IR level only can be used to
5420     // describe one input parameter on source level. If we for example have
5421     // source code like this
5422     //
5423     //    struct A { long x, y; };
5424     //    void foo(struct A a, long b) {
5425     //      ...
5426     //      b = a.x;
5427     //      ...
5428     //    }
5429     //
5430     // and IR like this
5431     //
5432     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5433     //  entry:
5434     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5435     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5436     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5437     //    ...
5438     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5439     //    ...
5440     //
5441     // then the last dbg.value is describing a parameter "b" using a value that
5442     // is an argument. But since we already has used %a1 to describe a parameter
5443     // we should not handle that last dbg.value here (that would result in an
5444     // incorrect hoisting of the DBG_VALUE to the function entry).
5445     // Notice that we allow one dbg.value per IR level argument, to accommodate
5446     // for the situation with fragments above.
5447     if (VariableIsFunctionInputArg) {
5448       unsigned ArgNo = Arg->getArgNo();
5449       if (ArgNo >= FuncInfo.DescribedArgs.size())
5450         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5451       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5452         return false;
5453       FuncInfo.DescribedArgs.set(ArgNo);
5454     }
5455   }
5456 
5457   MachineFunction &MF = DAG.getMachineFunction();
5458   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5459 
5460   bool IsIndirect = false;
5461   Optional<MachineOperand> Op;
5462   // Some arguments' frame index is recorded during argument lowering.
5463   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5464   if (FI != std::numeric_limits<int>::max())
5465     Op = MachineOperand::CreateFI(FI);
5466 
5467   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5468   if (!Op && N.getNode()) {
5469     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5470     Register Reg;
5471     if (ArgRegsAndSizes.size() == 1)
5472       Reg = ArgRegsAndSizes.front().first;
5473 
5474     if (Reg && Reg.isVirtual()) {
5475       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5476       Register PR = RegInfo.getLiveInPhysReg(Reg);
5477       if (PR)
5478         Reg = PR;
5479     }
5480     if (Reg) {
5481       Op = MachineOperand::CreateReg(Reg, false);
5482       IsIndirect = IsDbgDeclare;
5483     }
5484   }
5485 
5486   if (!Op && N.getNode()) {
5487     // Check if frame index is available.
5488     SDValue LCandidate = peekThroughBitcasts(N);
5489     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5490       if (FrameIndexSDNode *FINode =
5491           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5492         Op = MachineOperand::CreateFI(FINode->getIndex());
5493   }
5494 
5495   if (!Op) {
5496     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5497     auto splitMultiRegDbgValue
5498       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5499       unsigned Offset = 0;
5500       for (auto RegAndSize : SplitRegs) {
5501         // If the expression is already a fragment, the current register
5502         // offset+size might extend beyond the fragment. In this case, only
5503         // the register bits that are inside the fragment are relevant.
5504         int RegFragmentSizeInBits = RegAndSize.second;
5505         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5506           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5507           // The register is entirely outside the expression fragment,
5508           // so is irrelevant for debug info.
5509           if (Offset >= ExprFragmentSizeInBits)
5510             break;
5511           // The register is partially outside the expression fragment, only
5512           // the low bits within the fragment are relevant for debug info.
5513           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5514             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5515           }
5516         }
5517 
5518         auto FragmentExpr = DIExpression::createFragmentExpression(
5519             Expr, Offset, RegFragmentSizeInBits);
5520         Offset += RegAndSize.second;
5521         // If a valid fragment expression cannot be created, the variable's
5522         // correct value cannot be determined and so it is set as Undef.
5523         if (!FragmentExpr) {
5524           SDDbgValue *SDV = DAG.getConstantDbgValue(
5525               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5526           DAG.AddDbgValue(SDV, nullptr, false);
5527           continue;
5528         }
5529         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5530         FuncInfo.ArgDbgValues.push_back(
5531           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5532                   RegAndSize.first, Variable, *FragmentExpr));
5533       }
5534     };
5535 
5536     // Check if ValueMap has reg number.
5537     DenseMap<const Value *, Register>::const_iterator
5538       VMI = FuncInfo.ValueMap.find(V);
5539     if (VMI != FuncInfo.ValueMap.end()) {
5540       const auto &TLI = DAG.getTargetLoweringInfo();
5541       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5542                        V->getType(), getABIRegCopyCC(V));
5543       if (RFV.occupiesMultipleRegs()) {
5544         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5545         return true;
5546       }
5547 
5548       Op = MachineOperand::CreateReg(VMI->second, false);
5549       IsIndirect = IsDbgDeclare;
5550     } else if (ArgRegsAndSizes.size() > 1) {
5551       // This was split due to the calling convention, and no virtual register
5552       // mapping exists for the value.
5553       splitMultiRegDbgValue(ArgRegsAndSizes);
5554       return true;
5555     }
5556   }
5557 
5558   if (!Op)
5559     return false;
5560 
5561   assert(Variable->isValidLocationForIntrinsic(DL) &&
5562          "Expected inlined-at fields to agree");
5563   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5564   FuncInfo.ArgDbgValues.push_back(
5565       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5566               *Op, Variable, Expr));
5567 
5568   return true;
5569 }
5570 
5571 /// Return the appropriate SDDbgValue based on N.
5572 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5573                                              DILocalVariable *Variable,
5574                                              DIExpression *Expr,
5575                                              const DebugLoc &dl,
5576                                              unsigned DbgSDNodeOrder) {
5577   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5578     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5579     // stack slot locations.
5580     //
5581     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5582     // debug values here after optimization:
5583     //
5584     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5585     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5586     //
5587     // Both describe the direct values of their associated variables.
5588     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5589                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5590   }
5591   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5592                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5593 }
5594 
5595 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5596   switch (Intrinsic) {
5597   case Intrinsic::smul_fix:
5598     return ISD::SMULFIX;
5599   case Intrinsic::umul_fix:
5600     return ISD::UMULFIX;
5601   case Intrinsic::smul_fix_sat:
5602     return ISD::SMULFIXSAT;
5603   case Intrinsic::umul_fix_sat:
5604     return ISD::UMULFIXSAT;
5605   case Intrinsic::sdiv_fix:
5606     return ISD::SDIVFIX;
5607   case Intrinsic::udiv_fix:
5608     return ISD::UDIVFIX;
5609   case Intrinsic::sdiv_fix_sat:
5610     return ISD::SDIVFIXSAT;
5611   case Intrinsic::udiv_fix_sat:
5612     return ISD::UDIVFIXSAT;
5613   default:
5614     llvm_unreachable("Unhandled fixed point intrinsic");
5615   }
5616 }
5617 
5618 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5619                                            const char *FunctionName) {
5620   assert(FunctionName && "FunctionName must not be nullptr");
5621   SDValue Callee = DAG.getExternalSymbol(
5622       FunctionName,
5623       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5624   LowerCallTo(I, Callee, I.isTailCall());
5625 }
5626 
5627 /// Given a @llvm.call.preallocated.setup, return the corresponding
5628 /// preallocated call.
5629 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5630   assert(cast<CallBase>(PreallocatedSetup)
5631                  ->getCalledFunction()
5632                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5633          "expected call_preallocated_setup Value");
5634   for (auto *U : PreallocatedSetup->users()) {
5635     auto *UseCall = cast<CallBase>(U);
5636     const Function *Fn = UseCall->getCalledFunction();
5637     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5638       return UseCall;
5639     }
5640   }
5641   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5642 }
5643 
5644 /// Lower the call to the specified intrinsic function.
5645 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5646                                              unsigned Intrinsic) {
5647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5648   SDLoc sdl = getCurSDLoc();
5649   DebugLoc dl = getCurDebugLoc();
5650   SDValue Res;
5651 
5652   switch (Intrinsic) {
5653   default:
5654     // By default, turn this into a target intrinsic node.
5655     visitTargetIntrinsic(I, Intrinsic);
5656     return;
5657   case Intrinsic::vscale: {
5658     match(&I, m_VScale(DAG.getDataLayout()));
5659     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5660     setValue(&I,
5661              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5662     return;
5663   }
5664   case Intrinsic::vastart:  visitVAStart(I); return;
5665   case Intrinsic::vaend:    visitVAEnd(I); return;
5666   case Intrinsic::vacopy:   visitVACopy(I); return;
5667   case Intrinsic::returnaddress:
5668     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5669                              TLI.getPointerTy(DAG.getDataLayout()),
5670                              getValue(I.getArgOperand(0))));
5671     return;
5672   case Intrinsic::addressofreturnaddress:
5673     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5674                              TLI.getPointerTy(DAG.getDataLayout())));
5675     return;
5676   case Intrinsic::sponentry:
5677     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5678                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5679     return;
5680   case Intrinsic::frameaddress:
5681     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5682                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5683                              getValue(I.getArgOperand(0))));
5684     return;
5685   case Intrinsic::read_register: {
5686     Value *Reg = I.getArgOperand(0);
5687     SDValue Chain = getRoot();
5688     SDValue RegName =
5689         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5690     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5691     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5692       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5693     setValue(&I, Res);
5694     DAG.setRoot(Res.getValue(1));
5695     return;
5696   }
5697   case Intrinsic::write_register: {
5698     Value *Reg = I.getArgOperand(0);
5699     Value *RegValue = I.getArgOperand(1);
5700     SDValue Chain = getRoot();
5701     SDValue RegName =
5702         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5703     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5704                             RegName, getValue(RegValue)));
5705     return;
5706   }
5707   case Intrinsic::memcpy: {
5708     const auto &MCI = cast<MemCpyInst>(I);
5709     SDValue Op1 = getValue(I.getArgOperand(0));
5710     SDValue Op2 = getValue(I.getArgOperand(1));
5711     SDValue Op3 = getValue(I.getArgOperand(2));
5712     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5713     Align DstAlign = MCI.getDestAlign().valueOrOne();
5714     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5715     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5716     bool isVol = MCI.isVolatile();
5717     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5718     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5719     // node.
5720     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5721     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5722                                /* AlwaysInline */ false, isTC,
5723                                MachinePointerInfo(I.getArgOperand(0)),
5724                                MachinePointerInfo(I.getArgOperand(1)));
5725     updateDAGForMaybeTailCall(MC);
5726     return;
5727   }
5728   case Intrinsic::memcpy_inline: {
5729     const auto &MCI = cast<MemCpyInlineInst>(I);
5730     SDValue Dst = getValue(I.getArgOperand(0));
5731     SDValue Src = getValue(I.getArgOperand(1));
5732     SDValue Size = getValue(I.getArgOperand(2));
5733     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5734     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5735     Align DstAlign = MCI.getDestAlign().valueOrOne();
5736     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5737     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5738     bool isVol = MCI.isVolatile();
5739     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5740     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5741     // node.
5742     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5743                                /* AlwaysInline */ true, isTC,
5744                                MachinePointerInfo(I.getArgOperand(0)),
5745                                MachinePointerInfo(I.getArgOperand(1)));
5746     updateDAGForMaybeTailCall(MC);
5747     return;
5748   }
5749   case Intrinsic::memset: {
5750     const auto &MSI = cast<MemSetInst>(I);
5751     SDValue Op1 = getValue(I.getArgOperand(0));
5752     SDValue Op2 = getValue(I.getArgOperand(1));
5753     SDValue Op3 = getValue(I.getArgOperand(2));
5754     // @llvm.memset defines 0 and 1 to both mean no alignment.
5755     Align Alignment = MSI.getDestAlign().valueOrOne();
5756     bool isVol = MSI.isVolatile();
5757     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5758     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5759     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5760                                MachinePointerInfo(I.getArgOperand(0)));
5761     updateDAGForMaybeTailCall(MS);
5762     return;
5763   }
5764   case Intrinsic::memmove: {
5765     const auto &MMI = cast<MemMoveInst>(I);
5766     SDValue Op1 = getValue(I.getArgOperand(0));
5767     SDValue Op2 = getValue(I.getArgOperand(1));
5768     SDValue Op3 = getValue(I.getArgOperand(2));
5769     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5770     Align DstAlign = MMI.getDestAlign().valueOrOne();
5771     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5772     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5773     bool isVol = MMI.isVolatile();
5774     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5775     // FIXME: Support passing different dest/src alignments to the memmove DAG
5776     // node.
5777     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5778     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5779                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5780                                 MachinePointerInfo(I.getArgOperand(1)));
5781     updateDAGForMaybeTailCall(MM);
5782     return;
5783   }
5784   case Intrinsic::memcpy_element_unordered_atomic: {
5785     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5786     SDValue Dst = getValue(MI.getRawDest());
5787     SDValue Src = getValue(MI.getRawSource());
5788     SDValue Length = getValue(MI.getLength());
5789 
5790     unsigned DstAlign = MI.getDestAlignment();
5791     unsigned SrcAlign = MI.getSourceAlignment();
5792     Type *LengthTy = MI.getLength()->getType();
5793     unsigned ElemSz = MI.getElementSizeInBytes();
5794     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5795     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5796                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5797                                      MachinePointerInfo(MI.getRawDest()),
5798                                      MachinePointerInfo(MI.getRawSource()));
5799     updateDAGForMaybeTailCall(MC);
5800     return;
5801   }
5802   case Intrinsic::memmove_element_unordered_atomic: {
5803     auto &MI = cast<AtomicMemMoveInst>(I);
5804     SDValue Dst = getValue(MI.getRawDest());
5805     SDValue Src = getValue(MI.getRawSource());
5806     SDValue Length = getValue(MI.getLength());
5807 
5808     unsigned DstAlign = MI.getDestAlignment();
5809     unsigned SrcAlign = MI.getSourceAlignment();
5810     Type *LengthTy = MI.getLength()->getType();
5811     unsigned ElemSz = MI.getElementSizeInBytes();
5812     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5813     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5814                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5815                                       MachinePointerInfo(MI.getRawDest()),
5816                                       MachinePointerInfo(MI.getRawSource()));
5817     updateDAGForMaybeTailCall(MC);
5818     return;
5819   }
5820   case Intrinsic::memset_element_unordered_atomic: {
5821     auto &MI = cast<AtomicMemSetInst>(I);
5822     SDValue Dst = getValue(MI.getRawDest());
5823     SDValue Val = getValue(MI.getValue());
5824     SDValue Length = getValue(MI.getLength());
5825 
5826     unsigned DstAlign = MI.getDestAlignment();
5827     Type *LengthTy = MI.getLength()->getType();
5828     unsigned ElemSz = MI.getElementSizeInBytes();
5829     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5830     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5831                                      LengthTy, ElemSz, isTC,
5832                                      MachinePointerInfo(MI.getRawDest()));
5833     updateDAGForMaybeTailCall(MC);
5834     return;
5835   }
5836   case Intrinsic::call_preallocated_setup: {
5837     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5838     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5839     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5840                               getRoot(), SrcValue);
5841     setValue(&I, Res);
5842     DAG.setRoot(Res);
5843     return;
5844   }
5845   case Intrinsic::call_preallocated_arg: {
5846     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5847     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5848     SDValue Ops[3];
5849     Ops[0] = getRoot();
5850     Ops[1] = SrcValue;
5851     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5852                                    MVT::i32); // arg index
5853     SDValue Res = DAG.getNode(
5854         ISD::PREALLOCATED_ARG, sdl,
5855         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5856     setValue(&I, Res);
5857     DAG.setRoot(Res.getValue(1));
5858     return;
5859   }
5860   case Intrinsic::dbg_addr:
5861   case Intrinsic::dbg_declare: {
5862     const auto &DI = cast<DbgVariableIntrinsic>(I);
5863     DILocalVariable *Variable = DI.getVariable();
5864     DIExpression *Expression = DI.getExpression();
5865     dropDanglingDebugInfo(Variable, Expression);
5866     assert(Variable && "Missing variable");
5867     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5868                       << "\n");
5869     // Check if address has undef value.
5870     const Value *Address = DI.getVariableLocation();
5871     if (!Address || isa<UndefValue>(Address) ||
5872         (Address->use_empty() && !isa<Argument>(Address))) {
5873       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5874                         << " (bad/undef/unused-arg address)\n");
5875       return;
5876     }
5877 
5878     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5879 
5880     // Check if this variable can be described by a frame index, typically
5881     // either as a static alloca or a byval parameter.
5882     int FI = std::numeric_limits<int>::max();
5883     if (const auto *AI =
5884             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5885       if (AI->isStaticAlloca()) {
5886         auto I = FuncInfo.StaticAllocaMap.find(AI);
5887         if (I != FuncInfo.StaticAllocaMap.end())
5888           FI = I->second;
5889       }
5890     } else if (const auto *Arg = dyn_cast<Argument>(
5891                    Address->stripInBoundsConstantOffsets())) {
5892       FI = FuncInfo.getArgumentFrameIndex(Arg);
5893     }
5894 
5895     // llvm.dbg.addr is control dependent and always generates indirect
5896     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5897     // the MachineFunction variable table.
5898     if (FI != std::numeric_limits<int>::max()) {
5899       if (Intrinsic == Intrinsic::dbg_addr) {
5900         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5901             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5902         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5903       } else {
5904         LLVM_DEBUG(dbgs() << "Skipping " << DI
5905                           << " (variable info stashed in MF side table)\n");
5906       }
5907       return;
5908     }
5909 
5910     SDValue &N = NodeMap[Address];
5911     if (!N.getNode() && isa<Argument>(Address))
5912       // Check unused arguments map.
5913       N = UnusedArgNodeMap[Address];
5914     SDDbgValue *SDV;
5915     if (N.getNode()) {
5916       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5917         Address = BCI->getOperand(0);
5918       // Parameters are handled specially.
5919       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5920       if (isParameter && FINode) {
5921         // Byval parameter. We have a frame index at this point.
5922         SDV =
5923             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5924                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5925       } else if (isa<Argument>(Address)) {
5926         // Address is an argument, so try to emit its dbg value using
5927         // virtual register info from the FuncInfo.ValueMap.
5928         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5929         return;
5930       } else {
5931         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5932                               true, dl, SDNodeOrder);
5933       }
5934       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5935     } else {
5936       // If Address is an argument then try to emit its dbg value using
5937       // virtual register info from the FuncInfo.ValueMap.
5938       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5939                                     N)) {
5940         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5941                           << " (could not emit func-arg dbg_value)\n");
5942       }
5943     }
5944     return;
5945   }
5946   case Intrinsic::dbg_label: {
5947     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5948     DILabel *Label = DI.getLabel();
5949     assert(Label && "Missing label");
5950 
5951     SDDbgLabel *SDV;
5952     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5953     DAG.AddDbgLabel(SDV);
5954     return;
5955   }
5956   case Intrinsic::dbg_value: {
5957     const DbgValueInst &DI = cast<DbgValueInst>(I);
5958     assert(DI.getVariable() && "Missing variable");
5959 
5960     DILocalVariable *Variable = DI.getVariable();
5961     DIExpression *Expression = DI.getExpression();
5962     dropDanglingDebugInfo(Variable, Expression);
5963     const Value *V = DI.getValue();
5964     if (!V)
5965       return;
5966 
5967     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5968         SDNodeOrder))
5969       return;
5970 
5971     // TODO: Dangling debug info will eventually either be resolved or produce
5972     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5973     // between the original dbg.value location and its resolved DBG_VALUE, which
5974     // we should ideally fill with an extra Undef DBG_VALUE.
5975 
5976     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5977     return;
5978   }
5979 
5980   case Intrinsic::eh_typeid_for: {
5981     // Find the type id for the given typeinfo.
5982     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5983     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5984     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5985     setValue(&I, Res);
5986     return;
5987   }
5988 
5989   case Intrinsic::eh_return_i32:
5990   case Intrinsic::eh_return_i64:
5991     DAG.getMachineFunction().setCallsEHReturn(true);
5992     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5993                             MVT::Other,
5994                             getControlRoot(),
5995                             getValue(I.getArgOperand(0)),
5996                             getValue(I.getArgOperand(1))));
5997     return;
5998   case Intrinsic::eh_unwind_init:
5999     DAG.getMachineFunction().setCallsUnwindInit(true);
6000     return;
6001   case Intrinsic::eh_dwarf_cfa:
6002     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6003                              TLI.getPointerTy(DAG.getDataLayout()),
6004                              getValue(I.getArgOperand(0))));
6005     return;
6006   case Intrinsic::eh_sjlj_callsite: {
6007     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6008     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6009     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6010     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6011 
6012     MMI.setCurrentCallSite(CI->getZExtValue());
6013     return;
6014   }
6015   case Intrinsic::eh_sjlj_functioncontext: {
6016     // Get and store the index of the function context.
6017     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6018     AllocaInst *FnCtx =
6019       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6020     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6021     MFI.setFunctionContextIndex(FI);
6022     return;
6023   }
6024   case Intrinsic::eh_sjlj_setjmp: {
6025     SDValue Ops[2];
6026     Ops[0] = getRoot();
6027     Ops[1] = getValue(I.getArgOperand(0));
6028     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6029                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6030     setValue(&I, Op.getValue(0));
6031     DAG.setRoot(Op.getValue(1));
6032     return;
6033   }
6034   case Intrinsic::eh_sjlj_longjmp:
6035     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6036                             getRoot(), getValue(I.getArgOperand(0))));
6037     return;
6038   case Intrinsic::eh_sjlj_setup_dispatch:
6039     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6040                             getRoot()));
6041     return;
6042   case Intrinsic::masked_gather:
6043     visitMaskedGather(I);
6044     return;
6045   case Intrinsic::masked_load:
6046     visitMaskedLoad(I);
6047     return;
6048   case Intrinsic::masked_scatter:
6049     visitMaskedScatter(I);
6050     return;
6051   case Intrinsic::masked_store:
6052     visitMaskedStore(I);
6053     return;
6054   case Intrinsic::masked_expandload:
6055     visitMaskedLoad(I, true /* IsExpanding */);
6056     return;
6057   case Intrinsic::masked_compressstore:
6058     visitMaskedStore(I, true /* IsCompressing */);
6059     return;
6060   case Intrinsic::powi:
6061     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6062                             getValue(I.getArgOperand(1)), DAG));
6063     return;
6064   case Intrinsic::log:
6065     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6066     return;
6067   case Intrinsic::log2:
6068     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6069     return;
6070   case Intrinsic::log10:
6071     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6072     return;
6073   case Intrinsic::exp:
6074     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6075     return;
6076   case Intrinsic::exp2:
6077     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6078     return;
6079   case Intrinsic::pow:
6080     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6081                            getValue(I.getArgOperand(1)), DAG, TLI));
6082     return;
6083   case Intrinsic::sqrt:
6084   case Intrinsic::fabs:
6085   case Intrinsic::sin:
6086   case Intrinsic::cos:
6087   case Intrinsic::floor:
6088   case Intrinsic::ceil:
6089   case Intrinsic::trunc:
6090   case Intrinsic::rint:
6091   case Intrinsic::nearbyint:
6092   case Intrinsic::round:
6093   case Intrinsic::roundeven:
6094   case Intrinsic::canonicalize: {
6095     unsigned Opcode;
6096     switch (Intrinsic) {
6097     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6098     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6099     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6100     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6101     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6102     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6103     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6104     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6105     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6106     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6107     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6108     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6109     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6110     }
6111 
6112     setValue(&I, DAG.getNode(Opcode, sdl,
6113                              getValue(I.getArgOperand(0)).getValueType(),
6114                              getValue(I.getArgOperand(0))));
6115     return;
6116   }
6117   case Intrinsic::lround:
6118   case Intrinsic::llround:
6119   case Intrinsic::lrint:
6120   case Intrinsic::llrint: {
6121     unsigned Opcode;
6122     switch (Intrinsic) {
6123     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6124     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6125     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6126     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6127     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6128     }
6129 
6130     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6131     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6132                              getValue(I.getArgOperand(0))));
6133     return;
6134   }
6135   case Intrinsic::minnum:
6136     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6137                              getValue(I.getArgOperand(0)).getValueType(),
6138                              getValue(I.getArgOperand(0)),
6139                              getValue(I.getArgOperand(1))));
6140     return;
6141   case Intrinsic::maxnum:
6142     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6143                              getValue(I.getArgOperand(0)).getValueType(),
6144                              getValue(I.getArgOperand(0)),
6145                              getValue(I.getArgOperand(1))));
6146     return;
6147   case Intrinsic::minimum:
6148     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6149                              getValue(I.getArgOperand(0)).getValueType(),
6150                              getValue(I.getArgOperand(0)),
6151                              getValue(I.getArgOperand(1))));
6152     return;
6153   case Intrinsic::maximum:
6154     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6155                              getValue(I.getArgOperand(0)).getValueType(),
6156                              getValue(I.getArgOperand(0)),
6157                              getValue(I.getArgOperand(1))));
6158     return;
6159   case Intrinsic::copysign:
6160     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6161                              getValue(I.getArgOperand(0)).getValueType(),
6162                              getValue(I.getArgOperand(0)),
6163                              getValue(I.getArgOperand(1))));
6164     return;
6165   case Intrinsic::fma:
6166     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6167                              getValue(I.getArgOperand(0)).getValueType(),
6168                              getValue(I.getArgOperand(0)),
6169                              getValue(I.getArgOperand(1)),
6170                              getValue(I.getArgOperand(2))));
6171     return;
6172 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6173   case Intrinsic::INTRINSIC:
6174 #include "llvm/IR/ConstrainedOps.def"
6175     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6176     return;
6177   case Intrinsic::fmuladd: {
6178     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6179     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6180         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6181       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6182                                getValue(I.getArgOperand(0)).getValueType(),
6183                                getValue(I.getArgOperand(0)),
6184                                getValue(I.getArgOperand(1)),
6185                                getValue(I.getArgOperand(2))));
6186     } else {
6187       // TODO: Intrinsic calls should have fast-math-flags.
6188       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6189                                 getValue(I.getArgOperand(0)).getValueType(),
6190                                 getValue(I.getArgOperand(0)),
6191                                 getValue(I.getArgOperand(1)));
6192       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6193                                 getValue(I.getArgOperand(0)).getValueType(),
6194                                 Mul,
6195                                 getValue(I.getArgOperand(2)));
6196       setValue(&I, Add);
6197     }
6198     return;
6199   }
6200   case Intrinsic::convert_to_fp16:
6201     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6202                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6203                                          getValue(I.getArgOperand(0)),
6204                                          DAG.getTargetConstant(0, sdl,
6205                                                                MVT::i32))));
6206     return;
6207   case Intrinsic::convert_from_fp16:
6208     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6209                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6210                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6211                                          getValue(I.getArgOperand(0)))));
6212     return;
6213   case Intrinsic::pcmarker: {
6214     SDValue Tmp = getValue(I.getArgOperand(0));
6215     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6216     return;
6217   }
6218   case Intrinsic::readcyclecounter: {
6219     SDValue Op = getRoot();
6220     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6221                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6222     setValue(&I, Res);
6223     DAG.setRoot(Res.getValue(1));
6224     return;
6225   }
6226   case Intrinsic::bitreverse:
6227     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6228                              getValue(I.getArgOperand(0)).getValueType(),
6229                              getValue(I.getArgOperand(0))));
6230     return;
6231   case Intrinsic::bswap:
6232     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6233                              getValue(I.getArgOperand(0)).getValueType(),
6234                              getValue(I.getArgOperand(0))));
6235     return;
6236   case Intrinsic::cttz: {
6237     SDValue Arg = getValue(I.getArgOperand(0));
6238     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6239     EVT Ty = Arg.getValueType();
6240     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6241                              sdl, Ty, Arg));
6242     return;
6243   }
6244   case Intrinsic::ctlz: {
6245     SDValue Arg = getValue(I.getArgOperand(0));
6246     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6247     EVT Ty = Arg.getValueType();
6248     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6249                              sdl, Ty, Arg));
6250     return;
6251   }
6252   case Intrinsic::ctpop: {
6253     SDValue Arg = getValue(I.getArgOperand(0));
6254     EVT Ty = Arg.getValueType();
6255     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6256     return;
6257   }
6258   case Intrinsic::fshl:
6259   case Intrinsic::fshr: {
6260     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6261     SDValue X = getValue(I.getArgOperand(0));
6262     SDValue Y = getValue(I.getArgOperand(1));
6263     SDValue Z = getValue(I.getArgOperand(2));
6264     EVT VT = X.getValueType();
6265     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6266     SDValue Zero = DAG.getConstant(0, sdl, VT);
6267     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6268 
6269     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6270     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6271       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6272       return;
6273     }
6274 
6275     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6276     // avoid the select that is necessary in the general case to filter out
6277     // the 0-shift possibility that leads to UB.
6278     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6279       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6280       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6281         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6282         return;
6283       }
6284 
6285       // Some targets only rotate one way. Try the opposite direction.
6286       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6287       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6288         // Negate the shift amount because it is safe to ignore the high bits.
6289         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6290         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6291         return;
6292       }
6293 
6294       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6295       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6296       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6297       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6298       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6299       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6300       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6301       return;
6302     }
6303 
6304     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6305     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6306     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6307     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6308     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6309     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6310 
6311     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6312     // and that is undefined. We must compare and select to avoid UB.
6313     EVT CCVT = MVT::i1;
6314     if (VT.isVector())
6315       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6316 
6317     // For fshl, 0-shift returns the 1st arg (X).
6318     // For fshr, 0-shift returns the 2nd arg (Y).
6319     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6320     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6321     return;
6322   }
6323   case Intrinsic::sadd_sat: {
6324     SDValue Op1 = getValue(I.getArgOperand(0));
6325     SDValue Op2 = getValue(I.getArgOperand(1));
6326     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6327     return;
6328   }
6329   case Intrinsic::uadd_sat: {
6330     SDValue Op1 = getValue(I.getArgOperand(0));
6331     SDValue Op2 = getValue(I.getArgOperand(1));
6332     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6333     return;
6334   }
6335   case Intrinsic::ssub_sat: {
6336     SDValue Op1 = getValue(I.getArgOperand(0));
6337     SDValue Op2 = getValue(I.getArgOperand(1));
6338     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6339     return;
6340   }
6341   case Intrinsic::usub_sat: {
6342     SDValue Op1 = getValue(I.getArgOperand(0));
6343     SDValue Op2 = getValue(I.getArgOperand(1));
6344     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6345     return;
6346   }
6347   case Intrinsic::smul_fix:
6348   case Intrinsic::umul_fix:
6349   case Intrinsic::smul_fix_sat:
6350   case Intrinsic::umul_fix_sat: {
6351     SDValue Op1 = getValue(I.getArgOperand(0));
6352     SDValue Op2 = getValue(I.getArgOperand(1));
6353     SDValue Op3 = getValue(I.getArgOperand(2));
6354     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6355                              Op1.getValueType(), Op1, Op2, Op3));
6356     return;
6357   }
6358   case Intrinsic::sdiv_fix:
6359   case Intrinsic::udiv_fix:
6360   case Intrinsic::sdiv_fix_sat:
6361   case Intrinsic::udiv_fix_sat: {
6362     SDValue Op1 = getValue(I.getArgOperand(0));
6363     SDValue Op2 = getValue(I.getArgOperand(1));
6364     SDValue Op3 = getValue(I.getArgOperand(2));
6365     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6366                               Op1, Op2, Op3, DAG, TLI));
6367     return;
6368   }
6369   case Intrinsic::stacksave: {
6370     SDValue Op = getRoot();
6371     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6372     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6373     setValue(&I, Res);
6374     DAG.setRoot(Res.getValue(1));
6375     return;
6376   }
6377   case Intrinsic::stackrestore:
6378     Res = getValue(I.getArgOperand(0));
6379     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6380     return;
6381   case Intrinsic::get_dynamic_area_offset: {
6382     SDValue Op = getRoot();
6383     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6384     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6385     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6386     // target.
6387     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6388       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6389                          " intrinsic!");
6390     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6391                       Op);
6392     DAG.setRoot(Op);
6393     setValue(&I, Res);
6394     return;
6395   }
6396   case Intrinsic::stackguard: {
6397     MachineFunction &MF = DAG.getMachineFunction();
6398     const Module &M = *MF.getFunction().getParent();
6399     SDValue Chain = getRoot();
6400     if (TLI.useLoadStackGuardNode()) {
6401       Res = getLoadStackGuard(DAG, sdl, Chain);
6402     } else {
6403       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6404       const Value *Global = TLI.getSDagStackGuard(M);
6405       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6406       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6407                         MachinePointerInfo(Global, 0), Align,
6408                         MachineMemOperand::MOVolatile);
6409     }
6410     if (TLI.useStackGuardXorFP())
6411       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6412     DAG.setRoot(Chain);
6413     setValue(&I, Res);
6414     return;
6415   }
6416   case Intrinsic::stackprotector: {
6417     // Emit code into the DAG to store the stack guard onto the stack.
6418     MachineFunction &MF = DAG.getMachineFunction();
6419     MachineFrameInfo &MFI = MF.getFrameInfo();
6420     SDValue Src, Chain = getRoot();
6421 
6422     if (TLI.useLoadStackGuardNode())
6423       Src = getLoadStackGuard(DAG, sdl, Chain);
6424     else
6425       Src = getValue(I.getArgOperand(0));   // The guard's value.
6426 
6427     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6428 
6429     int FI = FuncInfo.StaticAllocaMap[Slot];
6430     MFI.setStackProtectorIndex(FI);
6431     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6432 
6433     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6434 
6435     // Store the stack protector onto the stack.
6436     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6437                                                  DAG.getMachineFunction(), FI),
6438                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6439     setValue(&I, Res);
6440     DAG.setRoot(Res);
6441     return;
6442   }
6443   case Intrinsic::objectsize:
6444     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6445 
6446   case Intrinsic::is_constant:
6447     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6448 
6449   case Intrinsic::annotation:
6450   case Intrinsic::ptr_annotation:
6451   case Intrinsic::launder_invariant_group:
6452   case Intrinsic::strip_invariant_group:
6453     // Drop the intrinsic, but forward the value
6454     setValue(&I, getValue(I.getOperand(0)));
6455     return;
6456   case Intrinsic::assume:
6457   case Intrinsic::var_annotation:
6458   case Intrinsic::sideeffect:
6459     // Discard annotate attributes, assumptions, and artificial side-effects.
6460     return;
6461 
6462   case Intrinsic::codeview_annotation: {
6463     // Emit a label associated with this metadata.
6464     MachineFunction &MF = DAG.getMachineFunction();
6465     MCSymbol *Label =
6466         MF.getMMI().getContext().createTempSymbol("annotation", true);
6467     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6468     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6469     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6470     DAG.setRoot(Res);
6471     return;
6472   }
6473 
6474   case Intrinsic::init_trampoline: {
6475     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6476 
6477     SDValue Ops[6];
6478     Ops[0] = getRoot();
6479     Ops[1] = getValue(I.getArgOperand(0));
6480     Ops[2] = getValue(I.getArgOperand(1));
6481     Ops[3] = getValue(I.getArgOperand(2));
6482     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6483     Ops[5] = DAG.getSrcValue(F);
6484 
6485     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6486 
6487     DAG.setRoot(Res);
6488     return;
6489   }
6490   case Intrinsic::adjust_trampoline:
6491     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6492                              TLI.getPointerTy(DAG.getDataLayout()),
6493                              getValue(I.getArgOperand(0))));
6494     return;
6495   case Intrinsic::gcroot: {
6496     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6497            "only valid in functions with gc specified, enforced by Verifier");
6498     assert(GFI && "implied by previous");
6499     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6500     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6501 
6502     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6503     GFI->addStackRoot(FI->getIndex(), TypeMap);
6504     return;
6505   }
6506   case Intrinsic::gcread:
6507   case Intrinsic::gcwrite:
6508     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6509   case Intrinsic::flt_rounds:
6510     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6511     setValue(&I, Res);
6512     DAG.setRoot(Res.getValue(1));
6513     return;
6514 
6515   case Intrinsic::expect:
6516     // Just replace __builtin_expect(exp, c) with EXP.
6517     setValue(&I, getValue(I.getArgOperand(0)));
6518     return;
6519 
6520   case Intrinsic::debugtrap:
6521   case Intrinsic::trap: {
6522     StringRef TrapFuncName =
6523         I.getAttributes()
6524             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6525             .getValueAsString();
6526     if (TrapFuncName.empty()) {
6527       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6528         ISD::TRAP : ISD::DEBUGTRAP;
6529       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6530       return;
6531     }
6532     TargetLowering::ArgListTy Args;
6533 
6534     TargetLowering::CallLoweringInfo CLI(DAG);
6535     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6536         CallingConv::C, I.getType(),
6537         DAG.getExternalSymbol(TrapFuncName.data(),
6538                               TLI.getPointerTy(DAG.getDataLayout())),
6539         std::move(Args));
6540 
6541     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6542     DAG.setRoot(Result.second);
6543     return;
6544   }
6545 
6546   case Intrinsic::uadd_with_overflow:
6547   case Intrinsic::sadd_with_overflow:
6548   case Intrinsic::usub_with_overflow:
6549   case Intrinsic::ssub_with_overflow:
6550   case Intrinsic::umul_with_overflow:
6551   case Intrinsic::smul_with_overflow: {
6552     ISD::NodeType Op;
6553     switch (Intrinsic) {
6554     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6555     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6556     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6557     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6558     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6559     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6560     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6561     }
6562     SDValue Op1 = getValue(I.getArgOperand(0));
6563     SDValue Op2 = getValue(I.getArgOperand(1));
6564 
6565     EVT ResultVT = Op1.getValueType();
6566     EVT OverflowVT = MVT::i1;
6567     if (ResultVT.isVector())
6568       OverflowVT = EVT::getVectorVT(
6569           *Context, OverflowVT, ResultVT.getVectorNumElements());
6570 
6571     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6572     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6573     return;
6574   }
6575   case Intrinsic::prefetch: {
6576     SDValue Ops[5];
6577     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6578     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6579     Ops[0] = DAG.getRoot();
6580     Ops[1] = getValue(I.getArgOperand(0));
6581     Ops[2] = getValue(I.getArgOperand(1));
6582     Ops[3] = getValue(I.getArgOperand(2));
6583     Ops[4] = getValue(I.getArgOperand(3));
6584     SDValue Result = DAG.getMemIntrinsicNode(
6585         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6586         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6587         /* align */ None, Flags);
6588 
6589     // Chain the prefetch in parallell with any pending loads, to stay out of
6590     // the way of later optimizations.
6591     PendingLoads.push_back(Result);
6592     Result = getRoot();
6593     DAG.setRoot(Result);
6594     return;
6595   }
6596   case Intrinsic::lifetime_start:
6597   case Intrinsic::lifetime_end: {
6598     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6599     // Stack coloring is not enabled in O0, discard region information.
6600     if (TM.getOptLevel() == CodeGenOpt::None)
6601       return;
6602 
6603     const int64_t ObjectSize =
6604         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6605     Value *const ObjectPtr = I.getArgOperand(1);
6606     SmallVector<const Value *, 4> Allocas;
6607     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6608 
6609     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6610            E = Allocas.end(); Object != E; ++Object) {
6611       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6612 
6613       // Could not find an Alloca.
6614       if (!LifetimeObject)
6615         continue;
6616 
6617       // First check that the Alloca is static, otherwise it won't have a
6618       // valid frame index.
6619       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6620       if (SI == FuncInfo.StaticAllocaMap.end())
6621         return;
6622 
6623       const int FrameIndex = SI->second;
6624       int64_t Offset;
6625       if (GetPointerBaseWithConstantOffset(
6626               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6627         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6628       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6629                                 Offset);
6630       DAG.setRoot(Res);
6631     }
6632     return;
6633   }
6634   case Intrinsic::invariant_start:
6635     // Discard region information.
6636     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6637     return;
6638   case Intrinsic::invariant_end:
6639     // Discard region information.
6640     return;
6641   case Intrinsic::clear_cache:
6642     /// FunctionName may be null.
6643     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6644       lowerCallToExternalSymbol(I, FunctionName);
6645     return;
6646   case Intrinsic::donothing:
6647     // ignore
6648     return;
6649   case Intrinsic::experimental_stackmap:
6650     visitStackmap(I);
6651     return;
6652   case Intrinsic::experimental_patchpoint_void:
6653   case Intrinsic::experimental_patchpoint_i64:
6654     visitPatchpoint(I);
6655     return;
6656   case Intrinsic::experimental_gc_statepoint:
6657     LowerStatepoint(cast<GCStatepointInst>(I));
6658     return;
6659   case Intrinsic::experimental_gc_result:
6660     visitGCResult(cast<GCResultInst>(I));
6661     return;
6662   case Intrinsic::experimental_gc_relocate:
6663     visitGCRelocate(cast<GCRelocateInst>(I));
6664     return;
6665   case Intrinsic::instrprof_increment:
6666     llvm_unreachable("instrprof failed to lower an increment");
6667   case Intrinsic::instrprof_value_profile:
6668     llvm_unreachable("instrprof failed to lower a value profiling call");
6669   case Intrinsic::localescape: {
6670     MachineFunction &MF = DAG.getMachineFunction();
6671     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6672 
6673     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6674     // is the same on all targets.
6675     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6676       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6677       if (isa<ConstantPointerNull>(Arg))
6678         continue; // Skip null pointers. They represent a hole in index space.
6679       AllocaInst *Slot = cast<AllocaInst>(Arg);
6680       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6681              "can only escape static allocas");
6682       int FI = FuncInfo.StaticAllocaMap[Slot];
6683       MCSymbol *FrameAllocSym =
6684           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6685               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6686       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6687               TII->get(TargetOpcode::LOCAL_ESCAPE))
6688           .addSym(FrameAllocSym)
6689           .addFrameIndex(FI);
6690     }
6691 
6692     return;
6693   }
6694 
6695   case Intrinsic::localrecover: {
6696     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6697     MachineFunction &MF = DAG.getMachineFunction();
6698 
6699     // Get the symbol that defines the frame offset.
6700     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6701     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6702     unsigned IdxVal =
6703         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6704     MCSymbol *FrameAllocSym =
6705         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6706             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6707 
6708     Value *FP = I.getArgOperand(1);
6709     SDValue FPVal = getValue(FP);
6710     EVT PtrVT = FPVal.getValueType();
6711 
6712     // Create a MCSymbol for the label to avoid any target lowering
6713     // that would make this PC relative.
6714     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6715     SDValue OffsetVal =
6716         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6717 
6718     // Add the offset to the FP.
6719     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6720     setValue(&I, Add);
6721 
6722     return;
6723   }
6724 
6725   case Intrinsic::eh_exceptionpointer:
6726   case Intrinsic::eh_exceptioncode: {
6727     // Get the exception pointer vreg, copy from it, and resize it to fit.
6728     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6729     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6730     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6731     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6732     SDValue N =
6733         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6734     if (Intrinsic == Intrinsic::eh_exceptioncode)
6735       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6736     setValue(&I, N);
6737     return;
6738   }
6739   case Intrinsic::xray_customevent: {
6740     // Here we want to make sure that the intrinsic behaves as if it has a
6741     // specific calling convention, and only for x86_64.
6742     // FIXME: Support other platforms later.
6743     const auto &Triple = DAG.getTarget().getTargetTriple();
6744     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6745       return;
6746 
6747     SDLoc DL = getCurSDLoc();
6748     SmallVector<SDValue, 8> Ops;
6749 
6750     // We want to say that we always want the arguments in registers.
6751     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6752     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6753     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6754     SDValue Chain = getRoot();
6755     Ops.push_back(LogEntryVal);
6756     Ops.push_back(StrSizeVal);
6757     Ops.push_back(Chain);
6758 
6759     // We need to enforce the calling convention for the callsite, so that
6760     // argument ordering is enforced correctly, and that register allocation can
6761     // see that some registers may be assumed clobbered and have to preserve
6762     // them across calls to the intrinsic.
6763     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6764                                            DL, NodeTys, Ops);
6765     SDValue patchableNode = SDValue(MN, 0);
6766     DAG.setRoot(patchableNode);
6767     setValue(&I, patchableNode);
6768     return;
6769   }
6770   case Intrinsic::xray_typedevent: {
6771     // Here we want to make sure that the intrinsic behaves as if it has a
6772     // specific calling convention, and only for x86_64.
6773     // FIXME: Support other platforms later.
6774     const auto &Triple = DAG.getTarget().getTargetTriple();
6775     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6776       return;
6777 
6778     SDLoc DL = getCurSDLoc();
6779     SmallVector<SDValue, 8> Ops;
6780 
6781     // We want to say that we always want the arguments in registers.
6782     // It's unclear to me how manipulating the selection DAG here forces callers
6783     // to provide arguments in registers instead of on the stack.
6784     SDValue LogTypeId = getValue(I.getArgOperand(0));
6785     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6786     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6787     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6788     SDValue Chain = getRoot();
6789     Ops.push_back(LogTypeId);
6790     Ops.push_back(LogEntryVal);
6791     Ops.push_back(StrSizeVal);
6792     Ops.push_back(Chain);
6793 
6794     // We need to enforce the calling convention for the callsite, so that
6795     // argument ordering is enforced correctly, and that register allocation can
6796     // see that some registers may be assumed clobbered and have to preserve
6797     // them across calls to the intrinsic.
6798     MachineSDNode *MN = DAG.getMachineNode(
6799         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6800     SDValue patchableNode = SDValue(MN, 0);
6801     DAG.setRoot(patchableNode);
6802     setValue(&I, patchableNode);
6803     return;
6804   }
6805   case Intrinsic::experimental_deoptimize:
6806     LowerDeoptimizeCall(&I);
6807     return;
6808 
6809   case Intrinsic::experimental_vector_reduce_v2_fadd:
6810   case Intrinsic::experimental_vector_reduce_v2_fmul:
6811   case Intrinsic::experimental_vector_reduce_add:
6812   case Intrinsic::experimental_vector_reduce_mul:
6813   case Intrinsic::experimental_vector_reduce_and:
6814   case Intrinsic::experimental_vector_reduce_or:
6815   case Intrinsic::experimental_vector_reduce_xor:
6816   case Intrinsic::experimental_vector_reduce_smax:
6817   case Intrinsic::experimental_vector_reduce_smin:
6818   case Intrinsic::experimental_vector_reduce_umax:
6819   case Intrinsic::experimental_vector_reduce_umin:
6820   case Intrinsic::experimental_vector_reduce_fmax:
6821   case Intrinsic::experimental_vector_reduce_fmin:
6822     visitVectorReduce(I, Intrinsic);
6823     return;
6824 
6825   case Intrinsic::icall_branch_funnel: {
6826     SmallVector<SDValue, 16> Ops;
6827     Ops.push_back(getValue(I.getArgOperand(0)));
6828 
6829     int64_t Offset;
6830     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6831         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6832     if (!Base)
6833       report_fatal_error(
6834           "llvm.icall.branch.funnel operand must be a GlobalValue");
6835     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6836 
6837     struct BranchFunnelTarget {
6838       int64_t Offset;
6839       SDValue Target;
6840     };
6841     SmallVector<BranchFunnelTarget, 8> Targets;
6842 
6843     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6844       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6845           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6846       if (ElemBase != Base)
6847         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6848                            "to the same GlobalValue");
6849 
6850       SDValue Val = getValue(I.getArgOperand(Op + 1));
6851       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6852       if (!GA)
6853         report_fatal_error(
6854             "llvm.icall.branch.funnel operand must be a GlobalValue");
6855       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6856                                      GA->getGlobal(), getCurSDLoc(),
6857                                      Val.getValueType(), GA->getOffset())});
6858     }
6859     llvm::sort(Targets,
6860                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6861                  return T1.Offset < T2.Offset;
6862                });
6863 
6864     for (auto &T : Targets) {
6865       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6866       Ops.push_back(T.Target);
6867     }
6868 
6869     Ops.push_back(DAG.getRoot()); // Chain
6870     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6871                                  getCurSDLoc(), MVT::Other, Ops),
6872               0);
6873     DAG.setRoot(N);
6874     setValue(&I, N);
6875     HasTailCall = true;
6876     return;
6877   }
6878 
6879   case Intrinsic::wasm_landingpad_index:
6880     // Information this intrinsic contained has been transferred to
6881     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6882     // delete it now.
6883     return;
6884 
6885   case Intrinsic::aarch64_settag:
6886   case Intrinsic::aarch64_settag_zero: {
6887     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6888     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6889     SDValue Val = TSI.EmitTargetCodeForSetTag(
6890         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6891         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6892         ZeroMemory);
6893     DAG.setRoot(Val);
6894     setValue(&I, Val);
6895     return;
6896   }
6897   case Intrinsic::ptrmask: {
6898     SDValue Ptr = getValue(I.getOperand(0));
6899     SDValue Const = getValue(I.getOperand(1));
6900 
6901     EVT PtrVT = Ptr.getValueType();
6902     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6903                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6904     return;
6905   }
6906   case Intrinsic::get_active_lane_mask: {
6907     auto DL = getCurSDLoc();
6908     SDValue Index = getValue(I.getOperand(0));
6909     SDValue BTC = getValue(I.getOperand(1));
6910     Type *ElementTy = I.getOperand(0)->getType();
6911     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6912     unsigned VecWidth = VT.getVectorNumElements();
6913 
6914     SmallVector<SDValue, 16> OpsBTC;
6915     SmallVector<SDValue, 16> OpsIndex;
6916     SmallVector<SDValue, 16> OpsStepConstants;
6917     for (unsigned i = 0; i < VecWidth; i++) {
6918       OpsBTC.push_back(BTC);
6919       OpsIndex.push_back(Index);
6920       OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy)));
6921     }
6922 
6923     EVT CCVT = MVT::i1;
6924     CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth);
6925 
6926     auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth));
6927     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6928     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6929     SDValue VectorInduction = DAG.getNode(
6930        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6931     SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC);
6932     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
6933                                  VectorBTC, ISD::CondCode::SETULE);
6934     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
6935                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
6936                              SetCC));
6937     return;
6938   }
6939   }
6940 }
6941 
6942 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6943     const ConstrainedFPIntrinsic &FPI) {
6944   SDLoc sdl = getCurSDLoc();
6945 
6946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6947   SmallVector<EVT, 4> ValueVTs;
6948   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6949   ValueVTs.push_back(MVT::Other); // Out chain
6950 
6951   // We do not need to serialize constrained FP intrinsics against
6952   // each other or against (nonvolatile) loads, so they can be
6953   // chained like loads.
6954   SDValue Chain = DAG.getRoot();
6955   SmallVector<SDValue, 4> Opers;
6956   Opers.push_back(Chain);
6957   if (FPI.isUnaryOp()) {
6958     Opers.push_back(getValue(FPI.getArgOperand(0)));
6959   } else if (FPI.isTernaryOp()) {
6960     Opers.push_back(getValue(FPI.getArgOperand(0)));
6961     Opers.push_back(getValue(FPI.getArgOperand(1)));
6962     Opers.push_back(getValue(FPI.getArgOperand(2)));
6963   } else {
6964     Opers.push_back(getValue(FPI.getArgOperand(0)));
6965     Opers.push_back(getValue(FPI.getArgOperand(1)));
6966   }
6967 
6968   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6969     assert(Result.getNode()->getNumValues() == 2);
6970 
6971     // Push node to the appropriate list so that future instructions can be
6972     // chained up correctly.
6973     SDValue OutChain = Result.getValue(1);
6974     switch (EB) {
6975     case fp::ExceptionBehavior::ebIgnore:
6976       // The only reason why ebIgnore nodes still need to be chained is that
6977       // they might depend on the current rounding mode, and therefore must
6978       // not be moved across instruction that may change that mode.
6979       LLVM_FALLTHROUGH;
6980     case fp::ExceptionBehavior::ebMayTrap:
6981       // These must not be moved across calls or instructions that may change
6982       // floating-point exception masks.
6983       PendingConstrainedFP.push_back(OutChain);
6984       break;
6985     case fp::ExceptionBehavior::ebStrict:
6986       // These must not be moved across calls or instructions that may change
6987       // floating-point exception masks or read floating-point exception flags.
6988       // In addition, they cannot be optimized out even if unused.
6989       PendingConstrainedFPStrict.push_back(OutChain);
6990       break;
6991     }
6992   };
6993 
6994   SDVTList VTs = DAG.getVTList(ValueVTs);
6995   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6996 
6997   SDNodeFlags Flags;
6998   if (EB == fp::ExceptionBehavior::ebIgnore)
6999     Flags.setNoFPExcept(true);
7000 
7001   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7002     Flags.copyFMF(*FPOp);
7003 
7004   unsigned Opcode;
7005   switch (FPI.getIntrinsicID()) {
7006   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7007 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7008   case Intrinsic::INTRINSIC:                                                   \
7009     Opcode = ISD::STRICT_##DAGN;                                               \
7010     break;
7011 #include "llvm/IR/ConstrainedOps.def"
7012   case Intrinsic::experimental_constrained_fmuladd: {
7013     Opcode = ISD::STRICT_FMA;
7014     // Break fmuladd into fmul and fadd.
7015     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7016         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7017                                         ValueVTs[0])) {
7018       Opers.pop_back();
7019       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7020       pushOutChain(Mul, EB);
7021       Opcode = ISD::STRICT_FADD;
7022       Opers.clear();
7023       Opers.push_back(Mul.getValue(1));
7024       Opers.push_back(Mul.getValue(0));
7025       Opers.push_back(getValue(FPI.getArgOperand(2)));
7026     }
7027     break;
7028   }
7029   }
7030 
7031   // A few strict DAG nodes carry additional operands that are not
7032   // set up by the default code above.
7033   switch (Opcode) {
7034   default: break;
7035   case ISD::STRICT_FP_ROUND:
7036     Opers.push_back(
7037         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7038     break;
7039   case ISD::STRICT_FSETCC:
7040   case ISD::STRICT_FSETCCS: {
7041     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7042     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7043     break;
7044   }
7045   }
7046 
7047   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7048   pushOutChain(Result, EB);
7049 
7050   SDValue FPResult = Result.getValue(0);
7051   setValue(&FPI, FPResult);
7052 }
7053 
7054 std::pair<SDValue, SDValue>
7055 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7056                                     const BasicBlock *EHPadBB) {
7057   MachineFunction &MF = DAG.getMachineFunction();
7058   MachineModuleInfo &MMI = MF.getMMI();
7059   MCSymbol *BeginLabel = nullptr;
7060 
7061   if (EHPadBB) {
7062     // Insert a label before the invoke call to mark the try range.  This can be
7063     // used to detect deletion of the invoke via the MachineModuleInfo.
7064     BeginLabel = MMI.getContext().createTempSymbol();
7065 
7066     // For SjLj, keep track of which landing pads go with which invokes
7067     // so as to maintain the ordering of pads in the LSDA.
7068     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7069     if (CallSiteIndex) {
7070       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7071       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7072 
7073       // Now that the call site is handled, stop tracking it.
7074       MMI.setCurrentCallSite(0);
7075     }
7076 
7077     // Both PendingLoads and PendingExports must be flushed here;
7078     // this call might not return.
7079     (void)getRoot();
7080     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7081 
7082     CLI.setChain(getRoot());
7083   }
7084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7085   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7086 
7087   assert((CLI.IsTailCall || Result.second.getNode()) &&
7088          "Non-null chain expected with non-tail call!");
7089   assert((Result.second.getNode() || !Result.first.getNode()) &&
7090          "Null value expected with tail call!");
7091 
7092   if (!Result.second.getNode()) {
7093     // As a special case, a null chain means that a tail call has been emitted
7094     // and the DAG root is already updated.
7095     HasTailCall = true;
7096 
7097     // Since there's no actual continuation from this block, nothing can be
7098     // relying on us setting vregs for them.
7099     PendingExports.clear();
7100   } else {
7101     DAG.setRoot(Result.second);
7102   }
7103 
7104   if (EHPadBB) {
7105     // Insert a label at the end of the invoke call to mark the try range.  This
7106     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7107     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7108     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7109 
7110     // Inform MachineModuleInfo of range.
7111     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7112     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7113     // actually use outlined funclets and their LSDA info style.
7114     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7115       assert(CLI.CB);
7116       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7117       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7118     } else if (!isScopedEHPersonality(Pers)) {
7119       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7120     }
7121   }
7122 
7123   return Result;
7124 }
7125 
7126 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7127                                       bool isTailCall,
7128                                       const BasicBlock *EHPadBB) {
7129   auto &DL = DAG.getDataLayout();
7130   FunctionType *FTy = CB.getFunctionType();
7131   Type *RetTy = CB.getType();
7132 
7133   TargetLowering::ArgListTy Args;
7134   Args.reserve(CB.arg_size());
7135 
7136   const Value *SwiftErrorVal = nullptr;
7137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7138 
7139   if (isTailCall) {
7140     // Avoid emitting tail calls in functions with the disable-tail-calls
7141     // attribute.
7142     auto *Caller = CB.getParent()->getParent();
7143     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7144         "true")
7145       isTailCall = false;
7146 
7147     // We can't tail call inside a function with a swifterror argument. Lowering
7148     // does not support this yet. It would have to move into the swifterror
7149     // register before the call.
7150     if (TLI.supportSwiftError() &&
7151         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7152       isTailCall = false;
7153   }
7154 
7155   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7156     TargetLowering::ArgListEntry Entry;
7157     const Value *V = *I;
7158 
7159     // Skip empty types
7160     if (V->getType()->isEmptyTy())
7161       continue;
7162 
7163     SDValue ArgNode = getValue(V);
7164     Entry.Node = ArgNode; Entry.Ty = V->getType();
7165 
7166     Entry.setAttributes(&CB, I - CB.arg_begin());
7167 
7168     // Use swifterror virtual register as input to the call.
7169     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7170       SwiftErrorVal = V;
7171       // We find the virtual register for the actual swifterror argument.
7172       // Instead of using the Value, we use the virtual register instead.
7173       Entry.Node =
7174           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7175                           EVT(TLI.getPointerTy(DL)));
7176     }
7177 
7178     Args.push_back(Entry);
7179 
7180     // If we have an explicit sret argument that is an Instruction, (i.e., it
7181     // might point to function-local memory), we can't meaningfully tail-call.
7182     if (Entry.IsSRet && isa<Instruction>(V))
7183       isTailCall = false;
7184   }
7185 
7186   // If call site has a cfguardtarget operand bundle, create and add an
7187   // additional ArgListEntry.
7188   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7189     TargetLowering::ArgListEntry Entry;
7190     Value *V = Bundle->Inputs[0];
7191     SDValue ArgNode = getValue(V);
7192     Entry.Node = ArgNode;
7193     Entry.Ty = V->getType();
7194     Entry.IsCFGuardTarget = true;
7195     Args.push_back(Entry);
7196   }
7197 
7198   // Check if target-independent constraints permit a tail call here.
7199   // Target-dependent constraints are checked within TLI->LowerCallTo.
7200   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7201     isTailCall = false;
7202 
7203   // Disable tail calls if there is an swifterror argument. Targets have not
7204   // been updated to support tail calls.
7205   if (TLI.supportSwiftError() && SwiftErrorVal)
7206     isTailCall = false;
7207 
7208   TargetLowering::CallLoweringInfo CLI(DAG);
7209   CLI.setDebugLoc(getCurSDLoc())
7210       .setChain(getRoot())
7211       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7212       .setTailCall(isTailCall)
7213       .setConvergent(CB.isConvergent())
7214       .setIsPreallocated(
7215           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7216   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7217 
7218   if (Result.first.getNode()) {
7219     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7220     setValue(&CB, Result.first);
7221   }
7222 
7223   // The last element of CLI.InVals has the SDValue for swifterror return.
7224   // Here we copy it to a virtual register and update SwiftErrorMap for
7225   // book-keeping.
7226   if (SwiftErrorVal && TLI.supportSwiftError()) {
7227     // Get the last element of InVals.
7228     SDValue Src = CLI.InVals.back();
7229     Register VReg =
7230         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7231     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7232     DAG.setRoot(CopyNode);
7233   }
7234 }
7235 
7236 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7237                              SelectionDAGBuilder &Builder) {
7238   // Check to see if this load can be trivially constant folded, e.g. if the
7239   // input is from a string literal.
7240   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7241     // Cast pointer to the type we really want to load.
7242     Type *LoadTy =
7243         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7244     if (LoadVT.isVector())
7245       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7246 
7247     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7248                                          PointerType::getUnqual(LoadTy));
7249 
7250     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7251             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7252       return Builder.getValue(LoadCst);
7253   }
7254 
7255   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7256   // still constant memory, the input chain can be the entry node.
7257   SDValue Root;
7258   bool ConstantMemory = false;
7259 
7260   // Do not serialize (non-volatile) loads of constant memory with anything.
7261   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7262     Root = Builder.DAG.getEntryNode();
7263     ConstantMemory = true;
7264   } else {
7265     // Do not serialize non-volatile loads against each other.
7266     Root = Builder.DAG.getRoot();
7267   }
7268 
7269   SDValue Ptr = Builder.getValue(PtrVal);
7270   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7271                                         Ptr, MachinePointerInfo(PtrVal),
7272                                         /* Alignment = */ 1);
7273 
7274   if (!ConstantMemory)
7275     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7276   return LoadVal;
7277 }
7278 
7279 /// Record the value for an instruction that produces an integer result,
7280 /// converting the type where necessary.
7281 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7282                                                   SDValue Value,
7283                                                   bool IsSigned) {
7284   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7285                                                     I.getType(), true);
7286   if (IsSigned)
7287     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7288   else
7289     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7290   setValue(&I, Value);
7291 }
7292 
7293 /// See if we can lower a memcmp call into an optimized form. If so, return
7294 /// true and lower it. Otherwise return false, and it will be lowered like a
7295 /// normal call.
7296 /// The caller already checked that \p I calls the appropriate LibFunc with a
7297 /// correct prototype.
7298 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7299   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7300   const Value *Size = I.getArgOperand(2);
7301   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7302   if (CSize && CSize->getZExtValue() == 0) {
7303     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7304                                                           I.getType(), true);
7305     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7306     return true;
7307   }
7308 
7309   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7310   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7311       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7312       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7313   if (Res.first.getNode()) {
7314     processIntegerCallValue(I, Res.first, true);
7315     PendingLoads.push_back(Res.second);
7316     return true;
7317   }
7318 
7319   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7320   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7321   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7322     return false;
7323 
7324   // If the target has a fast compare for the given size, it will return a
7325   // preferred load type for that size. Require that the load VT is legal and
7326   // that the target supports unaligned loads of that type. Otherwise, return
7327   // INVALID.
7328   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7329     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7330     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7331     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7332       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7333       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7334       // TODO: Check alignment of src and dest ptrs.
7335       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7336       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7337       if (!TLI.isTypeLegal(LVT) ||
7338           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7339           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7340         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7341     }
7342 
7343     return LVT;
7344   };
7345 
7346   // This turns into unaligned loads. We only do this if the target natively
7347   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7348   // we'll only produce a small number of byte loads.
7349   MVT LoadVT;
7350   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7351   switch (NumBitsToCompare) {
7352   default:
7353     return false;
7354   case 16:
7355     LoadVT = MVT::i16;
7356     break;
7357   case 32:
7358     LoadVT = MVT::i32;
7359     break;
7360   case 64:
7361   case 128:
7362   case 256:
7363     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7364     break;
7365   }
7366 
7367   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7368     return false;
7369 
7370   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7371   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7372 
7373   // Bitcast to a wide integer type if the loads are vectors.
7374   if (LoadVT.isVector()) {
7375     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7376     LoadL = DAG.getBitcast(CmpVT, LoadL);
7377     LoadR = DAG.getBitcast(CmpVT, LoadR);
7378   }
7379 
7380   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7381   processIntegerCallValue(I, Cmp, false);
7382   return true;
7383 }
7384 
7385 /// See if we can lower a memchr call into an optimized form. If so, return
7386 /// true and lower it. Otherwise return false, and it will be lowered like a
7387 /// normal call.
7388 /// The caller already checked that \p I calls the appropriate LibFunc with a
7389 /// correct prototype.
7390 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7391   const Value *Src = I.getArgOperand(0);
7392   const Value *Char = I.getArgOperand(1);
7393   const Value *Length = I.getArgOperand(2);
7394 
7395   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7396   std::pair<SDValue, SDValue> Res =
7397     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7398                                 getValue(Src), getValue(Char), getValue(Length),
7399                                 MachinePointerInfo(Src));
7400   if (Res.first.getNode()) {
7401     setValue(&I, Res.first);
7402     PendingLoads.push_back(Res.second);
7403     return true;
7404   }
7405 
7406   return false;
7407 }
7408 
7409 /// See if we can lower a mempcpy call into an optimized form. If so, return
7410 /// true and lower it. Otherwise return false, and it will be lowered like a
7411 /// normal call.
7412 /// The caller already checked that \p I calls the appropriate LibFunc with a
7413 /// correct prototype.
7414 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7415   SDValue Dst = getValue(I.getArgOperand(0));
7416   SDValue Src = getValue(I.getArgOperand(1));
7417   SDValue Size = getValue(I.getArgOperand(2));
7418 
7419   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7420   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7421   // DAG::getMemcpy needs Alignment to be defined.
7422   Align Alignment = std::min(DstAlign, SrcAlign);
7423 
7424   bool isVol = false;
7425   SDLoc sdl = getCurSDLoc();
7426 
7427   // In the mempcpy context we need to pass in a false value for isTailCall
7428   // because the return pointer needs to be adjusted by the size of
7429   // the copied memory.
7430   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7431   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7432                              /*isTailCall=*/false,
7433                              MachinePointerInfo(I.getArgOperand(0)),
7434                              MachinePointerInfo(I.getArgOperand(1)));
7435   assert(MC.getNode() != nullptr &&
7436          "** memcpy should not be lowered as TailCall in mempcpy context **");
7437   DAG.setRoot(MC);
7438 
7439   // Check if Size needs to be truncated or extended.
7440   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7441 
7442   // Adjust return pointer to point just past the last dst byte.
7443   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7444                                     Dst, Size);
7445   setValue(&I, DstPlusSize);
7446   return true;
7447 }
7448 
7449 /// See if we can lower a strcpy call into an optimized form.  If so, return
7450 /// true and lower it, otherwise return false and it will be lowered like a
7451 /// normal call.
7452 /// The caller already checked that \p I calls the appropriate LibFunc with a
7453 /// correct prototype.
7454 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7455   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7456 
7457   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7458   std::pair<SDValue, SDValue> Res =
7459     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7460                                 getValue(Arg0), getValue(Arg1),
7461                                 MachinePointerInfo(Arg0),
7462                                 MachinePointerInfo(Arg1), isStpcpy);
7463   if (Res.first.getNode()) {
7464     setValue(&I, Res.first);
7465     DAG.setRoot(Res.second);
7466     return true;
7467   }
7468 
7469   return false;
7470 }
7471 
7472 /// See if we can lower a strcmp call into an optimized form.  If so, return
7473 /// true and lower it, otherwise return false and it will be lowered like a
7474 /// normal call.
7475 /// The caller already checked that \p I calls the appropriate LibFunc with a
7476 /// correct prototype.
7477 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7478   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7479 
7480   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7481   std::pair<SDValue, SDValue> Res =
7482     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7483                                 getValue(Arg0), getValue(Arg1),
7484                                 MachinePointerInfo(Arg0),
7485                                 MachinePointerInfo(Arg1));
7486   if (Res.first.getNode()) {
7487     processIntegerCallValue(I, Res.first, true);
7488     PendingLoads.push_back(Res.second);
7489     return true;
7490   }
7491 
7492   return false;
7493 }
7494 
7495 /// See if we can lower a strlen call into an optimized form.  If so, return
7496 /// true and lower it, otherwise return false and it will be lowered like a
7497 /// normal call.
7498 /// The caller already checked that \p I calls the appropriate LibFunc with a
7499 /// correct prototype.
7500 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7501   const Value *Arg0 = I.getArgOperand(0);
7502 
7503   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7504   std::pair<SDValue, SDValue> Res =
7505     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7506                                 getValue(Arg0), MachinePointerInfo(Arg0));
7507   if (Res.first.getNode()) {
7508     processIntegerCallValue(I, Res.first, false);
7509     PendingLoads.push_back(Res.second);
7510     return true;
7511   }
7512 
7513   return false;
7514 }
7515 
7516 /// See if we can lower a strnlen call into an optimized form.  If so, return
7517 /// true and lower it, otherwise return false and it will be lowered like a
7518 /// normal call.
7519 /// The caller already checked that \p I calls the appropriate LibFunc with a
7520 /// correct prototype.
7521 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7522   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7523 
7524   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7525   std::pair<SDValue, SDValue> Res =
7526     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7527                                  getValue(Arg0), getValue(Arg1),
7528                                  MachinePointerInfo(Arg0));
7529   if (Res.first.getNode()) {
7530     processIntegerCallValue(I, Res.first, false);
7531     PendingLoads.push_back(Res.second);
7532     return true;
7533   }
7534 
7535   return false;
7536 }
7537 
7538 /// See if we can lower a unary floating-point operation into an SDNode with
7539 /// the specified Opcode.  If so, return true and lower it, otherwise return
7540 /// false and it will be lowered like a normal call.
7541 /// The caller already checked that \p I calls the appropriate LibFunc with a
7542 /// correct prototype.
7543 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7544                                               unsigned Opcode) {
7545   // We already checked this call's prototype; verify it doesn't modify errno.
7546   if (!I.onlyReadsMemory())
7547     return false;
7548 
7549   SDValue Tmp = getValue(I.getArgOperand(0));
7550   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7551   return true;
7552 }
7553 
7554 /// See if we can lower a binary floating-point operation into an SDNode with
7555 /// the specified Opcode. If so, return true and lower it. Otherwise return
7556 /// false, and it will be lowered like a normal call.
7557 /// The caller already checked that \p I calls the appropriate LibFunc with a
7558 /// correct prototype.
7559 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7560                                                unsigned Opcode) {
7561   // We already checked this call's prototype; verify it doesn't modify errno.
7562   if (!I.onlyReadsMemory())
7563     return false;
7564 
7565   SDValue Tmp0 = getValue(I.getArgOperand(0));
7566   SDValue Tmp1 = getValue(I.getArgOperand(1));
7567   EVT VT = Tmp0.getValueType();
7568   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7569   return true;
7570 }
7571 
7572 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7573   // Handle inline assembly differently.
7574   if (I.isInlineAsm()) {
7575     visitInlineAsm(I);
7576     return;
7577   }
7578 
7579   if (Function *F = I.getCalledFunction()) {
7580     if (F->isDeclaration()) {
7581       // Is this an LLVM intrinsic or a target-specific intrinsic?
7582       unsigned IID = F->getIntrinsicID();
7583       if (!IID)
7584         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7585           IID = II->getIntrinsicID(F);
7586 
7587       if (IID) {
7588         visitIntrinsicCall(I, IID);
7589         return;
7590       }
7591     }
7592 
7593     // Check for well-known libc/libm calls.  If the function is internal, it
7594     // can't be a library call.  Don't do the check if marked as nobuiltin for
7595     // some reason or the call site requires strict floating point semantics.
7596     LibFunc Func;
7597     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7598         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7599         LibInfo->hasOptimizedCodeGen(Func)) {
7600       switch (Func) {
7601       default: break;
7602       case LibFunc_copysign:
7603       case LibFunc_copysignf:
7604       case LibFunc_copysignl:
7605         // We already checked this call's prototype; verify it doesn't modify
7606         // errno.
7607         if (I.onlyReadsMemory()) {
7608           SDValue LHS = getValue(I.getArgOperand(0));
7609           SDValue RHS = getValue(I.getArgOperand(1));
7610           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7611                                    LHS.getValueType(), LHS, RHS));
7612           return;
7613         }
7614         break;
7615       case LibFunc_fabs:
7616       case LibFunc_fabsf:
7617       case LibFunc_fabsl:
7618         if (visitUnaryFloatCall(I, ISD::FABS))
7619           return;
7620         break;
7621       case LibFunc_fmin:
7622       case LibFunc_fminf:
7623       case LibFunc_fminl:
7624         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7625           return;
7626         break;
7627       case LibFunc_fmax:
7628       case LibFunc_fmaxf:
7629       case LibFunc_fmaxl:
7630         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7631           return;
7632         break;
7633       case LibFunc_sin:
7634       case LibFunc_sinf:
7635       case LibFunc_sinl:
7636         if (visitUnaryFloatCall(I, ISD::FSIN))
7637           return;
7638         break;
7639       case LibFunc_cos:
7640       case LibFunc_cosf:
7641       case LibFunc_cosl:
7642         if (visitUnaryFloatCall(I, ISD::FCOS))
7643           return;
7644         break;
7645       case LibFunc_sqrt:
7646       case LibFunc_sqrtf:
7647       case LibFunc_sqrtl:
7648       case LibFunc_sqrt_finite:
7649       case LibFunc_sqrtf_finite:
7650       case LibFunc_sqrtl_finite:
7651         if (visitUnaryFloatCall(I, ISD::FSQRT))
7652           return;
7653         break;
7654       case LibFunc_floor:
7655       case LibFunc_floorf:
7656       case LibFunc_floorl:
7657         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7658           return;
7659         break;
7660       case LibFunc_nearbyint:
7661       case LibFunc_nearbyintf:
7662       case LibFunc_nearbyintl:
7663         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7664           return;
7665         break;
7666       case LibFunc_ceil:
7667       case LibFunc_ceilf:
7668       case LibFunc_ceill:
7669         if (visitUnaryFloatCall(I, ISD::FCEIL))
7670           return;
7671         break;
7672       case LibFunc_rint:
7673       case LibFunc_rintf:
7674       case LibFunc_rintl:
7675         if (visitUnaryFloatCall(I, ISD::FRINT))
7676           return;
7677         break;
7678       case LibFunc_round:
7679       case LibFunc_roundf:
7680       case LibFunc_roundl:
7681         if (visitUnaryFloatCall(I, ISD::FROUND))
7682           return;
7683         break;
7684       case LibFunc_trunc:
7685       case LibFunc_truncf:
7686       case LibFunc_truncl:
7687         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7688           return;
7689         break;
7690       case LibFunc_log2:
7691       case LibFunc_log2f:
7692       case LibFunc_log2l:
7693         if (visitUnaryFloatCall(I, ISD::FLOG2))
7694           return;
7695         break;
7696       case LibFunc_exp2:
7697       case LibFunc_exp2f:
7698       case LibFunc_exp2l:
7699         if (visitUnaryFloatCall(I, ISD::FEXP2))
7700           return;
7701         break;
7702       case LibFunc_memcmp:
7703         if (visitMemCmpCall(I))
7704           return;
7705         break;
7706       case LibFunc_mempcpy:
7707         if (visitMemPCpyCall(I))
7708           return;
7709         break;
7710       case LibFunc_memchr:
7711         if (visitMemChrCall(I))
7712           return;
7713         break;
7714       case LibFunc_strcpy:
7715         if (visitStrCpyCall(I, false))
7716           return;
7717         break;
7718       case LibFunc_stpcpy:
7719         if (visitStrCpyCall(I, true))
7720           return;
7721         break;
7722       case LibFunc_strcmp:
7723         if (visitStrCmpCall(I))
7724           return;
7725         break;
7726       case LibFunc_strlen:
7727         if (visitStrLenCall(I))
7728           return;
7729         break;
7730       case LibFunc_strnlen:
7731         if (visitStrNLenCall(I))
7732           return;
7733         break;
7734       }
7735     }
7736   }
7737 
7738   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7739   // have to do anything here to lower funclet bundles.
7740   // CFGuardTarget bundles are lowered in LowerCallTo.
7741   assert(!I.hasOperandBundlesOtherThan(
7742              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7743               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7744          "Cannot lower calls with arbitrary operand bundles!");
7745 
7746   SDValue Callee = getValue(I.getCalledOperand());
7747 
7748   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7749     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7750   else
7751     // Check if we can potentially perform a tail call. More detailed checking
7752     // is be done within LowerCallTo, after more information about the call is
7753     // known.
7754     LowerCallTo(I, Callee, I.isTailCall());
7755 }
7756 
7757 namespace {
7758 
7759 /// AsmOperandInfo - This contains information for each constraint that we are
7760 /// lowering.
7761 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7762 public:
7763   /// CallOperand - If this is the result output operand or a clobber
7764   /// this is null, otherwise it is the incoming operand to the CallInst.
7765   /// This gets modified as the asm is processed.
7766   SDValue CallOperand;
7767 
7768   /// AssignedRegs - If this is a register or register class operand, this
7769   /// contains the set of register corresponding to the operand.
7770   RegsForValue AssignedRegs;
7771 
7772   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7773     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7774   }
7775 
7776   /// Whether or not this operand accesses memory
7777   bool hasMemory(const TargetLowering &TLI) const {
7778     // Indirect operand accesses access memory.
7779     if (isIndirect)
7780       return true;
7781 
7782     for (const auto &Code : Codes)
7783       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7784         return true;
7785 
7786     return false;
7787   }
7788 
7789   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7790   /// corresponds to.  If there is no Value* for this operand, it returns
7791   /// MVT::Other.
7792   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7793                            const DataLayout &DL) const {
7794     if (!CallOperandVal) return MVT::Other;
7795 
7796     if (isa<BasicBlock>(CallOperandVal))
7797       return TLI.getProgramPointerTy(DL);
7798 
7799     llvm::Type *OpTy = CallOperandVal->getType();
7800 
7801     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7802     // If this is an indirect operand, the operand is a pointer to the
7803     // accessed type.
7804     if (isIndirect) {
7805       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7806       if (!PtrTy)
7807         report_fatal_error("Indirect operand for inline asm not a pointer!");
7808       OpTy = PtrTy->getElementType();
7809     }
7810 
7811     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7812     if (StructType *STy = dyn_cast<StructType>(OpTy))
7813       if (STy->getNumElements() == 1)
7814         OpTy = STy->getElementType(0);
7815 
7816     // If OpTy is not a single value, it may be a struct/union that we
7817     // can tile with integers.
7818     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7819       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7820       switch (BitSize) {
7821       default: break;
7822       case 1:
7823       case 8:
7824       case 16:
7825       case 32:
7826       case 64:
7827       case 128:
7828         OpTy = IntegerType::get(Context, BitSize);
7829         break;
7830       }
7831     }
7832 
7833     return TLI.getValueType(DL, OpTy, true);
7834   }
7835 };
7836 
7837 
7838 } // end anonymous namespace
7839 
7840 /// Make sure that the output operand \p OpInfo and its corresponding input
7841 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7842 /// out).
7843 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7844                                SDISelAsmOperandInfo &MatchingOpInfo,
7845                                SelectionDAG &DAG) {
7846   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7847     return;
7848 
7849   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7850   const auto &TLI = DAG.getTargetLoweringInfo();
7851 
7852   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7853       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7854                                        OpInfo.ConstraintVT);
7855   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7856       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7857                                        MatchingOpInfo.ConstraintVT);
7858   if ((OpInfo.ConstraintVT.isInteger() !=
7859        MatchingOpInfo.ConstraintVT.isInteger()) ||
7860       (MatchRC.second != InputRC.second)) {
7861     // FIXME: error out in a more elegant fashion
7862     report_fatal_error("Unsupported asm: input constraint"
7863                        " with a matching output constraint of"
7864                        " incompatible type!");
7865   }
7866   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7867 }
7868 
7869 /// Get a direct memory input to behave well as an indirect operand.
7870 /// This may introduce stores, hence the need for a \p Chain.
7871 /// \return The (possibly updated) chain.
7872 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7873                                         SDISelAsmOperandInfo &OpInfo,
7874                                         SelectionDAG &DAG) {
7875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7876 
7877   // If we don't have an indirect input, put it in the constpool if we can,
7878   // otherwise spill it to a stack slot.
7879   // TODO: This isn't quite right. We need to handle these according to
7880   // the addressing mode that the constraint wants. Also, this may take
7881   // an additional register for the computation and we don't want that
7882   // either.
7883 
7884   // If the operand is a float, integer, or vector constant, spill to a
7885   // constant pool entry to get its address.
7886   const Value *OpVal = OpInfo.CallOperandVal;
7887   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7888       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7889     OpInfo.CallOperand = DAG.getConstantPool(
7890         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7891     return Chain;
7892   }
7893 
7894   // Otherwise, create a stack slot and emit a store to it before the asm.
7895   Type *Ty = OpVal->getType();
7896   auto &DL = DAG.getDataLayout();
7897   uint64_t TySize = DL.getTypeAllocSize(Ty);
7898   MachineFunction &MF = DAG.getMachineFunction();
7899   int SSFI = MF.getFrameInfo().CreateStackObject(
7900       TySize, DL.getPrefTypeAlign(Ty), false);
7901   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7902   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7903                             MachinePointerInfo::getFixedStack(MF, SSFI),
7904                             TLI.getMemValueType(DL, Ty));
7905   OpInfo.CallOperand = StackSlot;
7906 
7907   return Chain;
7908 }
7909 
7910 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7911 /// specified operand.  We prefer to assign virtual registers, to allow the
7912 /// register allocator to handle the assignment process.  However, if the asm
7913 /// uses features that we can't model on machineinstrs, we have SDISel do the
7914 /// allocation.  This produces generally horrible, but correct, code.
7915 ///
7916 ///   OpInfo describes the operand
7917 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7918 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7919                                  SDISelAsmOperandInfo &OpInfo,
7920                                  SDISelAsmOperandInfo &RefOpInfo) {
7921   LLVMContext &Context = *DAG.getContext();
7922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7923 
7924   MachineFunction &MF = DAG.getMachineFunction();
7925   SmallVector<unsigned, 4> Regs;
7926   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7927 
7928   // No work to do for memory operations.
7929   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7930     return;
7931 
7932   // If this is a constraint for a single physreg, or a constraint for a
7933   // register class, find it.
7934   unsigned AssignedReg;
7935   const TargetRegisterClass *RC;
7936   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7937       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7938   // RC is unset only on failure. Return immediately.
7939   if (!RC)
7940     return;
7941 
7942   // Get the actual register value type.  This is important, because the user
7943   // may have asked for (e.g.) the AX register in i32 type.  We need to
7944   // remember that AX is actually i16 to get the right extension.
7945   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7946 
7947   if (OpInfo.ConstraintVT != MVT::Other) {
7948     // If this is an FP operand in an integer register (or visa versa), or more
7949     // generally if the operand value disagrees with the register class we plan
7950     // to stick it in, fix the operand type.
7951     //
7952     // If this is an input value, the bitcast to the new type is done now.
7953     // Bitcast for output value is done at the end of visitInlineAsm().
7954     if ((OpInfo.Type == InlineAsm::isOutput ||
7955          OpInfo.Type == InlineAsm::isInput) &&
7956         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7957       // Try to convert to the first EVT that the reg class contains.  If the
7958       // types are identical size, use a bitcast to convert (e.g. two differing
7959       // vector types).  Note: output bitcast is done at the end of
7960       // visitInlineAsm().
7961       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7962         // Exclude indirect inputs while they are unsupported because the code
7963         // to perform the load is missing and thus OpInfo.CallOperand still
7964         // refers to the input address rather than the pointed-to value.
7965         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7966           OpInfo.CallOperand =
7967               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7968         OpInfo.ConstraintVT = RegVT;
7969         // If the operand is an FP value and we want it in integer registers,
7970         // use the corresponding integer type. This turns an f64 value into
7971         // i64, which can be passed with two i32 values on a 32-bit machine.
7972       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7973         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7974         if (OpInfo.Type == InlineAsm::isInput)
7975           OpInfo.CallOperand =
7976               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7977         OpInfo.ConstraintVT = VT;
7978       }
7979     }
7980   }
7981 
7982   // No need to allocate a matching input constraint since the constraint it's
7983   // matching to has already been allocated.
7984   if (OpInfo.isMatchingInputConstraint())
7985     return;
7986 
7987   EVT ValueVT = OpInfo.ConstraintVT;
7988   if (OpInfo.ConstraintVT == MVT::Other)
7989     ValueVT = RegVT;
7990 
7991   // Initialize NumRegs.
7992   unsigned NumRegs = 1;
7993   if (OpInfo.ConstraintVT != MVT::Other)
7994     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7995 
7996   // If this is a constraint for a specific physical register, like {r17},
7997   // assign it now.
7998 
7999   // If this associated to a specific register, initialize iterator to correct
8000   // place. If virtual, make sure we have enough registers
8001 
8002   // Initialize iterator if necessary
8003   TargetRegisterClass::iterator I = RC->begin();
8004   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8005 
8006   // Do not check for single registers.
8007   if (AssignedReg) {
8008       for (; *I != AssignedReg; ++I)
8009         assert(I != RC->end() && "AssignedReg should be member of RC");
8010   }
8011 
8012   for (; NumRegs; --NumRegs, ++I) {
8013     assert(I != RC->end() && "Ran out of registers to allocate!");
8014     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8015     Regs.push_back(R);
8016   }
8017 
8018   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8019 }
8020 
8021 static unsigned
8022 findMatchingInlineAsmOperand(unsigned OperandNo,
8023                              const std::vector<SDValue> &AsmNodeOperands) {
8024   // Scan until we find the definition we already emitted of this operand.
8025   unsigned CurOp = InlineAsm::Op_FirstOperand;
8026   for (; OperandNo; --OperandNo) {
8027     // Advance to the next operand.
8028     unsigned OpFlag =
8029         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8030     assert((InlineAsm::isRegDefKind(OpFlag) ||
8031             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8032             InlineAsm::isMemKind(OpFlag)) &&
8033            "Skipped past definitions?");
8034     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8035   }
8036   return CurOp;
8037 }
8038 
8039 namespace {
8040 
8041 class ExtraFlags {
8042   unsigned Flags = 0;
8043 
8044 public:
8045   explicit ExtraFlags(const CallBase &Call) {
8046     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8047     if (IA->hasSideEffects())
8048       Flags |= InlineAsm::Extra_HasSideEffects;
8049     if (IA->isAlignStack())
8050       Flags |= InlineAsm::Extra_IsAlignStack;
8051     if (Call.isConvergent())
8052       Flags |= InlineAsm::Extra_IsConvergent;
8053     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8054   }
8055 
8056   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8057     // Ideally, we would only check against memory constraints.  However, the
8058     // meaning of an Other constraint can be target-specific and we can't easily
8059     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8060     // for Other constraints as well.
8061     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8062         OpInfo.ConstraintType == TargetLowering::C_Other) {
8063       if (OpInfo.Type == InlineAsm::isInput)
8064         Flags |= InlineAsm::Extra_MayLoad;
8065       else if (OpInfo.Type == InlineAsm::isOutput)
8066         Flags |= InlineAsm::Extra_MayStore;
8067       else if (OpInfo.Type == InlineAsm::isClobber)
8068         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8069     }
8070   }
8071 
8072   unsigned get() const { return Flags; }
8073 };
8074 
8075 } // end anonymous namespace
8076 
8077 /// visitInlineAsm - Handle a call to an InlineAsm object.
8078 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8079   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8080 
8081   /// ConstraintOperands - Information about all of the constraints.
8082   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8083 
8084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8085   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8086       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8087 
8088   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8089   // AsmDialect, MayLoad, MayStore).
8090   bool HasSideEffect = IA->hasSideEffects();
8091   ExtraFlags ExtraInfo(Call);
8092 
8093   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8094   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8095   unsigned NumMatchingOps = 0;
8096   for (auto &T : TargetConstraints) {
8097     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8098     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8099 
8100     // Compute the value type for each operand.
8101     if (OpInfo.Type == InlineAsm::isInput ||
8102         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8103       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8104 
8105       // Process the call argument. BasicBlocks are labels, currently appearing
8106       // only in asm's.
8107       if (isa<CallBrInst>(Call) &&
8108           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8109                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8110                         NumMatchingOps) &&
8111           (NumMatchingOps == 0 ||
8112            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8113                         NumMatchingOps))) {
8114         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8115         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8116         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8117       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8118         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8119       } else {
8120         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8121       }
8122 
8123       OpInfo.ConstraintVT =
8124           OpInfo
8125               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8126               .getSimpleVT();
8127     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8128       // The return value of the call is this value.  As such, there is no
8129       // corresponding argument.
8130       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8131       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8132         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8133             DAG.getDataLayout(), STy->getElementType(ResNo));
8134       } else {
8135         assert(ResNo == 0 && "Asm only has one result!");
8136         OpInfo.ConstraintVT =
8137             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8138       }
8139       ++ResNo;
8140     } else {
8141       OpInfo.ConstraintVT = MVT::Other;
8142     }
8143 
8144     if (OpInfo.hasMatchingInput())
8145       ++NumMatchingOps;
8146 
8147     if (!HasSideEffect)
8148       HasSideEffect = OpInfo.hasMemory(TLI);
8149 
8150     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8151     // FIXME: Could we compute this on OpInfo rather than T?
8152 
8153     // Compute the constraint code and ConstraintType to use.
8154     TLI.ComputeConstraintToUse(T, SDValue());
8155 
8156     if (T.ConstraintType == TargetLowering::C_Immediate &&
8157         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8158       // We've delayed emitting a diagnostic like the "n" constraint because
8159       // inlining could cause an integer showing up.
8160       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8161                                           "' expects an integer constant "
8162                                           "expression");
8163 
8164     ExtraInfo.update(T);
8165   }
8166 
8167 
8168   // We won't need to flush pending loads if this asm doesn't touch
8169   // memory and is nonvolatile.
8170   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8171 
8172   bool IsCallBr = isa<CallBrInst>(Call);
8173   if (IsCallBr) {
8174     // If this is a callbr we need to flush pending exports since inlineasm_br
8175     // is a terminator. We need to do this before nodes are glued to
8176     // the inlineasm_br node.
8177     Chain = getControlRoot();
8178   }
8179 
8180   // Second pass over the constraints: compute which constraint option to use.
8181   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8182     // If this is an output operand with a matching input operand, look up the
8183     // matching input. If their types mismatch, e.g. one is an integer, the
8184     // other is floating point, or their sizes are different, flag it as an
8185     // error.
8186     if (OpInfo.hasMatchingInput()) {
8187       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8188       patchMatchingInput(OpInfo, Input, DAG);
8189     }
8190 
8191     // Compute the constraint code and ConstraintType to use.
8192     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8193 
8194     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8195         OpInfo.Type == InlineAsm::isClobber)
8196       continue;
8197 
8198     // If this is a memory input, and if the operand is not indirect, do what we
8199     // need to provide an address for the memory input.
8200     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8201         !OpInfo.isIndirect) {
8202       assert((OpInfo.isMultipleAlternative ||
8203               (OpInfo.Type == InlineAsm::isInput)) &&
8204              "Can only indirectify direct input operands!");
8205 
8206       // Memory operands really want the address of the value.
8207       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8208 
8209       // There is no longer a Value* corresponding to this operand.
8210       OpInfo.CallOperandVal = nullptr;
8211 
8212       // It is now an indirect operand.
8213       OpInfo.isIndirect = true;
8214     }
8215 
8216   }
8217 
8218   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8219   std::vector<SDValue> AsmNodeOperands;
8220   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8221   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8222       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8223 
8224   // If we have a !srcloc metadata node associated with it, we want to attach
8225   // this to the ultimately generated inline asm machineinstr.  To do this, we
8226   // pass in the third operand as this (potentially null) inline asm MDNode.
8227   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8228   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8229 
8230   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8231   // bits as operand 3.
8232   AsmNodeOperands.push_back(DAG.getTargetConstant(
8233       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8234 
8235   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8236   // this, assign virtual and physical registers for inputs and otput.
8237   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8238     // Assign Registers.
8239     SDISelAsmOperandInfo &RefOpInfo =
8240         OpInfo.isMatchingInputConstraint()
8241             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8242             : OpInfo;
8243     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8244 
8245     auto DetectWriteToReservedRegister = [&]() {
8246       const MachineFunction &MF = DAG.getMachineFunction();
8247       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8248       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8249         if (Register::isPhysicalRegister(Reg) &&
8250             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8251           const char *RegName = TRI.getName(Reg);
8252           emitInlineAsmError(Call, "write to reserved register '" +
8253                                        Twine(RegName) + "'");
8254           return true;
8255         }
8256       }
8257       return false;
8258     };
8259 
8260     switch (OpInfo.Type) {
8261     case InlineAsm::isOutput:
8262       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8263         unsigned ConstraintID =
8264             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8265         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8266                "Failed to convert memory constraint code to constraint id.");
8267 
8268         // Add information to the INLINEASM node to know about this output.
8269         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8270         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8271         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8272                                                         MVT::i32));
8273         AsmNodeOperands.push_back(OpInfo.CallOperand);
8274       } else {
8275         // Otherwise, this outputs to a register (directly for C_Register /
8276         // C_RegisterClass, and a target-defined fashion for
8277         // C_Immediate/C_Other). Find a register that we can use.
8278         if (OpInfo.AssignedRegs.Regs.empty()) {
8279           emitInlineAsmError(
8280               Call, "couldn't allocate output register for constraint '" +
8281                         Twine(OpInfo.ConstraintCode) + "'");
8282           return;
8283         }
8284 
8285         if (DetectWriteToReservedRegister())
8286           return;
8287 
8288         // Add information to the INLINEASM node to know that this register is
8289         // set.
8290         OpInfo.AssignedRegs.AddInlineAsmOperands(
8291             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8292                                   : InlineAsm::Kind_RegDef,
8293             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8294       }
8295       break;
8296 
8297     case InlineAsm::isInput: {
8298       SDValue InOperandVal = OpInfo.CallOperand;
8299 
8300       if (OpInfo.isMatchingInputConstraint()) {
8301         // If this is required to match an output register we have already set,
8302         // just use its register.
8303         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8304                                                   AsmNodeOperands);
8305         unsigned OpFlag =
8306           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8307         if (InlineAsm::isRegDefKind(OpFlag) ||
8308             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8309           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8310           if (OpInfo.isIndirect) {
8311             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8312             emitInlineAsmError(Call, "inline asm not supported yet: "
8313                                      "don't know how to handle tied "
8314                                      "indirect register inputs");
8315             return;
8316           }
8317 
8318           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8319           SmallVector<unsigned, 4> Regs;
8320 
8321           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8322             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8323             MachineRegisterInfo &RegInfo =
8324                 DAG.getMachineFunction().getRegInfo();
8325             for (unsigned i = 0; i != NumRegs; ++i)
8326               Regs.push_back(RegInfo.createVirtualRegister(RC));
8327           } else {
8328             emitInlineAsmError(Call,
8329                                "inline asm error: This value type register "
8330                                "class is not natively supported!");
8331             return;
8332           }
8333 
8334           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8335 
8336           SDLoc dl = getCurSDLoc();
8337           // Use the produced MatchedRegs object to
8338           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8339           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8340                                            true, OpInfo.getMatchedOperand(), dl,
8341                                            DAG, AsmNodeOperands);
8342           break;
8343         }
8344 
8345         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8346         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8347                "Unexpected number of operands");
8348         // Add information to the INLINEASM node to know about this input.
8349         // See InlineAsm.h isUseOperandTiedToDef.
8350         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8351         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8352                                                     OpInfo.getMatchedOperand());
8353         AsmNodeOperands.push_back(DAG.getTargetConstant(
8354             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8355         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8356         break;
8357       }
8358 
8359       // Treat indirect 'X' constraint as memory.
8360       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8361           OpInfo.isIndirect)
8362         OpInfo.ConstraintType = TargetLowering::C_Memory;
8363 
8364       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8365           OpInfo.ConstraintType == TargetLowering::C_Other) {
8366         std::vector<SDValue> Ops;
8367         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8368                                           Ops, DAG);
8369         if (Ops.empty()) {
8370           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8371             if (isa<ConstantSDNode>(InOperandVal)) {
8372               emitInlineAsmError(Call, "value out of range for constraint '" +
8373                                            Twine(OpInfo.ConstraintCode) + "'");
8374               return;
8375             }
8376 
8377           emitInlineAsmError(Call,
8378                              "invalid operand for inline asm constraint '" +
8379                                  Twine(OpInfo.ConstraintCode) + "'");
8380           return;
8381         }
8382 
8383         // Add information to the INLINEASM node to know about this input.
8384         unsigned ResOpType =
8385           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8386         AsmNodeOperands.push_back(DAG.getTargetConstant(
8387             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8388         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8389         break;
8390       }
8391 
8392       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8393         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8394         assert(InOperandVal.getValueType() ==
8395                    TLI.getPointerTy(DAG.getDataLayout()) &&
8396                "Memory operands expect pointer values");
8397 
8398         unsigned ConstraintID =
8399             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8400         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8401                "Failed to convert memory constraint code to constraint id.");
8402 
8403         // Add information to the INLINEASM node to know about this input.
8404         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8405         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8406         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8407                                                         getCurSDLoc(),
8408                                                         MVT::i32));
8409         AsmNodeOperands.push_back(InOperandVal);
8410         break;
8411       }
8412 
8413       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8414               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8415              "Unknown constraint type!");
8416 
8417       // TODO: Support this.
8418       if (OpInfo.isIndirect) {
8419         emitInlineAsmError(
8420             Call, "Don't know how to handle indirect register inputs yet "
8421                   "for constraint '" +
8422                       Twine(OpInfo.ConstraintCode) + "'");
8423         return;
8424       }
8425 
8426       // Copy the input into the appropriate registers.
8427       if (OpInfo.AssignedRegs.Regs.empty()) {
8428         emitInlineAsmError(Call,
8429                            "couldn't allocate input reg for constraint '" +
8430                                Twine(OpInfo.ConstraintCode) + "'");
8431         return;
8432       }
8433 
8434       if (DetectWriteToReservedRegister())
8435         return;
8436 
8437       SDLoc dl = getCurSDLoc();
8438 
8439       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8440                                         &Call);
8441 
8442       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8443                                                dl, DAG, AsmNodeOperands);
8444       break;
8445     }
8446     case InlineAsm::isClobber:
8447       // Add the clobbered value to the operand list, so that the register
8448       // allocator is aware that the physreg got clobbered.
8449       if (!OpInfo.AssignedRegs.Regs.empty())
8450         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8451                                                  false, 0, getCurSDLoc(), DAG,
8452                                                  AsmNodeOperands);
8453       break;
8454     }
8455   }
8456 
8457   // Finish up input operands.  Set the input chain and add the flag last.
8458   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8459   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8460 
8461   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8462   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8463                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8464   Flag = Chain.getValue(1);
8465 
8466   // Do additional work to generate outputs.
8467 
8468   SmallVector<EVT, 1> ResultVTs;
8469   SmallVector<SDValue, 1> ResultValues;
8470   SmallVector<SDValue, 8> OutChains;
8471 
8472   llvm::Type *CallResultType = Call.getType();
8473   ArrayRef<Type *> ResultTypes;
8474   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8475     ResultTypes = StructResult->elements();
8476   else if (!CallResultType->isVoidTy())
8477     ResultTypes = makeArrayRef(CallResultType);
8478 
8479   auto CurResultType = ResultTypes.begin();
8480   auto handleRegAssign = [&](SDValue V) {
8481     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8482     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8483     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8484     ++CurResultType;
8485     // If the type of the inline asm call site return value is different but has
8486     // same size as the type of the asm output bitcast it.  One example of this
8487     // is for vectors with different width / number of elements.  This can
8488     // happen for register classes that can contain multiple different value
8489     // types.  The preg or vreg allocated may not have the same VT as was
8490     // expected.
8491     //
8492     // This can also happen for a return value that disagrees with the register
8493     // class it is put in, eg. a double in a general-purpose register on a
8494     // 32-bit machine.
8495     if (ResultVT != V.getValueType() &&
8496         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8497       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8498     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8499              V.getValueType().isInteger()) {
8500       // If a result value was tied to an input value, the computed result
8501       // may have a wider width than the expected result.  Extract the
8502       // relevant portion.
8503       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8504     }
8505     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8506     ResultVTs.push_back(ResultVT);
8507     ResultValues.push_back(V);
8508   };
8509 
8510   // Deal with output operands.
8511   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8512     if (OpInfo.Type == InlineAsm::isOutput) {
8513       SDValue Val;
8514       // Skip trivial output operands.
8515       if (OpInfo.AssignedRegs.Regs.empty())
8516         continue;
8517 
8518       switch (OpInfo.ConstraintType) {
8519       case TargetLowering::C_Register:
8520       case TargetLowering::C_RegisterClass:
8521         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8522                                                   Chain, &Flag, &Call);
8523         break;
8524       case TargetLowering::C_Immediate:
8525       case TargetLowering::C_Other:
8526         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8527                                               OpInfo, DAG);
8528         break;
8529       case TargetLowering::C_Memory:
8530         break; // Already handled.
8531       case TargetLowering::C_Unknown:
8532         assert(false && "Unexpected unknown constraint");
8533       }
8534 
8535       // Indirect output manifest as stores. Record output chains.
8536       if (OpInfo.isIndirect) {
8537         const Value *Ptr = OpInfo.CallOperandVal;
8538         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8539         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8540                                      MachinePointerInfo(Ptr));
8541         OutChains.push_back(Store);
8542       } else {
8543         // generate CopyFromRegs to associated registers.
8544         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8545         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8546           for (const SDValue &V : Val->op_values())
8547             handleRegAssign(V);
8548         } else
8549           handleRegAssign(Val);
8550       }
8551     }
8552   }
8553 
8554   // Set results.
8555   if (!ResultValues.empty()) {
8556     assert(CurResultType == ResultTypes.end() &&
8557            "Mismatch in number of ResultTypes");
8558     assert(ResultValues.size() == ResultTypes.size() &&
8559            "Mismatch in number of output operands in asm result");
8560 
8561     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8562                             DAG.getVTList(ResultVTs), ResultValues);
8563     setValue(&Call, V);
8564   }
8565 
8566   // Collect store chains.
8567   if (!OutChains.empty())
8568     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8569 
8570   // Only Update Root if inline assembly has a memory effect.
8571   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8572     DAG.setRoot(Chain);
8573 }
8574 
8575 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8576                                              const Twine &Message) {
8577   LLVMContext &Ctx = *DAG.getContext();
8578   Ctx.emitError(&Call, Message);
8579 
8580   // Make sure we leave the DAG in a valid state
8581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8582   SmallVector<EVT, 1> ValueVTs;
8583   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8584 
8585   if (ValueVTs.empty())
8586     return;
8587 
8588   SmallVector<SDValue, 1> Ops;
8589   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8590     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8591 
8592   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8593 }
8594 
8595 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8596   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8597                           MVT::Other, getRoot(),
8598                           getValue(I.getArgOperand(0)),
8599                           DAG.getSrcValue(I.getArgOperand(0))));
8600 }
8601 
8602 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8604   const DataLayout &DL = DAG.getDataLayout();
8605   SDValue V = DAG.getVAArg(
8606       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8607       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8608       DL.getABITypeAlign(I.getType()).value());
8609   DAG.setRoot(V.getValue(1));
8610 
8611   if (I.getType()->isPointerTy())
8612     V = DAG.getPtrExtOrTrunc(
8613         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8614   setValue(&I, V);
8615 }
8616 
8617 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8618   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8619                           MVT::Other, getRoot(),
8620                           getValue(I.getArgOperand(0)),
8621                           DAG.getSrcValue(I.getArgOperand(0))));
8622 }
8623 
8624 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8625   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8626                           MVT::Other, getRoot(),
8627                           getValue(I.getArgOperand(0)),
8628                           getValue(I.getArgOperand(1)),
8629                           DAG.getSrcValue(I.getArgOperand(0)),
8630                           DAG.getSrcValue(I.getArgOperand(1))));
8631 }
8632 
8633 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8634                                                     const Instruction &I,
8635                                                     SDValue Op) {
8636   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8637   if (!Range)
8638     return Op;
8639 
8640   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8641   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8642     return Op;
8643 
8644   APInt Lo = CR.getUnsignedMin();
8645   if (!Lo.isMinValue())
8646     return Op;
8647 
8648   APInt Hi = CR.getUnsignedMax();
8649   unsigned Bits = std::max(Hi.getActiveBits(),
8650                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8651 
8652   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8653 
8654   SDLoc SL = getCurSDLoc();
8655 
8656   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8657                              DAG.getValueType(SmallVT));
8658   unsigned NumVals = Op.getNode()->getNumValues();
8659   if (NumVals == 1)
8660     return ZExt;
8661 
8662   SmallVector<SDValue, 4> Ops;
8663 
8664   Ops.push_back(ZExt);
8665   for (unsigned I = 1; I != NumVals; ++I)
8666     Ops.push_back(Op.getValue(I));
8667 
8668   return DAG.getMergeValues(Ops, SL);
8669 }
8670 
8671 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8672 /// the call being lowered.
8673 ///
8674 /// This is a helper for lowering intrinsics that follow a target calling
8675 /// convention or require stack pointer adjustment. Only a subset of the
8676 /// intrinsic's operands need to participate in the calling convention.
8677 void SelectionDAGBuilder::populateCallLoweringInfo(
8678     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8679     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8680     bool IsPatchPoint) {
8681   TargetLowering::ArgListTy Args;
8682   Args.reserve(NumArgs);
8683 
8684   // Populate the argument list.
8685   // Attributes for args start at offset 1, after the return attribute.
8686   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8687        ArgI != ArgE; ++ArgI) {
8688     const Value *V = Call->getOperand(ArgI);
8689 
8690     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8691 
8692     TargetLowering::ArgListEntry Entry;
8693     Entry.Node = getValue(V);
8694     Entry.Ty = V->getType();
8695     Entry.setAttributes(Call, ArgI);
8696     Args.push_back(Entry);
8697   }
8698 
8699   CLI.setDebugLoc(getCurSDLoc())
8700       .setChain(getRoot())
8701       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8702       .setDiscardResult(Call->use_empty())
8703       .setIsPatchPoint(IsPatchPoint)
8704       .setIsPreallocated(
8705           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8706 }
8707 
8708 /// Add a stack map intrinsic call's live variable operands to a stackmap
8709 /// or patchpoint target node's operand list.
8710 ///
8711 /// Constants are converted to TargetConstants purely as an optimization to
8712 /// avoid constant materialization and register allocation.
8713 ///
8714 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8715 /// generate addess computation nodes, and so FinalizeISel can convert the
8716 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8717 /// address materialization and register allocation, but may also be required
8718 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8719 /// alloca in the entry block, then the runtime may assume that the alloca's
8720 /// StackMap location can be read immediately after compilation and that the
8721 /// location is valid at any point during execution (this is similar to the
8722 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8723 /// only available in a register, then the runtime would need to trap when
8724 /// execution reaches the StackMap in order to read the alloca's location.
8725 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8726                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8727                                 SelectionDAGBuilder &Builder) {
8728   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8729     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8730     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8731       Ops.push_back(
8732         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8733       Ops.push_back(
8734         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8735     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8736       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8737       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8738           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8739     } else
8740       Ops.push_back(OpVal);
8741   }
8742 }
8743 
8744 /// Lower llvm.experimental.stackmap directly to its target opcode.
8745 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8746   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8747   //                                  [live variables...])
8748 
8749   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8750 
8751   SDValue Chain, InFlag, Callee, NullPtr;
8752   SmallVector<SDValue, 32> Ops;
8753 
8754   SDLoc DL = getCurSDLoc();
8755   Callee = getValue(CI.getCalledOperand());
8756   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8757 
8758   // The stackmap intrinsic only records the live variables (the arguments
8759   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8760   // intrinsic, this won't be lowered to a function call. This means we don't
8761   // have to worry about calling conventions and target specific lowering code.
8762   // Instead we perform the call lowering right here.
8763   //
8764   // chain, flag = CALLSEQ_START(chain, 0, 0)
8765   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8766   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8767   //
8768   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8769   InFlag = Chain.getValue(1);
8770 
8771   // Add the <id> and <numBytes> constants.
8772   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8773   Ops.push_back(DAG.getTargetConstant(
8774                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8775   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8776   Ops.push_back(DAG.getTargetConstant(
8777                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8778                   MVT::i32));
8779 
8780   // Push live variables for the stack map.
8781   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8782 
8783   // We are not pushing any register mask info here on the operands list,
8784   // because the stackmap doesn't clobber anything.
8785 
8786   // Push the chain and the glue flag.
8787   Ops.push_back(Chain);
8788   Ops.push_back(InFlag);
8789 
8790   // Create the STACKMAP node.
8791   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8792   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8793   Chain = SDValue(SM, 0);
8794   InFlag = Chain.getValue(1);
8795 
8796   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8797 
8798   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8799 
8800   // Set the root to the target-lowered call chain.
8801   DAG.setRoot(Chain);
8802 
8803   // Inform the Frame Information that we have a stackmap in this function.
8804   FuncInfo.MF->getFrameInfo().setHasStackMap();
8805 }
8806 
8807 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8808 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8809                                           const BasicBlock *EHPadBB) {
8810   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8811   //                                                 i32 <numBytes>,
8812   //                                                 i8* <target>,
8813   //                                                 i32 <numArgs>,
8814   //                                                 [Args...],
8815   //                                                 [live variables...])
8816 
8817   CallingConv::ID CC = CB.getCallingConv();
8818   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8819   bool HasDef = !CB.getType()->isVoidTy();
8820   SDLoc dl = getCurSDLoc();
8821   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8822 
8823   // Handle immediate and symbolic callees.
8824   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8825     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8826                                    /*isTarget=*/true);
8827   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8828     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8829                                          SDLoc(SymbolicCallee),
8830                                          SymbolicCallee->getValueType(0));
8831 
8832   // Get the real number of arguments participating in the call <numArgs>
8833   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8834   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8835 
8836   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8837   // Intrinsics include all meta-operands up to but not including CC.
8838   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8839   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8840          "Not enough arguments provided to the patchpoint intrinsic");
8841 
8842   // For AnyRegCC the arguments are lowered later on manually.
8843   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8844   Type *ReturnTy =
8845       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8846 
8847   TargetLowering::CallLoweringInfo CLI(DAG);
8848   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8849                            ReturnTy, true);
8850   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8851 
8852   SDNode *CallEnd = Result.second.getNode();
8853   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8854     CallEnd = CallEnd->getOperand(0).getNode();
8855 
8856   /// Get a call instruction from the call sequence chain.
8857   /// Tail calls are not allowed.
8858   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8859          "Expected a callseq node.");
8860   SDNode *Call = CallEnd->getOperand(0).getNode();
8861   bool HasGlue = Call->getGluedNode();
8862 
8863   // Replace the target specific call node with the patchable intrinsic.
8864   SmallVector<SDValue, 8> Ops;
8865 
8866   // Add the <id> and <numBytes> constants.
8867   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8868   Ops.push_back(DAG.getTargetConstant(
8869                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8870   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8871   Ops.push_back(DAG.getTargetConstant(
8872                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8873                   MVT::i32));
8874 
8875   // Add the callee.
8876   Ops.push_back(Callee);
8877 
8878   // Adjust <numArgs> to account for any arguments that have been passed on the
8879   // stack instead.
8880   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8881   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8882   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8883   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8884 
8885   // Add the calling convention
8886   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8887 
8888   // Add the arguments we omitted previously. The register allocator should
8889   // place these in any free register.
8890   if (IsAnyRegCC)
8891     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8892       Ops.push_back(getValue(CB.getArgOperand(i)));
8893 
8894   // Push the arguments from the call instruction up to the register mask.
8895   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8896   Ops.append(Call->op_begin() + 2, e);
8897 
8898   // Push live variables for the stack map.
8899   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8900 
8901   // Push the register mask info.
8902   if (HasGlue)
8903     Ops.push_back(*(Call->op_end()-2));
8904   else
8905     Ops.push_back(*(Call->op_end()-1));
8906 
8907   // Push the chain (this is originally the first operand of the call, but
8908   // becomes now the last or second to last operand).
8909   Ops.push_back(*(Call->op_begin()));
8910 
8911   // Push the glue flag (last operand).
8912   if (HasGlue)
8913     Ops.push_back(*(Call->op_end()-1));
8914 
8915   SDVTList NodeTys;
8916   if (IsAnyRegCC && HasDef) {
8917     // Create the return types based on the intrinsic definition
8918     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8919     SmallVector<EVT, 3> ValueVTs;
8920     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8921     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8922 
8923     // There is always a chain and a glue type at the end
8924     ValueVTs.push_back(MVT::Other);
8925     ValueVTs.push_back(MVT::Glue);
8926     NodeTys = DAG.getVTList(ValueVTs);
8927   } else
8928     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8929 
8930   // Replace the target specific call node with a PATCHPOINT node.
8931   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8932                                          dl, NodeTys, Ops);
8933 
8934   // Update the NodeMap.
8935   if (HasDef) {
8936     if (IsAnyRegCC)
8937       setValue(&CB, SDValue(MN, 0));
8938     else
8939       setValue(&CB, Result.first);
8940   }
8941 
8942   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8943   // call sequence. Furthermore the location of the chain and glue can change
8944   // when the AnyReg calling convention is used and the intrinsic returns a
8945   // value.
8946   if (IsAnyRegCC && HasDef) {
8947     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8948     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8949     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8950   } else
8951     DAG.ReplaceAllUsesWith(Call, MN);
8952   DAG.DeleteNode(Call);
8953 
8954   // Inform the Frame Information that we have a patchpoint in this function.
8955   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8956 }
8957 
8958 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8959                                             unsigned Intrinsic) {
8960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8961   SDValue Op1 = getValue(I.getArgOperand(0));
8962   SDValue Op2;
8963   if (I.getNumArgOperands() > 1)
8964     Op2 = getValue(I.getArgOperand(1));
8965   SDLoc dl = getCurSDLoc();
8966   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8967   SDValue Res;
8968   FastMathFlags FMF;
8969   if (isa<FPMathOperator>(I))
8970     FMF = I.getFastMathFlags();
8971 
8972   switch (Intrinsic) {
8973   case Intrinsic::experimental_vector_reduce_v2_fadd:
8974     if (FMF.allowReassoc())
8975       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8976                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8977     else
8978       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8979     break;
8980   case Intrinsic::experimental_vector_reduce_v2_fmul:
8981     if (FMF.allowReassoc())
8982       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8983                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8984     else
8985       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8986     break;
8987   case Intrinsic::experimental_vector_reduce_add:
8988     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8989     break;
8990   case Intrinsic::experimental_vector_reduce_mul:
8991     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8992     break;
8993   case Intrinsic::experimental_vector_reduce_and:
8994     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8995     break;
8996   case Intrinsic::experimental_vector_reduce_or:
8997     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8998     break;
8999   case Intrinsic::experimental_vector_reduce_xor:
9000     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9001     break;
9002   case Intrinsic::experimental_vector_reduce_smax:
9003     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9004     break;
9005   case Intrinsic::experimental_vector_reduce_smin:
9006     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9007     break;
9008   case Intrinsic::experimental_vector_reduce_umax:
9009     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9010     break;
9011   case Intrinsic::experimental_vector_reduce_umin:
9012     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9013     break;
9014   case Intrinsic::experimental_vector_reduce_fmax:
9015     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9016     break;
9017   case Intrinsic::experimental_vector_reduce_fmin:
9018     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9019     break;
9020   default:
9021     llvm_unreachable("Unhandled vector reduce intrinsic");
9022   }
9023   setValue(&I, Res);
9024 }
9025 
9026 /// Returns an AttributeList representing the attributes applied to the return
9027 /// value of the given call.
9028 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9029   SmallVector<Attribute::AttrKind, 2> Attrs;
9030   if (CLI.RetSExt)
9031     Attrs.push_back(Attribute::SExt);
9032   if (CLI.RetZExt)
9033     Attrs.push_back(Attribute::ZExt);
9034   if (CLI.IsInReg)
9035     Attrs.push_back(Attribute::InReg);
9036 
9037   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9038                             Attrs);
9039 }
9040 
9041 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9042 /// implementation, which just calls LowerCall.
9043 /// FIXME: When all targets are
9044 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9045 std::pair<SDValue, SDValue>
9046 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9047   // Handle the incoming return values from the call.
9048   CLI.Ins.clear();
9049   Type *OrigRetTy = CLI.RetTy;
9050   SmallVector<EVT, 4> RetTys;
9051   SmallVector<uint64_t, 4> Offsets;
9052   auto &DL = CLI.DAG.getDataLayout();
9053   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9054 
9055   if (CLI.IsPostTypeLegalization) {
9056     // If we are lowering a libcall after legalization, split the return type.
9057     SmallVector<EVT, 4> OldRetTys;
9058     SmallVector<uint64_t, 4> OldOffsets;
9059     RetTys.swap(OldRetTys);
9060     Offsets.swap(OldOffsets);
9061 
9062     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9063       EVT RetVT = OldRetTys[i];
9064       uint64_t Offset = OldOffsets[i];
9065       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9066       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9067       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9068       RetTys.append(NumRegs, RegisterVT);
9069       for (unsigned j = 0; j != NumRegs; ++j)
9070         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9071     }
9072   }
9073 
9074   SmallVector<ISD::OutputArg, 4> Outs;
9075   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9076 
9077   bool CanLowerReturn =
9078       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9079                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9080 
9081   SDValue DemoteStackSlot;
9082   int DemoteStackIdx = -100;
9083   if (!CanLowerReturn) {
9084     // FIXME: equivalent assert?
9085     // assert(!CS.hasInAllocaArgument() &&
9086     //        "sret demotion is incompatible with inalloca");
9087     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9088     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9089     MachineFunction &MF = CLI.DAG.getMachineFunction();
9090     DemoteStackIdx =
9091         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9092     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9093                                               DL.getAllocaAddrSpace());
9094 
9095     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9096     ArgListEntry Entry;
9097     Entry.Node = DemoteStackSlot;
9098     Entry.Ty = StackSlotPtrType;
9099     Entry.IsSExt = false;
9100     Entry.IsZExt = false;
9101     Entry.IsInReg = false;
9102     Entry.IsSRet = true;
9103     Entry.IsNest = false;
9104     Entry.IsByVal = false;
9105     Entry.IsReturned = false;
9106     Entry.IsSwiftSelf = false;
9107     Entry.IsSwiftError = false;
9108     Entry.IsCFGuardTarget = false;
9109     Entry.Alignment = Alignment;
9110     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9111     CLI.NumFixedArgs += 1;
9112     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9113 
9114     // sret demotion isn't compatible with tail-calls, since the sret argument
9115     // points into the callers stack frame.
9116     CLI.IsTailCall = false;
9117   } else {
9118     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9119         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9120     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9121       ISD::ArgFlagsTy Flags;
9122       if (NeedsRegBlock) {
9123         Flags.setInConsecutiveRegs();
9124         if (I == RetTys.size() - 1)
9125           Flags.setInConsecutiveRegsLast();
9126       }
9127       EVT VT = RetTys[I];
9128       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9129                                                      CLI.CallConv, VT);
9130       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9131                                                        CLI.CallConv, VT);
9132       for (unsigned i = 0; i != NumRegs; ++i) {
9133         ISD::InputArg MyFlags;
9134         MyFlags.Flags = Flags;
9135         MyFlags.VT = RegisterVT;
9136         MyFlags.ArgVT = VT;
9137         MyFlags.Used = CLI.IsReturnValueUsed;
9138         if (CLI.RetTy->isPointerTy()) {
9139           MyFlags.Flags.setPointer();
9140           MyFlags.Flags.setPointerAddrSpace(
9141               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9142         }
9143         if (CLI.RetSExt)
9144           MyFlags.Flags.setSExt();
9145         if (CLI.RetZExt)
9146           MyFlags.Flags.setZExt();
9147         if (CLI.IsInReg)
9148           MyFlags.Flags.setInReg();
9149         CLI.Ins.push_back(MyFlags);
9150       }
9151     }
9152   }
9153 
9154   // We push in swifterror return as the last element of CLI.Ins.
9155   ArgListTy &Args = CLI.getArgs();
9156   if (supportSwiftError()) {
9157     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9158       if (Args[i].IsSwiftError) {
9159         ISD::InputArg MyFlags;
9160         MyFlags.VT = getPointerTy(DL);
9161         MyFlags.ArgVT = EVT(getPointerTy(DL));
9162         MyFlags.Flags.setSwiftError();
9163         CLI.Ins.push_back(MyFlags);
9164       }
9165     }
9166   }
9167 
9168   // Handle all of the outgoing arguments.
9169   CLI.Outs.clear();
9170   CLI.OutVals.clear();
9171   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9172     SmallVector<EVT, 4> ValueVTs;
9173     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9174     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9175     Type *FinalType = Args[i].Ty;
9176     if (Args[i].IsByVal)
9177       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9178     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9179         FinalType, CLI.CallConv, CLI.IsVarArg);
9180     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9181          ++Value) {
9182       EVT VT = ValueVTs[Value];
9183       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9184       SDValue Op = SDValue(Args[i].Node.getNode(),
9185                            Args[i].Node.getResNo() + Value);
9186       ISD::ArgFlagsTy Flags;
9187 
9188       // Certain targets (such as MIPS), may have a different ABI alignment
9189       // for a type depending on the context. Give the target a chance to
9190       // specify the alignment it wants.
9191       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9192 
9193       if (Args[i].Ty->isPointerTy()) {
9194         Flags.setPointer();
9195         Flags.setPointerAddrSpace(
9196             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9197       }
9198       if (Args[i].IsZExt)
9199         Flags.setZExt();
9200       if (Args[i].IsSExt)
9201         Flags.setSExt();
9202       if (Args[i].IsInReg) {
9203         // If we are using vectorcall calling convention, a structure that is
9204         // passed InReg - is surely an HVA
9205         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9206             isa<StructType>(FinalType)) {
9207           // The first value of a structure is marked
9208           if (0 == Value)
9209             Flags.setHvaStart();
9210           Flags.setHva();
9211         }
9212         // Set InReg Flag
9213         Flags.setInReg();
9214       }
9215       if (Args[i].IsSRet)
9216         Flags.setSRet();
9217       if (Args[i].IsSwiftSelf)
9218         Flags.setSwiftSelf();
9219       if (Args[i].IsSwiftError)
9220         Flags.setSwiftError();
9221       if (Args[i].IsCFGuardTarget)
9222         Flags.setCFGuardTarget();
9223       if (Args[i].IsByVal)
9224         Flags.setByVal();
9225       if (Args[i].IsPreallocated) {
9226         Flags.setPreallocated();
9227         // Set the byval flag for CCAssignFn callbacks that don't know about
9228         // preallocated.  This way we can know how many bytes we should've
9229         // allocated and how many bytes a callee cleanup function will pop.  If
9230         // we port preallocated to more targets, we'll have to add custom
9231         // preallocated handling in the various CC lowering callbacks.
9232         Flags.setByVal();
9233       }
9234       if (Args[i].IsInAlloca) {
9235         Flags.setInAlloca();
9236         // Set the byval flag for CCAssignFn callbacks that don't know about
9237         // inalloca.  This way we can know how many bytes we should've allocated
9238         // and how many bytes a callee cleanup function will pop.  If we port
9239         // inalloca to more targets, we'll have to add custom inalloca handling
9240         // in the various CC lowering callbacks.
9241         Flags.setByVal();
9242       }
9243       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9244         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9245         Type *ElementTy = Ty->getElementType();
9246 
9247         unsigned FrameSize = DL.getTypeAllocSize(
9248             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9249         Flags.setByValSize(FrameSize);
9250 
9251         // info is not there but there are cases it cannot get right.
9252         Align FrameAlign;
9253         if (auto MA = Args[i].Alignment)
9254           FrameAlign = *MA;
9255         else
9256           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9257         Flags.setByValAlign(FrameAlign);
9258       }
9259       if (Args[i].IsNest)
9260         Flags.setNest();
9261       if (NeedsRegBlock)
9262         Flags.setInConsecutiveRegs();
9263       Flags.setOrigAlign(OriginalAlignment);
9264 
9265       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9266                                                  CLI.CallConv, VT);
9267       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9268                                                         CLI.CallConv, VT);
9269       SmallVector<SDValue, 4> Parts(NumParts);
9270       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9271 
9272       if (Args[i].IsSExt)
9273         ExtendKind = ISD::SIGN_EXTEND;
9274       else if (Args[i].IsZExt)
9275         ExtendKind = ISD::ZERO_EXTEND;
9276 
9277       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9278       // for now.
9279       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9280           CanLowerReturn) {
9281         assert((CLI.RetTy == Args[i].Ty ||
9282                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9283                  CLI.RetTy->getPointerAddressSpace() ==
9284                      Args[i].Ty->getPointerAddressSpace())) &&
9285                RetTys.size() == NumValues && "unexpected use of 'returned'");
9286         // Before passing 'returned' to the target lowering code, ensure that
9287         // either the register MVT and the actual EVT are the same size or that
9288         // the return value and argument are extended in the same way; in these
9289         // cases it's safe to pass the argument register value unchanged as the
9290         // return register value (although it's at the target's option whether
9291         // to do so)
9292         // TODO: allow code generation to take advantage of partially preserved
9293         // registers rather than clobbering the entire register when the
9294         // parameter extension method is not compatible with the return
9295         // extension method
9296         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9297             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9298              CLI.RetZExt == Args[i].IsZExt))
9299           Flags.setReturned();
9300       }
9301 
9302       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9303                      CLI.CallConv, ExtendKind);
9304 
9305       for (unsigned j = 0; j != NumParts; ++j) {
9306         // if it isn't first piece, alignment must be 1
9307         // For scalable vectors the scalable part is currently handled
9308         // by individual targets, so we just use the known minimum size here.
9309         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9310                     i < CLI.NumFixedArgs, i,
9311                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9312         if (NumParts > 1 && j == 0)
9313           MyFlags.Flags.setSplit();
9314         else if (j != 0) {
9315           MyFlags.Flags.setOrigAlign(Align(1));
9316           if (j == NumParts - 1)
9317             MyFlags.Flags.setSplitEnd();
9318         }
9319 
9320         CLI.Outs.push_back(MyFlags);
9321         CLI.OutVals.push_back(Parts[j]);
9322       }
9323 
9324       if (NeedsRegBlock && Value == NumValues - 1)
9325         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9326     }
9327   }
9328 
9329   SmallVector<SDValue, 4> InVals;
9330   CLI.Chain = LowerCall(CLI, InVals);
9331 
9332   // Update CLI.InVals to use outside of this function.
9333   CLI.InVals = InVals;
9334 
9335   // Verify that the target's LowerCall behaved as expected.
9336   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9337          "LowerCall didn't return a valid chain!");
9338   assert((!CLI.IsTailCall || InVals.empty()) &&
9339          "LowerCall emitted a return value for a tail call!");
9340   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9341          "LowerCall didn't emit the correct number of values!");
9342 
9343   // For a tail call, the return value is merely live-out and there aren't
9344   // any nodes in the DAG representing it. Return a special value to
9345   // indicate that a tail call has been emitted and no more Instructions
9346   // should be processed in the current block.
9347   if (CLI.IsTailCall) {
9348     CLI.DAG.setRoot(CLI.Chain);
9349     return std::make_pair(SDValue(), SDValue());
9350   }
9351 
9352 #ifndef NDEBUG
9353   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9354     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9355     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9356            "LowerCall emitted a value with the wrong type!");
9357   }
9358 #endif
9359 
9360   SmallVector<SDValue, 4> ReturnValues;
9361   if (!CanLowerReturn) {
9362     // The instruction result is the result of loading from the
9363     // hidden sret parameter.
9364     SmallVector<EVT, 1> PVTs;
9365     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9366 
9367     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9368     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9369     EVT PtrVT = PVTs[0];
9370 
9371     unsigned NumValues = RetTys.size();
9372     ReturnValues.resize(NumValues);
9373     SmallVector<SDValue, 4> Chains(NumValues);
9374 
9375     // An aggregate return value cannot wrap around the address space, so
9376     // offsets to its parts don't wrap either.
9377     SDNodeFlags Flags;
9378     Flags.setNoUnsignedWrap(true);
9379 
9380     MachineFunction &MF = CLI.DAG.getMachineFunction();
9381     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9382     for (unsigned i = 0; i < NumValues; ++i) {
9383       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9384                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9385                                                         PtrVT), Flags);
9386       SDValue L = CLI.DAG.getLoad(
9387           RetTys[i], CLI.DL, CLI.Chain, Add,
9388           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9389                                             DemoteStackIdx, Offsets[i]),
9390           HiddenSRetAlign);
9391       ReturnValues[i] = L;
9392       Chains[i] = L.getValue(1);
9393     }
9394 
9395     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9396   } else {
9397     // Collect the legal value parts into potentially illegal values
9398     // that correspond to the original function's return values.
9399     Optional<ISD::NodeType> AssertOp;
9400     if (CLI.RetSExt)
9401       AssertOp = ISD::AssertSext;
9402     else if (CLI.RetZExt)
9403       AssertOp = ISD::AssertZext;
9404     unsigned CurReg = 0;
9405     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9406       EVT VT = RetTys[I];
9407       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9408                                                      CLI.CallConv, VT);
9409       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9410                                                        CLI.CallConv, VT);
9411 
9412       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9413                                               NumRegs, RegisterVT, VT, nullptr,
9414                                               CLI.CallConv, AssertOp));
9415       CurReg += NumRegs;
9416     }
9417 
9418     // For a function returning void, there is no return value. We can't create
9419     // such a node, so we just return a null return value in that case. In
9420     // that case, nothing will actually look at the value.
9421     if (ReturnValues.empty())
9422       return std::make_pair(SDValue(), CLI.Chain);
9423   }
9424 
9425   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9426                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9427   return std::make_pair(Res, CLI.Chain);
9428 }
9429 
9430 void TargetLowering::LowerOperationWrapper(SDNode *N,
9431                                            SmallVectorImpl<SDValue> &Results,
9432                                            SelectionDAG &DAG) const {
9433   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9434     Results.push_back(Res);
9435 }
9436 
9437 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9438   llvm_unreachable("LowerOperation not implemented for this target!");
9439 }
9440 
9441 void
9442 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9443   SDValue Op = getNonRegisterValue(V);
9444   assert((Op.getOpcode() != ISD::CopyFromReg ||
9445           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9446          "Copy from a reg to the same reg!");
9447   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9448 
9449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9450   // If this is an InlineAsm we have to match the registers required, not the
9451   // notional registers required by the type.
9452 
9453   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9454                    None); // This is not an ABI copy.
9455   SDValue Chain = DAG.getEntryNode();
9456 
9457   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9458                               FuncInfo.PreferredExtendType.end())
9459                                  ? ISD::ANY_EXTEND
9460                                  : FuncInfo.PreferredExtendType[V];
9461   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9462   PendingExports.push_back(Chain);
9463 }
9464 
9465 #include "llvm/CodeGen/SelectionDAGISel.h"
9466 
9467 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9468 /// entry block, return true.  This includes arguments used by switches, since
9469 /// the switch may expand into multiple basic blocks.
9470 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9471   // With FastISel active, we may be splitting blocks, so force creation
9472   // of virtual registers for all non-dead arguments.
9473   if (FastISel)
9474     return A->use_empty();
9475 
9476   const BasicBlock &Entry = A->getParent()->front();
9477   for (const User *U : A->users())
9478     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9479       return false;  // Use not in entry block.
9480 
9481   return true;
9482 }
9483 
9484 using ArgCopyElisionMapTy =
9485     DenseMap<const Argument *,
9486              std::pair<const AllocaInst *, const StoreInst *>>;
9487 
9488 /// Scan the entry block of the function in FuncInfo for arguments that look
9489 /// like copies into a local alloca. Record any copied arguments in
9490 /// ArgCopyElisionCandidates.
9491 static void
9492 findArgumentCopyElisionCandidates(const DataLayout &DL,
9493                                   FunctionLoweringInfo *FuncInfo,
9494                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9495   // Record the state of every static alloca used in the entry block. Argument
9496   // allocas are all used in the entry block, so we need approximately as many
9497   // entries as we have arguments.
9498   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9499   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9500   unsigned NumArgs = FuncInfo->Fn->arg_size();
9501   StaticAllocas.reserve(NumArgs * 2);
9502 
9503   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9504     if (!V)
9505       return nullptr;
9506     V = V->stripPointerCasts();
9507     const auto *AI = dyn_cast<AllocaInst>(V);
9508     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9509       return nullptr;
9510     auto Iter = StaticAllocas.insert({AI, Unknown});
9511     return &Iter.first->second;
9512   };
9513 
9514   // Look for stores of arguments to static allocas. Look through bitcasts and
9515   // GEPs to handle type coercions, as long as the alloca is fully initialized
9516   // by the store. Any non-store use of an alloca escapes it and any subsequent
9517   // unanalyzed store might write it.
9518   // FIXME: Handle structs initialized with multiple stores.
9519   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9520     // Look for stores, and handle non-store uses conservatively.
9521     const auto *SI = dyn_cast<StoreInst>(&I);
9522     if (!SI) {
9523       // We will look through cast uses, so ignore them completely.
9524       if (I.isCast())
9525         continue;
9526       // Ignore debug info intrinsics, they don't escape or store to allocas.
9527       if (isa<DbgInfoIntrinsic>(I))
9528         continue;
9529       // This is an unknown instruction. Assume it escapes or writes to all
9530       // static alloca operands.
9531       for (const Use &U : I.operands()) {
9532         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9533           *Info = StaticAllocaInfo::Clobbered;
9534       }
9535       continue;
9536     }
9537 
9538     // If the stored value is a static alloca, mark it as escaped.
9539     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9540       *Info = StaticAllocaInfo::Clobbered;
9541 
9542     // Check if the destination is a static alloca.
9543     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9544     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9545     if (!Info)
9546       continue;
9547     const AllocaInst *AI = cast<AllocaInst>(Dst);
9548 
9549     // Skip allocas that have been initialized or clobbered.
9550     if (*Info != StaticAllocaInfo::Unknown)
9551       continue;
9552 
9553     // Check if the stored value is an argument, and that this store fully
9554     // initializes the alloca. Don't elide copies from the same argument twice.
9555     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9556     const auto *Arg = dyn_cast<Argument>(Val);
9557     if (!Arg || Arg->hasPassPointeeByValueAttr() ||
9558         Arg->getType()->isEmptyTy() ||
9559         DL.getTypeStoreSize(Arg->getType()) !=
9560             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9561         ArgCopyElisionCandidates.count(Arg)) {
9562       *Info = StaticAllocaInfo::Clobbered;
9563       continue;
9564     }
9565 
9566     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9567                       << '\n');
9568 
9569     // Mark this alloca and store for argument copy elision.
9570     *Info = StaticAllocaInfo::Elidable;
9571     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9572 
9573     // Stop scanning if we've seen all arguments. This will happen early in -O0
9574     // builds, which is useful, because -O0 builds have large entry blocks and
9575     // many allocas.
9576     if (ArgCopyElisionCandidates.size() == NumArgs)
9577       break;
9578   }
9579 }
9580 
9581 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9582 /// ArgVal is a load from a suitable fixed stack object.
9583 static void tryToElideArgumentCopy(
9584     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9585     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9586     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9587     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9588     SDValue ArgVal, bool &ArgHasUses) {
9589   // Check if this is a load from a fixed stack object.
9590   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9591   if (!LNode)
9592     return;
9593   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9594   if (!FINode)
9595     return;
9596 
9597   // Check that the fixed stack object is the right size and alignment.
9598   // Look at the alignment that the user wrote on the alloca instead of looking
9599   // at the stack object.
9600   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9601   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9602   const AllocaInst *AI = ArgCopyIter->second.first;
9603   int FixedIndex = FINode->getIndex();
9604   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9605   int OldIndex = AllocaIndex;
9606   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9607   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9608     LLVM_DEBUG(
9609         dbgs() << "  argument copy elision failed due to bad fixed stack "
9610                   "object size\n");
9611     return;
9612   }
9613   Align RequiredAlignment = AI->getAlign();
9614   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9615     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9616                          "greater than stack argument alignment ("
9617                       << DebugStr(RequiredAlignment) << " vs "
9618                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9619     return;
9620   }
9621 
9622   // Perform the elision. Delete the old stack object and replace its only use
9623   // in the variable info map. Mark the stack object as mutable.
9624   LLVM_DEBUG({
9625     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9626            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9627            << '\n';
9628   });
9629   MFI.RemoveStackObject(OldIndex);
9630   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9631   AllocaIndex = FixedIndex;
9632   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9633   Chains.push_back(ArgVal.getValue(1));
9634 
9635   // Avoid emitting code for the store implementing the copy.
9636   const StoreInst *SI = ArgCopyIter->second.second;
9637   ElidedArgCopyInstrs.insert(SI);
9638 
9639   // Check for uses of the argument again so that we can avoid exporting ArgVal
9640   // if it is't used by anything other than the store.
9641   for (const Value *U : Arg.users()) {
9642     if (U != SI) {
9643       ArgHasUses = true;
9644       break;
9645     }
9646   }
9647 }
9648 
9649 void SelectionDAGISel::LowerArguments(const Function &F) {
9650   SelectionDAG &DAG = SDB->DAG;
9651   SDLoc dl = SDB->getCurSDLoc();
9652   const DataLayout &DL = DAG.getDataLayout();
9653   SmallVector<ISD::InputArg, 16> Ins;
9654 
9655   // In Naked functions we aren't going to save any registers.
9656   if (F.hasFnAttribute(Attribute::Naked))
9657     return;
9658 
9659   if (!FuncInfo->CanLowerReturn) {
9660     // Put in an sret pointer parameter before all the other parameters.
9661     SmallVector<EVT, 1> ValueVTs;
9662     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9663                     F.getReturnType()->getPointerTo(
9664                         DAG.getDataLayout().getAllocaAddrSpace()),
9665                     ValueVTs);
9666 
9667     // NOTE: Assuming that a pointer will never break down to more than one VT
9668     // or one register.
9669     ISD::ArgFlagsTy Flags;
9670     Flags.setSRet();
9671     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9672     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9673                          ISD::InputArg::NoArgIndex, 0);
9674     Ins.push_back(RetArg);
9675   }
9676 
9677   // Look for stores of arguments to static allocas. Mark such arguments with a
9678   // flag to ask the target to give us the memory location of that argument if
9679   // available.
9680   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9681   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9682                                     ArgCopyElisionCandidates);
9683 
9684   // Set up the incoming argument description vector.
9685   for (const Argument &Arg : F.args()) {
9686     unsigned ArgNo = Arg.getArgNo();
9687     SmallVector<EVT, 4> ValueVTs;
9688     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9689     bool isArgValueUsed = !Arg.use_empty();
9690     unsigned PartBase = 0;
9691     Type *FinalType = Arg.getType();
9692     if (Arg.hasAttribute(Attribute::ByVal))
9693       FinalType = Arg.getParamByValType();
9694     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9695         FinalType, F.getCallingConv(), F.isVarArg());
9696     for (unsigned Value = 0, NumValues = ValueVTs.size();
9697          Value != NumValues; ++Value) {
9698       EVT VT = ValueVTs[Value];
9699       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9700       ISD::ArgFlagsTy Flags;
9701 
9702       // Certain targets (such as MIPS), may have a different ABI alignment
9703       // for a type depending on the context. Give the target a chance to
9704       // specify the alignment it wants.
9705       const Align OriginalAlignment(
9706           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9707 
9708       if (Arg.getType()->isPointerTy()) {
9709         Flags.setPointer();
9710         Flags.setPointerAddrSpace(
9711             cast<PointerType>(Arg.getType())->getAddressSpace());
9712       }
9713       if (Arg.hasAttribute(Attribute::ZExt))
9714         Flags.setZExt();
9715       if (Arg.hasAttribute(Attribute::SExt))
9716         Flags.setSExt();
9717       if (Arg.hasAttribute(Attribute::InReg)) {
9718         // If we are using vectorcall calling convention, a structure that is
9719         // passed InReg - is surely an HVA
9720         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9721             isa<StructType>(Arg.getType())) {
9722           // The first value of a structure is marked
9723           if (0 == Value)
9724             Flags.setHvaStart();
9725           Flags.setHva();
9726         }
9727         // Set InReg Flag
9728         Flags.setInReg();
9729       }
9730       if (Arg.hasAttribute(Attribute::StructRet))
9731         Flags.setSRet();
9732       if (Arg.hasAttribute(Attribute::SwiftSelf))
9733         Flags.setSwiftSelf();
9734       if (Arg.hasAttribute(Attribute::SwiftError))
9735         Flags.setSwiftError();
9736       if (Arg.hasAttribute(Attribute::ByVal))
9737         Flags.setByVal();
9738       if (Arg.hasAttribute(Attribute::InAlloca)) {
9739         Flags.setInAlloca();
9740         // Set the byval flag for CCAssignFn callbacks that don't know about
9741         // inalloca.  This way we can know how many bytes we should've allocated
9742         // and how many bytes a callee cleanup function will pop.  If we port
9743         // inalloca to more targets, we'll have to add custom inalloca handling
9744         // in the various CC lowering callbacks.
9745         Flags.setByVal();
9746       }
9747       if (Arg.hasAttribute(Attribute::Preallocated)) {
9748         Flags.setPreallocated();
9749         // Set the byval flag for CCAssignFn callbacks that don't know about
9750         // preallocated.  This way we can know how many bytes we should've
9751         // allocated and how many bytes a callee cleanup function will pop.  If
9752         // we port preallocated to more targets, we'll have to add custom
9753         // preallocated handling in the various CC lowering callbacks.
9754         Flags.setByVal();
9755       }
9756       if (F.getCallingConv() == CallingConv::X86_INTR) {
9757         // IA Interrupt passes frame (1st parameter) by value in the stack.
9758         if (ArgNo == 0)
9759           Flags.setByVal();
9760       }
9761       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
9762         Type *ElementTy = Arg.getParamByValType();
9763 
9764         // For ByVal, size and alignment should be passed from FE.  BE will
9765         // guess if this info is not there but there are cases it cannot get
9766         // right.
9767         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9768         Flags.setByValSize(FrameSize);
9769 
9770         unsigned FrameAlign;
9771         if (Arg.getParamAlignment())
9772           FrameAlign = Arg.getParamAlignment();
9773         else
9774           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9775         Flags.setByValAlign(Align(FrameAlign));
9776       }
9777       if (Arg.hasAttribute(Attribute::Nest))
9778         Flags.setNest();
9779       if (NeedsRegBlock)
9780         Flags.setInConsecutiveRegs();
9781       Flags.setOrigAlign(OriginalAlignment);
9782       if (ArgCopyElisionCandidates.count(&Arg))
9783         Flags.setCopyElisionCandidate();
9784       if (Arg.hasAttribute(Attribute::Returned))
9785         Flags.setReturned();
9786 
9787       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9788           *CurDAG->getContext(), F.getCallingConv(), VT);
9789       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9790           *CurDAG->getContext(), F.getCallingConv(), VT);
9791       for (unsigned i = 0; i != NumRegs; ++i) {
9792         // For scalable vectors, use the minimum size; individual targets
9793         // are responsible for handling scalable vector arguments and
9794         // return values.
9795         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9796                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9797         if (NumRegs > 1 && i == 0)
9798           MyFlags.Flags.setSplit();
9799         // if it isn't first piece, alignment must be 1
9800         else if (i > 0) {
9801           MyFlags.Flags.setOrigAlign(Align(1));
9802           if (i == NumRegs - 1)
9803             MyFlags.Flags.setSplitEnd();
9804         }
9805         Ins.push_back(MyFlags);
9806       }
9807       if (NeedsRegBlock && Value == NumValues - 1)
9808         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9809       PartBase += VT.getStoreSize().getKnownMinSize();
9810     }
9811   }
9812 
9813   // Call the target to set up the argument values.
9814   SmallVector<SDValue, 8> InVals;
9815   SDValue NewRoot = TLI->LowerFormalArguments(
9816       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9817 
9818   // Verify that the target's LowerFormalArguments behaved as expected.
9819   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9820          "LowerFormalArguments didn't return a valid chain!");
9821   assert(InVals.size() == Ins.size() &&
9822          "LowerFormalArguments didn't emit the correct number of values!");
9823   LLVM_DEBUG({
9824     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9825       assert(InVals[i].getNode() &&
9826              "LowerFormalArguments emitted a null value!");
9827       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9828              "LowerFormalArguments emitted a value with the wrong type!");
9829     }
9830   });
9831 
9832   // Update the DAG with the new chain value resulting from argument lowering.
9833   DAG.setRoot(NewRoot);
9834 
9835   // Set up the argument values.
9836   unsigned i = 0;
9837   if (!FuncInfo->CanLowerReturn) {
9838     // Create a virtual register for the sret pointer, and put in a copy
9839     // from the sret argument into it.
9840     SmallVector<EVT, 1> ValueVTs;
9841     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9842                     F.getReturnType()->getPointerTo(
9843                         DAG.getDataLayout().getAllocaAddrSpace()),
9844                     ValueVTs);
9845     MVT VT = ValueVTs[0].getSimpleVT();
9846     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9847     Optional<ISD::NodeType> AssertOp = None;
9848     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9849                                         nullptr, F.getCallingConv(), AssertOp);
9850 
9851     MachineFunction& MF = SDB->DAG.getMachineFunction();
9852     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9853     Register SRetReg =
9854         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9855     FuncInfo->DemoteRegister = SRetReg;
9856     NewRoot =
9857         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9858     DAG.setRoot(NewRoot);
9859 
9860     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9861     ++i;
9862   }
9863 
9864   SmallVector<SDValue, 4> Chains;
9865   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9866   for (const Argument &Arg : F.args()) {
9867     SmallVector<SDValue, 4> ArgValues;
9868     SmallVector<EVT, 4> ValueVTs;
9869     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9870     unsigned NumValues = ValueVTs.size();
9871     if (NumValues == 0)
9872       continue;
9873 
9874     bool ArgHasUses = !Arg.use_empty();
9875 
9876     // Elide the copying store if the target loaded this argument from a
9877     // suitable fixed stack object.
9878     if (Ins[i].Flags.isCopyElisionCandidate()) {
9879       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9880                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9881                              InVals[i], ArgHasUses);
9882     }
9883 
9884     // If this argument is unused then remember its value. It is used to generate
9885     // debugging information.
9886     bool isSwiftErrorArg =
9887         TLI->supportSwiftError() &&
9888         Arg.hasAttribute(Attribute::SwiftError);
9889     if (!ArgHasUses && !isSwiftErrorArg) {
9890       SDB->setUnusedArgValue(&Arg, InVals[i]);
9891 
9892       // Also remember any frame index for use in FastISel.
9893       if (FrameIndexSDNode *FI =
9894           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9895         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9896     }
9897 
9898     for (unsigned Val = 0; Val != NumValues; ++Val) {
9899       EVT VT = ValueVTs[Val];
9900       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9901                                                       F.getCallingConv(), VT);
9902       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9903           *CurDAG->getContext(), F.getCallingConv(), VT);
9904 
9905       // Even an apparent 'unused' swifterror argument needs to be returned. So
9906       // we do generate a copy for it that can be used on return from the
9907       // function.
9908       if (ArgHasUses || isSwiftErrorArg) {
9909         Optional<ISD::NodeType> AssertOp;
9910         if (Arg.hasAttribute(Attribute::SExt))
9911           AssertOp = ISD::AssertSext;
9912         else if (Arg.hasAttribute(Attribute::ZExt))
9913           AssertOp = ISD::AssertZext;
9914 
9915         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9916                                              PartVT, VT, nullptr,
9917                                              F.getCallingConv(), AssertOp));
9918       }
9919 
9920       i += NumParts;
9921     }
9922 
9923     // We don't need to do anything else for unused arguments.
9924     if (ArgValues.empty())
9925       continue;
9926 
9927     // Note down frame index.
9928     if (FrameIndexSDNode *FI =
9929         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9930       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9931 
9932     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9933                                      SDB->getCurSDLoc());
9934 
9935     SDB->setValue(&Arg, Res);
9936     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9937       // We want to associate the argument with the frame index, among
9938       // involved operands, that correspond to the lowest address. The
9939       // getCopyFromParts function, called earlier, is swapping the order of
9940       // the operands to BUILD_PAIR depending on endianness. The result of
9941       // that swapping is that the least significant bits of the argument will
9942       // be in the first operand of the BUILD_PAIR node, and the most
9943       // significant bits will be in the second operand.
9944       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9945       if (LoadSDNode *LNode =
9946           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9947         if (FrameIndexSDNode *FI =
9948             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9949           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9950     }
9951 
9952     // Analyses past this point are naive and don't expect an assertion.
9953     if (Res.getOpcode() == ISD::AssertZext)
9954       Res = Res.getOperand(0);
9955 
9956     // Update the SwiftErrorVRegDefMap.
9957     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9958       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9959       if (Register::isVirtualRegister(Reg))
9960         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9961                                    Reg);
9962     }
9963 
9964     // If this argument is live outside of the entry block, insert a copy from
9965     // wherever we got it to the vreg that other BB's will reference it as.
9966     if (Res.getOpcode() == ISD::CopyFromReg) {
9967       // If we can, though, try to skip creating an unnecessary vreg.
9968       // FIXME: This isn't very clean... it would be nice to make this more
9969       // general.
9970       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9971       if (Register::isVirtualRegister(Reg)) {
9972         FuncInfo->ValueMap[&Arg] = Reg;
9973         continue;
9974       }
9975     }
9976     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9977       FuncInfo->InitializeRegForValue(&Arg);
9978       SDB->CopyToExportRegsIfNeeded(&Arg);
9979     }
9980   }
9981 
9982   if (!Chains.empty()) {
9983     Chains.push_back(NewRoot);
9984     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9985   }
9986 
9987   DAG.setRoot(NewRoot);
9988 
9989   assert(i == InVals.size() && "Argument register count mismatch!");
9990 
9991   // If any argument copy elisions occurred and we have debug info, update the
9992   // stale frame indices used in the dbg.declare variable info table.
9993   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9994   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9995     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9996       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9997       if (I != ArgCopyElisionFrameIndexMap.end())
9998         VI.Slot = I->second;
9999     }
10000   }
10001 
10002   // Finally, if the target has anything special to do, allow it to do so.
10003   emitFunctionEntryCode();
10004 }
10005 
10006 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10007 /// ensure constants are generated when needed.  Remember the virtual registers
10008 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10009 /// directly add them, because expansion might result in multiple MBB's for one
10010 /// BB.  As such, the start of the BB might correspond to a different MBB than
10011 /// the end.
10012 void
10013 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10014   const Instruction *TI = LLVMBB->getTerminator();
10015 
10016   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10017 
10018   // Check PHI nodes in successors that expect a value to be available from this
10019   // block.
10020   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10021     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10022     if (!isa<PHINode>(SuccBB->begin())) continue;
10023     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10024 
10025     // If this terminator has multiple identical successors (common for
10026     // switches), only handle each succ once.
10027     if (!SuccsHandled.insert(SuccMBB).second)
10028       continue;
10029 
10030     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10031 
10032     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10033     // nodes and Machine PHI nodes, but the incoming operands have not been
10034     // emitted yet.
10035     for (const PHINode &PN : SuccBB->phis()) {
10036       // Ignore dead phi's.
10037       if (PN.use_empty())
10038         continue;
10039 
10040       // Skip empty types
10041       if (PN.getType()->isEmptyTy())
10042         continue;
10043 
10044       unsigned Reg;
10045       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10046 
10047       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10048         unsigned &RegOut = ConstantsOut[C];
10049         if (RegOut == 0) {
10050           RegOut = FuncInfo.CreateRegs(C);
10051           CopyValueToVirtualRegister(C, RegOut);
10052         }
10053         Reg = RegOut;
10054       } else {
10055         DenseMap<const Value *, Register>::iterator I =
10056           FuncInfo.ValueMap.find(PHIOp);
10057         if (I != FuncInfo.ValueMap.end())
10058           Reg = I->second;
10059         else {
10060           assert(isa<AllocaInst>(PHIOp) &&
10061                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10062                  "Didn't codegen value into a register!??");
10063           Reg = FuncInfo.CreateRegs(PHIOp);
10064           CopyValueToVirtualRegister(PHIOp, Reg);
10065         }
10066       }
10067 
10068       // Remember that this register needs to added to the machine PHI node as
10069       // the input for this MBB.
10070       SmallVector<EVT, 4> ValueVTs;
10071       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10072       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10073       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10074         EVT VT = ValueVTs[vti];
10075         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10076         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10077           FuncInfo.PHINodesToUpdate.push_back(
10078               std::make_pair(&*MBBI++, Reg + i));
10079         Reg += NumRegisters;
10080       }
10081     }
10082   }
10083 
10084   ConstantsOut.clear();
10085 }
10086 
10087 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10088 /// is 0.
10089 MachineBasicBlock *
10090 SelectionDAGBuilder::StackProtectorDescriptor::
10091 AddSuccessorMBB(const BasicBlock *BB,
10092                 MachineBasicBlock *ParentMBB,
10093                 bool IsLikely,
10094                 MachineBasicBlock *SuccMBB) {
10095   // If SuccBB has not been created yet, create it.
10096   if (!SuccMBB) {
10097     MachineFunction *MF = ParentMBB->getParent();
10098     MachineFunction::iterator BBI(ParentMBB);
10099     SuccMBB = MF->CreateMachineBasicBlock(BB);
10100     MF->insert(++BBI, SuccMBB);
10101   }
10102   // Add it as a successor of ParentMBB.
10103   ParentMBB->addSuccessor(
10104       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10105   return SuccMBB;
10106 }
10107 
10108 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10109   MachineFunction::iterator I(MBB);
10110   if (++I == FuncInfo.MF->end())
10111     return nullptr;
10112   return &*I;
10113 }
10114 
10115 /// During lowering new call nodes can be created (such as memset, etc.).
10116 /// Those will become new roots of the current DAG, but complications arise
10117 /// when they are tail calls. In such cases, the call lowering will update
10118 /// the root, but the builder still needs to know that a tail call has been
10119 /// lowered in order to avoid generating an additional return.
10120 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10121   // If the node is null, we do have a tail call.
10122   if (MaybeTC.getNode() != nullptr)
10123     DAG.setRoot(MaybeTC);
10124   else
10125     HasTailCall = true;
10126 }
10127 
10128 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10129                                         MachineBasicBlock *SwitchMBB,
10130                                         MachineBasicBlock *DefaultMBB) {
10131   MachineFunction *CurMF = FuncInfo.MF;
10132   MachineBasicBlock *NextMBB = nullptr;
10133   MachineFunction::iterator BBI(W.MBB);
10134   if (++BBI != FuncInfo.MF->end())
10135     NextMBB = &*BBI;
10136 
10137   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10138 
10139   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10140 
10141   if (Size == 2 && W.MBB == SwitchMBB) {
10142     // If any two of the cases has the same destination, and if one value
10143     // is the same as the other, but has one bit unset that the other has set,
10144     // use bit manipulation to do two compares at once.  For example:
10145     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10146     // TODO: This could be extended to merge any 2 cases in switches with 3
10147     // cases.
10148     // TODO: Handle cases where W.CaseBB != SwitchBB.
10149     CaseCluster &Small = *W.FirstCluster;
10150     CaseCluster &Big = *W.LastCluster;
10151 
10152     if (Small.Low == Small.High && Big.Low == Big.High &&
10153         Small.MBB == Big.MBB) {
10154       const APInt &SmallValue = Small.Low->getValue();
10155       const APInt &BigValue = Big.Low->getValue();
10156 
10157       // Check that there is only one bit different.
10158       APInt CommonBit = BigValue ^ SmallValue;
10159       if (CommonBit.isPowerOf2()) {
10160         SDValue CondLHS = getValue(Cond);
10161         EVT VT = CondLHS.getValueType();
10162         SDLoc DL = getCurSDLoc();
10163 
10164         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10165                                  DAG.getConstant(CommonBit, DL, VT));
10166         SDValue Cond = DAG.getSetCC(
10167             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10168             ISD::SETEQ);
10169 
10170         // Update successor info.
10171         // Both Small and Big will jump to Small.BB, so we sum up the
10172         // probabilities.
10173         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10174         if (BPI)
10175           addSuccessorWithProb(
10176               SwitchMBB, DefaultMBB,
10177               // The default destination is the first successor in IR.
10178               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10179         else
10180           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10181 
10182         // Insert the true branch.
10183         SDValue BrCond =
10184             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10185                         DAG.getBasicBlock(Small.MBB));
10186         // Insert the false branch.
10187         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10188                              DAG.getBasicBlock(DefaultMBB));
10189 
10190         DAG.setRoot(BrCond);
10191         return;
10192       }
10193     }
10194   }
10195 
10196   if (TM.getOptLevel() != CodeGenOpt::None) {
10197     // Here, we order cases by probability so the most likely case will be
10198     // checked first. However, two clusters can have the same probability in
10199     // which case their relative ordering is non-deterministic. So we use Low
10200     // as a tie-breaker as clusters are guaranteed to never overlap.
10201     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10202                [](const CaseCluster &a, const CaseCluster &b) {
10203       return a.Prob != b.Prob ?
10204              a.Prob > b.Prob :
10205              a.Low->getValue().slt(b.Low->getValue());
10206     });
10207 
10208     // Rearrange the case blocks so that the last one falls through if possible
10209     // without changing the order of probabilities.
10210     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10211       --I;
10212       if (I->Prob > W.LastCluster->Prob)
10213         break;
10214       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10215         std::swap(*I, *W.LastCluster);
10216         break;
10217       }
10218     }
10219   }
10220 
10221   // Compute total probability.
10222   BranchProbability DefaultProb = W.DefaultProb;
10223   BranchProbability UnhandledProbs = DefaultProb;
10224   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10225     UnhandledProbs += I->Prob;
10226 
10227   MachineBasicBlock *CurMBB = W.MBB;
10228   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10229     bool FallthroughUnreachable = false;
10230     MachineBasicBlock *Fallthrough;
10231     if (I == W.LastCluster) {
10232       // For the last cluster, fall through to the default destination.
10233       Fallthrough = DefaultMBB;
10234       FallthroughUnreachable = isa<UnreachableInst>(
10235           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10236     } else {
10237       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10238       CurMF->insert(BBI, Fallthrough);
10239       // Put Cond in a virtual register to make it available from the new blocks.
10240       ExportFromCurrentBlock(Cond);
10241     }
10242     UnhandledProbs -= I->Prob;
10243 
10244     switch (I->Kind) {
10245       case CC_JumpTable: {
10246         // FIXME: Optimize away range check based on pivot comparisons.
10247         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10248         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10249 
10250         // The jump block hasn't been inserted yet; insert it here.
10251         MachineBasicBlock *JumpMBB = JT->MBB;
10252         CurMF->insert(BBI, JumpMBB);
10253 
10254         auto JumpProb = I->Prob;
10255         auto FallthroughProb = UnhandledProbs;
10256 
10257         // If the default statement is a target of the jump table, we evenly
10258         // distribute the default probability to successors of CurMBB. Also
10259         // update the probability on the edge from JumpMBB to Fallthrough.
10260         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10261                                               SE = JumpMBB->succ_end();
10262              SI != SE; ++SI) {
10263           if (*SI == DefaultMBB) {
10264             JumpProb += DefaultProb / 2;
10265             FallthroughProb -= DefaultProb / 2;
10266             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10267             JumpMBB->normalizeSuccProbs();
10268             break;
10269           }
10270         }
10271 
10272         if (FallthroughUnreachable) {
10273           // Skip the range check if the fallthrough block is unreachable.
10274           JTH->OmitRangeCheck = true;
10275         }
10276 
10277         if (!JTH->OmitRangeCheck)
10278           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10279         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10280         CurMBB->normalizeSuccProbs();
10281 
10282         // The jump table header will be inserted in our current block, do the
10283         // range check, and fall through to our fallthrough block.
10284         JTH->HeaderBB = CurMBB;
10285         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10286 
10287         // If we're in the right place, emit the jump table header right now.
10288         if (CurMBB == SwitchMBB) {
10289           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10290           JTH->Emitted = true;
10291         }
10292         break;
10293       }
10294       case CC_BitTests: {
10295         // FIXME: Optimize away range check based on pivot comparisons.
10296         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10297 
10298         // The bit test blocks haven't been inserted yet; insert them here.
10299         for (BitTestCase &BTC : BTB->Cases)
10300           CurMF->insert(BBI, BTC.ThisBB);
10301 
10302         // Fill in fields of the BitTestBlock.
10303         BTB->Parent = CurMBB;
10304         BTB->Default = Fallthrough;
10305 
10306         BTB->DefaultProb = UnhandledProbs;
10307         // If the cases in bit test don't form a contiguous range, we evenly
10308         // distribute the probability on the edge to Fallthrough to two
10309         // successors of CurMBB.
10310         if (!BTB->ContiguousRange) {
10311           BTB->Prob += DefaultProb / 2;
10312           BTB->DefaultProb -= DefaultProb / 2;
10313         }
10314 
10315         if (FallthroughUnreachable) {
10316           // Skip the range check if the fallthrough block is unreachable.
10317           BTB->OmitRangeCheck = true;
10318         }
10319 
10320         // If we're in the right place, emit the bit test header right now.
10321         if (CurMBB == SwitchMBB) {
10322           visitBitTestHeader(*BTB, SwitchMBB);
10323           BTB->Emitted = true;
10324         }
10325         break;
10326       }
10327       case CC_Range: {
10328         const Value *RHS, *LHS, *MHS;
10329         ISD::CondCode CC;
10330         if (I->Low == I->High) {
10331           // Check Cond == I->Low.
10332           CC = ISD::SETEQ;
10333           LHS = Cond;
10334           RHS=I->Low;
10335           MHS = nullptr;
10336         } else {
10337           // Check I->Low <= Cond <= I->High.
10338           CC = ISD::SETLE;
10339           LHS = I->Low;
10340           MHS = Cond;
10341           RHS = I->High;
10342         }
10343 
10344         // If Fallthrough is unreachable, fold away the comparison.
10345         if (FallthroughUnreachable)
10346           CC = ISD::SETTRUE;
10347 
10348         // The false probability is the sum of all unhandled cases.
10349         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10350                      getCurSDLoc(), I->Prob, UnhandledProbs);
10351 
10352         if (CurMBB == SwitchMBB)
10353           visitSwitchCase(CB, SwitchMBB);
10354         else
10355           SL->SwitchCases.push_back(CB);
10356 
10357         break;
10358       }
10359     }
10360     CurMBB = Fallthrough;
10361   }
10362 }
10363 
10364 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10365                                               CaseClusterIt First,
10366                                               CaseClusterIt Last) {
10367   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10368     if (X.Prob != CC.Prob)
10369       return X.Prob > CC.Prob;
10370 
10371     // Ties are broken by comparing the case value.
10372     return X.Low->getValue().slt(CC.Low->getValue());
10373   });
10374 }
10375 
10376 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10377                                         const SwitchWorkListItem &W,
10378                                         Value *Cond,
10379                                         MachineBasicBlock *SwitchMBB) {
10380   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10381          "Clusters not sorted?");
10382 
10383   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10384 
10385   // Balance the tree based on branch probabilities to create a near-optimal (in
10386   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10387   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10388   CaseClusterIt LastLeft = W.FirstCluster;
10389   CaseClusterIt FirstRight = W.LastCluster;
10390   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10391   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10392 
10393   // Move LastLeft and FirstRight towards each other from opposite directions to
10394   // find a partitioning of the clusters which balances the probability on both
10395   // sides. If LeftProb and RightProb are equal, alternate which side is
10396   // taken to ensure 0-probability nodes are distributed evenly.
10397   unsigned I = 0;
10398   while (LastLeft + 1 < FirstRight) {
10399     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10400       LeftProb += (++LastLeft)->Prob;
10401     else
10402       RightProb += (--FirstRight)->Prob;
10403     I++;
10404   }
10405 
10406   while (true) {
10407     // Our binary search tree differs from a typical BST in that ours can have up
10408     // to three values in each leaf. The pivot selection above doesn't take that
10409     // into account, which means the tree might require more nodes and be less
10410     // efficient. We compensate for this here.
10411 
10412     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10413     unsigned NumRight = W.LastCluster - FirstRight + 1;
10414 
10415     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10416       // If one side has less than 3 clusters, and the other has more than 3,
10417       // consider taking a cluster from the other side.
10418 
10419       if (NumLeft < NumRight) {
10420         // Consider moving the first cluster on the right to the left side.
10421         CaseCluster &CC = *FirstRight;
10422         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10423         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10424         if (LeftSideRank <= RightSideRank) {
10425           // Moving the cluster to the left does not demote it.
10426           ++LastLeft;
10427           ++FirstRight;
10428           continue;
10429         }
10430       } else {
10431         assert(NumRight < NumLeft);
10432         // Consider moving the last element on the left to the right side.
10433         CaseCluster &CC = *LastLeft;
10434         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10435         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10436         if (RightSideRank <= LeftSideRank) {
10437           // Moving the cluster to the right does not demot it.
10438           --LastLeft;
10439           --FirstRight;
10440           continue;
10441         }
10442       }
10443     }
10444     break;
10445   }
10446 
10447   assert(LastLeft + 1 == FirstRight);
10448   assert(LastLeft >= W.FirstCluster);
10449   assert(FirstRight <= W.LastCluster);
10450 
10451   // Use the first element on the right as pivot since we will make less-than
10452   // comparisons against it.
10453   CaseClusterIt PivotCluster = FirstRight;
10454   assert(PivotCluster > W.FirstCluster);
10455   assert(PivotCluster <= W.LastCluster);
10456 
10457   CaseClusterIt FirstLeft = W.FirstCluster;
10458   CaseClusterIt LastRight = W.LastCluster;
10459 
10460   const ConstantInt *Pivot = PivotCluster->Low;
10461 
10462   // New blocks will be inserted immediately after the current one.
10463   MachineFunction::iterator BBI(W.MBB);
10464   ++BBI;
10465 
10466   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10467   // we can branch to its destination directly if it's squeezed exactly in
10468   // between the known lower bound and Pivot - 1.
10469   MachineBasicBlock *LeftMBB;
10470   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10471       FirstLeft->Low == W.GE &&
10472       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10473     LeftMBB = FirstLeft->MBB;
10474   } else {
10475     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10476     FuncInfo.MF->insert(BBI, LeftMBB);
10477     WorkList.push_back(
10478         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10479     // Put Cond in a virtual register to make it available from the new blocks.
10480     ExportFromCurrentBlock(Cond);
10481   }
10482 
10483   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10484   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10485   // directly if RHS.High equals the current upper bound.
10486   MachineBasicBlock *RightMBB;
10487   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10488       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10489     RightMBB = FirstRight->MBB;
10490   } else {
10491     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10492     FuncInfo.MF->insert(BBI, RightMBB);
10493     WorkList.push_back(
10494         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10495     // Put Cond in a virtual register to make it available from the new blocks.
10496     ExportFromCurrentBlock(Cond);
10497   }
10498 
10499   // Create the CaseBlock record that will be used to lower the branch.
10500   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10501                getCurSDLoc(), LeftProb, RightProb);
10502 
10503   if (W.MBB == SwitchMBB)
10504     visitSwitchCase(CB, SwitchMBB);
10505   else
10506     SL->SwitchCases.push_back(CB);
10507 }
10508 
10509 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10510 // from the swith statement.
10511 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10512                                             BranchProbability PeeledCaseProb) {
10513   if (PeeledCaseProb == BranchProbability::getOne())
10514     return BranchProbability::getZero();
10515   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10516 
10517   uint32_t Numerator = CaseProb.getNumerator();
10518   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10519   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10520 }
10521 
10522 // Try to peel the top probability case if it exceeds the threshold.
10523 // Return current MachineBasicBlock for the switch statement if the peeling
10524 // does not occur.
10525 // If the peeling is performed, return the newly created MachineBasicBlock
10526 // for the peeled switch statement. Also update Clusters to remove the peeled
10527 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10528 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10529     const SwitchInst &SI, CaseClusterVector &Clusters,
10530     BranchProbability &PeeledCaseProb) {
10531   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10532   // Don't perform if there is only one cluster or optimizing for size.
10533   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10534       TM.getOptLevel() == CodeGenOpt::None ||
10535       SwitchMBB->getParent()->getFunction().hasMinSize())
10536     return SwitchMBB;
10537 
10538   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10539   unsigned PeeledCaseIndex = 0;
10540   bool SwitchPeeled = false;
10541   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10542     CaseCluster &CC = Clusters[Index];
10543     if (CC.Prob < TopCaseProb)
10544       continue;
10545     TopCaseProb = CC.Prob;
10546     PeeledCaseIndex = Index;
10547     SwitchPeeled = true;
10548   }
10549   if (!SwitchPeeled)
10550     return SwitchMBB;
10551 
10552   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10553                     << TopCaseProb << "\n");
10554 
10555   // Record the MBB for the peeled switch statement.
10556   MachineFunction::iterator BBI(SwitchMBB);
10557   ++BBI;
10558   MachineBasicBlock *PeeledSwitchMBB =
10559       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10560   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10561 
10562   ExportFromCurrentBlock(SI.getCondition());
10563   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10564   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10565                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10566   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10567 
10568   Clusters.erase(PeeledCaseIt);
10569   for (CaseCluster &CC : Clusters) {
10570     LLVM_DEBUG(
10571         dbgs() << "Scale the probablity for one cluster, before scaling: "
10572                << CC.Prob << "\n");
10573     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10574     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10575   }
10576   PeeledCaseProb = TopCaseProb;
10577   return PeeledSwitchMBB;
10578 }
10579 
10580 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10581   // Extract cases from the switch.
10582   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10583   CaseClusterVector Clusters;
10584   Clusters.reserve(SI.getNumCases());
10585   for (auto I : SI.cases()) {
10586     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10587     const ConstantInt *CaseVal = I.getCaseValue();
10588     BranchProbability Prob =
10589         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10590             : BranchProbability(1, SI.getNumCases() + 1);
10591     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10592   }
10593 
10594   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10595 
10596   // Cluster adjacent cases with the same destination. We do this at all
10597   // optimization levels because it's cheap to do and will make codegen faster
10598   // if there are many clusters.
10599   sortAndRangeify(Clusters);
10600 
10601   // The branch probablity of the peeled case.
10602   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10603   MachineBasicBlock *PeeledSwitchMBB =
10604       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10605 
10606   // If there is only the default destination, jump there directly.
10607   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10608   if (Clusters.empty()) {
10609     assert(PeeledSwitchMBB == SwitchMBB);
10610     SwitchMBB->addSuccessor(DefaultMBB);
10611     if (DefaultMBB != NextBlock(SwitchMBB)) {
10612       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10613                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10614     }
10615     return;
10616   }
10617 
10618   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10619   SL->findBitTestClusters(Clusters, &SI);
10620 
10621   LLVM_DEBUG({
10622     dbgs() << "Case clusters: ";
10623     for (const CaseCluster &C : Clusters) {
10624       if (C.Kind == CC_JumpTable)
10625         dbgs() << "JT:";
10626       if (C.Kind == CC_BitTests)
10627         dbgs() << "BT:";
10628 
10629       C.Low->getValue().print(dbgs(), true);
10630       if (C.Low != C.High) {
10631         dbgs() << '-';
10632         C.High->getValue().print(dbgs(), true);
10633       }
10634       dbgs() << ' ';
10635     }
10636     dbgs() << '\n';
10637   });
10638 
10639   assert(!Clusters.empty());
10640   SwitchWorkList WorkList;
10641   CaseClusterIt First = Clusters.begin();
10642   CaseClusterIt Last = Clusters.end() - 1;
10643   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10644   // Scale the branchprobability for DefaultMBB if the peel occurs and
10645   // DefaultMBB is not replaced.
10646   if (PeeledCaseProb != BranchProbability::getZero() &&
10647       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10648     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10649   WorkList.push_back(
10650       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10651 
10652   while (!WorkList.empty()) {
10653     SwitchWorkListItem W = WorkList.back();
10654     WorkList.pop_back();
10655     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10656 
10657     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10658         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10659       // For optimized builds, lower large range as a balanced binary tree.
10660       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10661       continue;
10662     }
10663 
10664     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10665   }
10666 }
10667 
10668 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10669   SmallVector<EVT, 4> ValueVTs;
10670   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10671                   ValueVTs);
10672   unsigned NumValues = ValueVTs.size();
10673   if (NumValues == 0) return;
10674 
10675   SmallVector<SDValue, 4> Values(NumValues);
10676   SDValue Op = getValue(I.getOperand(0));
10677 
10678   for (unsigned i = 0; i != NumValues; ++i)
10679     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10680                             SDValue(Op.getNode(), Op.getResNo() + i));
10681 
10682   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10683                            DAG.getVTList(ValueVTs), Values));
10684 }
10685