xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision d85b3877dcd283feb6075162765664173cf1488f)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         IntermediateVT.isVector()
419             ? EVT::getVectorVT(
420                   *DAG.getContext(), IntermediateVT.getScalarType(),
421                   IntermediateVT.getVectorElementCount() * NumParts)
422             : EVT::getVectorVT(*DAG.getContext(),
423                                IntermediateVT.getScalarType(),
424                                NumIntermediates);
425     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
426                                                 : ISD::BUILD_VECTOR,
427                       DL, BuiltVectorTy, Ops);
428   }
429 
430   // There is now one part, held in Val.  Correct it to match ValueVT.
431   EVT PartEVT = Val.getValueType();
432 
433   if (PartEVT == ValueVT)
434     return Val;
435 
436   if (PartEVT.isVector()) {
437     // If the element type of the source/dest vectors are the same, but the
438     // parts vector has more elements than the value vector, then we have a
439     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
440     // elements we want.
441     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
442       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
443              "Cannot narrow, it would be a lossy transformation");
444       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
445                          DAG.getVectorIdxConstant(0, DL));
446     }
447 
448     // Vector/Vector bitcast.
449     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
450       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
451 
452     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
453       "Cannot handle this kind of promotion");
454     // Promoted vector extract
455     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
456 
457   }
458 
459   // Trivial bitcast if the types are the same size and the destination
460   // vector type is legal.
461   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
462       TLI.isTypeLegal(ValueVT))
463     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464 
465   if (ValueVT.getVectorNumElements() != 1) {
466      // Certain ABIs require that vectors are passed as integers. For vectors
467      // are the same size, this is an obvious bitcast.
468      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
469        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
470      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
471        // Bitcast Val back the original type and extract the corresponding
472        // vector we want.
473        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
474        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
475                                            ValueVT.getVectorElementType(), Elts);
476        Val = DAG.getBitcast(WiderVecType, Val);
477        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
478                           DAG.getVectorIdxConstant(0, DL));
479      }
480 
481      diagnosePossiblyInvalidConstraint(
482          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
483      return DAG.getUNDEF(ValueVT);
484   }
485 
486   // Handle cases such as i8 -> <1 x i1>
487   EVT ValueSVT = ValueVT.getVectorElementType();
488   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
489     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
490       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
491     else
492       Val = ValueVT.isFloatingPoint()
493                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
494                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
495   }
496 
497   return DAG.getBuildVector(ValueVT, DL, Val);
498 }
499 
500 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
501                                  SDValue Val, SDValue *Parts, unsigned NumParts,
502                                  MVT PartVT, const Value *V,
503                                  Optional<CallingConv::ID> CallConv);
504 
505 /// getCopyToParts - Create a series of nodes that contain the specified value
506 /// split into legal parts.  If the parts contain more bits than Val, then, for
507 /// integers, ExtendKind can be used to specify how to generate the extra bits.
508 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
509                            SDValue *Parts, unsigned NumParts, MVT PartVT,
510                            const Value *V,
511                            Optional<CallingConv::ID> CallConv = None,
512                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
513   EVT ValueVT = Val.getValueType();
514 
515   // Handle the vector case separately.
516   if (ValueVT.isVector())
517     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
518                                 CallConv);
519 
520   unsigned PartBits = PartVT.getSizeInBits();
521   unsigned OrigNumParts = NumParts;
522   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
523          "Copying to an illegal type!");
524 
525   if (NumParts == 0)
526     return;
527 
528   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529   EVT PartEVT = PartVT;
530   if (PartEVT == ValueVT) {
531     assert(NumParts == 1 && "No-op copy with multiple parts!");
532     Parts[0] = Val;
533     return;
534   }
535 
536   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537     // If the parts cover more bits than the value has, promote the value.
538     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539       assert(NumParts == 1 && "Do not know what to promote to!");
540       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
541     } else {
542       if (ValueVT.isFloatingPoint()) {
543         // FP values need to be bitcast, then extended if they are being put
544         // into a larger container.
545         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
546         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
547       }
548       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549              ValueVT.isInteger() &&
550              "Unknown mismatch!");
551       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
552       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
553       if (PartVT == MVT::x86mmx)
554         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
555     }
556   } else if (PartBits == ValueVT.getSizeInBits()) {
557     // Different types of the same size.
558     assert(NumParts == 1 && PartEVT != ValueVT);
559     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561     // If the parts cover less bits than value has, truncate the value.
562     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563            ValueVT.isInteger() &&
564            "Unknown mismatch!");
565     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
567     if (PartVT == MVT::x86mmx)
568       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569   }
570 
571   // The value may have changed - recompute ValueVT.
572   ValueVT = Val.getValueType();
573   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574          "Failed to tile the value with PartVT!");
575 
576   if (NumParts == 1) {
577     if (PartEVT != ValueVT) {
578       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
579                                         "scalar-to-vector conversion failed");
580       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581     }
582 
583     Parts[0] = Val;
584     return;
585   }
586 
587   // Expand the value into multiple parts.
588   if (NumParts & (NumParts - 1)) {
589     // The number of parts is not a power of 2.  Split off and copy the tail.
590     assert(PartVT.isInteger() && ValueVT.isInteger() &&
591            "Do not know what to expand to!");
592     unsigned RoundParts = 1 << Log2_32(NumParts);
593     unsigned RoundBits = RoundParts * PartBits;
594     unsigned OddParts = NumParts - RoundParts;
595     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
596       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
597 
598     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
599                    CallConv);
600 
601     if (DAG.getDataLayout().isBigEndian())
602       // The odd parts were reversed by getCopyToParts - unreverse them.
603       std::reverse(Parts + RoundParts, Parts + NumParts);
604 
605     NumParts = RoundParts;
606     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
607     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
608   }
609 
610   // The number of parts is a power of 2.  Repeatedly bisect the value using
611   // EXTRACT_ELEMENT.
612   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
613                          EVT::getIntegerVT(*DAG.getContext(),
614                                            ValueVT.getSizeInBits()),
615                          Val);
616 
617   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618     for (unsigned i = 0; i < NumParts; i += StepSize) {
619       unsigned ThisBits = StepSize * PartBits / 2;
620       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
621       SDValue &Part0 = Parts[i];
622       SDValue &Part1 = Parts[i+StepSize/2];
623 
624       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
625                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
626       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
628 
629       if (ThisBits == PartBits && ThisVT != PartVT) {
630         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
631         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
632       }
633     }
634   }
635 
636   if (DAG.getDataLayout().isBigEndian())
637     std::reverse(Parts, Parts + OrigNumParts);
638 }
639 
640 static SDValue widenVectorToPartType(SelectionDAG &DAG,
641                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
642   if (!PartVT.isVector())
643     return SDValue();
644 
645   EVT ValueVT = Val.getValueType();
646   unsigned PartNumElts = PartVT.getVectorNumElements();
647   unsigned ValueNumElts = ValueVT.getVectorNumElements();
648   if (PartNumElts > ValueNumElts &&
649       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
650     EVT ElementVT = PartVT.getVectorElementType();
651     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
652     // undef elements.
653     SmallVector<SDValue, 16> Ops;
654     DAG.ExtractVectorElements(Val, Ops);
655     SDValue EltUndef = DAG.getUNDEF(ElementVT);
656     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
657       Ops.push_back(EltUndef);
658 
659     // FIXME: Use CONCAT for 2x -> 4x.
660     return DAG.getBuildVector(PartVT, DL, Ops);
661   }
662 
663   return SDValue();
664 }
665 
666 /// getCopyToPartsVector - Create a series of nodes that contain the specified
667 /// value split into legal parts.
668 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
669                                  SDValue Val, SDValue *Parts, unsigned NumParts,
670                                  MVT PartVT, const Value *V,
671                                  Optional<CallingConv::ID> CallConv) {
672   EVT ValueVT = Val.getValueType();
673   assert(ValueVT.isVector() && "Not a vector");
674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
675   const bool IsABIRegCopy = CallConv.hasValue();
676 
677   if (NumParts == 1) {
678     EVT PartEVT = PartVT;
679     if (PartEVT == ValueVT) {
680       // Nothing to do.
681     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
682       // Bitconvert vector->vector case.
683       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
684     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
685       Val = Widened;
686     } else if (PartVT.isVector() &&
687                PartEVT.getVectorElementType().bitsGE(
688                  ValueVT.getVectorElementType()) &&
689                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
690 
691       // Promoted vector extract
692       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
693     } else {
694       if (ValueVT.getVectorNumElements() == 1) {
695         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
696                           DAG.getVectorIdxConstant(0, DL));
697       } else {
698         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
699                "lossy conversion of vector to scalar type");
700         EVT IntermediateType =
701             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
702         Val = DAG.getBitcast(IntermediateType, Val);
703         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
704       }
705     }
706 
707     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
708     Parts[0] = Val;
709     return;
710   }
711 
712   // Handle a multi-element vector.
713   EVT IntermediateVT;
714   MVT RegisterVT;
715   unsigned NumIntermediates;
716   unsigned NumRegs;
717   if (IsABIRegCopy) {
718     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
719         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
720         NumIntermediates, RegisterVT);
721   } else {
722     NumRegs =
723         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
724                                    NumIntermediates, RegisterVT);
725   }
726 
727   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
728   NumParts = NumRegs; // Silence a compiler warning.
729   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
730 
731   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
732     IntermediateVT.getVectorNumElements() : 1;
733 
734   // Convert the vector to the appropriate type if necessary.
735   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
736 
737   EVT BuiltVectorTy = EVT::getVectorVT(
738       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
739   if (ValueVT != BuiltVectorTy) {
740     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
741       Val = Widened;
742 
743     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
744   }
745 
746   // Split the vector into intermediate operands.
747   SmallVector<SDValue, 8> Ops(NumIntermediates);
748   for (unsigned i = 0; i != NumIntermediates; ++i) {
749     if (IntermediateVT.isVector()) {
750       Ops[i] =
751           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
752                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
753     } else {
754       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
755                            DAG.getVectorIdxConstant(i, DL));
756     }
757   }
758 
759   // Split the intermediate operands into legal parts.
760   if (NumParts == NumIntermediates) {
761     // If the register was not expanded, promote or copy the value,
762     // as appropriate.
763     for (unsigned i = 0; i != NumParts; ++i)
764       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
765   } else if (NumParts > 0) {
766     // If the intermediate type was expanded, split each the value into
767     // legal parts.
768     assert(NumIntermediates != 0 && "division by zero");
769     assert(NumParts % NumIntermediates == 0 &&
770            "Must expand into a divisible number of parts!");
771     unsigned Factor = NumParts / NumIntermediates;
772     for (unsigned i = 0; i != NumIntermediates; ++i)
773       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
774                      CallConv);
775   }
776 }
777 
778 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
779                            EVT valuevt, Optional<CallingConv::ID> CC)
780     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
781       RegCount(1, regs.size()), CallConv(CC) {}
782 
783 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
784                            const DataLayout &DL, unsigned Reg, Type *Ty,
785                            Optional<CallingConv::ID> CC) {
786   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
787 
788   CallConv = CC;
789 
790   for (EVT ValueVT : ValueVTs) {
791     unsigned NumRegs =
792         isABIMangled()
793             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getNumRegisters(Context, ValueVT);
795     MVT RegisterVT =
796         isABIMangled()
797             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
798             : TLI.getRegisterType(Context, ValueVT);
799     for (unsigned i = 0; i != NumRegs; ++i)
800       Regs.push_back(Reg + i);
801     RegVTs.push_back(RegisterVT);
802     RegCount.push_back(NumRegs);
803     Reg += NumRegs;
804   }
805 }
806 
807 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
808                                       FunctionLoweringInfo &FuncInfo,
809                                       const SDLoc &dl, SDValue &Chain,
810                                       SDValue *Flag, const Value *V) const {
811   // A Value with type {} or [0 x %t] needs no registers.
812   if (ValueVTs.empty())
813     return SDValue();
814 
815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
816 
817   // Assemble the legal parts into the final values.
818   SmallVector<SDValue, 4> Values(ValueVTs.size());
819   SmallVector<SDValue, 8> Parts;
820   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
821     // Copy the legal parts from the registers.
822     EVT ValueVT = ValueVTs[Value];
823     unsigned NumRegs = RegCount[Value];
824     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
825                                           *DAG.getContext(),
826                                           CallConv.getValue(), RegVTs[Value])
827                                     : RegVTs[Value];
828 
829     Parts.resize(NumRegs);
830     for (unsigned i = 0; i != NumRegs; ++i) {
831       SDValue P;
832       if (!Flag) {
833         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
834       } else {
835         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
836         *Flag = P.getValue(2);
837       }
838 
839       Chain = P.getValue(1);
840       Parts[i] = P;
841 
842       // If the source register was virtual and if we know something about it,
843       // add an assert node.
844       if (!Register::isVirtualRegister(Regs[Part + i]) ||
845           !RegisterVT.isInteger())
846         continue;
847 
848       const FunctionLoweringInfo::LiveOutInfo *LOI =
849         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
850       if (!LOI)
851         continue;
852 
853       unsigned RegSize = RegisterVT.getScalarSizeInBits();
854       unsigned NumSignBits = LOI->NumSignBits;
855       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
856 
857       if (NumZeroBits == RegSize) {
858         // The current value is a zero.
859         // Explicitly express that as it would be easier for
860         // optimizations to kick in.
861         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
862         continue;
863       }
864 
865       // FIXME: We capture more information than the dag can represent.  For
866       // now, just use the tightest assertzext/assertsext possible.
867       bool isSExt;
868       EVT FromVT(MVT::Other);
869       if (NumZeroBits) {
870         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
871         isSExt = false;
872       } else if (NumSignBits > 1) {
873         FromVT =
874             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
875         isSExt = true;
876       } else {
877         continue;
878       }
879       // Add an assertion node.
880       assert(FromVT != MVT::Other);
881       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
882                              RegisterVT, P, DAG.getValueType(FromVT));
883     }
884 
885     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
886                                      RegisterVT, ValueVT, V, CallConv);
887     Part += NumRegs;
888     Parts.clear();
889   }
890 
891   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
892 }
893 
894 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
895                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
896                                  const Value *V,
897                                  ISD::NodeType PreferredExtendType) const {
898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
899   ISD::NodeType ExtendKind = PreferredExtendType;
900 
901   // Get the list of the values's legal parts.
902   unsigned NumRegs = Regs.size();
903   SmallVector<SDValue, 8> Parts(NumRegs);
904   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
905     unsigned NumParts = RegCount[Value];
906 
907     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
908                                           *DAG.getContext(),
909                                           CallConv.getValue(), RegVTs[Value])
910                                     : RegVTs[Value];
911 
912     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
913       ExtendKind = ISD::ZERO_EXTEND;
914 
915     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
916                    NumParts, RegisterVT, V, CallConv, ExtendKind);
917     Part += NumParts;
918   }
919 
920   // Copy the parts into the registers.
921   SmallVector<SDValue, 8> Chains(NumRegs);
922   for (unsigned i = 0; i != NumRegs; ++i) {
923     SDValue Part;
924     if (!Flag) {
925       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
926     } else {
927       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
928       *Flag = Part.getValue(1);
929     }
930 
931     Chains[i] = Part.getValue(0);
932   }
933 
934   if (NumRegs == 1 || Flag)
935     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
936     // flagged to it. That is the CopyToReg nodes and the user are considered
937     // a single scheduling unit. If we create a TokenFactor and return it as
938     // chain, then the TokenFactor is both a predecessor (operand) of the
939     // user as well as a successor (the TF operands are flagged to the user).
940     // c1, f1 = CopyToReg
941     // c2, f2 = CopyToReg
942     // c3     = TokenFactor c1, c2
943     // ...
944     //        = op c3, ..., f2
945     Chain = Chains[NumRegs-1];
946   else
947     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
948 }
949 
950 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
951                                         unsigned MatchingIdx, const SDLoc &dl,
952                                         SelectionDAG &DAG,
953                                         std::vector<SDValue> &Ops) const {
954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
955 
956   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
957   if (HasMatching)
958     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
959   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
960     // Put the register class of the virtual registers in the flag word.  That
961     // way, later passes can recompute register class constraints for inline
962     // assembly as well as normal instructions.
963     // Don't do this for tied operands that can use the regclass information
964     // from the def.
965     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
966     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
967     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
968   }
969 
970   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
971   Ops.push_back(Res);
972 
973   if (Code == InlineAsm::Kind_Clobber) {
974     // Clobbers should always have a 1:1 mapping with registers, and may
975     // reference registers that have illegal (e.g. vector) types. Hence, we
976     // shouldn't try to apply any sort of splitting logic to them.
977     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
978            "No 1:1 mapping from clobbers to regs?");
979     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
980     (void)SP;
981     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
982       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
983       assert(
984           (Regs[I] != SP ||
985            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
986           "If we clobbered the stack pointer, MFI should know about it.");
987     }
988     return;
989   }
990 
991   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
992     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
993     MVT RegisterVT = RegVTs[Value];
994     for (unsigned i = 0; i != NumRegs; ++i) {
995       assert(Reg < Regs.size() && "Mismatch in # registers expected");
996       unsigned TheReg = Regs[Reg++];
997       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
998     }
999   }
1000 }
1001 
1002 SmallVector<std::pair<unsigned, unsigned>, 4>
1003 RegsForValue::getRegsAndSizes() const {
1004   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1005   unsigned I = 0;
1006   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1007     unsigned RegCount = std::get<0>(CountAndVT);
1008     MVT RegisterVT = std::get<1>(CountAndVT);
1009     unsigned RegisterSize = RegisterVT.getSizeInBits();
1010     for (unsigned E = I + RegCount; I != E; ++I)
1011       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1012   }
1013   return OutVec;
1014 }
1015 
1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1017                                const TargetLibraryInfo *li) {
1018   AA = aa;
1019   GFI = gfi;
1020   LibInfo = li;
1021   DL = &DAG.getDataLayout();
1022   Context = DAG.getContext();
1023   LPadToCallSiteMap.clear();
1024   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1025 }
1026 
1027 void SelectionDAGBuilder::clear() {
1028   NodeMap.clear();
1029   UnusedArgNodeMap.clear();
1030   PendingLoads.clear();
1031   PendingExports.clear();
1032   PendingConstrainedFP.clear();
1033   PendingConstrainedFPStrict.clear();
1034   CurInst = nullptr;
1035   HasTailCall = false;
1036   SDNodeOrder = LowestSDNodeOrder;
1037   StatepointLowering.clear();
1038 }
1039 
1040 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1041   DanglingDebugInfoMap.clear();
1042 }
1043 
1044 // Update DAG root to include dependencies on Pending chains.
1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1046   SDValue Root = DAG.getRoot();
1047 
1048   if (Pending.empty())
1049     return Root;
1050 
1051   // Add current root to PendingChains, unless we already indirectly
1052   // depend on it.
1053   if (Root.getOpcode() != ISD::EntryToken) {
1054     unsigned i = 0, e = Pending.size();
1055     for (; i != e; ++i) {
1056       assert(Pending[i].getNode()->getNumOperands() > 1);
1057       if (Pending[i].getNode()->getOperand(0) == Root)
1058         break;  // Don't add the root if we already indirectly depend on it.
1059     }
1060 
1061     if (i == e)
1062       Pending.push_back(Root);
1063   }
1064 
1065   if (Pending.size() == 1)
1066     Root = Pending[0];
1067   else
1068     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1069 
1070   DAG.setRoot(Root);
1071   Pending.clear();
1072   return Root;
1073 }
1074 
1075 SDValue SelectionDAGBuilder::getMemoryRoot() {
1076   return updateRoot(PendingLoads);
1077 }
1078 
1079 SDValue SelectionDAGBuilder::getRoot() {
1080   // Chain up all pending constrained intrinsics together with all
1081   // pending loads, by simply appending them to PendingLoads and
1082   // then calling getMemoryRoot().
1083   PendingLoads.reserve(PendingLoads.size() +
1084                        PendingConstrainedFP.size() +
1085                        PendingConstrainedFPStrict.size());
1086   PendingLoads.append(PendingConstrainedFP.begin(),
1087                       PendingConstrainedFP.end());
1088   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1089                       PendingConstrainedFPStrict.end());
1090   PendingConstrainedFP.clear();
1091   PendingConstrainedFPStrict.clear();
1092   return getMemoryRoot();
1093 }
1094 
1095 SDValue SelectionDAGBuilder::getControlRoot() {
1096   // We need to emit pending fpexcept.strict constrained intrinsics,
1097   // so append them to the PendingExports list.
1098   PendingExports.append(PendingConstrainedFPStrict.begin(),
1099                         PendingConstrainedFPStrict.end());
1100   PendingConstrainedFPStrict.clear();
1101   return updateRoot(PendingExports);
1102 }
1103 
1104 void SelectionDAGBuilder::visit(const Instruction &I) {
1105   // Set up outgoing PHI node register values before emitting the terminator.
1106   if (I.isTerminator()) {
1107     HandlePHINodesInSuccessorBlocks(I.getParent());
1108   }
1109 
1110   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1111   if (!isa<DbgInfoIntrinsic>(I))
1112     ++SDNodeOrder;
1113 
1114   CurInst = &I;
1115 
1116   visit(I.getOpcode(), I);
1117 
1118   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1119     // ConstrainedFPIntrinsics handle their own FMF.
1120     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1121       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1122       // maps to this instruction.
1123       // TODO: We could handle all flags (nsw, etc) here.
1124       // TODO: If an IR instruction maps to >1 node, only the final node will have
1125       //       flags set.
1126       if (SDNode *Node = getNodeForIRValue(&I)) {
1127         SDNodeFlags IncomingFlags;
1128         IncomingFlags.copyFMF(*FPMO);
1129         if (!Node->getFlags().isDefined())
1130           Node->setFlags(IncomingFlags);
1131         else
1132           Node->intersectFlagsWith(IncomingFlags);
1133       }
1134     }
1135   }
1136 
1137   if (!I.isTerminator() && !HasTailCall &&
1138       !isStatepoint(&I)) // statepoints handle their exports internally
1139     CopyToExportRegsIfNeeded(&I);
1140 
1141   CurInst = nullptr;
1142 }
1143 
1144 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1145   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1146 }
1147 
1148 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1149   // Note: this doesn't use InstVisitor, because it has to work with
1150   // ConstantExpr's in addition to instructions.
1151   switch (Opcode) {
1152   default: llvm_unreachable("Unknown instruction type encountered!");
1153     // Build the switch statement using the Instruction.def file.
1154 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1155     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1156 #include "llvm/IR/Instruction.def"
1157   }
1158 }
1159 
1160 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1161                                                 const DIExpression *Expr) {
1162   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1163     const DbgValueInst *DI = DDI.getDI();
1164     DIVariable *DanglingVariable = DI->getVariable();
1165     DIExpression *DanglingExpr = DI->getExpression();
1166     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1167       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1168       return true;
1169     }
1170     return false;
1171   };
1172 
1173   for (auto &DDIMI : DanglingDebugInfoMap) {
1174     DanglingDebugInfoVector &DDIV = DDIMI.second;
1175 
1176     // If debug info is to be dropped, run it through final checks to see
1177     // whether it can be salvaged.
1178     for (auto &DDI : DDIV)
1179       if (isMatchingDbgValue(DDI))
1180         salvageUnresolvedDbgValue(DDI);
1181 
1182     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1183   }
1184 }
1185 
1186 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1187 // generate the debug data structures now that we've seen its definition.
1188 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1189                                                    SDValue Val) {
1190   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1191   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1192     return;
1193 
1194   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1195   for (auto &DDI : DDIV) {
1196     const DbgValueInst *DI = DDI.getDI();
1197     assert(DI && "Ill-formed DanglingDebugInfo");
1198     DebugLoc dl = DDI.getdl();
1199     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1200     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1201     DILocalVariable *Variable = DI->getVariable();
1202     DIExpression *Expr = DI->getExpression();
1203     assert(Variable->isValidLocationForIntrinsic(dl) &&
1204            "Expected inlined-at fields to agree");
1205     SDDbgValue *SDV;
1206     if (Val.getNode()) {
1207       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1208       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1209       // we couldn't resolve it directly when examining the DbgValue intrinsic
1210       // in the first place we should not be more successful here). Unless we
1211       // have some test case that prove this to be correct we should avoid
1212       // calling EmitFuncArgumentDbgValue here.
1213       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1214         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1215                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1216         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1217         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1218         // inserted after the definition of Val when emitting the instructions
1219         // after ISel. An alternative could be to teach
1220         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1221         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1222                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1223                    << ValSDNodeOrder << "\n");
1224         SDV = getDbgValue(Val, Variable, Expr, dl,
1225                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1226         DAG.AddDbgValue(SDV, Val.getNode(), false);
1227       } else
1228         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1229                           << "in EmitFuncArgumentDbgValue\n");
1230     } else {
1231       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1232       auto Undef =
1233           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1234       auto SDV =
1235           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1236       DAG.AddDbgValue(SDV, nullptr, false);
1237     }
1238   }
1239   DDIV.clear();
1240 }
1241 
1242 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1243   Value *V = DDI.getDI()->getValue();
1244   DILocalVariable *Var = DDI.getDI()->getVariable();
1245   DIExpression *Expr = DDI.getDI()->getExpression();
1246   DebugLoc DL = DDI.getdl();
1247   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1248   unsigned SDOrder = DDI.getSDNodeOrder();
1249 
1250   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1251   // that DW_OP_stack_value is desired.
1252   assert(isa<DbgValueInst>(DDI.getDI()));
1253   bool StackValue = true;
1254 
1255   // Can this Value can be encoded without any further work?
1256   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1257     return;
1258 
1259   // Attempt to salvage back through as many instructions as possible. Bail if
1260   // a non-instruction is seen, such as a constant expression or global
1261   // variable. FIXME: Further work could recover those too.
1262   while (isa<Instruction>(V)) {
1263     Instruction &VAsInst = *cast<Instruction>(V);
1264     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1265 
1266     // If we cannot salvage any further, and haven't yet found a suitable debug
1267     // expression, bail out.
1268     if (!NewExpr)
1269       break;
1270 
1271     // New value and expr now represent this debuginfo.
1272     V = VAsInst.getOperand(0);
1273     Expr = NewExpr;
1274 
1275     // Some kind of simplification occurred: check whether the operand of the
1276     // salvaged debug expression can be encoded in this DAG.
1277     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1278       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1279                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1280       return;
1281     }
1282   }
1283 
1284   // This was the final opportunity to salvage this debug information, and it
1285   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1286   // any earlier variable location.
1287   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1288   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1289   DAG.AddDbgValue(SDV, nullptr, false);
1290 
1291   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1292                     << "\n");
1293   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1294                     << "\n");
1295 }
1296 
1297 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1298                                            DIExpression *Expr, DebugLoc dl,
1299                                            DebugLoc InstDL, unsigned Order) {
1300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1301   SDDbgValue *SDV;
1302   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1303       isa<ConstantPointerNull>(V)) {
1304     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1305     DAG.AddDbgValue(SDV, nullptr, false);
1306     return true;
1307   }
1308 
1309   // If the Value is a frame index, we can create a FrameIndex debug value
1310   // without relying on the DAG at all.
1311   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1312     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1313     if (SI != FuncInfo.StaticAllocaMap.end()) {
1314       auto SDV =
1315           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1316                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1317       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1318       // is still available even if the SDNode gets optimized out.
1319       DAG.AddDbgValue(SDV, nullptr, false);
1320       return true;
1321     }
1322   }
1323 
1324   // Do not use getValue() in here; we don't want to generate code at
1325   // this point if it hasn't been done yet.
1326   SDValue N = NodeMap[V];
1327   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1328     N = UnusedArgNodeMap[V];
1329   if (N.getNode()) {
1330     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1331       return true;
1332     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1333     DAG.AddDbgValue(SDV, N.getNode(), false);
1334     return true;
1335   }
1336 
1337   // Special rules apply for the first dbg.values of parameter variables in a
1338   // function. Identify them by the fact they reference Argument Values, that
1339   // they're parameters, and they are parameters of the current function. We
1340   // need to let them dangle until they get an SDNode.
1341   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1342                        !InstDL.getInlinedAt();
1343   if (!IsParamOfFunc) {
1344     // The value is not used in this block yet (or it would have an SDNode).
1345     // We still want the value to appear for the user if possible -- if it has
1346     // an associated VReg, we can refer to that instead.
1347     auto VMI = FuncInfo.ValueMap.find(V);
1348     if (VMI != FuncInfo.ValueMap.end()) {
1349       unsigned Reg = VMI->second;
1350       // If this is a PHI node, it may be split up into several MI PHI nodes
1351       // (in FunctionLoweringInfo::set).
1352       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1353                        V->getType(), None);
1354       if (RFV.occupiesMultipleRegs()) {
1355         unsigned Offset = 0;
1356         unsigned BitsToDescribe = 0;
1357         if (auto VarSize = Var->getSizeInBits())
1358           BitsToDescribe = *VarSize;
1359         if (auto Fragment = Expr->getFragmentInfo())
1360           BitsToDescribe = Fragment->SizeInBits;
1361         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1362           unsigned RegisterSize = RegAndSize.second;
1363           // Bail out if all bits are described already.
1364           if (Offset >= BitsToDescribe)
1365             break;
1366           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1367               ? BitsToDescribe - Offset
1368               : RegisterSize;
1369           auto FragmentExpr = DIExpression::createFragmentExpression(
1370               Expr, Offset, FragmentSize);
1371           if (!FragmentExpr)
1372               continue;
1373           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1374                                     false, dl, SDNodeOrder);
1375           DAG.AddDbgValue(SDV, nullptr, false);
1376           Offset += RegisterSize;
1377         }
1378       } else {
1379         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1380         DAG.AddDbgValue(SDV, nullptr, false);
1381       }
1382       return true;
1383     }
1384   }
1385 
1386   return false;
1387 }
1388 
1389 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1390   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1391   for (auto &Pair : DanglingDebugInfoMap)
1392     for (auto &DDI : Pair.second)
1393       salvageUnresolvedDbgValue(DDI);
1394   clearDanglingDebugInfo();
1395 }
1396 
1397 /// getCopyFromRegs - If there was virtual register allocated for the value V
1398 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1399 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1400   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1401   SDValue Result;
1402 
1403   if (It != FuncInfo.ValueMap.end()) {
1404     Register InReg = It->second;
1405 
1406     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1407                      DAG.getDataLayout(), InReg, Ty,
1408                      None); // This is not an ABI copy.
1409     SDValue Chain = DAG.getEntryNode();
1410     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1411                                  V);
1412     resolveDanglingDebugInfo(V, Result);
1413   }
1414 
1415   return Result;
1416 }
1417 
1418 /// getValue - Return an SDValue for the given Value.
1419 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1420   // If we already have an SDValue for this value, use it. It's important
1421   // to do this first, so that we don't create a CopyFromReg if we already
1422   // have a regular SDValue.
1423   SDValue &N = NodeMap[V];
1424   if (N.getNode()) return N;
1425 
1426   // If there's a virtual register allocated and initialized for this
1427   // value, use it.
1428   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1429     return copyFromReg;
1430 
1431   // Otherwise create a new SDValue and remember it.
1432   SDValue Val = getValueImpl(V);
1433   NodeMap[V] = Val;
1434   resolveDanglingDebugInfo(V, Val);
1435   return Val;
1436 }
1437 
1438 // Return true if SDValue exists for the given Value
1439 bool SelectionDAGBuilder::findValue(const Value *V) const {
1440   return (NodeMap.find(V) != NodeMap.end()) ||
1441     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1442 }
1443 
1444 /// getNonRegisterValue - Return an SDValue for the given Value, but
1445 /// don't look in FuncInfo.ValueMap for a virtual register.
1446 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1447   // If we already have an SDValue for this value, use it.
1448   SDValue &N = NodeMap[V];
1449   if (N.getNode()) {
1450     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1451       // Remove the debug location from the node as the node is about to be used
1452       // in a location which may differ from the original debug location.  This
1453       // is relevant to Constant and ConstantFP nodes because they can appear
1454       // as constant expressions inside PHI nodes.
1455       N->setDebugLoc(DebugLoc());
1456     }
1457     return N;
1458   }
1459 
1460   // Otherwise create a new SDValue and remember it.
1461   SDValue Val = getValueImpl(V);
1462   NodeMap[V] = Val;
1463   resolveDanglingDebugInfo(V, Val);
1464   return Val;
1465 }
1466 
1467 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1468 /// Create an SDValue for the given value.
1469 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1471 
1472   if (const Constant *C = dyn_cast<Constant>(V)) {
1473     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1474 
1475     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1476       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1477 
1478     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1479       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1480 
1481     if (isa<ConstantPointerNull>(C)) {
1482       unsigned AS = V->getType()->getPointerAddressSpace();
1483       return DAG.getConstant(0, getCurSDLoc(),
1484                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1485     }
1486 
1487     if (match(C, m_VScale(DAG.getDataLayout())))
1488       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1489 
1490     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1491       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1492 
1493     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1494       return DAG.getUNDEF(VT);
1495 
1496     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1497       visit(CE->getOpcode(), *CE);
1498       SDValue N1 = NodeMap[V];
1499       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1500       return N1;
1501     }
1502 
1503     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1504       SmallVector<SDValue, 4> Constants;
1505       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1506            OI != OE; ++OI) {
1507         SDNode *Val = getValue(*OI).getNode();
1508         // If the operand is an empty aggregate, there are no values.
1509         if (!Val) continue;
1510         // Add each leaf value from the operand to the Constants list
1511         // to form a flattened list of all the values.
1512         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1513           Constants.push_back(SDValue(Val, i));
1514       }
1515 
1516       return DAG.getMergeValues(Constants, getCurSDLoc());
1517     }
1518 
1519     if (const ConstantDataSequential *CDS =
1520           dyn_cast<ConstantDataSequential>(C)) {
1521       SmallVector<SDValue, 4> Ops;
1522       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1523         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1524         // Add each leaf value from the operand to the Constants list
1525         // to form a flattened list of all the values.
1526         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1527           Ops.push_back(SDValue(Val, i));
1528       }
1529 
1530       if (isa<ArrayType>(CDS->getType()))
1531         return DAG.getMergeValues(Ops, getCurSDLoc());
1532       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1533     }
1534 
1535     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1536       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1537              "Unknown struct or array constant!");
1538 
1539       SmallVector<EVT, 4> ValueVTs;
1540       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1541       unsigned NumElts = ValueVTs.size();
1542       if (NumElts == 0)
1543         return SDValue(); // empty struct
1544       SmallVector<SDValue, 4> Constants(NumElts);
1545       for (unsigned i = 0; i != NumElts; ++i) {
1546         EVT EltVT = ValueVTs[i];
1547         if (isa<UndefValue>(C))
1548           Constants[i] = DAG.getUNDEF(EltVT);
1549         else if (EltVT.isFloatingPoint())
1550           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1551         else
1552           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1553       }
1554 
1555       return DAG.getMergeValues(Constants, getCurSDLoc());
1556     }
1557 
1558     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1559       return DAG.getBlockAddress(BA, VT);
1560 
1561     VectorType *VecTy = cast<VectorType>(V->getType());
1562     unsigned NumElements = VecTy->getNumElements();
1563 
1564     // Now that we know the number and type of the elements, get that number of
1565     // elements into the Ops array based on what kind of constant it is.
1566     SmallVector<SDValue, 16> Ops;
1567     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1568       for (unsigned i = 0; i != NumElements; ++i)
1569         Ops.push_back(getValue(CV->getOperand(i)));
1570     } else {
1571       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1572       EVT EltVT =
1573           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1574 
1575       SDValue Op;
1576       if (EltVT.isFloatingPoint())
1577         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1578       else
1579         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1580       Ops.assign(NumElements, Op);
1581     }
1582 
1583     // Create a BUILD_VECTOR node.
1584     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1585   }
1586 
1587   // If this is a static alloca, generate it as the frameindex instead of
1588   // computation.
1589   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1590     DenseMap<const AllocaInst*, int>::iterator SI =
1591       FuncInfo.StaticAllocaMap.find(AI);
1592     if (SI != FuncInfo.StaticAllocaMap.end())
1593       return DAG.getFrameIndex(SI->second,
1594                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1595   }
1596 
1597   // If this is an instruction which fast-isel has deferred, select it now.
1598   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1599     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1600 
1601     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1602                      Inst->getType(), getABIRegCopyCC(V));
1603     SDValue Chain = DAG.getEntryNode();
1604     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1605   }
1606 
1607   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1608     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1609   }
1610   llvm_unreachable("Can't get register for value!");
1611 }
1612 
1613 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1614   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1615   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1616   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1617   bool IsSEH = isAsynchronousEHPersonality(Pers);
1618   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1619   if (!IsSEH)
1620     CatchPadMBB->setIsEHScopeEntry();
1621   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1622   if (IsMSVCCXX || IsCoreCLR)
1623     CatchPadMBB->setIsEHFuncletEntry();
1624 }
1625 
1626 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1627   // Update machine-CFG edge.
1628   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1629   FuncInfo.MBB->addSuccessor(TargetMBB);
1630 
1631   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1632   bool IsSEH = isAsynchronousEHPersonality(Pers);
1633   if (IsSEH) {
1634     // If this is not a fall-through branch or optimizations are switched off,
1635     // emit the branch.
1636     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1637         TM.getOptLevel() == CodeGenOpt::None)
1638       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1639                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1640     return;
1641   }
1642 
1643   // Figure out the funclet membership for the catchret's successor.
1644   // This will be used by the FuncletLayout pass to determine how to order the
1645   // BB's.
1646   // A 'catchret' returns to the outer scope's color.
1647   Value *ParentPad = I.getCatchSwitchParentPad();
1648   const BasicBlock *SuccessorColor;
1649   if (isa<ConstantTokenNone>(ParentPad))
1650     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1651   else
1652     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1653   assert(SuccessorColor && "No parent funclet for catchret!");
1654   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1655   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1656 
1657   // Create the terminator node.
1658   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1659                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1660                             DAG.getBasicBlock(SuccessorColorMBB));
1661   DAG.setRoot(Ret);
1662 }
1663 
1664 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1665   // Don't emit any special code for the cleanuppad instruction. It just marks
1666   // the start of an EH scope/funclet.
1667   FuncInfo.MBB->setIsEHScopeEntry();
1668   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1669   if (Pers != EHPersonality::Wasm_CXX) {
1670     FuncInfo.MBB->setIsEHFuncletEntry();
1671     FuncInfo.MBB->setIsCleanupFuncletEntry();
1672   }
1673 }
1674 
1675 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1676 // the control flow always stops at the single catch pad, as it does for a
1677 // cleanup pad. In case the exception caught is not of the types the catch pad
1678 // catches, it will be rethrown by a rethrow.
1679 static void findWasmUnwindDestinations(
1680     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1681     BranchProbability Prob,
1682     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1683         &UnwindDests) {
1684   while (EHPadBB) {
1685     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1686     if (isa<CleanupPadInst>(Pad)) {
1687       // Stop on cleanup pads.
1688       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1689       UnwindDests.back().first->setIsEHScopeEntry();
1690       break;
1691     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1692       // Add the catchpad handlers to the possible destinations. We don't
1693       // continue to the unwind destination of the catchswitch for wasm.
1694       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1695         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1696         UnwindDests.back().first->setIsEHScopeEntry();
1697       }
1698       break;
1699     } else {
1700       continue;
1701     }
1702   }
1703 }
1704 
1705 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1706 /// many places it could ultimately go. In the IR, we have a single unwind
1707 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1708 /// This function skips over imaginary basic blocks that hold catchswitch
1709 /// instructions, and finds all the "real" machine
1710 /// basic block destinations. As those destinations may not be successors of
1711 /// EHPadBB, here we also calculate the edge probability to those destinations.
1712 /// The passed-in Prob is the edge probability to EHPadBB.
1713 static void findUnwindDestinations(
1714     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1715     BranchProbability Prob,
1716     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1717         &UnwindDests) {
1718   EHPersonality Personality =
1719     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1720   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1721   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1722   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1723   bool IsSEH = isAsynchronousEHPersonality(Personality);
1724 
1725   if (IsWasmCXX) {
1726     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1727     assert(UnwindDests.size() <= 1 &&
1728            "There should be at most one unwind destination for wasm");
1729     return;
1730   }
1731 
1732   while (EHPadBB) {
1733     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1734     BasicBlock *NewEHPadBB = nullptr;
1735     if (isa<LandingPadInst>(Pad)) {
1736       // Stop on landingpads. They are not funclets.
1737       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1738       break;
1739     } else if (isa<CleanupPadInst>(Pad)) {
1740       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1741       // personalities.
1742       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1743       UnwindDests.back().first->setIsEHScopeEntry();
1744       UnwindDests.back().first->setIsEHFuncletEntry();
1745       break;
1746     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1747       // Add the catchpad handlers to the possible destinations.
1748       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1749         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1750         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1751         if (IsMSVCCXX || IsCoreCLR)
1752           UnwindDests.back().first->setIsEHFuncletEntry();
1753         if (!IsSEH)
1754           UnwindDests.back().first->setIsEHScopeEntry();
1755       }
1756       NewEHPadBB = CatchSwitch->getUnwindDest();
1757     } else {
1758       continue;
1759     }
1760 
1761     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1762     if (BPI && NewEHPadBB)
1763       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1764     EHPadBB = NewEHPadBB;
1765   }
1766 }
1767 
1768 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1769   // Update successor info.
1770   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1771   auto UnwindDest = I.getUnwindDest();
1772   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1773   BranchProbability UnwindDestProb =
1774       (BPI && UnwindDest)
1775           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1776           : BranchProbability::getZero();
1777   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1778   for (auto &UnwindDest : UnwindDests) {
1779     UnwindDest.first->setIsEHPad();
1780     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1781   }
1782   FuncInfo.MBB->normalizeSuccProbs();
1783 
1784   // Create the terminator node.
1785   SDValue Ret =
1786       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1787   DAG.setRoot(Ret);
1788 }
1789 
1790 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1791   report_fatal_error("visitCatchSwitch not yet implemented!");
1792 }
1793 
1794 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796   auto &DL = DAG.getDataLayout();
1797   SDValue Chain = getControlRoot();
1798   SmallVector<ISD::OutputArg, 8> Outs;
1799   SmallVector<SDValue, 8> OutVals;
1800 
1801   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1802   // lower
1803   //
1804   //   %val = call <ty> @llvm.experimental.deoptimize()
1805   //   ret <ty> %val
1806   //
1807   // differently.
1808   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1809     LowerDeoptimizingReturn();
1810     return;
1811   }
1812 
1813   if (!FuncInfo.CanLowerReturn) {
1814     unsigned DemoteReg = FuncInfo.DemoteRegister;
1815     const Function *F = I.getParent()->getParent();
1816 
1817     // Emit a store of the return value through the virtual register.
1818     // Leave Outs empty so that LowerReturn won't try to load return
1819     // registers the usual way.
1820     SmallVector<EVT, 1> PtrValueVTs;
1821     ComputeValueVTs(TLI, DL,
1822                     F->getReturnType()->getPointerTo(
1823                         DAG.getDataLayout().getAllocaAddrSpace()),
1824                     PtrValueVTs);
1825 
1826     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1827                                         DemoteReg, PtrValueVTs[0]);
1828     SDValue RetOp = getValue(I.getOperand(0));
1829 
1830     SmallVector<EVT, 4> ValueVTs, MemVTs;
1831     SmallVector<uint64_t, 4> Offsets;
1832     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1833                     &Offsets);
1834     unsigned NumValues = ValueVTs.size();
1835 
1836     SmallVector<SDValue, 4> Chains(NumValues);
1837     for (unsigned i = 0; i != NumValues; ++i) {
1838       // An aggregate return value cannot wrap around the address space, so
1839       // offsets to its parts don't wrap either.
1840       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1841 
1842       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1843       if (MemVTs[i] != ValueVTs[i])
1844         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1845       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1846           // FIXME: better loc info would be nice.
1847           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1848     }
1849 
1850     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1851                         MVT::Other, Chains);
1852   } else if (I.getNumOperands() != 0) {
1853     SmallVector<EVT, 4> ValueVTs;
1854     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1855     unsigned NumValues = ValueVTs.size();
1856     if (NumValues) {
1857       SDValue RetOp = getValue(I.getOperand(0));
1858 
1859       const Function *F = I.getParent()->getParent();
1860 
1861       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1862           I.getOperand(0)->getType(), F->getCallingConv(),
1863           /*IsVarArg*/ false);
1864 
1865       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1866       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1867                                           Attribute::SExt))
1868         ExtendKind = ISD::SIGN_EXTEND;
1869       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1870                                                Attribute::ZExt))
1871         ExtendKind = ISD::ZERO_EXTEND;
1872 
1873       LLVMContext &Context = F->getContext();
1874       bool RetInReg = F->getAttributes().hasAttribute(
1875           AttributeList::ReturnIndex, Attribute::InReg);
1876 
1877       for (unsigned j = 0; j != NumValues; ++j) {
1878         EVT VT = ValueVTs[j];
1879 
1880         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1881           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1882 
1883         CallingConv::ID CC = F->getCallingConv();
1884 
1885         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1886         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1887         SmallVector<SDValue, 4> Parts(NumParts);
1888         getCopyToParts(DAG, getCurSDLoc(),
1889                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1890                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1891 
1892         // 'inreg' on function refers to return value
1893         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1894         if (RetInReg)
1895           Flags.setInReg();
1896 
1897         if (I.getOperand(0)->getType()->isPointerTy()) {
1898           Flags.setPointer();
1899           Flags.setPointerAddrSpace(
1900               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1901         }
1902 
1903         if (NeedsRegBlock) {
1904           Flags.setInConsecutiveRegs();
1905           if (j == NumValues - 1)
1906             Flags.setInConsecutiveRegsLast();
1907         }
1908 
1909         // Propagate extension type if any
1910         if (ExtendKind == ISD::SIGN_EXTEND)
1911           Flags.setSExt();
1912         else if (ExtendKind == ISD::ZERO_EXTEND)
1913           Flags.setZExt();
1914 
1915         for (unsigned i = 0; i < NumParts; ++i) {
1916           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1917                                         VT, /*isfixed=*/true, 0, 0));
1918           OutVals.push_back(Parts[i]);
1919         }
1920       }
1921     }
1922   }
1923 
1924   // Push in swifterror virtual register as the last element of Outs. This makes
1925   // sure swifterror virtual register will be returned in the swifterror
1926   // physical register.
1927   const Function *F = I.getParent()->getParent();
1928   if (TLI.supportSwiftError() &&
1929       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1930     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1931     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1932     Flags.setSwiftError();
1933     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1934                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1935                                   true /*isfixed*/, 1 /*origidx*/,
1936                                   0 /*partOffs*/));
1937     // Create SDNode for the swifterror virtual register.
1938     OutVals.push_back(
1939         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1940                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1941                         EVT(TLI.getPointerTy(DL))));
1942   }
1943 
1944   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1945   CallingConv::ID CallConv =
1946     DAG.getMachineFunction().getFunction().getCallingConv();
1947   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1948       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1949 
1950   // Verify that the target's LowerReturn behaved as expected.
1951   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1952          "LowerReturn didn't return a valid chain!");
1953 
1954   // Update the DAG with the new chain value resulting from return lowering.
1955   DAG.setRoot(Chain);
1956 }
1957 
1958 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1959 /// created for it, emit nodes to copy the value into the virtual
1960 /// registers.
1961 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1962   // Skip empty types
1963   if (V->getType()->isEmptyTy())
1964     return;
1965 
1966   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1967   if (VMI != FuncInfo.ValueMap.end()) {
1968     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1969     CopyValueToVirtualRegister(V, VMI->second);
1970   }
1971 }
1972 
1973 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1974 /// the current basic block, add it to ValueMap now so that we'll get a
1975 /// CopyTo/FromReg.
1976 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1977   // No need to export constants.
1978   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1979 
1980   // Already exported?
1981   if (FuncInfo.isExportedInst(V)) return;
1982 
1983   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1984   CopyValueToVirtualRegister(V, Reg);
1985 }
1986 
1987 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1988                                                      const BasicBlock *FromBB) {
1989   // The operands of the setcc have to be in this block.  We don't know
1990   // how to export them from some other block.
1991   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1992     // Can export from current BB.
1993     if (VI->getParent() == FromBB)
1994       return true;
1995 
1996     // Is already exported, noop.
1997     return FuncInfo.isExportedInst(V);
1998   }
1999 
2000   // If this is an argument, we can export it if the BB is the entry block or
2001   // if it is already exported.
2002   if (isa<Argument>(V)) {
2003     if (FromBB == &FromBB->getParent()->getEntryBlock())
2004       return true;
2005 
2006     // Otherwise, can only export this if it is already exported.
2007     return FuncInfo.isExportedInst(V);
2008   }
2009 
2010   // Otherwise, constants can always be exported.
2011   return true;
2012 }
2013 
2014 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2015 BranchProbability
2016 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2017                                         const MachineBasicBlock *Dst) const {
2018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2019   const BasicBlock *SrcBB = Src->getBasicBlock();
2020   const BasicBlock *DstBB = Dst->getBasicBlock();
2021   if (!BPI) {
2022     // If BPI is not available, set the default probability as 1 / N, where N is
2023     // the number of successors.
2024     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2025     return BranchProbability(1, SuccSize);
2026   }
2027   return BPI->getEdgeProbability(SrcBB, DstBB);
2028 }
2029 
2030 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2031                                                MachineBasicBlock *Dst,
2032                                                BranchProbability Prob) {
2033   if (!FuncInfo.BPI)
2034     Src->addSuccessorWithoutProb(Dst);
2035   else {
2036     if (Prob.isUnknown())
2037       Prob = getEdgeProbability(Src, Dst);
2038     Src->addSuccessor(Dst, Prob);
2039   }
2040 }
2041 
2042 static bool InBlock(const Value *V, const BasicBlock *BB) {
2043   if (const Instruction *I = dyn_cast<Instruction>(V))
2044     return I->getParent() == BB;
2045   return true;
2046 }
2047 
2048 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2049 /// This function emits a branch and is used at the leaves of an OR or an
2050 /// AND operator tree.
2051 void
2052 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2053                                                   MachineBasicBlock *TBB,
2054                                                   MachineBasicBlock *FBB,
2055                                                   MachineBasicBlock *CurBB,
2056                                                   MachineBasicBlock *SwitchBB,
2057                                                   BranchProbability TProb,
2058                                                   BranchProbability FProb,
2059                                                   bool InvertCond) {
2060   const BasicBlock *BB = CurBB->getBasicBlock();
2061 
2062   // If the leaf of the tree is a comparison, merge the condition into
2063   // the caseblock.
2064   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2065     // The operands of the cmp have to be in this block.  We don't know
2066     // how to export them from some other block.  If this is the first block
2067     // of the sequence, no exporting is needed.
2068     if (CurBB == SwitchBB ||
2069         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2070          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2071       ISD::CondCode Condition;
2072       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2073         ICmpInst::Predicate Pred =
2074             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2075         Condition = getICmpCondCode(Pred);
2076       } else {
2077         const FCmpInst *FC = cast<FCmpInst>(Cond);
2078         FCmpInst::Predicate Pred =
2079             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2080         Condition = getFCmpCondCode(Pred);
2081         if (TM.Options.NoNaNsFPMath)
2082           Condition = getFCmpCodeWithoutNaN(Condition);
2083       }
2084 
2085       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2086                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2087       SL->SwitchCases.push_back(CB);
2088       return;
2089     }
2090   }
2091 
2092   // Create a CaseBlock record representing this branch.
2093   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2094   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2095                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2096   SL->SwitchCases.push_back(CB);
2097 }
2098 
2099 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2100                                                MachineBasicBlock *TBB,
2101                                                MachineBasicBlock *FBB,
2102                                                MachineBasicBlock *CurBB,
2103                                                MachineBasicBlock *SwitchBB,
2104                                                Instruction::BinaryOps Opc,
2105                                                BranchProbability TProb,
2106                                                BranchProbability FProb,
2107                                                bool InvertCond) {
2108   // Skip over not part of the tree and remember to invert op and operands at
2109   // next level.
2110   Value *NotCond;
2111   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2112       InBlock(NotCond, CurBB->getBasicBlock())) {
2113     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2114                          !InvertCond);
2115     return;
2116   }
2117 
2118   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2119   // Compute the effective opcode for Cond, taking into account whether it needs
2120   // to be inverted, e.g.
2121   //   and (not (or A, B)), C
2122   // gets lowered as
2123   //   and (and (not A, not B), C)
2124   unsigned BOpc = 0;
2125   if (BOp) {
2126     BOpc = BOp->getOpcode();
2127     if (InvertCond) {
2128       if (BOpc == Instruction::And)
2129         BOpc = Instruction::Or;
2130       else if (BOpc == Instruction::Or)
2131         BOpc = Instruction::And;
2132     }
2133   }
2134 
2135   // If this node is not part of the or/and tree, emit it as a branch.
2136   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2137       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2138       BOp->getParent() != CurBB->getBasicBlock() ||
2139       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2140       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2141     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2142                                  TProb, FProb, InvertCond);
2143     return;
2144   }
2145 
2146   //  Create TmpBB after CurBB.
2147   MachineFunction::iterator BBI(CurBB);
2148   MachineFunction &MF = DAG.getMachineFunction();
2149   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2150   CurBB->getParent()->insert(++BBI, TmpBB);
2151 
2152   if (Opc == Instruction::Or) {
2153     // Codegen X | Y as:
2154     // BB1:
2155     //   jmp_if_X TBB
2156     //   jmp TmpBB
2157     // TmpBB:
2158     //   jmp_if_Y TBB
2159     //   jmp FBB
2160     //
2161 
2162     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2163     // The requirement is that
2164     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2165     //     = TrueProb for original BB.
2166     // Assuming the original probabilities are A and B, one choice is to set
2167     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2168     // A/(1+B) and 2B/(1+B). This choice assumes that
2169     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2170     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2171     // TmpBB, but the math is more complicated.
2172 
2173     auto NewTrueProb = TProb / 2;
2174     auto NewFalseProb = TProb / 2 + FProb;
2175     // Emit the LHS condition.
2176     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2177                          NewTrueProb, NewFalseProb, InvertCond);
2178 
2179     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2180     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2181     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2182     // Emit the RHS condition into TmpBB.
2183     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2184                          Probs[0], Probs[1], InvertCond);
2185   } else {
2186     assert(Opc == Instruction::And && "Unknown merge op!");
2187     // Codegen X & Y as:
2188     // BB1:
2189     //   jmp_if_X TmpBB
2190     //   jmp FBB
2191     // TmpBB:
2192     //   jmp_if_Y TBB
2193     //   jmp FBB
2194     //
2195     //  This requires creation of TmpBB after CurBB.
2196 
2197     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2198     // The requirement is that
2199     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2200     //     = FalseProb for original BB.
2201     // Assuming the original probabilities are A and B, one choice is to set
2202     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2203     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2204     // TrueProb for BB1 * FalseProb for TmpBB.
2205 
2206     auto NewTrueProb = TProb + FProb / 2;
2207     auto NewFalseProb = FProb / 2;
2208     // Emit the LHS condition.
2209     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2210                          NewTrueProb, NewFalseProb, InvertCond);
2211 
2212     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2213     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2214     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2215     // Emit the RHS condition into TmpBB.
2216     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2217                          Probs[0], Probs[1], InvertCond);
2218   }
2219 }
2220 
2221 /// If the set of cases should be emitted as a series of branches, return true.
2222 /// If we should emit this as a bunch of and/or'd together conditions, return
2223 /// false.
2224 bool
2225 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2226   if (Cases.size() != 2) return true;
2227 
2228   // If this is two comparisons of the same values or'd or and'd together, they
2229   // will get folded into a single comparison, so don't emit two blocks.
2230   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2231        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2232       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2233        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2234     return false;
2235   }
2236 
2237   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2238   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2239   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2240       Cases[0].CC == Cases[1].CC &&
2241       isa<Constant>(Cases[0].CmpRHS) &&
2242       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2243     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2244       return false;
2245     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2246       return false;
2247   }
2248 
2249   return true;
2250 }
2251 
2252 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2253   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2254 
2255   // Update machine-CFG edges.
2256   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2257 
2258   if (I.isUnconditional()) {
2259     // Update machine-CFG edges.
2260     BrMBB->addSuccessor(Succ0MBB);
2261 
2262     // If this is not a fall-through branch or optimizations are switched off,
2263     // emit the branch.
2264     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2265       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2266                               MVT::Other, getControlRoot(),
2267                               DAG.getBasicBlock(Succ0MBB)));
2268 
2269     return;
2270   }
2271 
2272   // If this condition is one of the special cases we handle, do special stuff
2273   // now.
2274   const Value *CondVal = I.getCondition();
2275   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2276 
2277   // If this is a series of conditions that are or'd or and'd together, emit
2278   // this as a sequence of branches instead of setcc's with and/or operations.
2279   // As long as jumps are not expensive, this should improve performance.
2280   // For example, instead of something like:
2281   //     cmp A, B
2282   //     C = seteq
2283   //     cmp D, E
2284   //     F = setle
2285   //     or C, F
2286   //     jnz foo
2287   // Emit:
2288   //     cmp A, B
2289   //     je foo
2290   //     cmp D, E
2291   //     jle foo
2292   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2293     Instruction::BinaryOps Opcode = BOp->getOpcode();
2294     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2295         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2296         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2297       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2298                            Opcode,
2299                            getEdgeProbability(BrMBB, Succ0MBB),
2300                            getEdgeProbability(BrMBB, Succ1MBB),
2301                            /*InvertCond=*/false);
2302       // If the compares in later blocks need to use values not currently
2303       // exported from this block, export them now.  This block should always
2304       // be the first entry.
2305       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2306 
2307       // Allow some cases to be rejected.
2308       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2309         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2310           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2311           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2312         }
2313 
2314         // Emit the branch for this block.
2315         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2316         SL->SwitchCases.erase(SL->SwitchCases.begin());
2317         return;
2318       }
2319 
2320       // Okay, we decided not to do this, remove any inserted MBB's and clear
2321       // SwitchCases.
2322       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2323         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2324 
2325       SL->SwitchCases.clear();
2326     }
2327   }
2328 
2329   // Create a CaseBlock record representing this branch.
2330   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2331                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2332 
2333   // Use visitSwitchCase to actually insert the fast branch sequence for this
2334   // cond branch.
2335   visitSwitchCase(CB, BrMBB);
2336 }
2337 
2338 /// visitSwitchCase - Emits the necessary code to represent a single node in
2339 /// the binary search tree resulting from lowering a switch instruction.
2340 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2341                                           MachineBasicBlock *SwitchBB) {
2342   SDValue Cond;
2343   SDValue CondLHS = getValue(CB.CmpLHS);
2344   SDLoc dl = CB.DL;
2345 
2346   if (CB.CC == ISD::SETTRUE) {
2347     // Branch or fall through to TrueBB.
2348     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2349     SwitchBB->normalizeSuccProbs();
2350     if (CB.TrueBB != NextBlock(SwitchBB)) {
2351       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2352                               DAG.getBasicBlock(CB.TrueBB)));
2353     }
2354     return;
2355   }
2356 
2357   auto &TLI = DAG.getTargetLoweringInfo();
2358   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2359 
2360   // Build the setcc now.
2361   if (!CB.CmpMHS) {
2362     // Fold "(X == true)" to X and "(X == false)" to !X to
2363     // handle common cases produced by branch lowering.
2364     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2365         CB.CC == ISD::SETEQ)
2366       Cond = CondLHS;
2367     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2368              CB.CC == ISD::SETEQ) {
2369       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2370       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2371     } else {
2372       SDValue CondRHS = getValue(CB.CmpRHS);
2373 
2374       // If a pointer's DAG type is larger than its memory type then the DAG
2375       // values are zero-extended. This breaks signed comparisons so truncate
2376       // back to the underlying type before doing the compare.
2377       if (CondLHS.getValueType() != MemVT) {
2378         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2379         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2380       }
2381       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2382     }
2383   } else {
2384     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2385 
2386     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2387     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2388 
2389     SDValue CmpOp = getValue(CB.CmpMHS);
2390     EVT VT = CmpOp.getValueType();
2391 
2392     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2393       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2394                           ISD::SETLE);
2395     } else {
2396       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2397                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2398       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2399                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2400     }
2401   }
2402 
2403   // Update successor info
2404   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2405   // TrueBB and FalseBB are always different unless the incoming IR is
2406   // degenerate. This only happens when running llc on weird IR.
2407   if (CB.TrueBB != CB.FalseBB)
2408     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2409   SwitchBB->normalizeSuccProbs();
2410 
2411   // If the lhs block is the next block, invert the condition so that we can
2412   // fall through to the lhs instead of the rhs block.
2413   if (CB.TrueBB == NextBlock(SwitchBB)) {
2414     std::swap(CB.TrueBB, CB.FalseBB);
2415     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2416     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2417   }
2418 
2419   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2420                                MVT::Other, getControlRoot(), Cond,
2421                                DAG.getBasicBlock(CB.TrueBB));
2422 
2423   // Insert the false branch. Do this even if it's a fall through branch,
2424   // this makes it easier to do DAG optimizations which require inverting
2425   // the branch condition.
2426   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2427                        DAG.getBasicBlock(CB.FalseBB));
2428 
2429   DAG.setRoot(BrCond);
2430 }
2431 
2432 /// visitJumpTable - Emit JumpTable node in the current MBB
2433 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2434   // Emit the code for the jump table
2435   assert(JT.Reg != -1U && "Should lower JT Header first!");
2436   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2437   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2438                                      JT.Reg, PTy);
2439   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2440   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2441                                     MVT::Other, Index.getValue(1),
2442                                     Table, Index);
2443   DAG.setRoot(BrJumpTable);
2444 }
2445 
2446 /// visitJumpTableHeader - This function emits necessary code to produce index
2447 /// in the JumpTable from switch case.
2448 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2449                                                JumpTableHeader &JTH,
2450                                                MachineBasicBlock *SwitchBB) {
2451   SDLoc dl = getCurSDLoc();
2452 
2453   // Subtract the lowest switch case value from the value being switched on.
2454   SDValue SwitchOp = getValue(JTH.SValue);
2455   EVT VT = SwitchOp.getValueType();
2456   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2457                             DAG.getConstant(JTH.First, dl, VT));
2458 
2459   // The SDNode we just created, which holds the value being switched on minus
2460   // the smallest case value, needs to be copied to a virtual register so it
2461   // can be used as an index into the jump table in a subsequent basic block.
2462   // This value may be smaller or larger than the target's pointer type, and
2463   // therefore require extension or truncating.
2464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2465   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2466 
2467   unsigned JumpTableReg =
2468       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2469   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2470                                     JumpTableReg, SwitchOp);
2471   JT.Reg = JumpTableReg;
2472 
2473   if (!JTH.OmitRangeCheck) {
2474     // Emit the range check for the jump table, and branch to the default block
2475     // for the switch statement if the value being switched on exceeds the
2476     // largest case in the switch.
2477     SDValue CMP = DAG.getSetCC(
2478         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2479                                    Sub.getValueType()),
2480         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2481 
2482     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2483                                  MVT::Other, CopyTo, CMP,
2484                                  DAG.getBasicBlock(JT.Default));
2485 
2486     // Avoid emitting unnecessary branches to the next block.
2487     if (JT.MBB != NextBlock(SwitchBB))
2488       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2489                            DAG.getBasicBlock(JT.MBB));
2490 
2491     DAG.setRoot(BrCond);
2492   } else {
2493     // Avoid emitting unnecessary branches to the next block.
2494     if (JT.MBB != NextBlock(SwitchBB))
2495       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2496                               DAG.getBasicBlock(JT.MBB)));
2497     else
2498       DAG.setRoot(CopyTo);
2499   }
2500 }
2501 
2502 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2503 /// variable if there exists one.
2504 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2505                                  SDValue &Chain) {
2506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2508   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2511   MachineSDNode *Node =
2512       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2513   if (Global) {
2514     MachinePointerInfo MPInfo(Global);
2515     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2516                  MachineMemOperand::MODereferenceable;
2517     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2518         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2519     DAG.setNodeMemRefs(Node, {MemRef});
2520   }
2521   if (PtrTy != PtrMemTy)
2522     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2523   return SDValue(Node, 0);
2524 }
2525 
2526 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2527 /// tail spliced into a stack protector check success bb.
2528 ///
2529 /// For a high level explanation of how this fits into the stack protector
2530 /// generation see the comment on the declaration of class
2531 /// StackProtectorDescriptor.
2532 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2533                                                   MachineBasicBlock *ParentBB) {
2534 
2535   // First create the loads to the guard/stack slot for the comparison.
2536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2537   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2538   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2539 
2540   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2541   int FI = MFI.getStackProtectorIndex();
2542 
2543   SDValue Guard;
2544   SDLoc dl = getCurSDLoc();
2545   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2546   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2547   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2548 
2549   // Generate code to load the content of the guard slot.
2550   SDValue GuardVal = DAG.getLoad(
2551       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2552       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2553       MachineMemOperand::MOVolatile);
2554 
2555   if (TLI.useStackGuardXorFP())
2556     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2557 
2558   // Retrieve guard check function, nullptr if instrumentation is inlined.
2559   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2560     // The target provides a guard check function to validate the guard value.
2561     // Generate a call to that function with the content of the guard slot as
2562     // argument.
2563     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2564     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2565 
2566     TargetLowering::ArgListTy Args;
2567     TargetLowering::ArgListEntry Entry;
2568     Entry.Node = GuardVal;
2569     Entry.Ty = FnTy->getParamType(0);
2570     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2571       Entry.IsInReg = true;
2572     Args.push_back(Entry);
2573 
2574     TargetLowering::CallLoweringInfo CLI(DAG);
2575     CLI.setDebugLoc(getCurSDLoc())
2576         .setChain(DAG.getEntryNode())
2577         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2578                    getValue(GuardCheckFn), std::move(Args));
2579 
2580     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2581     DAG.setRoot(Result.second);
2582     return;
2583   }
2584 
2585   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2586   // Otherwise, emit a volatile load to retrieve the stack guard value.
2587   SDValue Chain = DAG.getEntryNode();
2588   if (TLI.useLoadStackGuardNode()) {
2589     Guard = getLoadStackGuard(DAG, dl, Chain);
2590   } else {
2591     const Value *IRGuard = TLI.getSDagStackGuard(M);
2592     SDValue GuardPtr = getValue(IRGuard);
2593 
2594     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2595                         MachinePointerInfo(IRGuard, 0), Align,
2596                         MachineMemOperand::MOVolatile);
2597   }
2598 
2599   // Perform the comparison via a getsetcc.
2600   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2601                                                         *DAG.getContext(),
2602                                                         Guard.getValueType()),
2603                              Guard, GuardVal, ISD::SETNE);
2604 
2605   // If the guard/stackslot do not equal, branch to failure MBB.
2606   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2607                                MVT::Other, GuardVal.getOperand(0),
2608                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2609   // Otherwise branch to success MBB.
2610   SDValue Br = DAG.getNode(ISD::BR, dl,
2611                            MVT::Other, BrCond,
2612                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2613 
2614   DAG.setRoot(Br);
2615 }
2616 
2617 /// Codegen the failure basic block for a stack protector check.
2618 ///
2619 /// A failure stack protector machine basic block consists simply of a call to
2620 /// __stack_chk_fail().
2621 ///
2622 /// For a high level explanation of how this fits into the stack protector
2623 /// generation see the comment on the declaration of class
2624 /// StackProtectorDescriptor.
2625 void
2626 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2628   TargetLowering::MakeLibCallOptions CallOptions;
2629   CallOptions.setDiscardResult(true);
2630   SDValue Chain =
2631       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2632                       None, CallOptions, getCurSDLoc()).second;
2633   // On PS4, the "return address" must still be within the calling function,
2634   // even if it's at the very end, so emit an explicit TRAP here.
2635   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2636   if (TM.getTargetTriple().isPS4CPU())
2637     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2638 
2639   DAG.setRoot(Chain);
2640 }
2641 
2642 /// visitBitTestHeader - This function emits necessary code to produce value
2643 /// suitable for "bit tests"
2644 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2645                                              MachineBasicBlock *SwitchBB) {
2646   SDLoc dl = getCurSDLoc();
2647 
2648   // Subtract the minimum value.
2649   SDValue SwitchOp = getValue(B.SValue);
2650   EVT VT = SwitchOp.getValueType();
2651   SDValue RangeSub =
2652       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2653 
2654   // Determine the type of the test operands.
2655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2656   bool UsePtrType = false;
2657   if (!TLI.isTypeLegal(VT)) {
2658     UsePtrType = true;
2659   } else {
2660     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2661       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2662         // Switch table case range are encoded into series of masks.
2663         // Just use pointer type, it's guaranteed to fit.
2664         UsePtrType = true;
2665         break;
2666       }
2667   }
2668   SDValue Sub = RangeSub;
2669   if (UsePtrType) {
2670     VT = TLI.getPointerTy(DAG.getDataLayout());
2671     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2672   }
2673 
2674   B.RegVT = VT.getSimpleVT();
2675   B.Reg = FuncInfo.CreateReg(B.RegVT);
2676   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2677 
2678   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2679 
2680   if (!B.OmitRangeCheck)
2681     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2682   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2683   SwitchBB->normalizeSuccProbs();
2684 
2685   SDValue Root = CopyTo;
2686   if (!B.OmitRangeCheck) {
2687     // Conditional branch to the default block.
2688     SDValue RangeCmp = DAG.getSetCC(dl,
2689         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2690                                RangeSub.getValueType()),
2691         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2692         ISD::SETUGT);
2693 
2694     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2695                        DAG.getBasicBlock(B.Default));
2696   }
2697 
2698   // Avoid emitting unnecessary branches to the next block.
2699   if (MBB != NextBlock(SwitchBB))
2700     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2701 
2702   DAG.setRoot(Root);
2703 }
2704 
2705 /// visitBitTestCase - this function produces one "bit test"
2706 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2707                                            MachineBasicBlock* NextMBB,
2708                                            BranchProbability BranchProbToNext,
2709                                            unsigned Reg,
2710                                            BitTestCase &B,
2711                                            MachineBasicBlock *SwitchBB) {
2712   SDLoc dl = getCurSDLoc();
2713   MVT VT = BB.RegVT;
2714   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2715   SDValue Cmp;
2716   unsigned PopCount = countPopulation(B.Mask);
2717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2718   if (PopCount == 1) {
2719     // Testing for a single bit; just compare the shift count with what it
2720     // would need to be to shift a 1 bit in that position.
2721     Cmp = DAG.getSetCC(
2722         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2723         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2724         ISD::SETEQ);
2725   } else if (PopCount == BB.Range) {
2726     // There is only one zero bit in the range, test for it directly.
2727     Cmp = DAG.getSetCC(
2728         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2729         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2730         ISD::SETNE);
2731   } else {
2732     // Make desired shift
2733     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2734                                     DAG.getConstant(1, dl, VT), ShiftOp);
2735 
2736     // Emit bit tests and jumps
2737     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2738                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2739     Cmp = DAG.getSetCC(
2740         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2741         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2742   }
2743 
2744   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2745   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2746   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2747   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2748   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2749   // one as they are relative probabilities (and thus work more like weights),
2750   // and hence we need to normalize them to let the sum of them become one.
2751   SwitchBB->normalizeSuccProbs();
2752 
2753   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2754                               MVT::Other, getControlRoot(),
2755                               Cmp, DAG.getBasicBlock(B.TargetBB));
2756 
2757   // Avoid emitting unnecessary branches to the next block.
2758   if (NextMBB != NextBlock(SwitchBB))
2759     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2760                         DAG.getBasicBlock(NextMBB));
2761 
2762   DAG.setRoot(BrAnd);
2763 }
2764 
2765 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2766   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2767 
2768   // Retrieve successors. Look through artificial IR level blocks like
2769   // catchswitch for successors.
2770   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2771   const BasicBlock *EHPadBB = I.getSuccessor(1);
2772 
2773   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2774   // have to do anything here to lower funclet bundles.
2775   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2776                                         LLVMContext::OB_funclet,
2777                                         LLVMContext::OB_cfguardtarget}) &&
2778          "Cannot lower invokes with arbitrary operand bundles yet!");
2779 
2780   const Value *Callee(I.getCalledValue());
2781   const Function *Fn = dyn_cast<Function>(Callee);
2782   if (isa<InlineAsm>(Callee))
2783     visitInlineAsm(I);
2784   else if (Fn && Fn->isIntrinsic()) {
2785     switch (Fn->getIntrinsicID()) {
2786     default:
2787       llvm_unreachable("Cannot invoke this intrinsic");
2788     case Intrinsic::donothing:
2789       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2790       break;
2791     case Intrinsic::experimental_patchpoint_void:
2792     case Intrinsic::experimental_patchpoint_i64:
2793       visitPatchpoint(I, EHPadBB);
2794       break;
2795     case Intrinsic::experimental_gc_statepoint:
2796       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2797       break;
2798     case Intrinsic::wasm_rethrow_in_catch: {
2799       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2800       // special because it can be invoked, so we manually lower it to a DAG
2801       // node here.
2802       SmallVector<SDValue, 8> Ops;
2803       Ops.push_back(getRoot()); // inchain
2804       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2805       Ops.push_back(
2806           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2807                                 TLI.getPointerTy(DAG.getDataLayout())));
2808       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2809       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2810       break;
2811     }
2812     }
2813   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2814     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2815     // Eventually we will support lowering the @llvm.experimental.deoptimize
2816     // intrinsic, and right now there are no plans to support other intrinsics
2817     // with deopt state.
2818     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2819   } else {
2820     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2821   }
2822 
2823   // If the value of the invoke is used outside of its defining block, make it
2824   // available as a virtual register.
2825   // We already took care of the exported value for the statepoint instruction
2826   // during call to the LowerStatepoint.
2827   if (!isStatepoint(I)) {
2828     CopyToExportRegsIfNeeded(&I);
2829   }
2830 
2831   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2832   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2833   BranchProbability EHPadBBProb =
2834       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2835           : BranchProbability::getZero();
2836   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2837 
2838   // Update successor info.
2839   addSuccessorWithProb(InvokeMBB, Return);
2840   for (auto &UnwindDest : UnwindDests) {
2841     UnwindDest.first->setIsEHPad();
2842     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2843   }
2844   InvokeMBB->normalizeSuccProbs();
2845 
2846   // Drop into normal successor.
2847   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2848                           DAG.getBasicBlock(Return)));
2849 }
2850 
2851 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2852   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2853 
2854   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2855   // have to do anything here to lower funclet bundles.
2856   assert(!I.hasOperandBundlesOtherThan(
2857              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2858          "Cannot lower callbrs with arbitrary operand bundles yet!");
2859 
2860   assert(isa<InlineAsm>(I.getCalledValue()) &&
2861          "Only know how to handle inlineasm callbr");
2862   visitInlineAsm(I);
2863   CopyToExportRegsIfNeeded(&I);
2864 
2865   // Retrieve successors.
2866   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2867   Return->setInlineAsmBrDefaultTarget();
2868 
2869   // Update successor info.
2870   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2871   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2872     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2873     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2874     CallBrMBB->addInlineAsmBrIndirectTarget(Target);
2875   }
2876   CallBrMBB->normalizeSuccProbs();
2877 
2878   // Drop into default successor.
2879   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2880                           MVT::Other, getControlRoot(),
2881                           DAG.getBasicBlock(Return)));
2882 }
2883 
2884 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2885   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2886 }
2887 
2888 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2889   assert(FuncInfo.MBB->isEHPad() &&
2890          "Call to landingpad not in landing pad!");
2891 
2892   // If there aren't registers to copy the values into (e.g., during SjLj
2893   // exceptions), then don't bother to create these DAG nodes.
2894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2895   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2896   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2897       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2898     return;
2899 
2900   // If landingpad's return type is token type, we don't create DAG nodes
2901   // for its exception pointer and selector value. The extraction of exception
2902   // pointer or selector value from token type landingpads is not currently
2903   // supported.
2904   if (LP.getType()->isTokenTy())
2905     return;
2906 
2907   SmallVector<EVT, 2> ValueVTs;
2908   SDLoc dl = getCurSDLoc();
2909   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2910   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2911 
2912   // Get the two live-in registers as SDValues. The physregs have already been
2913   // copied into virtual registers.
2914   SDValue Ops[2];
2915   if (FuncInfo.ExceptionPointerVirtReg) {
2916     Ops[0] = DAG.getZExtOrTrunc(
2917         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2918                            FuncInfo.ExceptionPointerVirtReg,
2919                            TLI.getPointerTy(DAG.getDataLayout())),
2920         dl, ValueVTs[0]);
2921   } else {
2922     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2923   }
2924   Ops[1] = DAG.getZExtOrTrunc(
2925       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2926                          FuncInfo.ExceptionSelectorVirtReg,
2927                          TLI.getPointerTy(DAG.getDataLayout())),
2928       dl, ValueVTs[1]);
2929 
2930   // Merge into one.
2931   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2932                             DAG.getVTList(ValueVTs), Ops);
2933   setValue(&LP, Res);
2934 }
2935 
2936 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2937                                            MachineBasicBlock *Last) {
2938   // Update JTCases.
2939   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2940     if (SL->JTCases[i].first.HeaderBB == First)
2941       SL->JTCases[i].first.HeaderBB = Last;
2942 
2943   // Update BitTestCases.
2944   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2945     if (SL->BitTestCases[i].Parent == First)
2946       SL->BitTestCases[i].Parent = Last;
2947 
2948   // SelectionDAGISel::FinishBasicBlock will add PHI operands for the
2949   // successors of the fallthrough block. Here, we add PHI operands for the
2950   // successors of the INLINEASM_BR block itself.
2951   if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR)
2952     for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate)
2953       if (First->isSuccessor(pair.first->getParent()))
2954         MachineInstrBuilder(*First->getParent(), pair.first)
2955             .addReg(pair.second)
2956             .addMBB(First);
2957 }
2958 
2959 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2960   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2961 
2962   // Update machine-CFG edges with unique successors.
2963   SmallSet<BasicBlock*, 32> Done;
2964   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2965     BasicBlock *BB = I.getSuccessor(i);
2966     bool Inserted = Done.insert(BB).second;
2967     if (!Inserted)
2968         continue;
2969 
2970     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2971     addSuccessorWithProb(IndirectBrMBB, Succ);
2972   }
2973   IndirectBrMBB->normalizeSuccProbs();
2974 
2975   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2976                           MVT::Other, getControlRoot(),
2977                           getValue(I.getAddress())));
2978 }
2979 
2980 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2981   if (!DAG.getTarget().Options.TrapUnreachable)
2982     return;
2983 
2984   // We may be able to ignore unreachable behind a noreturn call.
2985   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2986     const BasicBlock &BB = *I.getParent();
2987     if (&I != &BB.front()) {
2988       BasicBlock::const_iterator PredI =
2989         std::prev(BasicBlock::const_iterator(&I));
2990       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2991         if (Call->doesNotReturn())
2992           return;
2993       }
2994     }
2995   }
2996 
2997   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2998 }
2999 
3000 void SelectionDAGBuilder::visitFSub(const User &I) {
3001   // -0.0 - X --> fneg
3002   Type *Ty = I.getType();
3003   if (isa<Constant>(I.getOperand(0)) &&
3004       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3005     SDValue Op2 = getValue(I.getOperand(1));
3006     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3007                              Op2.getValueType(), Op2));
3008     return;
3009   }
3010 
3011   visitBinary(I, ISD::FSUB);
3012 }
3013 
3014 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3015   SDNodeFlags Flags;
3016 
3017   SDValue Op = getValue(I.getOperand(0));
3018   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3019                                     Op, Flags);
3020   setValue(&I, UnNodeValue);
3021 }
3022 
3023 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3024   SDNodeFlags Flags;
3025   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3026     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3027     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3028   }
3029   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3030     Flags.setExact(ExactOp->isExact());
3031   }
3032 
3033   SDValue Op1 = getValue(I.getOperand(0));
3034   SDValue Op2 = getValue(I.getOperand(1));
3035   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3036                                      Op1, Op2, Flags);
3037   setValue(&I, BinNodeValue);
3038 }
3039 
3040 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3041   SDValue Op1 = getValue(I.getOperand(0));
3042   SDValue Op2 = getValue(I.getOperand(1));
3043 
3044   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3045       Op1.getValueType(), DAG.getDataLayout());
3046 
3047   // Coerce the shift amount to the right type if we can.
3048   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3049     unsigned ShiftSize = ShiftTy.getSizeInBits();
3050     unsigned Op2Size = Op2.getValueSizeInBits();
3051     SDLoc DL = getCurSDLoc();
3052 
3053     // If the operand is smaller than the shift count type, promote it.
3054     if (ShiftSize > Op2Size)
3055       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3056 
3057     // If the operand is larger than the shift count type but the shift
3058     // count type has enough bits to represent any shift value, truncate
3059     // it now. This is a common case and it exposes the truncate to
3060     // optimization early.
3061     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3062       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3063     // Otherwise we'll need to temporarily settle for some other convenient
3064     // type.  Type legalization will make adjustments once the shiftee is split.
3065     else
3066       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3067   }
3068 
3069   bool nuw = false;
3070   bool nsw = false;
3071   bool exact = false;
3072 
3073   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3074 
3075     if (const OverflowingBinaryOperator *OFBinOp =
3076             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3077       nuw = OFBinOp->hasNoUnsignedWrap();
3078       nsw = OFBinOp->hasNoSignedWrap();
3079     }
3080     if (const PossiblyExactOperator *ExactOp =
3081             dyn_cast<const PossiblyExactOperator>(&I))
3082       exact = ExactOp->isExact();
3083   }
3084   SDNodeFlags Flags;
3085   Flags.setExact(exact);
3086   Flags.setNoSignedWrap(nsw);
3087   Flags.setNoUnsignedWrap(nuw);
3088   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3089                             Flags);
3090   setValue(&I, Res);
3091 }
3092 
3093 void SelectionDAGBuilder::visitSDiv(const User &I) {
3094   SDValue Op1 = getValue(I.getOperand(0));
3095   SDValue Op2 = getValue(I.getOperand(1));
3096 
3097   SDNodeFlags Flags;
3098   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3099                  cast<PossiblyExactOperator>(&I)->isExact());
3100   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3101                            Op2, Flags));
3102 }
3103 
3104 void SelectionDAGBuilder::visitICmp(const User &I) {
3105   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3106   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3107     predicate = IC->getPredicate();
3108   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3109     predicate = ICmpInst::Predicate(IC->getPredicate());
3110   SDValue Op1 = getValue(I.getOperand(0));
3111   SDValue Op2 = getValue(I.getOperand(1));
3112   ISD::CondCode Opcode = getICmpCondCode(predicate);
3113 
3114   auto &TLI = DAG.getTargetLoweringInfo();
3115   EVT MemVT =
3116       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3117 
3118   // If a pointer's DAG type is larger than its memory type then the DAG values
3119   // are zero-extended. This breaks signed comparisons so truncate back to the
3120   // underlying type before doing the compare.
3121   if (Op1.getValueType() != MemVT) {
3122     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3123     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3124   }
3125 
3126   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3127                                                         I.getType());
3128   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3129 }
3130 
3131 void SelectionDAGBuilder::visitFCmp(const User &I) {
3132   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3133   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3134     predicate = FC->getPredicate();
3135   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3136     predicate = FCmpInst::Predicate(FC->getPredicate());
3137   SDValue Op1 = getValue(I.getOperand(0));
3138   SDValue Op2 = getValue(I.getOperand(1));
3139 
3140   ISD::CondCode Condition = getFCmpCondCode(predicate);
3141   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3142   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3143     Condition = getFCmpCodeWithoutNaN(Condition);
3144 
3145   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3146                                                         I.getType());
3147   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3148 }
3149 
3150 // Check if the condition of the select has one use or two users that are both
3151 // selects with the same condition.
3152 static bool hasOnlySelectUsers(const Value *Cond) {
3153   return llvm::all_of(Cond->users(), [](const Value *V) {
3154     return isa<SelectInst>(V);
3155   });
3156 }
3157 
3158 void SelectionDAGBuilder::visitSelect(const User &I) {
3159   SmallVector<EVT, 4> ValueVTs;
3160   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3161                   ValueVTs);
3162   unsigned NumValues = ValueVTs.size();
3163   if (NumValues == 0) return;
3164 
3165   SmallVector<SDValue, 4> Values(NumValues);
3166   SDValue Cond     = getValue(I.getOperand(0));
3167   SDValue LHSVal   = getValue(I.getOperand(1));
3168   SDValue RHSVal   = getValue(I.getOperand(2));
3169   SmallVector<SDValue, 1> BaseOps(1, Cond);
3170   ISD::NodeType OpCode =
3171       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3172 
3173   bool IsUnaryAbs = false;
3174 
3175   // Min/max matching is only viable if all output VTs are the same.
3176   if (is_splat(ValueVTs)) {
3177     EVT VT = ValueVTs[0];
3178     LLVMContext &Ctx = *DAG.getContext();
3179     auto &TLI = DAG.getTargetLoweringInfo();
3180 
3181     // We care about the legality of the operation after it has been type
3182     // legalized.
3183     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3184       VT = TLI.getTypeToTransformTo(Ctx, VT);
3185 
3186     // If the vselect is legal, assume we want to leave this as a vector setcc +
3187     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3188     // min/max is legal on the scalar type.
3189     bool UseScalarMinMax = VT.isVector() &&
3190       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3191 
3192     Value *LHS, *RHS;
3193     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3194     ISD::NodeType Opc = ISD::DELETED_NODE;
3195     switch (SPR.Flavor) {
3196     case SPF_UMAX:    Opc = ISD::UMAX; break;
3197     case SPF_UMIN:    Opc = ISD::UMIN; break;
3198     case SPF_SMAX:    Opc = ISD::SMAX; break;
3199     case SPF_SMIN:    Opc = ISD::SMIN; break;
3200     case SPF_FMINNUM:
3201       switch (SPR.NaNBehavior) {
3202       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3203       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3204       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3205       case SPNB_RETURNS_ANY: {
3206         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3207           Opc = ISD::FMINNUM;
3208         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3209           Opc = ISD::FMINIMUM;
3210         else if (UseScalarMinMax)
3211           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3212             ISD::FMINNUM : ISD::FMINIMUM;
3213         break;
3214       }
3215       }
3216       break;
3217     case SPF_FMAXNUM:
3218       switch (SPR.NaNBehavior) {
3219       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3220       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3221       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3222       case SPNB_RETURNS_ANY:
3223 
3224         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3225           Opc = ISD::FMAXNUM;
3226         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3227           Opc = ISD::FMAXIMUM;
3228         else if (UseScalarMinMax)
3229           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3230             ISD::FMAXNUM : ISD::FMAXIMUM;
3231         break;
3232       }
3233       break;
3234     case SPF_ABS:
3235       IsUnaryAbs = true;
3236       Opc = ISD::ABS;
3237       break;
3238     case SPF_NABS:
3239       // TODO: we need to produce sub(0, abs(X)).
3240     default: break;
3241     }
3242 
3243     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3244         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3245          (UseScalarMinMax &&
3246           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3247         // If the underlying comparison instruction is used by any other
3248         // instruction, the consumed instructions won't be destroyed, so it is
3249         // not profitable to convert to a min/max.
3250         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3251       OpCode = Opc;
3252       LHSVal = getValue(LHS);
3253       RHSVal = getValue(RHS);
3254       BaseOps.clear();
3255     }
3256 
3257     if (IsUnaryAbs) {
3258       OpCode = Opc;
3259       LHSVal = getValue(LHS);
3260       BaseOps.clear();
3261     }
3262   }
3263 
3264   if (IsUnaryAbs) {
3265     for (unsigned i = 0; i != NumValues; ++i) {
3266       Values[i] =
3267           DAG.getNode(OpCode, getCurSDLoc(),
3268                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3269                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3270     }
3271   } else {
3272     for (unsigned i = 0; i != NumValues; ++i) {
3273       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3274       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3275       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3276       Values[i] = DAG.getNode(
3277           OpCode, getCurSDLoc(),
3278           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3279     }
3280   }
3281 
3282   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3283                            DAG.getVTList(ValueVTs), Values));
3284 }
3285 
3286 void SelectionDAGBuilder::visitTrunc(const User &I) {
3287   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3288   SDValue N = getValue(I.getOperand(0));
3289   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3290                                                         I.getType());
3291   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3292 }
3293 
3294 void SelectionDAGBuilder::visitZExt(const User &I) {
3295   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3296   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3297   SDValue N = getValue(I.getOperand(0));
3298   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3299                                                         I.getType());
3300   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3301 }
3302 
3303 void SelectionDAGBuilder::visitSExt(const User &I) {
3304   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3305   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3306   SDValue N = getValue(I.getOperand(0));
3307   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3308                                                         I.getType());
3309   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3310 }
3311 
3312 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3313   // FPTrunc is never a no-op cast, no need to check
3314   SDValue N = getValue(I.getOperand(0));
3315   SDLoc dl = getCurSDLoc();
3316   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3317   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3318   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3319                            DAG.getTargetConstant(
3320                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3321 }
3322 
3323 void SelectionDAGBuilder::visitFPExt(const User &I) {
3324   // FPExt is never a no-op cast, no need to check
3325   SDValue N = getValue(I.getOperand(0));
3326   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3327                                                         I.getType());
3328   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3329 }
3330 
3331 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3332   // FPToUI is never a no-op cast, no need to check
3333   SDValue N = getValue(I.getOperand(0));
3334   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3335                                                         I.getType());
3336   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3337 }
3338 
3339 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3340   // FPToSI is never a no-op cast, no need to check
3341   SDValue N = getValue(I.getOperand(0));
3342   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3343                                                         I.getType());
3344   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3345 }
3346 
3347 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3348   // UIToFP is never a no-op cast, no need to check
3349   SDValue N = getValue(I.getOperand(0));
3350   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3351                                                         I.getType());
3352   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3353 }
3354 
3355 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3356   // SIToFP is never a no-op cast, no need to check
3357   SDValue N = getValue(I.getOperand(0));
3358   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3359                                                         I.getType());
3360   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3361 }
3362 
3363 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3364   // What to do depends on the size of the integer and the size of the pointer.
3365   // We can either truncate, zero extend, or no-op, accordingly.
3366   SDValue N = getValue(I.getOperand(0));
3367   auto &TLI = DAG.getTargetLoweringInfo();
3368   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3369                                                         I.getType());
3370   EVT PtrMemVT =
3371       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3372   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3373   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3374   setValue(&I, N);
3375 }
3376 
3377 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3378   // What to do depends on the size of the integer and the size of the pointer.
3379   // We can either truncate, zero extend, or no-op, accordingly.
3380   SDValue N = getValue(I.getOperand(0));
3381   auto &TLI = DAG.getTargetLoweringInfo();
3382   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3383   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3384   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3385   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3386   setValue(&I, N);
3387 }
3388 
3389 void SelectionDAGBuilder::visitBitCast(const User &I) {
3390   SDValue N = getValue(I.getOperand(0));
3391   SDLoc dl = getCurSDLoc();
3392   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3393                                                         I.getType());
3394 
3395   // BitCast assures us that source and destination are the same size so this is
3396   // either a BITCAST or a no-op.
3397   if (DestVT != N.getValueType())
3398     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3399                              DestVT, N)); // convert types.
3400   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3401   // might fold any kind of constant expression to an integer constant and that
3402   // is not what we are looking for. Only recognize a bitcast of a genuine
3403   // constant integer as an opaque constant.
3404   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3405     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3406                                  /*isOpaque*/true));
3407   else
3408     setValue(&I, N);            // noop cast.
3409 }
3410 
3411 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3413   const Value *SV = I.getOperand(0);
3414   SDValue N = getValue(SV);
3415   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3416 
3417   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3418   unsigned DestAS = I.getType()->getPointerAddressSpace();
3419 
3420   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3421     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3422 
3423   setValue(&I, N);
3424 }
3425 
3426 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3428   SDValue InVec = getValue(I.getOperand(0));
3429   SDValue InVal = getValue(I.getOperand(1));
3430   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3431                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3432   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3433                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3434                            InVec, InVal, InIdx));
3435 }
3436 
3437 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3439   SDValue InVec = getValue(I.getOperand(0));
3440   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3441                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3442   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3443                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3444                            InVec, InIdx));
3445 }
3446 
3447 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3448   SDValue Src1 = getValue(I.getOperand(0));
3449   SDValue Src2 = getValue(I.getOperand(1));
3450   ArrayRef<int> Mask;
3451   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3452     Mask = SVI->getShuffleMask();
3453   else
3454     Mask = cast<ConstantExpr>(I).getShuffleMask();
3455   SDLoc DL = getCurSDLoc();
3456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3457   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3458   EVT SrcVT = Src1.getValueType();
3459   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3460 
3461   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3462       VT.isScalableVector()) {
3463     // Canonical splat form of first element of first input vector.
3464     SDValue FirstElt =
3465         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3466                     DAG.getVectorIdxConstant(0, DL));
3467     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3468     return;
3469   }
3470 
3471   // For now, we only handle splats for scalable vectors.
3472   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3473   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3474   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3475 
3476   unsigned MaskNumElts = Mask.size();
3477 
3478   if (SrcNumElts == MaskNumElts) {
3479     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3480     return;
3481   }
3482 
3483   // Normalize the shuffle vector since mask and vector length don't match.
3484   if (SrcNumElts < MaskNumElts) {
3485     // Mask is longer than the source vectors. We can use concatenate vector to
3486     // make the mask and vectors lengths match.
3487 
3488     if (MaskNumElts % SrcNumElts == 0) {
3489       // Mask length is a multiple of the source vector length.
3490       // Check if the shuffle is some kind of concatenation of the input
3491       // vectors.
3492       unsigned NumConcat = MaskNumElts / SrcNumElts;
3493       bool IsConcat = true;
3494       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3495       for (unsigned i = 0; i != MaskNumElts; ++i) {
3496         int Idx = Mask[i];
3497         if (Idx < 0)
3498           continue;
3499         // Ensure the indices in each SrcVT sized piece are sequential and that
3500         // the same source is used for the whole piece.
3501         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3502             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3503              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3504           IsConcat = false;
3505           break;
3506         }
3507         // Remember which source this index came from.
3508         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3509       }
3510 
3511       // The shuffle is concatenating multiple vectors together. Just emit
3512       // a CONCAT_VECTORS operation.
3513       if (IsConcat) {
3514         SmallVector<SDValue, 8> ConcatOps;
3515         for (auto Src : ConcatSrcs) {
3516           if (Src < 0)
3517             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3518           else if (Src == 0)
3519             ConcatOps.push_back(Src1);
3520           else
3521             ConcatOps.push_back(Src2);
3522         }
3523         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3524         return;
3525       }
3526     }
3527 
3528     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3529     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3530     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3531                                     PaddedMaskNumElts);
3532 
3533     // Pad both vectors with undefs to make them the same length as the mask.
3534     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3535 
3536     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3537     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3538     MOps1[0] = Src1;
3539     MOps2[0] = Src2;
3540 
3541     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3542     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3543 
3544     // Readjust mask for new input vector length.
3545     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3546     for (unsigned i = 0; i != MaskNumElts; ++i) {
3547       int Idx = Mask[i];
3548       if (Idx >= (int)SrcNumElts)
3549         Idx -= SrcNumElts - PaddedMaskNumElts;
3550       MappedOps[i] = Idx;
3551     }
3552 
3553     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3554 
3555     // If the concatenated vector was padded, extract a subvector with the
3556     // correct number of elements.
3557     if (MaskNumElts != PaddedMaskNumElts)
3558       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3559                            DAG.getVectorIdxConstant(0, DL));
3560 
3561     setValue(&I, Result);
3562     return;
3563   }
3564 
3565   if (SrcNumElts > MaskNumElts) {
3566     // Analyze the access pattern of the vector to see if we can extract
3567     // two subvectors and do the shuffle.
3568     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3569     bool CanExtract = true;
3570     for (int Idx : Mask) {
3571       unsigned Input = 0;
3572       if (Idx < 0)
3573         continue;
3574 
3575       if (Idx >= (int)SrcNumElts) {
3576         Input = 1;
3577         Idx -= SrcNumElts;
3578       }
3579 
3580       // If all the indices come from the same MaskNumElts sized portion of
3581       // the sources we can use extract. Also make sure the extract wouldn't
3582       // extract past the end of the source.
3583       int NewStartIdx = alignDown(Idx, MaskNumElts);
3584       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3585           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3586         CanExtract = false;
3587       // Make sure we always update StartIdx as we use it to track if all
3588       // elements are undef.
3589       StartIdx[Input] = NewStartIdx;
3590     }
3591 
3592     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3593       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3594       return;
3595     }
3596     if (CanExtract) {
3597       // Extract appropriate subvector and generate a vector shuffle
3598       for (unsigned Input = 0; Input < 2; ++Input) {
3599         SDValue &Src = Input == 0 ? Src1 : Src2;
3600         if (StartIdx[Input] < 0)
3601           Src = DAG.getUNDEF(VT);
3602         else {
3603           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3604                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3605         }
3606       }
3607 
3608       // Calculate new mask.
3609       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3610       for (int &Idx : MappedOps) {
3611         if (Idx >= (int)SrcNumElts)
3612           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3613         else if (Idx >= 0)
3614           Idx -= StartIdx[0];
3615       }
3616 
3617       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3618       return;
3619     }
3620   }
3621 
3622   // We can't use either concat vectors or extract subvectors so fall back to
3623   // replacing the shuffle with extract and build vector.
3624   // to insert and build vector.
3625   EVT EltVT = VT.getVectorElementType();
3626   SmallVector<SDValue,8> Ops;
3627   for (int Idx : Mask) {
3628     SDValue Res;
3629 
3630     if (Idx < 0) {
3631       Res = DAG.getUNDEF(EltVT);
3632     } else {
3633       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3634       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3635 
3636       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3637                         DAG.getVectorIdxConstant(Idx, DL));
3638     }
3639 
3640     Ops.push_back(Res);
3641   }
3642 
3643   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3644 }
3645 
3646 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3647   ArrayRef<unsigned> Indices;
3648   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3649     Indices = IV->getIndices();
3650   else
3651     Indices = cast<ConstantExpr>(&I)->getIndices();
3652 
3653   const Value *Op0 = I.getOperand(0);
3654   const Value *Op1 = I.getOperand(1);
3655   Type *AggTy = I.getType();
3656   Type *ValTy = Op1->getType();
3657   bool IntoUndef = isa<UndefValue>(Op0);
3658   bool FromUndef = isa<UndefValue>(Op1);
3659 
3660   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3661 
3662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3663   SmallVector<EVT, 4> AggValueVTs;
3664   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3665   SmallVector<EVT, 4> ValValueVTs;
3666   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3667 
3668   unsigned NumAggValues = AggValueVTs.size();
3669   unsigned NumValValues = ValValueVTs.size();
3670   SmallVector<SDValue, 4> Values(NumAggValues);
3671 
3672   // Ignore an insertvalue that produces an empty object
3673   if (!NumAggValues) {
3674     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3675     return;
3676   }
3677 
3678   SDValue Agg = getValue(Op0);
3679   unsigned i = 0;
3680   // Copy the beginning value(s) from the original aggregate.
3681   for (; i != LinearIndex; ++i)
3682     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3683                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3684   // Copy values from the inserted value(s).
3685   if (NumValValues) {
3686     SDValue Val = getValue(Op1);
3687     for (; i != LinearIndex + NumValValues; ++i)
3688       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3689                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3690   }
3691   // Copy remaining value(s) from the original aggregate.
3692   for (; i != NumAggValues; ++i)
3693     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3694                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3695 
3696   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3697                            DAG.getVTList(AggValueVTs), Values));
3698 }
3699 
3700 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3701   ArrayRef<unsigned> Indices;
3702   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3703     Indices = EV->getIndices();
3704   else
3705     Indices = cast<ConstantExpr>(&I)->getIndices();
3706 
3707   const Value *Op0 = I.getOperand(0);
3708   Type *AggTy = Op0->getType();
3709   Type *ValTy = I.getType();
3710   bool OutOfUndef = isa<UndefValue>(Op0);
3711 
3712   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3713 
3714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3715   SmallVector<EVT, 4> ValValueVTs;
3716   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3717 
3718   unsigned NumValValues = ValValueVTs.size();
3719 
3720   // Ignore a extractvalue that produces an empty object
3721   if (!NumValValues) {
3722     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3723     return;
3724   }
3725 
3726   SmallVector<SDValue, 4> Values(NumValValues);
3727 
3728   SDValue Agg = getValue(Op0);
3729   // Copy out the selected value(s).
3730   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3731     Values[i - LinearIndex] =
3732       OutOfUndef ?
3733         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3734         SDValue(Agg.getNode(), Agg.getResNo() + i);
3735 
3736   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3737                            DAG.getVTList(ValValueVTs), Values));
3738 }
3739 
3740 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3741   Value *Op0 = I.getOperand(0);
3742   // Note that the pointer operand may be a vector of pointers. Take the scalar
3743   // element which holds a pointer.
3744   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3745   SDValue N = getValue(Op0);
3746   SDLoc dl = getCurSDLoc();
3747   auto &TLI = DAG.getTargetLoweringInfo();
3748   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3749   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3750 
3751   // Normalize Vector GEP - all scalar operands should be converted to the
3752   // splat vector.
3753   bool IsVectorGEP = I.getType()->isVectorTy();
3754   ElementCount VectorElementCount =
3755       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3756                   : ElementCount(0, false);
3757 
3758   if (IsVectorGEP && !N.getValueType().isVector()) {
3759     LLVMContext &Context = *DAG.getContext();
3760     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3761     if (VectorElementCount.Scalable)
3762       N = DAG.getSplatVector(VT, dl, N);
3763     else
3764       N = DAG.getSplatBuildVector(VT, dl, N);
3765   }
3766 
3767   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3768        GTI != E; ++GTI) {
3769     const Value *Idx = GTI.getOperand();
3770     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3771       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3772       if (Field) {
3773         // N = N + Offset
3774         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3775 
3776         // In an inbounds GEP with an offset that is nonnegative even when
3777         // interpreted as signed, assume there is no unsigned overflow.
3778         SDNodeFlags Flags;
3779         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3780           Flags.setNoUnsignedWrap(true);
3781 
3782         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3783                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3784       }
3785     } else {
3786       // IdxSize is the width of the arithmetic according to IR semantics.
3787       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3788       // (and fix up the result later).
3789       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3790       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3791       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3792       // We intentionally mask away the high bits here; ElementSize may not
3793       // fit in IdxTy.
3794       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3795       bool ElementScalable = ElementSize.isScalable();
3796 
3797       // If this is a scalar constant or a splat vector of constants,
3798       // handle it quickly.
3799       const auto *C = dyn_cast<Constant>(Idx);
3800       if (C && isa<VectorType>(C->getType()))
3801         C = C->getSplatValue();
3802 
3803       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3804       if (CI && CI->isZero())
3805         continue;
3806       if (CI && !ElementScalable) {
3807         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3808         LLVMContext &Context = *DAG.getContext();
3809         SDValue OffsVal;
3810         if (IsVectorGEP)
3811           OffsVal = DAG.getConstant(
3812               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3813         else
3814           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3815 
3816         // In an inbounds GEP with an offset that is nonnegative even when
3817         // interpreted as signed, assume there is no unsigned overflow.
3818         SDNodeFlags Flags;
3819         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3820           Flags.setNoUnsignedWrap(true);
3821 
3822         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3823 
3824         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3825         continue;
3826       }
3827 
3828       // N = N + Idx * ElementMul;
3829       SDValue IdxN = getValue(Idx);
3830 
3831       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3832         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3833                                   VectorElementCount);
3834         if (VectorElementCount.Scalable)
3835           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3836         else
3837           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3838       }
3839 
3840       // If the index is smaller or larger than intptr_t, truncate or extend
3841       // it.
3842       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3843 
3844       if (ElementScalable) {
3845         EVT VScaleTy = N.getValueType().getScalarType();
3846         SDValue VScale = DAG.getNode(
3847             ISD::VSCALE, dl, VScaleTy,
3848             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3849         if (IsVectorGEP)
3850           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3851         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3852       } else {
3853         // If this is a multiply by a power of two, turn it into a shl
3854         // immediately.  This is a very common case.
3855         if (ElementMul != 1) {
3856           if (ElementMul.isPowerOf2()) {
3857             unsigned Amt = ElementMul.logBase2();
3858             IdxN = DAG.getNode(ISD::SHL, dl,
3859                                N.getValueType(), IdxN,
3860                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3861           } else {
3862             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3863                                             IdxN.getValueType());
3864             IdxN = DAG.getNode(ISD::MUL, dl,
3865                                N.getValueType(), IdxN, Scale);
3866           }
3867         }
3868       }
3869 
3870       N = DAG.getNode(ISD::ADD, dl,
3871                       N.getValueType(), N, IdxN);
3872     }
3873   }
3874 
3875   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3876     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3877 
3878   setValue(&I, N);
3879 }
3880 
3881 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3882   // If this is a fixed sized alloca in the entry block of the function,
3883   // allocate it statically on the stack.
3884   if (FuncInfo.StaticAllocaMap.count(&I))
3885     return;   // getValue will auto-populate this.
3886 
3887   SDLoc dl = getCurSDLoc();
3888   Type *Ty = I.getAllocatedType();
3889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3890   auto &DL = DAG.getDataLayout();
3891   uint64_t TySize = DL.getTypeAllocSize(Ty);
3892   MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign());
3893 
3894   SDValue AllocSize = getValue(I.getArraySize());
3895 
3896   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3897   if (AllocSize.getValueType() != IntPtr)
3898     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3899 
3900   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3901                           AllocSize,
3902                           DAG.getConstant(TySize, dl, IntPtr));
3903 
3904   // Handle alignment.  If the requested alignment is less than or equal to
3905   // the stack alignment, ignore it.  If the size is greater than or equal to
3906   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3907   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3908   if (Alignment <= StackAlign)
3909     Alignment = None;
3910 
3911   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3912   // Round the size of the allocation up to the stack alignment size
3913   // by add SA-1 to the size. This doesn't overflow because we're computing
3914   // an address inside an alloca.
3915   SDNodeFlags Flags;
3916   Flags.setNoUnsignedWrap(true);
3917   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3918                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3919 
3920   // Mask out the low bits for alignment purposes.
3921   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3922                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3923 
3924   SDValue Ops[] = {
3925       getRoot(), AllocSize,
3926       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3927   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3928   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3929   setValue(&I, DSA);
3930   DAG.setRoot(DSA.getValue(1));
3931 
3932   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3933 }
3934 
3935 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3936   if (I.isAtomic())
3937     return visitAtomicLoad(I);
3938 
3939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3940   const Value *SV = I.getOperand(0);
3941   if (TLI.supportSwiftError()) {
3942     // Swifterror values can come from either a function parameter with
3943     // swifterror attribute or an alloca with swifterror attribute.
3944     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3945       if (Arg->hasSwiftErrorAttr())
3946         return visitLoadFromSwiftError(I);
3947     }
3948 
3949     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3950       if (Alloca->isSwiftError())
3951         return visitLoadFromSwiftError(I);
3952     }
3953   }
3954 
3955   SDValue Ptr = getValue(SV);
3956 
3957   Type *Ty = I.getType();
3958   unsigned Alignment = I.getAlignment();
3959 
3960   AAMDNodes AAInfo;
3961   I.getAAMetadata(AAInfo);
3962   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3963 
3964   SmallVector<EVT, 4> ValueVTs, MemVTs;
3965   SmallVector<uint64_t, 4> Offsets;
3966   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3967   unsigned NumValues = ValueVTs.size();
3968   if (NumValues == 0)
3969     return;
3970 
3971   bool isVolatile = I.isVolatile();
3972 
3973   SDValue Root;
3974   bool ConstantMemory = false;
3975   if (isVolatile)
3976     // Serialize volatile loads with other side effects.
3977     Root = getRoot();
3978   else if (NumValues > MaxParallelChains)
3979     Root = getMemoryRoot();
3980   else if (AA &&
3981            AA->pointsToConstantMemory(MemoryLocation(
3982                SV,
3983                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3984                AAInfo))) {
3985     // Do not serialize (non-volatile) loads of constant memory with anything.
3986     Root = DAG.getEntryNode();
3987     ConstantMemory = true;
3988   } else {
3989     // Do not serialize non-volatile loads against each other.
3990     Root = DAG.getRoot();
3991   }
3992 
3993   SDLoc dl = getCurSDLoc();
3994 
3995   if (isVolatile)
3996     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3997 
3998   // An aggregate load cannot wrap around the address space, so offsets to its
3999   // parts don't wrap either.
4000   SDNodeFlags Flags;
4001   Flags.setNoUnsignedWrap(true);
4002 
4003   SmallVector<SDValue, 4> Values(NumValues);
4004   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4005   EVT PtrVT = Ptr.getValueType();
4006 
4007   MachineMemOperand::Flags MMOFlags
4008     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4009 
4010   unsigned ChainI = 0;
4011   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4012     // Serializing loads here may result in excessive register pressure, and
4013     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4014     // could recover a bit by hoisting nodes upward in the chain by recognizing
4015     // they are side-effect free or do not alias. The optimizer should really
4016     // avoid this case by converting large object/array copies to llvm.memcpy
4017     // (MaxParallelChains should always remain as failsafe).
4018     if (ChainI == MaxParallelChains) {
4019       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4020       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4021                                   makeArrayRef(Chains.data(), ChainI));
4022       Root = Chain;
4023       ChainI = 0;
4024     }
4025     SDValue A = DAG.getNode(ISD::ADD, dl,
4026                             PtrVT, Ptr,
4027                             DAG.getConstant(Offsets[i], dl, PtrVT),
4028                             Flags);
4029 
4030     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4031                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4032                             MMOFlags, AAInfo, Ranges);
4033     Chains[ChainI] = L.getValue(1);
4034 
4035     if (MemVTs[i] != ValueVTs[i])
4036       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4037 
4038     Values[i] = L;
4039   }
4040 
4041   if (!ConstantMemory) {
4042     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4043                                 makeArrayRef(Chains.data(), ChainI));
4044     if (isVolatile)
4045       DAG.setRoot(Chain);
4046     else
4047       PendingLoads.push_back(Chain);
4048   }
4049 
4050   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4051                            DAG.getVTList(ValueVTs), Values));
4052 }
4053 
4054 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4055   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4056          "call visitStoreToSwiftError when backend supports swifterror");
4057 
4058   SmallVector<EVT, 4> ValueVTs;
4059   SmallVector<uint64_t, 4> Offsets;
4060   const Value *SrcV = I.getOperand(0);
4061   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4062                   SrcV->getType(), ValueVTs, &Offsets);
4063   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4064          "expect a single EVT for swifterror");
4065 
4066   SDValue Src = getValue(SrcV);
4067   // Create a virtual register, then update the virtual register.
4068   Register VReg =
4069       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4070   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4071   // Chain can be getRoot or getControlRoot.
4072   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4073                                       SDValue(Src.getNode(), Src.getResNo()));
4074   DAG.setRoot(CopyNode);
4075 }
4076 
4077 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4078   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4079          "call visitLoadFromSwiftError when backend supports swifterror");
4080 
4081   assert(!I.isVolatile() &&
4082          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4083          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4084          "Support volatile, non temporal, invariant for load_from_swift_error");
4085 
4086   const Value *SV = I.getOperand(0);
4087   Type *Ty = I.getType();
4088   AAMDNodes AAInfo;
4089   I.getAAMetadata(AAInfo);
4090   assert(
4091       (!AA ||
4092        !AA->pointsToConstantMemory(MemoryLocation(
4093            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4094            AAInfo))) &&
4095       "load_from_swift_error should not be constant memory");
4096 
4097   SmallVector<EVT, 4> ValueVTs;
4098   SmallVector<uint64_t, 4> Offsets;
4099   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4100                   ValueVTs, &Offsets);
4101   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4102          "expect a single EVT for swifterror");
4103 
4104   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4105   SDValue L = DAG.getCopyFromReg(
4106       getRoot(), getCurSDLoc(),
4107       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4108 
4109   setValue(&I, L);
4110 }
4111 
4112 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4113   if (I.isAtomic())
4114     return visitAtomicStore(I);
4115 
4116   const Value *SrcV = I.getOperand(0);
4117   const Value *PtrV = I.getOperand(1);
4118 
4119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4120   if (TLI.supportSwiftError()) {
4121     // Swifterror values can come from either a function parameter with
4122     // swifterror attribute or an alloca with swifterror attribute.
4123     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4124       if (Arg->hasSwiftErrorAttr())
4125         return visitStoreToSwiftError(I);
4126     }
4127 
4128     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4129       if (Alloca->isSwiftError())
4130         return visitStoreToSwiftError(I);
4131     }
4132   }
4133 
4134   SmallVector<EVT, 4> ValueVTs, MemVTs;
4135   SmallVector<uint64_t, 4> Offsets;
4136   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4137                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4138   unsigned NumValues = ValueVTs.size();
4139   if (NumValues == 0)
4140     return;
4141 
4142   // Get the lowered operands. Note that we do this after
4143   // checking if NumResults is zero, because with zero results
4144   // the operands won't have values in the map.
4145   SDValue Src = getValue(SrcV);
4146   SDValue Ptr = getValue(PtrV);
4147 
4148   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4149   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4150   SDLoc dl = getCurSDLoc();
4151   unsigned Alignment = I.getAlignment();
4152   AAMDNodes AAInfo;
4153   I.getAAMetadata(AAInfo);
4154 
4155   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4156 
4157   // An aggregate load cannot wrap around the address space, so offsets to its
4158   // parts don't wrap either.
4159   SDNodeFlags Flags;
4160   Flags.setNoUnsignedWrap(true);
4161 
4162   unsigned ChainI = 0;
4163   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4164     // See visitLoad comments.
4165     if (ChainI == MaxParallelChains) {
4166       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4167                                   makeArrayRef(Chains.data(), ChainI));
4168       Root = Chain;
4169       ChainI = 0;
4170     }
4171     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4172     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4173     if (MemVTs[i] != ValueVTs[i])
4174       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4175     SDValue St =
4176         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4177                      Alignment, MMOFlags, AAInfo);
4178     Chains[ChainI] = St;
4179   }
4180 
4181   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4182                                   makeArrayRef(Chains.data(), ChainI));
4183   DAG.setRoot(StoreNode);
4184 }
4185 
4186 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4187                                            bool IsCompressing) {
4188   SDLoc sdl = getCurSDLoc();
4189 
4190   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4191                                MaybeAlign &Alignment) {
4192     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4193     Src0 = I.getArgOperand(0);
4194     Ptr = I.getArgOperand(1);
4195     Alignment =
4196         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4197     Mask = I.getArgOperand(3);
4198   };
4199   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4200                                     MaybeAlign &Alignment) {
4201     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4202     Src0 = I.getArgOperand(0);
4203     Ptr = I.getArgOperand(1);
4204     Mask = I.getArgOperand(2);
4205     Alignment = None;
4206   };
4207 
4208   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4209   MaybeAlign Alignment;
4210   if (IsCompressing)
4211     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4212   else
4213     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4214 
4215   SDValue Ptr = getValue(PtrOperand);
4216   SDValue Src0 = getValue(Src0Operand);
4217   SDValue Mask = getValue(MaskOperand);
4218   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4219 
4220   EVT VT = Src0.getValueType();
4221   if (!Alignment)
4222     Alignment = DAG.getEVTAlign(VT);
4223 
4224   AAMDNodes AAInfo;
4225   I.getAAMetadata(AAInfo);
4226 
4227   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4228       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4229       // TODO: Make MachineMemOperands aware of scalable
4230       // vectors.
4231       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4232   SDValue StoreNode =
4233       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4234                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4235   DAG.setRoot(StoreNode);
4236   setValue(&I, StoreNode);
4237 }
4238 
4239 // Get a uniform base for the Gather/Scatter intrinsic.
4240 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4241 // We try to represent it as a base pointer + vector of indices.
4242 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4243 // The first operand of the GEP may be a single pointer or a vector of pointers
4244 // Example:
4245 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4246 //  or
4247 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4248 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4249 //
4250 // When the first GEP operand is a single pointer - it is the uniform base we
4251 // are looking for. If first operand of the GEP is a splat vector - we
4252 // extract the splat value and use it as a uniform base.
4253 // In all other cases the function returns 'false'.
4254 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4255                            ISD::MemIndexType &IndexType, SDValue &Scale,
4256                            SelectionDAGBuilder *SDB) {
4257   SelectionDAG& DAG = SDB->DAG;
4258   LLVMContext &Context = *DAG.getContext();
4259 
4260   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4261   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4262   if (!GEP)
4263     return false;
4264 
4265   const Value *BasePtr = GEP->getPointerOperand();
4266   if (BasePtr->getType()->isVectorTy()) {
4267     BasePtr = getSplatValue(BasePtr);
4268     if (!BasePtr)
4269       return false;
4270   }
4271 
4272   unsigned FinalIndex = GEP->getNumOperands() - 1;
4273   Value *IndexVal = GEP->getOperand(FinalIndex);
4274   gep_type_iterator GTI = gep_type_begin(*GEP);
4275 
4276   // Ensure all the other indices are 0.
4277   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4278     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4279     if (!C)
4280       return false;
4281     if (isa<VectorType>(C->getType()))
4282       C = C->getSplatValue();
4283     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4284     if (!CI || !CI->isZero())
4285       return false;
4286   }
4287 
4288   // The operands of the GEP may be defined in another basic block.
4289   // In this case we'll not find nodes for the operands.
4290   if (!SDB->findValue(BasePtr))
4291     return false;
4292   Constant *C = dyn_cast<Constant>(IndexVal);
4293   if (!C && !SDB->findValue(IndexVal))
4294     return false;
4295 
4296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4297   const DataLayout &DL = DAG.getDataLayout();
4298   StructType *STy = GTI.getStructTypeOrNull();
4299 
4300   if (STy) {
4301     const StructLayout *SL = DL.getStructLayout(STy);
4302     unsigned Field = cast<Constant>(IndexVal)->getUniqueInteger().getZExtValue();
4303     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4304     Index = DAG.getConstant(SL->getElementOffset(Field),
4305                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4306   } else {
4307     Scale = DAG.getTargetConstant(
4308                 DL.getTypeAllocSize(GEP->getResultElementType()),
4309                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4310     Index = SDB->getValue(IndexVal);
4311   }
4312   Base = SDB->getValue(BasePtr);
4313   IndexType = ISD::SIGNED_SCALED;
4314 
4315   if (STy || !Index.getValueType().isVector()) {
4316     unsigned GEPWidth = cast<VectorType>(GEP->getType())->getNumElements();
4317     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4318     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4319   }
4320   return true;
4321 }
4322 
4323 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4324   SDLoc sdl = getCurSDLoc();
4325 
4326   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4327   const Value *Ptr = I.getArgOperand(1);
4328   SDValue Src0 = getValue(I.getArgOperand(0));
4329   SDValue Mask = getValue(I.getArgOperand(3));
4330   EVT VT = Src0.getValueType();
4331   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4332   if (!Alignment)
4333     Alignment = DAG.getEVTAlign(VT);
4334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4335 
4336   AAMDNodes AAInfo;
4337   I.getAAMetadata(AAInfo);
4338 
4339   SDValue Base;
4340   SDValue Index;
4341   ISD::MemIndexType IndexType;
4342   SDValue Scale;
4343   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this);
4344 
4345   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4346   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4347       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4348       // TODO: Make MachineMemOperands aware of scalable
4349       // vectors.
4350       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4351   if (!UniformBase) {
4352     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4353     Index = getValue(Ptr);
4354     IndexType = ISD::SIGNED_SCALED;
4355     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4356   }
4357   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4358   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4359                                          Ops, MMO, IndexType);
4360   DAG.setRoot(Scatter);
4361   setValue(&I, Scatter);
4362 }
4363 
4364 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4365   SDLoc sdl = getCurSDLoc();
4366 
4367   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4368                               MaybeAlign &Alignment) {
4369     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4370     Ptr = I.getArgOperand(0);
4371     Alignment =
4372         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4373     Mask = I.getArgOperand(2);
4374     Src0 = I.getArgOperand(3);
4375   };
4376   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4377                                  MaybeAlign &Alignment) {
4378     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4379     Ptr = I.getArgOperand(0);
4380     Alignment = None;
4381     Mask = I.getArgOperand(1);
4382     Src0 = I.getArgOperand(2);
4383   };
4384 
4385   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4386   MaybeAlign Alignment;
4387   if (IsExpanding)
4388     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4389   else
4390     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4391 
4392   SDValue Ptr = getValue(PtrOperand);
4393   SDValue Src0 = getValue(Src0Operand);
4394   SDValue Mask = getValue(MaskOperand);
4395   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4396 
4397   EVT VT = Src0.getValueType();
4398   if (!Alignment)
4399     Alignment = DAG.getEVTAlign(VT);
4400 
4401   AAMDNodes AAInfo;
4402   I.getAAMetadata(AAInfo);
4403   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4404 
4405   // Do not serialize masked loads of constant memory with anything.
4406   MemoryLocation ML;
4407   if (VT.isScalableVector())
4408     ML = MemoryLocation(PtrOperand);
4409   else
4410     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4411                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4412                            AAInfo);
4413   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4414 
4415   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4416 
4417   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4418       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4419       // TODO: Make MachineMemOperands aware of scalable
4420       // vectors.
4421       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4422 
4423   SDValue Load =
4424       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4425                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4426   if (AddToChain)
4427     PendingLoads.push_back(Load.getValue(1));
4428   setValue(&I, Load);
4429 }
4430 
4431 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4432   SDLoc sdl = getCurSDLoc();
4433 
4434   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4435   const Value *Ptr = I.getArgOperand(0);
4436   SDValue Src0 = getValue(I.getArgOperand(3));
4437   SDValue Mask = getValue(I.getArgOperand(2));
4438 
4439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4440   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4441   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4442   if (!Alignment)
4443     Alignment = DAG.getEVTAlign(VT);
4444 
4445   AAMDNodes AAInfo;
4446   I.getAAMetadata(AAInfo);
4447   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4448 
4449   SDValue Root = DAG.getRoot();
4450   SDValue Base;
4451   SDValue Index;
4452   ISD::MemIndexType IndexType;
4453   SDValue Scale;
4454   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this);
4455   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4456   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4457       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4458       // TODO: Make MachineMemOperands aware of scalable
4459       // vectors.
4460       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4461 
4462   if (!UniformBase) {
4463     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4464     Index = getValue(Ptr);
4465     IndexType = ISD::SIGNED_SCALED;
4466     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4467   }
4468   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4469   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4470                                        Ops, MMO, IndexType);
4471 
4472   PendingLoads.push_back(Gather.getValue(1));
4473   setValue(&I, Gather);
4474 }
4475 
4476 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4477   SDLoc dl = getCurSDLoc();
4478   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4479   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4480   SyncScope::ID SSID = I.getSyncScopeID();
4481 
4482   SDValue InChain = getRoot();
4483 
4484   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4485   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4486 
4487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4488   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4489 
4490   MachineFunction &MF = DAG.getMachineFunction();
4491   MachineMemOperand *MMO = MF.getMachineMemOperand(
4492       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4493       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4494       FailureOrdering);
4495 
4496   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4497                                    dl, MemVT, VTs, InChain,
4498                                    getValue(I.getPointerOperand()),
4499                                    getValue(I.getCompareOperand()),
4500                                    getValue(I.getNewValOperand()), MMO);
4501 
4502   SDValue OutChain = L.getValue(2);
4503 
4504   setValue(&I, L);
4505   DAG.setRoot(OutChain);
4506 }
4507 
4508 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4509   SDLoc dl = getCurSDLoc();
4510   ISD::NodeType NT;
4511   switch (I.getOperation()) {
4512   default: llvm_unreachable("Unknown atomicrmw operation");
4513   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4514   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4515   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4516   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4517   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4518   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4519   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4520   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4521   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4522   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4523   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4524   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4525   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4526   }
4527   AtomicOrdering Ordering = I.getOrdering();
4528   SyncScope::ID SSID = I.getSyncScopeID();
4529 
4530   SDValue InChain = getRoot();
4531 
4532   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4534   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4535 
4536   MachineFunction &MF = DAG.getMachineFunction();
4537   MachineMemOperand *MMO = MF.getMachineMemOperand(
4538       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4539       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4540 
4541   SDValue L =
4542     DAG.getAtomic(NT, dl, MemVT, InChain,
4543                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4544                   MMO);
4545 
4546   SDValue OutChain = L.getValue(1);
4547 
4548   setValue(&I, L);
4549   DAG.setRoot(OutChain);
4550 }
4551 
4552 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4553   SDLoc dl = getCurSDLoc();
4554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4555   SDValue Ops[3];
4556   Ops[0] = getRoot();
4557   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4558                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4559   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4560                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4561   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4562 }
4563 
4564 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4565   SDLoc dl = getCurSDLoc();
4566   AtomicOrdering Order = I.getOrdering();
4567   SyncScope::ID SSID = I.getSyncScopeID();
4568 
4569   SDValue InChain = getRoot();
4570 
4571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4572   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4573   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4574 
4575   if (!TLI.supportsUnalignedAtomics() &&
4576       I.getAlignment() < MemVT.getSizeInBits() / 8)
4577     report_fatal_error("Cannot generate unaligned atomic load");
4578 
4579   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4580 
4581   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4582       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4583       I.getAlign().getValueOr(DAG.getEVTAlign(MemVT)), AAMDNodes(), nullptr,
4584       SSID, Order);
4585 
4586   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4587 
4588   SDValue Ptr = getValue(I.getPointerOperand());
4589 
4590   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4591     // TODO: Once this is better exercised by tests, it should be merged with
4592     // the normal path for loads to prevent future divergence.
4593     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4594     if (MemVT != VT)
4595       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4596 
4597     setValue(&I, L);
4598     SDValue OutChain = L.getValue(1);
4599     if (!I.isUnordered())
4600       DAG.setRoot(OutChain);
4601     else
4602       PendingLoads.push_back(OutChain);
4603     return;
4604   }
4605 
4606   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4607                             Ptr, MMO);
4608 
4609   SDValue OutChain = L.getValue(1);
4610   if (MemVT != VT)
4611     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4612 
4613   setValue(&I, L);
4614   DAG.setRoot(OutChain);
4615 }
4616 
4617 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4618   SDLoc dl = getCurSDLoc();
4619 
4620   AtomicOrdering Ordering = I.getOrdering();
4621   SyncScope::ID SSID = I.getSyncScopeID();
4622 
4623   SDValue InChain = getRoot();
4624 
4625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4626   EVT MemVT =
4627       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4628 
4629   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4630     report_fatal_error("Cannot generate unaligned atomic store");
4631 
4632   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4633 
4634   MachineFunction &MF = DAG.getMachineFunction();
4635   MachineMemOperand *MMO = MF.getMachineMemOperand(
4636       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4637       *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4638 
4639   SDValue Val = getValue(I.getValueOperand());
4640   if (Val.getValueType() != MemVT)
4641     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4642   SDValue Ptr = getValue(I.getPointerOperand());
4643 
4644   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4645     // TODO: Once this is better exercised by tests, it should be merged with
4646     // the normal path for stores to prevent future divergence.
4647     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4648     DAG.setRoot(S);
4649     return;
4650   }
4651   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4652                                    Ptr, Val, MMO);
4653 
4654 
4655   DAG.setRoot(OutChain);
4656 }
4657 
4658 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4659 /// node.
4660 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4661                                                unsigned Intrinsic) {
4662   // Ignore the callsite's attributes. A specific call site may be marked with
4663   // readnone, but the lowering code will expect the chain based on the
4664   // definition.
4665   const Function *F = I.getCalledFunction();
4666   bool HasChain = !F->doesNotAccessMemory();
4667   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4668 
4669   // Build the operand list.
4670   SmallVector<SDValue, 8> Ops;
4671   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4672     if (OnlyLoad) {
4673       // We don't need to serialize loads against other loads.
4674       Ops.push_back(DAG.getRoot());
4675     } else {
4676       Ops.push_back(getRoot());
4677     }
4678   }
4679 
4680   // Info is set by getTgtMemInstrinsic
4681   TargetLowering::IntrinsicInfo Info;
4682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4683   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4684                                                DAG.getMachineFunction(),
4685                                                Intrinsic);
4686 
4687   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4688   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4689       Info.opc == ISD::INTRINSIC_W_CHAIN)
4690     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4691                                         TLI.getPointerTy(DAG.getDataLayout())));
4692 
4693   // Add all operands of the call to the operand list.
4694   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4695     const Value *Arg = I.getArgOperand(i);
4696     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4697       Ops.push_back(getValue(Arg));
4698       continue;
4699     }
4700 
4701     // Use TargetConstant instead of a regular constant for immarg.
4702     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4703     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4704       assert(CI->getBitWidth() <= 64 &&
4705              "large intrinsic immediates not handled");
4706       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4707     } else {
4708       Ops.push_back(
4709           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4710     }
4711   }
4712 
4713   SmallVector<EVT, 4> ValueVTs;
4714   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4715 
4716   if (HasChain)
4717     ValueVTs.push_back(MVT::Other);
4718 
4719   SDVTList VTs = DAG.getVTList(ValueVTs);
4720 
4721   // Create the node.
4722   SDValue Result;
4723   if (IsTgtIntrinsic) {
4724     // This is target intrinsic that touches memory
4725     AAMDNodes AAInfo;
4726     I.getAAMetadata(AAInfo);
4727     Result =
4728         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4729                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4730                                 Info.align, Info.flags, Info.size, AAInfo);
4731   } else if (!HasChain) {
4732     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4733   } else if (!I.getType()->isVoidTy()) {
4734     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4735   } else {
4736     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4737   }
4738 
4739   if (HasChain) {
4740     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4741     if (OnlyLoad)
4742       PendingLoads.push_back(Chain);
4743     else
4744       DAG.setRoot(Chain);
4745   }
4746 
4747   if (!I.getType()->isVoidTy()) {
4748     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4749       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4750       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4751     } else
4752       Result = lowerRangeToAssertZExt(DAG, I, Result);
4753 
4754     setValue(&I, Result);
4755   }
4756 }
4757 
4758 /// GetSignificand - Get the significand and build it into a floating-point
4759 /// number with exponent of 1:
4760 ///
4761 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4762 ///
4763 /// where Op is the hexadecimal representation of floating point value.
4764 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4765   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4766                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4767   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4768                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4769   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4770 }
4771 
4772 /// GetExponent - Get the exponent:
4773 ///
4774 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4775 ///
4776 /// where Op is the hexadecimal representation of floating point value.
4777 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4778                            const TargetLowering &TLI, const SDLoc &dl) {
4779   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4780                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4781   SDValue t1 = DAG.getNode(
4782       ISD::SRL, dl, MVT::i32, t0,
4783       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4784   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4785                            DAG.getConstant(127, dl, MVT::i32));
4786   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4787 }
4788 
4789 /// getF32Constant - Get 32-bit floating point constant.
4790 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4791                               const SDLoc &dl) {
4792   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4793                            MVT::f32);
4794 }
4795 
4796 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4797                                        SelectionDAG &DAG) {
4798   // TODO: What fast-math-flags should be set on the floating-point nodes?
4799 
4800   //   IntegerPartOfX = ((int32_t)(t0);
4801   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4802 
4803   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4804   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4805   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4806 
4807   //   IntegerPartOfX <<= 23;
4808   IntegerPartOfX = DAG.getNode(
4809       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4810       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4811                                   DAG.getDataLayout())));
4812 
4813   SDValue TwoToFractionalPartOfX;
4814   if (LimitFloatPrecision <= 6) {
4815     // For floating-point precision of 6:
4816     //
4817     //   TwoToFractionalPartOfX =
4818     //     0.997535578f +
4819     //       (0.735607626f + 0.252464424f * x) * x;
4820     //
4821     // error 0.0144103317, which is 6 bits
4822     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4823                              getF32Constant(DAG, 0x3e814304, dl));
4824     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4825                              getF32Constant(DAG, 0x3f3c50c8, dl));
4826     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4827     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4828                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4829   } else if (LimitFloatPrecision <= 12) {
4830     // For floating-point precision of 12:
4831     //
4832     //   TwoToFractionalPartOfX =
4833     //     0.999892986f +
4834     //       (0.696457318f +
4835     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4836     //
4837     // error 0.000107046256, which is 13 to 14 bits
4838     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4839                              getF32Constant(DAG, 0x3da235e3, dl));
4840     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4841                              getF32Constant(DAG, 0x3e65b8f3, dl));
4842     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4843     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4844                              getF32Constant(DAG, 0x3f324b07, dl));
4845     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4846     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4847                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4848   } else { // LimitFloatPrecision <= 18
4849     // For floating-point precision of 18:
4850     //
4851     //   TwoToFractionalPartOfX =
4852     //     0.999999982f +
4853     //       (0.693148872f +
4854     //         (0.240227044f +
4855     //           (0.554906021e-1f +
4856     //             (0.961591928e-2f +
4857     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4858     // error 2.47208000*10^(-7), which is better than 18 bits
4859     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4860                              getF32Constant(DAG, 0x3924b03e, dl));
4861     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4862                              getF32Constant(DAG, 0x3ab24b87, dl));
4863     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4864     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4865                              getF32Constant(DAG, 0x3c1d8c17, dl));
4866     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4867     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4868                              getF32Constant(DAG, 0x3d634a1d, dl));
4869     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4870     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4871                              getF32Constant(DAG, 0x3e75fe14, dl));
4872     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4873     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4874                               getF32Constant(DAG, 0x3f317234, dl));
4875     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4876     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4877                                          getF32Constant(DAG, 0x3f800000, dl));
4878   }
4879 
4880   // Add the exponent into the result in integer domain.
4881   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4882   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4883                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4884 }
4885 
4886 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4887 /// limited-precision mode.
4888 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4889                          const TargetLowering &TLI) {
4890   if (Op.getValueType() == MVT::f32 &&
4891       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4892 
4893     // Put the exponent in the right bit position for later addition to the
4894     // final result:
4895     //
4896     // t0 = Op * log2(e)
4897 
4898     // TODO: What fast-math-flags should be set here?
4899     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4900                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4901     return getLimitedPrecisionExp2(t0, dl, DAG);
4902   }
4903 
4904   // No special expansion.
4905   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4906 }
4907 
4908 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4909 /// limited-precision mode.
4910 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4911                          const TargetLowering &TLI) {
4912   // TODO: What fast-math-flags should be set on the floating-point nodes?
4913 
4914   if (Op.getValueType() == MVT::f32 &&
4915       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4916     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4917 
4918     // Scale the exponent by log(2).
4919     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4920     SDValue LogOfExponent =
4921         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4922                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4923 
4924     // Get the significand and build it into a floating-point number with
4925     // exponent of 1.
4926     SDValue X = GetSignificand(DAG, Op1, dl);
4927 
4928     SDValue LogOfMantissa;
4929     if (LimitFloatPrecision <= 6) {
4930       // For floating-point precision of 6:
4931       //
4932       //   LogofMantissa =
4933       //     -1.1609546f +
4934       //       (1.4034025f - 0.23903021f * x) * x;
4935       //
4936       // error 0.0034276066, which is better than 8 bits
4937       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4938                                getF32Constant(DAG, 0xbe74c456, dl));
4939       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4940                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4941       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4942       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4943                                   getF32Constant(DAG, 0x3f949a29, dl));
4944     } else if (LimitFloatPrecision <= 12) {
4945       // For floating-point precision of 12:
4946       //
4947       //   LogOfMantissa =
4948       //     -1.7417939f +
4949       //       (2.8212026f +
4950       //         (-1.4699568f +
4951       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4952       //
4953       // error 0.000061011436, which is 14 bits
4954       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4955                                getF32Constant(DAG, 0xbd67b6d6, dl));
4956       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4957                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4958       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4959       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4960                                getF32Constant(DAG, 0x3fbc278b, dl));
4961       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4962       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4963                                getF32Constant(DAG, 0x40348e95, dl));
4964       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4965       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4966                                   getF32Constant(DAG, 0x3fdef31a, dl));
4967     } else { // LimitFloatPrecision <= 18
4968       // For floating-point precision of 18:
4969       //
4970       //   LogOfMantissa =
4971       //     -2.1072184f +
4972       //       (4.2372794f +
4973       //         (-3.7029485f +
4974       //           (2.2781945f +
4975       //             (-0.87823314f +
4976       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4977       //
4978       // error 0.0000023660568, which is better than 18 bits
4979       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4980                                getF32Constant(DAG, 0xbc91e5ac, dl));
4981       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4982                                getF32Constant(DAG, 0x3e4350aa, dl));
4983       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4984       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4985                                getF32Constant(DAG, 0x3f60d3e3, dl));
4986       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4987       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4988                                getF32Constant(DAG, 0x4011cdf0, dl));
4989       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4990       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4991                                getF32Constant(DAG, 0x406cfd1c, dl));
4992       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4993       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4994                                getF32Constant(DAG, 0x408797cb, dl));
4995       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4996       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4997                                   getF32Constant(DAG, 0x4006dcab, dl));
4998     }
4999 
5000     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5001   }
5002 
5003   // No special expansion.
5004   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5005 }
5006 
5007 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5008 /// limited-precision mode.
5009 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5010                           const TargetLowering &TLI) {
5011   // TODO: What fast-math-flags should be set on the floating-point nodes?
5012 
5013   if (Op.getValueType() == MVT::f32 &&
5014       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5015     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5016 
5017     // Get the exponent.
5018     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5019 
5020     // Get the significand and build it into a floating-point number with
5021     // exponent of 1.
5022     SDValue X = GetSignificand(DAG, Op1, dl);
5023 
5024     // Different possible minimax approximations of significand in
5025     // floating-point for various degrees of accuracy over [1,2].
5026     SDValue Log2ofMantissa;
5027     if (LimitFloatPrecision <= 6) {
5028       // For floating-point precision of 6:
5029       //
5030       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5031       //
5032       // error 0.0049451742, which is more than 7 bits
5033       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5034                                getF32Constant(DAG, 0xbeb08fe0, dl));
5035       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5036                                getF32Constant(DAG, 0x40019463, dl));
5037       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5038       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5039                                    getF32Constant(DAG, 0x3fd6633d, dl));
5040     } else if (LimitFloatPrecision <= 12) {
5041       // For floating-point precision of 12:
5042       //
5043       //   Log2ofMantissa =
5044       //     -2.51285454f +
5045       //       (4.07009056f +
5046       //         (-2.12067489f +
5047       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5048       //
5049       // error 0.0000876136000, which is better than 13 bits
5050       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5051                                getF32Constant(DAG, 0xbda7262e, dl));
5052       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5053                                getF32Constant(DAG, 0x3f25280b, dl));
5054       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5055       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5056                                getF32Constant(DAG, 0x4007b923, dl));
5057       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5058       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5059                                getF32Constant(DAG, 0x40823e2f, dl));
5060       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5061       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5062                                    getF32Constant(DAG, 0x4020d29c, dl));
5063     } else { // LimitFloatPrecision <= 18
5064       // For floating-point precision of 18:
5065       //
5066       //   Log2ofMantissa =
5067       //     -3.0400495f +
5068       //       (6.1129976f +
5069       //         (-5.3420409f +
5070       //           (3.2865683f +
5071       //             (-1.2669343f +
5072       //               (0.27515199f -
5073       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5074       //
5075       // error 0.0000018516, which is better than 18 bits
5076       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5077                                getF32Constant(DAG, 0xbcd2769e, dl));
5078       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5079                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5080       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5081       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5082                                getF32Constant(DAG, 0x3fa22ae7, dl));
5083       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5084       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5085                                getF32Constant(DAG, 0x40525723, dl));
5086       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5087       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5088                                getF32Constant(DAG, 0x40aaf200, dl));
5089       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5090       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5091                                getF32Constant(DAG, 0x40c39dad, dl));
5092       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5093       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5094                                    getF32Constant(DAG, 0x4042902c, dl));
5095     }
5096 
5097     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5098   }
5099 
5100   // No special expansion.
5101   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5102 }
5103 
5104 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5105 /// limited-precision mode.
5106 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5107                            const TargetLowering &TLI) {
5108   // TODO: What fast-math-flags should be set on the floating-point nodes?
5109 
5110   if (Op.getValueType() == MVT::f32 &&
5111       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5112     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5113 
5114     // Scale the exponent by log10(2) [0.30102999f].
5115     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5116     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5117                                         getF32Constant(DAG, 0x3e9a209a, dl));
5118 
5119     // Get the significand and build it into a floating-point number with
5120     // exponent of 1.
5121     SDValue X = GetSignificand(DAG, Op1, dl);
5122 
5123     SDValue Log10ofMantissa;
5124     if (LimitFloatPrecision <= 6) {
5125       // For floating-point precision of 6:
5126       //
5127       //   Log10ofMantissa =
5128       //     -0.50419619f +
5129       //       (0.60948995f - 0.10380950f * x) * x;
5130       //
5131       // error 0.0014886165, which is 6 bits
5132       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5133                                getF32Constant(DAG, 0xbdd49a13, dl));
5134       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5135                                getF32Constant(DAG, 0x3f1c0789, dl));
5136       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5137       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5138                                     getF32Constant(DAG, 0x3f011300, dl));
5139     } else if (LimitFloatPrecision <= 12) {
5140       // For floating-point precision of 12:
5141       //
5142       //   Log10ofMantissa =
5143       //     -0.64831180f +
5144       //       (0.91751397f +
5145       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5146       //
5147       // error 0.00019228036, which is better than 12 bits
5148       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5149                                getF32Constant(DAG, 0x3d431f31, dl));
5150       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5151                                getF32Constant(DAG, 0x3ea21fb2, dl));
5152       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5153       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5154                                getF32Constant(DAG, 0x3f6ae232, dl));
5155       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5156       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5157                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5158     } else { // LimitFloatPrecision <= 18
5159       // For floating-point precision of 18:
5160       //
5161       //   Log10ofMantissa =
5162       //     -0.84299375f +
5163       //       (1.5327582f +
5164       //         (-1.0688956f +
5165       //           (0.49102474f +
5166       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5167       //
5168       // error 0.0000037995730, which is better than 18 bits
5169       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5170                                getF32Constant(DAG, 0x3c5d51ce, dl));
5171       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5172                                getF32Constant(DAG, 0x3e00685a, dl));
5173       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5174       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5175                                getF32Constant(DAG, 0x3efb6798, dl));
5176       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5177       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5178                                getF32Constant(DAG, 0x3f88d192, dl));
5179       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5180       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5181                                getF32Constant(DAG, 0x3fc4316c, dl));
5182       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5183       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5184                                     getF32Constant(DAG, 0x3f57ce70, dl));
5185     }
5186 
5187     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5188   }
5189 
5190   // No special expansion.
5191   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5192 }
5193 
5194 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5195 /// limited-precision mode.
5196 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5197                           const TargetLowering &TLI) {
5198   if (Op.getValueType() == MVT::f32 &&
5199       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5200     return getLimitedPrecisionExp2(Op, dl, DAG);
5201 
5202   // No special expansion.
5203   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5204 }
5205 
5206 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5207 /// limited-precision mode with x == 10.0f.
5208 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5209                          SelectionDAG &DAG, const TargetLowering &TLI) {
5210   bool IsExp10 = false;
5211   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5212       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5213     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5214       APFloat Ten(10.0f);
5215       IsExp10 = LHSC->isExactlyValue(Ten);
5216     }
5217   }
5218 
5219   // TODO: What fast-math-flags should be set on the FMUL node?
5220   if (IsExp10) {
5221     // Put the exponent in the right bit position for later addition to the
5222     // final result:
5223     //
5224     //   #define LOG2OF10 3.3219281f
5225     //   t0 = Op * LOG2OF10;
5226     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5227                              getF32Constant(DAG, 0x40549a78, dl));
5228     return getLimitedPrecisionExp2(t0, dl, DAG);
5229   }
5230 
5231   // No special expansion.
5232   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5233 }
5234 
5235 /// ExpandPowI - Expand a llvm.powi intrinsic.
5236 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5237                           SelectionDAG &DAG) {
5238   // If RHS is a constant, we can expand this out to a multiplication tree,
5239   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5240   // optimizing for size, we only want to do this if the expansion would produce
5241   // a small number of multiplies, otherwise we do the full expansion.
5242   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5243     // Get the exponent as a positive value.
5244     unsigned Val = RHSC->getSExtValue();
5245     if ((int)Val < 0) Val = -Val;
5246 
5247     // powi(x, 0) -> 1.0
5248     if (Val == 0)
5249       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5250 
5251     bool OptForSize = DAG.shouldOptForSize();
5252     if (!OptForSize ||
5253         // If optimizing for size, don't insert too many multiplies.
5254         // This inserts up to 5 multiplies.
5255         countPopulation(Val) + Log2_32(Val) < 7) {
5256       // We use the simple binary decomposition method to generate the multiply
5257       // sequence.  There are more optimal ways to do this (for example,
5258       // powi(x,15) generates one more multiply than it should), but this has
5259       // the benefit of being both really simple and much better than a libcall.
5260       SDValue Res;  // Logically starts equal to 1.0
5261       SDValue CurSquare = LHS;
5262       // TODO: Intrinsics should have fast-math-flags that propagate to these
5263       // nodes.
5264       while (Val) {
5265         if (Val & 1) {
5266           if (Res.getNode())
5267             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5268           else
5269             Res = CurSquare;  // 1.0*CurSquare.
5270         }
5271 
5272         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5273                                 CurSquare, CurSquare);
5274         Val >>= 1;
5275       }
5276 
5277       // If the original was negative, invert the result, producing 1/(x*x*x).
5278       if (RHSC->getSExtValue() < 0)
5279         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5280                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5281       return Res;
5282     }
5283   }
5284 
5285   // Otherwise, expand to a libcall.
5286   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5287 }
5288 
5289 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5290                             SDValue LHS, SDValue RHS, SDValue Scale,
5291                             SelectionDAG &DAG, const TargetLowering &TLI) {
5292   EVT VT = LHS.getValueType();
5293   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5294   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5295   LLVMContext &Ctx = *DAG.getContext();
5296 
5297   // If the type is legal but the operation isn't, this node might survive all
5298   // the way to operation legalization. If we end up there and we do not have
5299   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5300   // node.
5301 
5302   // Coax the legalizer into expanding the node during type legalization instead
5303   // by bumping the size by one bit. This will force it to Promote, enabling the
5304   // early expansion and avoiding the need to expand later.
5305 
5306   // We don't have to do this if Scale is 0; that can always be expanded, unless
5307   // it's a saturating signed operation. Those can experience true integer
5308   // division overflow, a case which we must avoid.
5309 
5310   // FIXME: We wouldn't have to do this (or any of the early
5311   // expansion/promotion) if it was possible to expand a libcall of an
5312   // illegal type during operation legalization. But it's not, so things
5313   // get a bit hacky.
5314   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5315   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5316       (TLI.isTypeLegal(VT) ||
5317        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5318     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5319         Opcode, VT, ScaleInt);
5320     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5321       EVT PromVT;
5322       if (VT.isScalarInteger())
5323         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5324       else if (VT.isVector()) {
5325         PromVT = VT.getVectorElementType();
5326         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5327         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5328       } else
5329         llvm_unreachable("Wrong VT for DIVFIX?");
5330       if (Signed) {
5331         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5332         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5333       } else {
5334         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5335         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5336       }
5337       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5338       // For saturating operations, we need to shift up the LHS to get the
5339       // proper saturation width, and then shift down again afterwards.
5340       if (Saturating)
5341         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5342                           DAG.getConstant(1, DL, ShiftTy));
5343       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5344       if (Saturating)
5345         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5346                           DAG.getConstant(1, DL, ShiftTy));
5347       return DAG.getZExtOrTrunc(Res, DL, VT);
5348     }
5349   }
5350 
5351   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5352 }
5353 
5354 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5355 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5356 static void
5357 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5358                      const SDValue &N) {
5359   switch (N.getOpcode()) {
5360   case ISD::CopyFromReg: {
5361     SDValue Op = N.getOperand(1);
5362     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5363                       Op.getValueType().getSizeInBits());
5364     return;
5365   }
5366   case ISD::BITCAST:
5367   case ISD::AssertZext:
5368   case ISD::AssertSext:
5369   case ISD::TRUNCATE:
5370     getUnderlyingArgRegs(Regs, N.getOperand(0));
5371     return;
5372   case ISD::BUILD_PAIR:
5373   case ISD::BUILD_VECTOR:
5374   case ISD::CONCAT_VECTORS:
5375     for (SDValue Op : N->op_values())
5376       getUnderlyingArgRegs(Regs, Op);
5377     return;
5378   default:
5379     return;
5380   }
5381 }
5382 
5383 /// If the DbgValueInst is a dbg_value of a function argument, create the
5384 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5385 /// instruction selection, they will be inserted to the entry BB.
5386 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5387     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5388     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5389   const Argument *Arg = dyn_cast<Argument>(V);
5390   if (!Arg)
5391     return false;
5392 
5393   if (!IsDbgDeclare) {
5394     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5395     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5396     // the entry block.
5397     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5398     if (!IsInEntryBlock)
5399       return false;
5400 
5401     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5402     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5403     // variable that also is a param.
5404     //
5405     // Although, if we are at the top of the entry block already, we can still
5406     // emit using ArgDbgValue. This might catch some situations when the
5407     // dbg.value refers to an argument that isn't used in the entry block, so
5408     // any CopyToReg node would be optimized out and the only way to express
5409     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5410     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5411     // we should only emit as ArgDbgValue if the Variable is an argument to the
5412     // current function, and the dbg.value intrinsic is found in the entry
5413     // block.
5414     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5415         !DL->getInlinedAt();
5416     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5417     if (!IsInPrologue && !VariableIsFunctionInputArg)
5418       return false;
5419 
5420     // Here we assume that a function argument on IR level only can be used to
5421     // describe one input parameter on source level. If we for example have
5422     // source code like this
5423     //
5424     //    struct A { long x, y; };
5425     //    void foo(struct A a, long b) {
5426     //      ...
5427     //      b = a.x;
5428     //      ...
5429     //    }
5430     //
5431     // and IR like this
5432     //
5433     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5434     //  entry:
5435     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5436     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5437     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5438     //    ...
5439     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5440     //    ...
5441     //
5442     // then the last dbg.value is describing a parameter "b" using a value that
5443     // is an argument. But since we already has used %a1 to describe a parameter
5444     // we should not handle that last dbg.value here (that would result in an
5445     // incorrect hoisting of the DBG_VALUE to the function entry).
5446     // Notice that we allow one dbg.value per IR level argument, to accommodate
5447     // for the situation with fragments above.
5448     if (VariableIsFunctionInputArg) {
5449       unsigned ArgNo = Arg->getArgNo();
5450       if (ArgNo >= FuncInfo.DescribedArgs.size())
5451         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5452       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5453         return false;
5454       FuncInfo.DescribedArgs.set(ArgNo);
5455     }
5456   }
5457 
5458   MachineFunction &MF = DAG.getMachineFunction();
5459   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5460 
5461   bool IsIndirect = false;
5462   Optional<MachineOperand> Op;
5463   // Some arguments' frame index is recorded during argument lowering.
5464   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5465   if (FI != std::numeric_limits<int>::max())
5466     Op = MachineOperand::CreateFI(FI);
5467 
5468   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5469   if (!Op && N.getNode()) {
5470     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5471     Register Reg;
5472     if (ArgRegsAndSizes.size() == 1)
5473       Reg = ArgRegsAndSizes.front().first;
5474 
5475     if (Reg && Reg.isVirtual()) {
5476       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5477       Register PR = RegInfo.getLiveInPhysReg(Reg);
5478       if (PR)
5479         Reg = PR;
5480     }
5481     if (Reg) {
5482       Op = MachineOperand::CreateReg(Reg, false);
5483       IsIndirect = IsDbgDeclare;
5484     }
5485   }
5486 
5487   if (!Op && N.getNode()) {
5488     // Check if frame index is available.
5489     SDValue LCandidate = peekThroughBitcasts(N);
5490     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5491       if (FrameIndexSDNode *FINode =
5492           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5493         Op = MachineOperand::CreateFI(FINode->getIndex());
5494   }
5495 
5496   if (!Op) {
5497     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5498     auto splitMultiRegDbgValue
5499       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5500       unsigned Offset = 0;
5501       for (auto RegAndSize : SplitRegs) {
5502         // If the expression is already a fragment, the current register
5503         // offset+size might extend beyond the fragment. In this case, only
5504         // the register bits that are inside the fragment are relevant.
5505         int RegFragmentSizeInBits = RegAndSize.second;
5506         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5507           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5508           // The register is entirely outside the expression fragment,
5509           // so is irrelevant for debug info.
5510           if (Offset >= ExprFragmentSizeInBits)
5511             break;
5512           // The register is partially outside the expression fragment, only
5513           // the low bits within the fragment are relevant for debug info.
5514           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5515             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5516           }
5517         }
5518 
5519         auto FragmentExpr = DIExpression::createFragmentExpression(
5520             Expr, Offset, RegFragmentSizeInBits);
5521         Offset += RegAndSize.second;
5522         // If a valid fragment expression cannot be created, the variable's
5523         // correct value cannot be determined and so it is set as Undef.
5524         if (!FragmentExpr) {
5525           SDDbgValue *SDV = DAG.getConstantDbgValue(
5526               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5527           DAG.AddDbgValue(SDV, nullptr, false);
5528           continue;
5529         }
5530         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5531         FuncInfo.ArgDbgValues.push_back(
5532           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5533                   RegAndSize.first, Variable, *FragmentExpr));
5534       }
5535     };
5536 
5537     // Check if ValueMap has reg number.
5538     DenseMap<const Value *, Register>::const_iterator
5539       VMI = FuncInfo.ValueMap.find(V);
5540     if (VMI != FuncInfo.ValueMap.end()) {
5541       const auto &TLI = DAG.getTargetLoweringInfo();
5542       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5543                        V->getType(), getABIRegCopyCC(V));
5544       if (RFV.occupiesMultipleRegs()) {
5545         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5546         return true;
5547       }
5548 
5549       Op = MachineOperand::CreateReg(VMI->second, false);
5550       IsIndirect = IsDbgDeclare;
5551     } else if (ArgRegsAndSizes.size() > 1) {
5552       // This was split due to the calling convention, and no virtual register
5553       // mapping exists for the value.
5554       splitMultiRegDbgValue(ArgRegsAndSizes);
5555       return true;
5556     }
5557   }
5558 
5559   if (!Op)
5560     return false;
5561 
5562   assert(Variable->isValidLocationForIntrinsic(DL) &&
5563          "Expected inlined-at fields to agree");
5564   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5565   FuncInfo.ArgDbgValues.push_back(
5566       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5567               *Op, Variable, Expr));
5568 
5569   return true;
5570 }
5571 
5572 /// Return the appropriate SDDbgValue based on N.
5573 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5574                                              DILocalVariable *Variable,
5575                                              DIExpression *Expr,
5576                                              const DebugLoc &dl,
5577                                              unsigned DbgSDNodeOrder) {
5578   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5579     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5580     // stack slot locations.
5581     //
5582     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5583     // debug values here after optimization:
5584     //
5585     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5586     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5587     //
5588     // Both describe the direct values of their associated variables.
5589     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5590                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5591   }
5592   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5593                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5594 }
5595 
5596 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5597   switch (Intrinsic) {
5598   case Intrinsic::smul_fix:
5599     return ISD::SMULFIX;
5600   case Intrinsic::umul_fix:
5601     return ISD::UMULFIX;
5602   case Intrinsic::smul_fix_sat:
5603     return ISD::SMULFIXSAT;
5604   case Intrinsic::umul_fix_sat:
5605     return ISD::UMULFIXSAT;
5606   case Intrinsic::sdiv_fix:
5607     return ISD::SDIVFIX;
5608   case Intrinsic::udiv_fix:
5609     return ISD::UDIVFIX;
5610   case Intrinsic::sdiv_fix_sat:
5611     return ISD::SDIVFIXSAT;
5612   case Intrinsic::udiv_fix_sat:
5613     return ISD::UDIVFIXSAT;
5614   default:
5615     llvm_unreachable("Unhandled fixed point intrinsic");
5616   }
5617 }
5618 
5619 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5620                                            const char *FunctionName) {
5621   assert(FunctionName && "FunctionName must not be nullptr");
5622   SDValue Callee = DAG.getExternalSymbol(
5623       FunctionName,
5624       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5625   LowerCallTo(I, Callee, I.isTailCall());
5626 }
5627 
5628 /// Lower the call to the specified intrinsic function.
5629 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5630                                              unsigned Intrinsic) {
5631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5632   SDLoc sdl = getCurSDLoc();
5633   DebugLoc dl = getCurDebugLoc();
5634   SDValue Res;
5635 
5636   switch (Intrinsic) {
5637   default:
5638     // By default, turn this into a target intrinsic node.
5639     visitTargetIntrinsic(I, Intrinsic);
5640     return;
5641   case Intrinsic::vscale: {
5642     match(&I, m_VScale(DAG.getDataLayout()));
5643     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5644     setValue(&I,
5645              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5646     return;
5647   }
5648   case Intrinsic::vastart:  visitVAStart(I); return;
5649   case Intrinsic::vaend:    visitVAEnd(I); return;
5650   case Intrinsic::vacopy:   visitVACopy(I); return;
5651   case Intrinsic::returnaddress:
5652     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5653                              TLI.getPointerTy(DAG.getDataLayout()),
5654                              getValue(I.getArgOperand(0))));
5655     return;
5656   case Intrinsic::addressofreturnaddress:
5657     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5658                              TLI.getPointerTy(DAG.getDataLayout())));
5659     return;
5660   case Intrinsic::sponentry:
5661     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5662                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5663     return;
5664   case Intrinsic::frameaddress:
5665     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5666                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5667                              getValue(I.getArgOperand(0))));
5668     return;
5669   case Intrinsic::read_register: {
5670     Value *Reg = I.getArgOperand(0);
5671     SDValue Chain = getRoot();
5672     SDValue RegName =
5673         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5674     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5675     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5676       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5677     setValue(&I, Res);
5678     DAG.setRoot(Res.getValue(1));
5679     return;
5680   }
5681   case Intrinsic::write_register: {
5682     Value *Reg = I.getArgOperand(0);
5683     Value *RegValue = I.getArgOperand(1);
5684     SDValue Chain = getRoot();
5685     SDValue RegName =
5686         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5687     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5688                             RegName, getValue(RegValue)));
5689     return;
5690   }
5691   case Intrinsic::memcpy: {
5692     const auto &MCI = cast<MemCpyInst>(I);
5693     SDValue Op1 = getValue(I.getArgOperand(0));
5694     SDValue Op2 = getValue(I.getArgOperand(1));
5695     SDValue Op3 = getValue(I.getArgOperand(2));
5696     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5697     Align DstAlign = MCI.getDestAlign().valueOrOne();
5698     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5699     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5700     bool isVol = MCI.isVolatile();
5701     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5702     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5703     // node.
5704     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5705     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5706                                /* AlwaysInline */ false, isTC,
5707                                MachinePointerInfo(I.getArgOperand(0)),
5708                                MachinePointerInfo(I.getArgOperand(1)));
5709     updateDAGForMaybeTailCall(MC);
5710     return;
5711   }
5712   case Intrinsic::memcpy_inline: {
5713     const auto &MCI = cast<MemCpyInlineInst>(I);
5714     SDValue Dst = getValue(I.getArgOperand(0));
5715     SDValue Src = getValue(I.getArgOperand(1));
5716     SDValue Size = getValue(I.getArgOperand(2));
5717     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5718     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5719     Align DstAlign = MCI.getDestAlign().valueOrOne();
5720     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5721     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5722     bool isVol = MCI.isVolatile();
5723     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5724     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5725     // node.
5726     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5727                                /* AlwaysInline */ true, isTC,
5728                                MachinePointerInfo(I.getArgOperand(0)),
5729                                MachinePointerInfo(I.getArgOperand(1)));
5730     updateDAGForMaybeTailCall(MC);
5731     return;
5732   }
5733   case Intrinsic::memset: {
5734     const auto &MSI = cast<MemSetInst>(I);
5735     SDValue Op1 = getValue(I.getArgOperand(0));
5736     SDValue Op2 = getValue(I.getArgOperand(1));
5737     SDValue Op3 = getValue(I.getArgOperand(2));
5738     // @llvm.memset defines 0 and 1 to both mean no alignment.
5739     Align Alignment = MSI.getDestAlign().valueOrOne();
5740     bool isVol = MSI.isVolatile();
5741     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5742     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5743     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5744                                MachinePointerInfo(I.getArgOperand(0)));
5745     updateDAGForMaybeTailCall(MS);
5746     return;
5747   }
5748   case Intrinsic::memmove: {
5749     const auto &MMI = cast<MemMoveInst>(I);
5750     SDValue Op1 = getValue(I.getArgOperand(0));
5751     SDValue Op2 = getValue(I.getArgOperand(1));
5752     SDValue Op3 = getValue(I.getArgOperand(2));
5753     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5754     Align DstAlign = MMI.getDestAlign().valueOrOne();
5755     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5756     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5757     bool isVol = MMI.isVolatile();
5758     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5759     // FIXME: Support passing different dest/src alignments to the memmove DAG
5760     // node.
5761     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5762     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5763                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5764                                 MachinePointerInfo(I.getArgOperand(1)));
5765     updateDAGForMaybeTailCall(MM);
5766     return;
5767   }
5768   case Intrinsic::memcpy_element_unordered_atomic: {
5769     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5770     SDValue Dst = getValue(MI.getRawDest());
5771     SDValue Src = getValue(MI.getRawSource());
5772     SDValue Length = getValue(MI.getLength());
5773 
5774     unsigned DstAlign = MI.getDestAlignment();
5775     unsigned SrcAlign = MI.getSourceAlignment();
5776     Type *LengthTy = MI.getLength()->getType();
5777     unsigned ElemSz = MI.getElementSizeInBytes();
5778     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5779     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5780                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5781                                      MachinePointerInfo(MI.getRawDest()),
5782                                      MachinePointerInfo(MI.getRawSource()));
5783     updateDAGForMaybeTailCall(MC);
5784     return;
5785   }
5786   case Intrinsic::memmove_element_unordered_atomic: {
5787     auto &MI = cast<AtomicMemMoveInst>(I);
5788     SDValue Dst = getValue(MI.getRawDest());
5789     SDValue Src = getValue(MI.getRawSource());
5790     SDValue Length = getValue(MI.getLength());
5791 
5792     unsigned DstAlign = MI.getDestAlignment();
5793     unsigned SrcAlign = MI.getSourceAlignment();
5794     Type *LengthTy = MI.getLength()->getType();
5795     unsigned ElemSz = MI.getElementSizeInBytes();
5796     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5797     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5798                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5799                                       MachinePointerInfo(MI.getRawDest()),
5800                                       MachinePointerInfo(MI.getRawSource()));
5801     updateDAGForMaybeTailCall(MC);
5802     return;
5803   }
5804   case Intrinsic::memset_element_unordered_atomic: {
5805     auto &MI = cast<AtomicMemSetInst>(I);
5806     SDValue Dst = getValue(MI.getRawDest());
5807     SDValue Val = getValue(MI.getValue());
5808     SDValue Length = getValue(MI.getLength());
5809 
5810     unsigned DstAlign = MI.getDestAlignment();
5811     Type *LengthTy = MI.getLength()->getType();
5812     unsigned ElemSz = MI.getElementSizeInBytes();
5813     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5814     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5815                                      LengthTy, ElemSz, isTC,
5816                                      MachinePointerInfo(MI.getRawDest()));
5817     updateDAGForMaybeTailCall(MC);
5818     return;
5819   }
5820   case Intrinsic::dbg_addr:
5821   case Intrinsic::dbg_declare: {
5822     const auto &DI = cast<DbgVariableIntrinsic>(I);
5823     DILocalVariable *Variable = DI.getVariable();
5824     DIExpression *Expression = DI.getExpression();
5825     dropDanglingDebugInfo(Variable, Expression);
5826     assert(Variable && "Missing variable");
5827     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5828                       << "\n");
5829     // Check if address has undef value.
5830     const Value *Address = DI.getVariableLocation();
5831     if (!Address || isa<UndefValue>(Address) ||
5832         (Address->use_empty() && !isa<Argument>(Address))) {
5833       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5834                         << " (bad/undef/unused-arg address)\n");
5835       return;
5836     }
5837 
5838     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5839 
5840     // Check if this variable can be described by a frame index, typically
5841     // either as a static alloca or a byval parameter.
5842     int FI = std::numeric_limits<int>::max();
5843     if (const auto *AI =
5844             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5845       if (AI->isStaticAlloca()) {
5846         auto I = FuncInfo.StaticAllocaMap.find(AI);
5847         if (I != FuncInfo.StaticAllocaMap.end())
5848           FI = I->second;
5849       }
5850     } else if (const auto *Arg = dyn_cast<Argument>(
5851                    Address->stripInBoundsConstantOffsets())) {
5852       FI = FuncInfo.getArgumentFrameIndex(Arg);
5853     }
5854 
5855     // llvm.dbg.addr is control dependent and always generates indirect
5856     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5857     // the MachineFunction variable table.
5858     if (FI != std::numeric_limits<int>::max()) {
5859       if (Intrinsic == Intrinsic::dbg_addr) {
5860         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5861             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5862         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5863       } else {
5864         LLVM_DEBUG(dbgs() << "Skipping " << DI
5865                           << " (variable info stashed in MF side table)\n");
5866       }
5867       return;
5868     }
5869 
5870     SDValue &N = NodeMap[Address];
5871     if (!N.getNode() && isa<Argument>(Address))
5872       // Check unused arguments map.
5873       N = UnusedArgNodeMap[Address];
5874     SDDbgValue *SDV;
5875     if (N.getNode()) {
5876       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5877         Address = BCI->getOperand(0);
5878       // Parameters are handled specially.
5879       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5880       if (isParameter && FINode) {
5881         // Byval parameter. We have a frame index at this point.
5882         SDV =
5883             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5884                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5885       } else if (isa<Argument>(Address)) {
5886         // Address is an argument, so try to emit its dbg value using
5887         // virtual register info from the FuncInfo.ValueMap.
5888         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5889         return;
5890       } else {
5891         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5892                               true, dl, SDNodeOrder);
5893       }
5894       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5895     } else {
5896       // If Address is an argument then try to emit its dbg value using
5897       // virtual register info from the FuncInfo.ValueMap.
5898       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5899                                     N)) {
5900         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5901                           << " (could not emit func-arg dbg_value)\n");
5902       }
5903     }
5904     return;
5905   }
5906   case Intrinsic::dbg_label: {
5907     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5908     DILabel *Label = DI.getLabel();
5909     assert(Label && "Missing label");
5910 
5911     SDDbgLabel *SDV;
5912     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5913     DAG.AddDbgLabel(SDV);
5914     return;
5915   }
5916   case Intrinsic::dbg_value: {
5917     const DbgValueInst &DI = cast<DbgValueInst>(I);
5918     assert(DI.getVariable() && "Missing variable");
5919 
5920     DILocalVariable *Variable = DI.getVariable();
5921     DIExpression *Expression = DI.getExpression();
5922     dropDanglingDebugInfo(Variable, Expression);
5923     const Value *V = DI.getValue();
5924     if (!V)
5925       return;
5926 
5927     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5928         SDNodeOrder))
5929       return;
5930 
5931     // TODO: Dangling debug info will eventually either be resolved or produce
5932     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5933     // between the original dbg.value location and its resolved DBG_VALUE, which
5934     // we should ideally fill with an extra Undef DBG_VALUE.
5935 
5936     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5937     return;
5938   }
5939 
5940   case Intrinsic::eh_typeid_for: {
5941     // Find the type id for the given typeinfo.
5942     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5943     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5944     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5945     setValue(&I, Res);
5946     return;
5947   }
5948 
5949   case Intrinsic::eh_return_i32:
5950   case Intrinsic::eh_return_i64:
5951     DAG.getMachineFunction().setCallsEHReturn(true);
5952     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5953                             MVT::Other,
5954                             getControlRoot(),
5955                             getValue(I.getArgOperand(0)),
5956                             getValue(I.getArgOperand(1))));
5957     return;
5958   case Intrinsic::eh_unwind_init:
5959     DAG.getMachineFunction().setCallsUnwindInit(true);
5960     return;
5961   case Intrinsic::eh_dwarf_cfa:
5962     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5963                              TLI.getPointerTy(DAG.getDataLayout()),
5964                              getValue(I.getArgOperand(0))));
5965     return;
5966   case Intrinsic::eh_sjlj_callsite: {
5967     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5968     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5969     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5970     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5971 
5972     MMI.setCurrentCallSite(CI->getZExtValue());
5973     return;
5974   }
5975   case Intrinsic::eh_sjlj_functioncontext: {
5976     // Get and store the index of the function context.
5977     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5978     AllocaInst *FnCtx =
5979       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5980     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5981     MFI.setFunctionContextIndex(FI);
5982     return;
5983   }
5984   case Intrinsic::eh_sjlj_setjmp: {
5985     SDValue Ops[2];
5986     Ops[0] = getRoot();
5987     Ops[1] = getValue(I.getArgOperand(0));
5988     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5989                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5990     setValue(&I, Op.getValue(0));
5991     DAG.setRoot(Op.getValue(1));
5992     return;
5993   }
5994   case Intrinsic::eh_sjlj_longjmp:
5995     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5996                             getRoot(), getValue(I.getArgOperand(0))));
5997     return;
5998   case Intrinsic::eh_sjlj_setup_dispatch:
5999     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6000                             getRoot()));
6001     return;
6002   case Intrinsic::masked_gather:
6003     visitMaskedGather(I);
6004     return;
6005   case Intrinsic::masked_load:
6006     visitMaskedLoad(I);
6007     return;
6008   case Intrinsic::masked_scatter:
6009     visitMaskedScatter(I);
6010     return;
6011   case Intrinsic::masked_store:
6012     visitMaskedStore(I);
6013     return;
6014   case Intrinsic::masked_expandload:
6015     visitMaskedLoad(I, true /* IsExpanding */);
6016     return;
6017   case Intrinsic::masked_compressstore:
6018     visitMaskedStore(I, true /* IsCompressing */);
6019     return;
6020   case Intrinsic::powi:
6021     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6022                             getValue(I.getArgOperand(1)), DAG));
6023     return;
6024   case Intrinsic::log:
6025     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6026     return;
6027   case Intrinsic::log2:
6028     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6029     return;
6030   case Intrinsic::log10:
6031     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6032     return;
6033   case Intrinsic::exp:
6034     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6035     return;
6036   case Intrinsic::exp2:
6037     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6038     return;
6039   case Intrinsic::pow:
6040     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6041                            getValue(I.getArgOperand(1)), DAG, TLI));
6042     return;
6043   case Intrinsic::sqrt:
6044   case Intrinsic::fabs:
6045   case Intrinsic::sin:
6046   case Intrinsic::cos:
6047   case Intrinsic::floor:
6048   case Intrinsic::ceil:
6049   case Intrinsic::trunc:
6050   case Intrinsic::rint:
6051   case Intrinsic::nearbyint:
6052   case Intrinsic::round:
6053   case Intrinsic::canonicalize: {
6054     unsigned Opcode;
6055     switch (Intrinsic) {
6056     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6057     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6058     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6059     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6060     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6061     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6062     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6063     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6064     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6065     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6066     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6067     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6068     }
6069 
6070     setValue(&I, DAG.getNode(Opcode, sdl,
6071                              getValue(I.getArgOperand(0)).getValueType(),
6072                              getValue(I.getArgOperand(0))));
6073     return;
6074   }
6075   case Intrinsic::lround:
6076   case Intrinsic::llround:
6077   case Intrinsic::lrint:
6078   case Intrinsic::llrint: {
6079     unsigned Opcode;
6080     switch (Intrinsic) {
6081     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6082     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6083     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6084     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6085     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6086     }
6087 
6088     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6089     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6090                              getValue(I.getArgOperand(0))));
6091     return;
6092   }
6093   case Intrinsic::minnum:
6094     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6095                              getValue(I.getArgOperand(0)).getValueType(),
6096                              getValue(I.getArgOperand(0)),
6097                              getValue(I.getArgOperand(1))));
6098     return;
6099   case Intrinsic::maxnum:
6100     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6101                              getValue(I.getArgOperand(0)).getValueType(),
6102                              getValue(I.getArgOperand(0)),
6103                              getValue(I.getArgOperand(1))));
6104     return;
6105   case Intrinsic::minimum:
6106     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6107                              getValue(I.getArgOperand(0)).getValueType(),
6108                              getValue(I.getArgOperand(0)),
6109                              getValue(I.getArgOperand(1))));
6110     return;
6111   case Intrinsic::maximum:
6112     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6113                              getValue(I.getArgOperand(0)).getValueType(),
6114                              getValue(I.getArgOperand(0)),
6115                              getValue(I.getArgOperand(1))));
6116     return;
6117   case Intrinsic::copysign:
6118     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6119                              getValue(I.getArgOperand(0)).getValueType(),
6120                              getValue(I.getArgOperand(0)),
6121                              getValue(I.getArgOperand(1))));
6122     return;
6123   case Intrinsic::fma:
6124     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6125                              getValue(I.getArgOperand(0)).getValueType(),
6126                              getValue(I.getArgOperand(0)),
6127                              getValue(I.getArgOperand(1)),
6128                              getValue(I.getArgOperand(2))));
6129     return;
6130 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6131   case Intrinsic::INTRINSIC:
6132 #include "llvm/IR/ConstrainedOps.def"
6133     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6134     return;
6135   case Intrinsic::fmuladd: {
6136     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6137     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6138         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6139       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6140                                getValue(I.getArgOperand(0)).getValueType(),
6141                                getValue(I.getArgOperand(0)),
6142                                getValue(I.getArgOperand(1)),
6143                                getValue(I.getArgOperand(2))));
6144     } else {
6145       // TODO: Intrinsic calls should have fast-math-flags.
6146       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6147                                 getValue(I.getArgOperand(0)).getValueType(),
6148                                 getValue(I.getArgOperand(0)),
6149                                 getValue(I.getArgOperand(1)));
6150       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6151                                 getValue(I.getArgOperand(0)).getValueType(),
6152                                 Mul,
6153                                 getValue(I.getArgOperand(2)));
6154       setValue(&I, Add);
6155     }
6156     return;
6157   }
6158   case Intrinsic::convert_to_fp16:
6159     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6160                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6161                                          getValue(I.getArgOperand(0)),
6162                                          DAG.getTargetConstant(0, sdl,
6163                                                                MVT::i32))));
6164     return;
6165   case Intrinsic::convert_from_fp16:
6166     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6167                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6168                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6169                                          getValue(I.getArgOperand(0)))));
6170     return;
6171   case Intrinsic::pcmarker: {
6172     SDValue Tmp = getValue(I.getArgOperand(0));
6173     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6174     return;
6175   }
6176   case Intrinsic::readcyclecounter: {
6177     SDValue Op = getRoot();
6178     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6179                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6180     setValue(&I, Res);
6181     DAG.setRoot(Res.getValue(1));
6182     return;
6183   }
6184   case Intrinsic::bitreverse:
6185     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6186                              getValue(I.getArgOperand(0)).getValueType(),
6187                              getValue(I.getArgOperand(0))));
6188     return;
6189   case Intrinsic::bswap:
6190     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6191                              getValue(I.getArgOperand(0)).getValueType(),
6192                              getValue(I.getArgOperand(0))));
6193     return;
6194   case Intrinsic::cttz: {
6195     SDValue Arg = getValue(I.getArgOperand(0));
6196     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6197     EVT Ty = Arg.getValueType();
6198     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6199                              sdl, Ty, Arg));
6200     return;
6201   }
6202   case Intrinsic::ctlz: {
6203     SDValue Arg = getValue(I.getArgOperand(0));
6204     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6205     EVT Ty = Arg.getValueType();
6206     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6207                              sdl, Ty, Arg));
6208     return;
6209   }
6210   case Intrinsic::ctpop: {
6211     SDValue Arg = getValue(I.getArgOperand(0));
6212     EVT Ty = Arg.getValueType();
6213     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6214     return;
6215   }
6216   case Intrinsic::fshl:
6217   case Intrinsic::fshr: {
6218     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6219     SDValue X = getValue(I.getArgOperand(0));
6220     SDValue Y = getValue(I.getArgOperand(1));
6221     SDValue Z = getValue(I.getArgOperand(2));
6222     EVT VT = X.getValueType();
6223     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6224     SDValue Zero = DAG.getConstant(0, sdl, VT);
6225     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6226 
6227     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6228     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6229       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6230       return;
6231     }
6232 
6233     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6234     // avoid the select that is necessary in the general case to filter out
6235     // the 0-shift possibility that leads to UB.
6236     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6237       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6238       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6239         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6240         return;
6241       }
6242 
6243       // Some targets only rotate one way. Try the opposite direction.
6244       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6245       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6246         // Negate the shift amount because it is safe to ignore the high bits.
6247         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6248         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6249         return;
6250       }
6251 
6252       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6253       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6254       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6255       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6256       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6257       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6258       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6259       return;
6260     }
6261 
6262     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6263     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6264     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6265     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6266     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6267     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6268 
6269     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6270     // and that is undefined. We must compare and select to avoid UB.
6271     EVT CCVT = MVT::i1;
6272     if (VT.isVector())
6273       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6274 
6275     // For fshl, 0-shift returns the 1st arg (X).
6276     // For fshr, 0-shift returns the 2nd arg (Y).
6277     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6278     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6279     return;
6280   }
6281   case Intrinsic::sadd_sat: {
6282     SDValue Op1 = getValue(I.getArgOperand(0));
6283     SDValue Op2 = getValue(I.getArgOperand(1));
6284     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6285     return;
6286   }
6287   case Intrinsic::uadd_sat: {
6288     SDValue Op1 = getValue(I.getArgOperand(0));
6289     SDValue Op2 = getValue(I.getArgOperand(1));
6290     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6291     return;
6292   }
6293   case Intrinsic::ssub_sat: {
6294     SDValue Op1 = getValue(I.getArgOperand(0));
6295     SDValue Op2 = getValue(I.getArgOperand(1));
6296     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6297     return;
6298   }
6299   case Intrinsic::usub_sat: {
6300     SDValue Op1 = getValue(I.getArgOperand(0));
6301     SDValue Op2 = getValue(I.getArgOperand(1));
6302     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6303     return;
6304   }
6305   case Intrinsic::smul_fix:
6306   case Intrinsic::umul_fix:
6307   case Intrinsic::smul_fix_sat:
6308   case Intrinsic::umul_fix_sat: {
6309     SDValue Op1 = getValue(I.getArgOperand(0));
6310     SDValue Op2 = getValue(I.getArgOperand(1));
6311     SDValue Op3 = getValue(I.getArgOperand(2));
6312     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6313                              Op1.getValueType(), Op1, Op2, Op3));
6314     return;
6315   }
6316   case Intrinsic::sdiv_fix:
6317   case Intrinsic::udiv_fix:
6318   case Intrinsic::sdiv_fix_sat:
6319   case Intrinsic::udiv_fix_sat: {
6320     SDValue Op1 = getValue(I.getArgOperand(0));
6321     SDValue Op2 = getValue(I.getArgOperand(1));
6322     SDValue Op3 = getValue(I.getArgOperand(2));
6323     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6324                               Op1, Op2, Op3, DAG, TLI));
6325     return;
6326   }
6327   case Intrinsic::stacksave: {
6328     SDValue Op = getRoot();
6329     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6330     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6331     setValue(&I, Res);
6332     DAG.setRoot(Res.getValue(1));
6333     return;
6334   }
6335   case Intrinsic::stackrestore:
6336     Res = getValue(I.getArgOperand(0));
6337     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6338     return;
6339   case Intrinsic::get_dynamic_area_offset: {
6340     SDValue Op = getRoot();
6341     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6342     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6343     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6344     // target.
6345     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6346       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6347                          " intrinsic!");
6348     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6349                       Op);
6350     DAG.setRoot(Op);
6351     setValue(&I, Res);
6352     return;
6353   }
6354   case Intrinsic::stackguard: {
6355     MachineFunction &MF = DAG.getMachineFunction();
6356     const Module &M = *MF.getFunction().getParent();
6357     SDValue Chain = getRoot();
6358     if (TLI.useLoadStackGuardNode()) {
6359       Res = getLoadStackGuard(DAG, sdl, Chain);
6360     } else {
6361       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6362       const Value *Global = TLI.getSDagStackGuard(M);
6363       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6364       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6365                         MachinePointerInfo(Global, 0), Align,
6366                         MachineMemOperand::MOVolatile);
6367     }
6368     if (TLI.useStackGuardXorFP())
6369       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6370     DAG.setRoot(Chain);
6371     setValue(&I, Res);
6372     return;
6373   }
6374   case Intrinsic::stackprotector: {
6375     // Emit code into the DAG to store the stack guard onto the stack.
6376     MachineFunction &MF = DAG.getMachineFunction();
6377     MachineFrameInfo &MFI = MF.getFrameInfo();
6378     SDValue Src, Chain = getRoot();
6379 
6380     if (TLI.useLoadStackGuardNode())
6381       Src = getLoadStackGuard(DAG, sdl, Chain);
6382     else
6383       Src = getValue(I.getArgOperand(0));   // The guard's value.
6384 
6385     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6386 
6387     int FI = FuncInfo.StaticAllocaMap[Slot];
6388     MFI.setStackProtectorIndex(FI);
6389     EVT PtrTy = Src.getValueType();
6390 
6391     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6392 
6393     // Store the stack protector onto the stack.
6394     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6395                                                  DAG.getMachineFunction(), FI),
6396                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6397     setValue(&I, Res);
6398     DAG.setRoot(Res);
6399     return;
6400   }
6401   case Intrinsic::objectsize:
6402     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6403 
6404   case Intrinsic::is_constant:
6405     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6406 
6407   case Intrinsic::annotation:
6408   case Intrinsic::ptr_annotation:
6409   case Intrinsic::launder_invariant_group:
6410   case Intrinsic::strip_invariant_group:
6411     // Drop the intrinsic, but forward the value
6412     setValue(&I, getValue(I.getOperand(0)));
6413     return;
6414   case Intrinsic::assume:
6415   case Intrinsic::var_annotation:
6416   case Intrinsic::sideeffect:
6417     // Discard annotate attributes, assumptions, and artificial side-effects.
6418     return;
6419 
6420   case Intrinsic::codeview_annotation: {
6421     // Emit a label associated with this metadata.
6422     MachineFunction &MF = DAG.getMachineFunction();
6423     MCSymbol *Label =
6424         MF.getMMI().getContext().createTempSymbol("annotation", true);
6425     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6426     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6427     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6428     DAG.setRoot(Res);
6429     return;
6430   }
6431 
6432   case Intrinsic::init_trampoline: {
6433     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6434 
6435     SDValue Ops[6];
6436     Ops[0] = getRoot();
6437     Ops[1] = getValue(I.getArgOperand(0));
6438     Ops[2] = getValue(I.getArgOperand(1));
6439     Ops[3] = getValue(I.getArgOperand(2));
6440     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6441     Ops[5] = DAG.getSrcValue(F);
6442 
6443     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6444 
6445     DAG.setRoot(Res);
6446     return;
6447   }
6448   case Intrinsic::adjust_trampoline:
6449     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6450                              TLI.getPointerTy(DAG.getDataLayout()),
6451                              getValue(I.getArgOperand(0))));
6452     return;
6453   case Intrinsic::gcroot: {
6454     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6455            "only valid in functions with gc specified, enforced by Verifier");
6456     assert(GFI && "implied by previous");
6457     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6458     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6459 
6460     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6461     GFI->addStackRoot(FI->getIndex(), TypeMap);
6462     return;
6463   }
6464   case Intrinsic::gcread:
6465   case Intrinsic::gcwrite:
6466     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6467   case Intrinsic::flt_rounds:
6468     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6469     setValue(&I, Res);
6470     DAG.setRoot(Res.getValue(1));
6471     return;
6472 
6473   case Intrinsic::expect:
6474     // Just replace __builtin_expect(exp, c) with EXP.
6475     setValue(&I, getValue(I.getArgOperand(0)));
6476     return;
6477 
6478   case Intrinsic::debugtrap:
6479   case Intrinsic::trap: {
6480     StringRef TrapFuncName =
6481         I.getAttributes()
6482             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6483             .getValueAsString();
6484     if (TrapFuncName.empty()) {
6485       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6486         ISD::TRAP : ISD::DEBUGTRAP;
6487       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6488       return;
6489     }
6490     TargetLowering::ArgListTy Args;
6491 
6492     TargetLowering::CallLoweringInfo CLI(DAG);
6493     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6494         CallingConv::C, I.getType(),
6495         DAG.getExternalSymbol(TrapFuncName.data(),
6496                               TLI.getPointerTy(DAG.getDataLayout())),
6497         std::move(Args));
6498 
6499     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6500     DAG.setRoot(Result.second);
6501     return;
6502   }
6503 
6504   case Intrinsic::uadd_with_overflow:
6505   case Intrinsic::sadd_with_overflow:
6506   case Intrinsic::usub_with_overflow:
6507   case Intrinsic::ssub_with_overflow:
6508   case Intrinsic::umul_with_overflow:
6509   case Intrinsic::smul_with_overflow: {
6510     ISD::NodeType Op;
6511     switch (Intrinsic) {
6512     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6513     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6514     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6515     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6516     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6517     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6518     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6519     }
6520     SDValue Op1 = getValue(I.getArgOperand(0));
6521     SDValue Op2 = getValue(I.getArgOperand(1));
6522 
6523     EVT ResultVT = Op1.getValueType();
6524     EVT OverflowVT = MVT::i1;
6525     if (ResultVT.isVector())
6526       OverflowVT = EVT::getVectorVT(
6527           *Context, OverflowVT, ResultVT.getVectorNumElements());
6528 
6529     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6530     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6531     return;
6532   }
6533   case Intrinsic::prefetch: {
6534     SDValue Ops[5];
6535     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6536     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6537     Ops[0] = DAG.getRoot();
6538     Ops[1] = getValue(I.getArgOperand(0));
6539     Ops[2] = getValue(I.getArgOperand(1));
6540     Ops[3] = getValue(I.getArgOperand(2));
6541     Ops[4] = getValue(I.getArgOperand(3));
6542     SDValue Result = DAG.getMemIntrinsicNode(
6543         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6544         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6545         /* align */ None, Flags);
6546 
6547     // Chain the prefetch in parallell with any pending loads, to stay out of
6548     // the way of later optimizations.
6549     PendingLoads.push_back(Result);
6550     Result = getRoot();
6551     DAG.setRoot(Result);
6552     return;
6553   }
6554   case Intrinsic::lifetime_start:
6555   case Intrinsic::lifetime_end: {
6556     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6557     // Stack coloring is not enabled in O0, discard region information.
6558     if (TM.getOptLevel() == CodeGenOpt::None)
6559       return;
6560 
6561     const int64_t ObjectSize =
6562         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6563     Value *const ObjectPtr = I.getArgOperand(1);
6564     SmallVector<const Value *, 4> Allocas;
6565     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6566 
6567     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6568            E = Allocas.end(); Object != E; ++Object) {
6569       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6570 
6571       // Could not find an Alloca.
6572       if (!LifetimeObject)
6573         continue;
6574 
6575       // First check that the Alloca is static, otherwise it won't have a
6576       // valid frame index.
6577       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6578       if (SI == FuncInfo.StaticAllocaMap.end())
6579         return;
6580 
6581       const int FrameIndex = SI->second;
6582       int64_t Offset;
6583       if (GetPointerBaseWithConstantOffset(
6584               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6585         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6586       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6587                                 Offset);
6588       DAG.setRoot(Res);
6589     }
6590     return;
6591   }
6592   case Intrinsic::invariant_start:
6593     // Discard region information.
6594     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6595     return;
6596   case Intrinsic::invariant_end:
6597     // Discard region information.
6598     return;
6599   case Intrinsic::clear_cache:
6600     /// FunctionName may be null.
6601     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6602       lowerCallToExternalSymbol(I, FunctionName);
6603     return;
6604   case Intrinsic::donothing:
6605     // ignore
6606     return;
6607   case Intrinsic::experimental_stackmap:
6608     visitStackmap(I);
6609     return;
6610   case Intrinsic::experimental_patchpoint_void:
6611   case Intrinsic::experimental_patchpoint_i64:
6612     visitPatchpoint(I);
6613     return;
6614   case Intrinsic::experimental_gc_statepoint:
6615     LowerStatepoint(ImmutableStatepoint(&I));
6616     return;
6617   case Intrinsic::experimental_gc_result:
6618     visitGCResult(cast<GCResultInst>(I));
6619     return;
6620   case Intrinsic::experimental_gc_relocate:
6621     visitGCRelocate(cast<GCRelocateInst>(I));
6622     return;
6623   case Intrinsic::instrprof_increment:
6624     llvm_unreachable("instrprof failed to lower an increment");
6625   case Intrinsic::instrprof_value_profile:
6626     llvm_unreachable("instrprof failed to lower a value profiling call");
6627   case Intrinsic::localescape: {
6628     MachineFunction &MF = DAG.getMachineFunction();
6629     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6630 
6631     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6632     // is the same on all targets.
6633     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6634       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6635       if (isa<ConstantPointerNull>(Arg))
6636         continue; // Skip null pointers. They represent a hole in index space.
6637       AllocaInst *Slot = cast<AllocaInst>(Arg);
6638       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6639              "can only escape static allocas");
6640       int FI = FuncInfo.StaticAllocaMap[Slot];
6641       MCSymbol *FrameAllocSym =
6642           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6643               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6644       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6645               TII->get(TargetOpcode::LOCAL_ESCAPE))
6646           .addSym(FrameAllocSym)
6647           .addFrameIndex(FI);
6648     }
6649 
6650     return;
6651   }
6652 
6653   case Intrinsic::localrecover: {
6654     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6655     MachineFunction &MF = DAG.getMachineFunction();
6656 
6657     // Get the symbol that defines the frame offset.
6658     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6659     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6660     unsigned IdxVal =
6661         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6662     MCSymbol *FrameAllocSym =
6663         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6664             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6665 
6666     Value *FP = I.getArgOperand(1);
6667     SDValue FPVal = getValue(FP);
6668     EVT PtrVT = FPVal.getValueType();
6669 
6670     // Create a MCSymbol for the label to avoid any target lowering
6671     // that would make this PC relative.
6672     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6673     SDValue OffsetVal =
6674         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6675 
6676     // Add the offset to the FP.
6677     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6678     setValue(&I, Add);
6679 
6680     return;
6681   }
6682 
6683   case Intrinsic::eh_exceptionpointer:
6684   case Intrinsic::eh_exceptioncode: {
6685     // Get the exception pointer vreg, copy from it, and resize it to fit.
6686     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6687     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6688     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6689     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6690     SDValue N =
6691         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6692     if (Intrinsic == Intrinsic::eh_exceptioncode)
6693       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6694     setValue(&I, N);
6695     return;
6696   }
6697   case Intrinsic::xray_customevent: {
6698     // Here we want to make sure that the intrinsic behaves as if it has a
6699     // specific calling convention, and only for x86_64.
6700     // FIXME: Support other platforms later.
6701     const auto &Triple = DAG.getTarget().getTargetTriple();
6702     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6703       return;
6704 
6705     SDLoc DL = getCurSDLoc();
6706     SmallVector<SDValue, 8> Ops;
6707 
6708     // We want to say that we always want the arguments in registers.
6709     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6710     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6711     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6712     SDValue Chain = getRoot();
6713     Ops.push_back(LogEntryVal);
6714     Ops.push_back(StrSizeVal);
6715     Ops.push_back(Chain);
6716 
6717     // We need to enforce the calling convention for the callsite, so that
6718     // argument ordering is enforced correctly, and that register allocation can
6719     // see that some registers may be assumed clobbered and have to preserve
6720     // them across calls to the intrinsic.
6721     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6722                                            DL, NodeTys, Ops);
6723     SDValue patchableNode = SDValue(MN, 0);
6724     DAG.setRoot(patchableNode);
6725     setValue(&I, patchableNode);
6726     return;
6727   }
6728   case Intrinsic::xray_typedevent: {
6729     // Here we want to make sure that the intrinsic behaves as if it has a
6730     // specific calling convention, and only for x86_64.
6731     // FIXME: Support other platforms later.
6732     const auto &Triple = DAG.getTarget().getTargetTriple();
6733     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6734       return;
6735 
6736     SDLoc DL = getCurSDLoc();
6737     SmallVector<SDValue, 8> Ops;
6738 
6739     // We want to say that we always want the arguments in registers.
6740     // It's unclear to me how manipulating the selection DAG here forces callers
6741     // to provide arguments in registers instead of on the stack.
6742     SDValue LogTypeId = getValue(I.getArgOperand(0));
6743     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6744     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6745     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6746     SDValue Chain = getRoot();
6747     Ops.push_back(LogTypeId);
6748     Ops.push_back(LogEntryVal);
6749     Ops.push_back(StrSizeVal);
6750     Ops.push_back(Chain);
6751 
6752     // We need to enforce the calling convention for the callsite, so that
6753     // argument ordering is enforced correctly, and that register allocation can
6754     // see that some registers may be assumed clobbered and have to preserve
6755     // them across calls to the intrinsic.
6756     MachineSDNode *MN = DAG.getMachineNode(
6757         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6758     SDValue patchableNode = SDValue(MN, 0);
6759     DAG.setRoot(patchableNode);
6760     setValue(&I, patchableNode);
6761     return;
6762   }
6763   case Intrinsic::experimental_deoptimize:
6764     LowerDeoptimizeCall(&I);
6765     return;
6766 
6767   case Intrinsic::experimental_vector_reduce_v2_fadd:
6768   case Intrinsic::experimental_vector_reduce_v2_fmul:
6769   case Intrinsic::experimental_vector_reduce_add:
6770   case Intrinsic::experimental_vector_reduce_mul:
6771   case Intrinsic::experimental_vector_reduce_and:
6772   case Intrinsic::experimental_vector_reduce_or:
6773   case Intrinsic::experimental_vector_reduce_xor:
6774   case Intrinsic::experimental_vector_reduce_smax:
6775   case Intrinsic::experimental_vector_reduce_smin:
6776   case Intrinsic::experimental_vector_reduce_umax:
6777   case Intrinsic::experimental_vector_reduce_umin:
6778   case Intrinsic::experimental_vector_reduce_fmax:
6779   case Intrinsic::experimental_vector_reduce_fmin:
6780     visitVectorReduce(I, Intrinsic);
6781     return;
6782 
6783   case Intrinsic::icall_branch_funnel: {
6784     SmallVector<SDValue, 16> Ops;
6785     Ops.push_back(getValue(I.getArgOperand(0)));
6786 
6787     int64_t Offset;
6788     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6789         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6790     if (!Base)
6791       report_fatal_error(
6792           "llvm.icall.branch.funnel operand must be a GlobalValue");
6793     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6794 
6795     struct BranchFunnelTarget {
6796       int64_t Offset;
6797       SDValue Target;
6798     };
6799     SmallVector<BranchFunnelTarget, 8> Targets;
6800 
6801     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6802       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6803           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6804       if (ElemBase != Base)
6805         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6806                            "to the same GlobalValue");
6807 
6808       SDValue Val = getValue(I.getArgOperand(Op + 1));
6809       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6810       if (!GA)
6811         report_fatal_error(
6812             "llvm.icall.branch.funnel operand must be a GlobalValue");
6813       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6814                                      GA->getGlobal(), getCurSDLoc(),
6815                                      Val.getValueType(), GA->getOffset())});
6816     }
6817     llvm::sort(Targets,
6818                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6819                  return T1.Offset < T2.Offset;
6820                });
6821 
6822     for (auto &T : Targets) {
6823       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6824       Ops.push_back(T.Target);
6825     }
6826 
6827     Ops.push_back(DAG.getRoot()); // Chain
6828     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6829                                  getCurSDLoc(), MVT::Other, Ops),
6830               0);
6831     DAG.setRoot(N);
6832     setValue(&I, N);
6833     HasTailCall = true;
6834     return;
6835   }
6836 
6837   case Intrinsic::wasm_landingpad_index:
6838     // Information this intrinsic contained has been transferred to
6839     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6840     // delete it now.
6841     return;
6842 
6843   case Intrinsic::aarch64_settag:
6844   case Intrinsic::aarch64_settag_zero: {
6845     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6846     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6847     SDValue Val = TSI.EmitTargetCodeForSetTag(
6848         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6849         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6850         ZeroMemory);
6851     DAG.setRoot(Val);
6852     setValue(&I, Val);
6853     return;
6854   }
6855   case Intrinsic::ptrmask: {
6856     SDValue Ptr = getValue(I.getOperand(0));
6857     SDValue Const = getValue(I.getOperand(1));
6858 
6859     EVT DestVT =
6860         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6861 
6862     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6863                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6864     return;
6865   }
6866   }
6867 }
6868 
6869 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6870     const ConstrainedFPIntrinsic &FPI) {
6871   SDLoc sdl = getCurSDLoc();
6872 
6873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6874   SmallVector<EVT, 4> ValueVTs;
6875   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6876   ValueVTs.push_back(MVT::Other); // Out chain
6877 
6878   // We do not need to serialize constrained FP intrinsics against
6879   // each other or against (nonvolatile) loads, so they can be
6880   // chained like loads.
6881   SDValue Chain = DAG.getRoot();
6882   SmallVector<SDValue, 4> Opers;
6883   Opers.push_back(Chain);
6884   if (FPI.isUnaryOp()) {
6885     Opers.push_back(getValue(FPI.getArgOperand(0)));
6886   } else if (FPI.isTernaryOp()) {
6887     Opers.push_back(getValue(FPI.getArgOperand(0)));
6888     Opers.push_back(getValue(FPI.getArgOperand(1)));
6889     Opers.push_back(getValue(FPI.getArgOperand(2)));
6890   } else {
6891     Opers.push_back(getValue(FPI.getArgOperand(0)));
6892     Opers.push_back(getValue(FPI.getArgOperand(1)));
6893   }
6894 
6895   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6896     assert(Result.getNode()->getNumValues() == 2);
6897 
6898     // Push node to the appropriate list so that future instructions can be
6899     // chained up correctly.
6900     SDValue OutChain = Result.getValue(1);
6901     switch (EB) {
6902     case fp::ExceptionBehavior::ebIgnore:
6903       // The only reason why ebIgnore nodes still need to be chained is that
6904       // they might depend on the current rounding mode, and therefore must
6905       // not be moved across instruction that may change that mode.
6906       LLVM_FALLTHROUGH;
6907     case fp::ExceptionBehavior::ebMayTrap:
6908       // These must not be moved across calls or instructions that may change
6909       // floating-point exception masks.
6910       PendingConstrainedFP.push_back(OutChain);
6911       break;
6912     case fp::ExceptionBehavior::ebStrict:
6913       // These must not be moved across calls or instructions that may change
6914       // floating-point exception masks or read floating-point exception flags.
6915       // In addition, they cannot be optimized out even if unused.
6916       PendingConstrainedFPStrict.push_back(OutChain);
6917       break;
6918     }
6919   };
6920 
6921   SDVTList VTs = DAG.getVTList(ValueVTs);
6922   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6923 
6924   SDNodeFlags Flags;
6925   if (EB == fp::ExceptionBehavior::ebIgnore)
6926     Flags.setNoFPExcept(true);
6927 
6928   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6929     Flags.copyFMF(*FPOp);
6930 
6931   unsigned Opcode;
6932   switch (FPI.getIntrinsicID()) {
6933   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6934 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6935   case Intrinsic::INTRINSIC:                                                   \
6936     Opcode = ISD::STRICT_##DAGN;                                               \
6937     break;
6938 #include "llvm/IR/ConstrainedOps.def"
6939   case Intrinsic::experimental_constrained_fmuladd: {
6940     Opcode = ISD::STRICT_FMA;
6941     // Break fmuladd into fmul and fadd.
6942     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6943         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6944                                         ValueVTs[0])) {
6945       Opers.pop_back();
6946       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6947       pushOutChain(Mul, EB);
6948       Opcode = ISD::STRICT_FADD;
6949       Opers.clear();
6950       Opers.push_back(Mul.getValue(1));
6951       Opers.push_back(Mul.getValue(0));
6952       Opers.push_back(getValue(FPI.getArgOperand(2)));
6953     }
6954     break;
6955   }
6956   }
6957 
6958   // A few strict DAG nodes carry additional operands that are not
6959   // set up by the default code above.
6960   switch (Opcode) {
6961   default: break;
6962   case ISD::STRICT_FP_ROUND:
6963     Opers.push_back(
6964         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6965     break;
6966   case ISD::STRICT_FSETCC:
6967   case ISD::STRICT_FSETCCS: {
6968     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6969     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6970     break;
6971   }
6972   }
6973 
6974   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
6975   pushOutChain(Result, EB);
6976 
6977   SDValue FPResult = Result.getValue(0);
6978   setValue(&FPI, FPResult);
6979 }
6980 
6981 std::pair<SDValue, SDValue>
6982 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6983                                     const BasicBlock *EHPadBB) {
6984   MachineFunction &MF = DAG.getMachineFunction();
6985   MachineModuleInfo &MMI = MF.getMMI();
6986   MCSymbol *BeginLabel = nullptr;
6987 
6988   if (EHPadBB) {
6989     // Insert a label before the invoke call to mark the try range.  This can be
6990     // used to detect deletion of the invoke via the MachineModuleInfo.
6991     BeginLabel = MMI.getContext().createTempSymbol();
6992 
6993     // For SjLj, keep track of which landing pads go with which invokes
6994     // so as to maintain the ordering of pads in the LSDA.
6995     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6996     if (CallSiteIndex) {
6997       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6998       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6999 
7000       // Now that the call site is handled, stop tracking it.
7001       MMI.setCurrentCallSite(0);
7002     }
7003 
7004     // Both PendingLoads and PendingExports must be flushed here;
7005     // this call might not return.
7006     (void)getRoot();
7007     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7008 
7009     CLI.setChain(getRoot());
7010   }
7011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7012   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7013 
7014   assert((CLI.IsTailCall || Result.second.getNode()) &&
7015          "Non-null chain expected with non-tail call!");
7016   assert((Result.second.getNode() || !Result.first.getNode()) &&
7017          "Null value expected with tail call!");
7018 
7019   if (!Result.second.getNode()) {
7020     // As a special case, a null chain means that a tail call has been emitted
7021     // and the DAG root is already updated.
7022     HasTailCall = true;
7023 
7024     // Since there's no actual continuation from this block, nothing can be
7025     // relying on us setting vregs for them.
7026     PendingExports.clear();
7027   } else {
7028     DAG.setRoot(Result.second);
7029   }
7030 
7031   if (EHPadBB) {
7032     // Insert a label at the end of the invoke call to mark the try range.  This
7033     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7034     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7035     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7036 
7037     // Inform MachineModuleInfo of range.
7038     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7039     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7040     // actually use outlined funclets and their LSDA info style.
7041     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7042       assert(CLI.CB);
7043       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7044       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7045     } else if (!isScopedEHPersonality(Pers)) {
7046       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7047     }
7048   }
7049 
7050   return Result;
7051 }
7052 
7053 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7054                                       bool isTailCall,
7055                                       const BasicBlock *EHPadBB) {
7056   auto &DL = DAG.getDataLayout();
7057   FunctionType *FTy = CB.getFunctionType();
7058   Type *RetTy = CB.getType();
7059 
7060   TargetLowering::ArgListTy Args;
7061   Args.reserve(CB.arg_size());
7062 
7063   const Value *SwiftErrorVal = nullptr;
7064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7065 
7066   if (isTailCall) {
7067     // Avoid emitting tail calls in functions with the disable-tail-calls
7068     // attribute.
7069     auto *Caller = CB.getParent()->getParent();
7070     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7071         "true")
7072       isTailCall = false;
7073 
7074     // We can't tail call inside a function with a swifterror argument. Lowering
7075     // does not support this yet. It would have to move into the swifterror
7076     // register before the call.
7077     if (TLI.supportSwiftError() &&
7078         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7079       isTailCall = false;
7080   }
7081 
7082   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7083     TargetLowering::ArgListEntry Entry;
7084     const Value *V = *I;
7085 
7086     // Skip empty types
7087     if (V->getType()->isEmptyTy())
7088       continue;
7089 
7090     SDValue ArgNode = getValue(V);
7091     Entry.Node = ArgNode; Entry.Ty = V->getType();
7092 
7093     Entry.setAttributes(&CB, I - CB.arg_begin());
7094 
7095     // Use swifterror virtual register as input to the call.
7096     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7097       SwiftErrorVal = V;
7098       // We find the virtual register for the actual swifterror argument.
7099       // Instead of using the Value, we use the virtual register instead.
7100       Entry.Node =
7101           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7102                           EVT(TLI.getPointerTy(DL)));
7103     }
7104 
7105     Args.push_back(Entry);
7106 
7107     // If we have an explicit sret argument that is an Instruction, (i.e., it
7108     // might point to function-local memory), we can't meaningfully tail-call.
7109     if (Entry.IsSRet && isa<Instruction>(V))
7110       isTailCall = false;
7111   }
7112 
7113   // If call site has a cfguardtarget operand bundle, create and add an
7114   // additional ArgListEntry.
7115   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7116     TargetLowering::ArgListEntry Entry;
7117     Value *V = Bundle->Inputs[0];
7118     SDValue ArgNode = getValue(V);
7119     Entry.Node = ArgNode;
7120     Entry.Ty = V->getType();
7121     Entry.IsCFGuardTarget = true;
7122     Args.push_back(Entry);
7123   }
7124 
7125   // Check if target-independent constraints permit a tail call here.
7126   // Target-dependent constraints are checked within TLI->LowerCallTo.
7127   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7128     isTailCall = false;
7129 
7130   // Disable tail calls if there is an swifterror argument. Targets have not
7131   // been updated to support tail calls.
7132   if (TLI.supportSwiftError() && SwiftErrorVal)
7133     isTailCall = false;
7134 
7135   TargetLowering::CallLoweringInfo CLI(DAG);
7136   CLI.setDebugLoc(getCurSDLoc())
7137       .setChain(getRoot())
7138       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7139       .setTailCall(isTailCall)
7140       .setConvergent(CB.isConvergent());
7141   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7142 
7143   if (Result.first.getNode()) {
7144     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7145     setValue(&CB, Result.first);
7146   }
7147 
7148   // The last element of CLI.InVals has the SDValue for swifterror return.
7149   // Here we copy it to a virtual register and update SwiftErrorMap for
7150   // book-keeping.
7151   if (SwiftErrorVal && TLI.supportSwiftError()) {
7152     // Get the last element of InVals.
7153     SDValue Src = CLI.InVals.back();
7154     Register VReg =
7155         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7156     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7157     DAG.setRoot(CopyNode);
7158   }
7159 }
7160 
7161 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7162                              SelectionDAGBuilder &Builder) {
7163   // Check to see if this load can be trivially constant folded, e.g. if the
7164   // input is from a string literal.
7165   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7166     // Cast pointer to the type we really want to load.
7167     Type *LoadTy =
7168         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7169     if (LoadVT.isVector())
7170       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7171 
7172     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7173                                          PointerType::getUnqual(LoadTy));
7174 
7175     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7176             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7177       return Builder.getValue(LoadCst);
7178   }
7179 
7180   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7181   // still constant memory, the input chain can be the entry node.
7182   SDValue Root;
7183   bool ConstantMemory = false;
7184 
7185   // Do not serialize (non-volatile) loads of constant memory with anything.
7186   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7187     Root = Builder.DAG.getEntryNode();
7188     ConstantMemory = true;
7189   } else {
7190     // Do not serialize non-volatile loads against each other.
7191     Root = Builder.DAG.getRoot();
7192   }
7193 
7194   SDValue Ptr = Builder.getValue(PtrVal);
7195   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7196                                         Ptr, MachinePointerInfo(PtrVal),
7197                                         /* Alignment = */ 1);
7198 
7199   if (!ConstantMemory)
7200     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7201   return LoadVal;
7202 }
7203 
7204 /// Record the value for an instruction that produces an integer result,
7205 /// converting the type where necessary.
7206 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7207                                                   SDValue Value,
7208                                                   bool IsSigned) {
7209   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7210                                                     I.getType(), true);
7211   if (IsSigned)
7212     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7213   else
7214     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7215   setValue(&I, Value);
7216 }
7217 
7218 /// See if we can lower a memcmp call into an optimized form. If so, return
7219 /// true and lower it. Otherwise return false, and it will be lowered like a
7220 /// normal call.
7221 /// The caller already checked that \p I calls the appropriate LibFunc with a
7222 /// correct prototype.
7223 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7224   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7225   const Value *Size = I.getArgOperand(2);
7226   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7227   if (CSize && CSize->getZExtValue() == 0) {
7228     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7229                                                           I.getType(), true);
7230     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7231     return true;
7232   }
7233 
7234   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7235   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7236       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7237       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7238   if (Res.first.getNode()) {
7239     processIntegerCallValue(I, Res.first, true);
7240     PendingLoads.push_back(Res.second);
7241     return true;
7242   }
7243 
7244   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7245   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7246   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7247     return false;
7248 
7249   // If the target has a fast compare for the given size, it will return a
7250   // preferred load type for that size. Require that the load VT is legal and
7251   // that the target supports unaligned loads of that type. Otherwise, return
7252   // INVALID.
7253   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7254     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7255     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7256     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7257       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7258       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7259       // TODO: Check alignment of src and dest ptrs.
7260       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7261       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7262       if (!TLI.isTypeLegal(LVT) ||
7263           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7264           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7265         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7266     }
7267 
7268     return LVT;
7269   };
7270 
7271   // This turns into unaligned loads. We only do this if the target natively
7272   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7273   // we'll only produce a small number of byte loads.
7274   MVT LoadVT;
7275   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7276   switch (NumBitsToCompare) {
7277   default:
7278     return false;
7279   case 16:
7280     LoadVT = MVT::i16;
7281     break;
7282   case 32:
7283     LoadVT = MVT::i32;
7284     break;
7285   case 64:
7286   case 128:
7287   case 256:
7288     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7289     break;
7290   }
7291 
7292   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7293     return false;
7294 
7295   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7296   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7297 
7298   // Bitcast to a wide integer type if the loads are vectors.
7299   if (LoadVT.isVector()) {
7300     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7301     LoadL = DAG.getBitcast(CmpVT, LoadL);
7302     LoadR = DAG.getBitcast(CmpVT, LoadR);
7303   }
7304 
7305   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7306   processIntegerCallValue(I, Cmp, false);
7307   return true;
7308 }
7309 
7310 /// See if we can lower a memchr call into an optimized form. If so, return
7311 /// true and lower it. Otherwise return false, and it will be lowered like a
7312 /// normal call.
7313 /// The caller already checked that \p I calls the appropriate LibFunc with a
7314 /// correct prototype.
7315 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7316   const Value *Src = I.getArgOperand(0);
7317   const Value *Char = I.getArgOperand(1);
7318   const Value *Length = I.getArgOperand(2);
7319 
7320   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7321   std::pair<SDValue, SDValue> Res =
7322     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7323                                 getValue(Src), getValue(Char), getValue(Length),
7324                                 MachinePointerInfo(Src));
7325   if (Res.first.getNode()) {
7326     setValue(&I, Res.first);
7327     PendingLoads.push_back(Res.second);
7328     return true;
7329   }
7330 
7331   return false;
7332 }
7333 
7334 /// See if we can lower a mempcpy call into an optimized form. If so, return
7335 /// true and lower it. Otherwise return false, and it will be lowered like a
7336 /// normal call.
7337 /// The caller already checked that \p I calls the appropriate LibFunc with a
7338 /// correct prototype.
7339 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7340   SDValue Dst = getValue(I.getArgOperand(0));
7341   SDValue Src = getValue(I.getArgOperand(1));
7342   SDValue Size = getValue(I.getArgOperand(2));
7343 
7344   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7345   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7346   // DAG::getMemcpy needs Alignment to be defined.
7347   Align Alignment = std::min(DstAlign, SrcAlign);
7348 
7349   bool isVol = false;
7350   SDLoc sdl = getCurSDLoc();
7351 
7352   // In the mempcpy context we need to pass in a false value for isTailCall
7353   // because the return pointer needs to be adjusted by the size of
7354   // the copied memory.
7355   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7356   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7357                              /*isTailCall=*/false,
7358                              MachinePointerInfo(I.getArgOperand(0)),
7359                              MachinePointerInfo(I.getArgOperand(1)));
7360   assert(MC.getNode() != nullptr &&
7361          "** memcpy should not be lowered as TailCall in mempcpy context **");
7362   DAG.setRoot(MC);
7363 
7364   // Check if Size needs to be truncated or extended.
7365   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7366 
7367   // Adjust return pointer to point just past the last dst byte.
7368   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7369                                     Dst, Size);
7370   setValue(&I, DstPlusSize);
7371   return true;
7372 }
7373 
7374 /// See if we can lower a strcpy call into an optimized form.  If so, return
7375 /// true and lower it, otherwise return false and it will be lowered like a
7376 /// normal call.
7377 /// The caller already checked that \p I calls the appropriate LibFunc with a
7378 /// correct prototype.
7379 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7380   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7381 
7382   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7383   std::pair<SDValue, SDValue> Res =
7384     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7385                                 getValue(Arg0), getValue(Arg1),
7386                                 MachinePointerInfo(Arg0),
7387                                 MachinePointerInfo(Arg1), isStpcpy);
7388   if (Res.first.getNode()) {
7389     setValue(&I, Res.first);
7390     DAG.setRoot(Res.second);
7391     return true;
7392   }
7393 
7394   return false;
7395 }
7396 
7397 /// See if we can lower a strcmp call into an optimized form.  If so, return
7398 /// true and lower it, otherwise return false and it will be lowered like a
7399 /// normal call.
7400 /// The caller already checked that \p I calls the appropriate LibFunc with a
7401 /// correct prototype.
7402 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7403   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7404 
7405   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7406   std::pair<SDValue, SDValue> Res =
7407     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7408                                 getValue(Arg0), getValue(Arg1),
7409                                 MachinePointerInfo(Arg0),
7410                                 MachinePointerInfo(Arg1));
7411   if (Res.first.getNode()) {
7412     processIntegerCallValue(I, Res.first, true);
7413     PendingLoads.push_back(Res.second);
7414     return true;
7415   }
7416 
7417   return false;
7418 }
7419 
7420 /// See if we can lower a strlen call into an optimized form.  If so, return
7421 /// true and lower it, otherwise return false and it will be lowered like a
7422 /// normal call.
7423 /// The caller already checked that \p I calls the appropriate LibFunc with a
7424 /// correct prototype.
7425 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7426   const Value *Arg0 = I.getArgOperand(0);
7427 
7428   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7429   std::pair<SDValue, SDValue> Res =
7430     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7431                                 getValue(Arg0), MachinePointerInfo(Arg0));
7432   if (Res.first.getNode()) {
7433     processIntegerCallValue(I, Res.first, false);
7434     PendingLoads.push_back(Res.second);
7435     return true;
7436   }
7437 
7438   return false;
7439 }
7440 
7441 /// See if we can lower a strnlen call into an optimized form.  If so, return
7442 /// true and lower it, otherwise return false and it will be lowered like a
7443 /// normal call.
7444 /// The caller already checked that \p I calls the appropriate LibFunc with a
7445 /// correct prototype.
7446 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7447   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7448 
7449   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7450   std::pair<SDValue, SDValue> Res =
7451     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7452                                  getValue(Arg0), getValue(Arg1),
7453                                  MachinePointerInfo(Arg0));
7454   if (Res.first.getNode()) {
7455     processIntegerCallValue(I, Res.first, false);
7456     PendingLoads.push_back(Res.second);
7457     return true;
7458   }
7459 
7460   return false;
7461 }
7462 
7463 /// See if we can lower a unary floating-point operation into an SDNode with
7464 /// the specified Opcode.  If so, return true and lower it, otherwise return
7465 /// false and it will be lowered like a normal call.
7466 /// The caller already checked that \p I calls the appropriate LibFunc with a
7467 /// correct prototype.
7468 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7469                                               unsigned Opcode) {
7470   // We already checked this call's prototype; verify it doesn't modify errno.
7471   if (!I.onlyReadsMemory())
7472     return false;
7473 
7474   SDValue Tmp = getValue(I.getArgOperand(0));
7475   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7476   return true;
7477 }
7478 
7479 /// See if we can lower a binary floating-point operation into an SDNode with
7480 /// the specified Opcode. If so, return true and lower it. Otherwise return
7481 /// false, and it will be lowered like a normal call.
7482 /// The caller already checked that \p I calls the appropriate LibFunc with a
7483 /// correct prototype.
7484 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7485                                                unsigned Opcode) {
7486   // We already checked this call's prototype; verify it doesn't modify errno.
7487   if (!I.onlyReadsMemory())
7488     return false;
7489 
7490   SDValue Tmp0 = getValue(I.getArgOperand(0));
7491   SDValue Tmp1 = getValue(I.getArgOperand(1));
7492   EVT VT = Tmp0.getValueType();
7493   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7494   return true;
7495 }
7496 
7497 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7498   // Handle inline assembly differently.
7499   if (isa<InlineAsm>(I.getCalledValue())) {
7500     visitInlineAsm(I);
7501     return;
7502   }
7503 
7504   if (Function *F = I.getCalledFunction()) {
7505     if (F->isDeclaration()) {
7506       // Is this an LLVM intrinsic or a target-specific intrinsic?
7507       unsigned IID = F->getIntrinsicID();
7508       if (!IID)
7509         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7510           IID = II->getIntrinsicID(F);
7511 
7512       if (IID) {
7513         visitIntrinsicCall(I, IID);
7514         return;
7515       }
7516     }
7517 
7518     // Check for well-known libc/libm calls.  If the function is internal, it
7519     // can't be a library call.  Don't do the check if marked as nobuiltin for
7520     // some reason or the call site requires strict floating point semantics.
7521     LibFunc Func;
7522     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7523         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7524         LibInfo->hasOptimizedCodeGen(Func)) {
7525       switch (Func) {
7526       default: break;
7527       case LibFunc_copysign:
7528       case LibFunc_copysignf:
7529       case LibFunc_copysignl:
7530         // We already checked this call's prototype; verify it doesn't modify
7531         // errno.
7532         if (I.onlyReadsMemory()) {
7533           SDValue LHS = getValue(I.getArgOperand(0));
7534           SDValue RHS = getValue(I.getArgOperand(1));
7535           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7536                                    LHS.getValueType(), LHS, RHS));
7537           return;
7538         }
7539         break;
7540       case LibFunc_fabs:
7541       case LibFunc_fabsf:
7542       case LibFunc_fabsl:
7543         if (visitUnaryFloatCall(I, ISD::FABS))
7544           return;
7545         break;
7546       case LibFunc_fmin:
7547       case LibFunc_fminf:
7548       case LibFunc_fminl:
7549         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7550           return;
7551         break;
7552       case LibFunc_fmax:
7553       case LibFunc_fmaxf:
7554       case LibFunc_fmaxl:
7555         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7556           return;
7557         break;
7558       case LibFunc_sin:
7559       case LibFunc_sinf:
7560       case LibFunc_sinl:
7561         if (visitUnaryFloatCall(I, ISD::FSIN))
7562           return;
7563         break;
7564       case LibFunc_cos:
7565       case LibFunc_cosf:
7566       case LibFunc_cosl:
7567         if (visitUnaryFloatCall(I, ISD::FCOS))
7568           return;
7569         break;
7570       case LibFunc_sqrt:
7571       case LibFunc_sqrtf:
7572       case LibFunc_sqrtl:
7573       case LibFunc_sqrt_finite:
7574       case LibFunc_sqrtf_finite:
7575       case LibFunc_sqrtl_finite:
7576         if (visitUnaryFloatCall(I, ISD::FSQRT))
7577           return;
7578         break;
7579       case LibFunc_floor:
7580       case LibFunc_floorf:
7581       case LibFunc_floorl:
7582         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7583           return;
7584         break;
7585       case LibFunc_nearbyint:
7586       case LibFunc_nearbyintf:
7587       case LibFunc_nearbyintl:
7588         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7589           return;
7590         break;
7591       case LibFunc_ceil:
7592       case LibFunc_ceilf:
7593       case LibFunc_ceill:
7594         if (visitUnaryFloatCall(I, ISD::FCEIL))
7595           return;
7596         break;
7597       case LibFunc_rint:
7598       case LibFunc_rintf:
7599       case LibFunc_rintl:
7600         if (visitUnaryFloatCall(I, ISD::FRINT))
7601           return;
7602         break;
7603       case LibFunc_round:
7604       case LibFunc_roundf:
7605       case LibFunc_roundl:
7606         if (visitUnaryFloatCall(I, ISD::FROUND))
7607           return;
7608         break;
7609       case LibFunc_trunc:
7610       case LibFunc_truncf:
7611       case LibFunc_truncl:
7612         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7613           return;
7614         break;
7615       case LibFunc_log2:
7616       case LibFunc_log2f:
7617       case LibFunc_log2l:
7618         if (visitUnaryFloatCall(I, ISD::FLOG2))
7619           return;
7620         break;
7621       case LibFunc_exp2:
7622       case LibFunc_exp2f:
7623       case LibFunc_exp2l:
7624         if (visitUnaryFloatCall(I, ISD::FEXP2))
7625           return;
7626         break;
7627       case LibFunc_memcmp:
7628         if (visitMemCmpCall(I))
7629           return;
7630         break;
7631       case LibFunc_mempcpy:
7632         if (visitMemPCpyCall(I))
7633           return;
7634         break;
7635       case LibFunc_memchr:
7636         if (visitMemChrCall(I))
7637           return;
7638         break;
7639       case LibFunc_strcpy:
7640         if (visitStrCpyCall(I, false))
7641           return;
7642         break;
7643       case LibFunc_stpcpy:
7644         if (visitStrCpyCall(I, true))
7645           return;
7646         break;
7647       case LibFunc_strcmp:
7648         if (visitStrCmpCall(I))
7649           return;
7650         break;
7651       case LibFunc_strlen:
7652         if (visitStrLenCall(I))
7653           return;
7654         break;
7655       case LibFunc_strnlen:
7656         if (visitStrNLenCall(I))
7657           return;
7658         break;
7659       }
7660     }
7661   }
7662 
7663   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7664   // have to do anything here to lower funclet bundles.
7665   // CFGuardTarget bundles are lowered in LowerCallTo.
7666   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7667                                         LLVMContext::OB_funclet,
7668                                         LLVMContext::OB_cfguardtarget}) &&
7669          "Cannot lower calls with arbitrary operand bundles!");
7670 
7671   SDValue Callee = getValue(I.getCalledValue());
7672 
7673   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7674     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7675   else
7676     // Check if we can potentially perform a tail call. More detailed checking
7677     // is be done within LowerCallTo, after more information about the call is
7678     // known.
7679     LowerCallTo(I, Callee, I.isTailCall());
7680 }
7681 
7682 namespace {
7683 
7684 /// AsmOperandInfo - This contains information for each constraint that we are
7685 /// lowering.
7686 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7687 public:
7688   /// CallOperand - If this is the result output operand or a clobber
7689   /// this is null, otherwise it is the incoming operand to the CallInst.
7690   /// This gets modified as the asm is processed.
7691   SDValue CallOperand;
7692 
7693   /// AssignedRegs - If this is a register or register class operand, this
7694   /// contains the set of register corresponding to the operand.
7695   RegsForValue AssignedRegs;
7696 
7697   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7698     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7699   }
7700 
7701   /// Whether or not this operand accesses memory
7702   bool hasMemory(const TargetLowering &TLI) const {
7703     // Indirect operand accesses access memory.
7704     if (isIndirect)
7705       return true;
7706 
7707     for (const auto &Code : Codes)
7708       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7709         return true;
7710 
7711     return false;
7712   }
7713 
7714   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7715   /// corresponds to.  If there is no Value* for this operand, it returns
7716   /// MVT::Other.
7717   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7718                            const DataLayout &DL) const {
7719     if (!CallOperandVal) return MVT::Other;
7720 
7721     if (isa<BasicBlock>(CallOperandVal))
7722       return TLI.getProgramPointerTy(DL);
7723 
7724     llvm::Type *OpTy = CallOperandVal->getType();
7725 
7726     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7727     // If this is an indirect operand, the operand is a pointer to the
7728     // accessed type.
7729     if (isIndirect) {
7730       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7731       if (!PtrTy)
7732         report_fatal_error("Indirect operand for inline asm not a pointer!");
7733       OpTy = PtrTy->getElementType();
7734     }
7735 
7736     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7737     if (StructType *STy = dyn_cast<StructType>(OpTy))
7738       if (STy->getNumElements() == 1)
7739         OpTy = STy->getElementType(0);
7740 
7741     // If OpTy is not a single value, it may be a struct/union that we
7742     // can tile with integers.
7743     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7744       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7745       switch (BitSize) {
7746       default: break;
7747       case 1:
7748       case 8:
7749       case 16:
7750       case 32:
7751       case 64:
7752       case 128:
7753         OpTy = IntegerType::get(Context, BitSize);
7754         break;
7755       }
7756     }
7757 
7758     return TLI.getValueType(DL, OpTy, true);
7759   }
7760 };
7761 
7762 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7763 
7764 } // end anonymous namespace
7765 
7766 /// Make sure that the output operand \p OpInfo and its corresponding input
7767 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7768 /// out).
7769 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7770                                SDISelAsmOperandInfo &MatchingOpInfo,
7771                                SelectionDAG &DAG) {
7772   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7773     return;
7774 
7775   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7776   const auto &TLI = DAG.getTargetLoweringInfo();
7777 
7778   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7779       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7780                                        OpInfo.ConstraintVT);
7781   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7782       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7783                                        MatchingOpInfo.ConstraintVT);
7784   if ((OpInfo.ConstraintVT.isInteger() !=
7785        MatchingOpInfo.ConstraintVT.isInteger()) ||
7786       (MatchRC.second != InputRC.second)) {
7787     // FIXME: error out in a more elegant fashion
7788     report_fatal_error("Unsupported asm: input constraint"
7789                        " with a matching output constraint of"
7790                        " incompatible type!");
7791   }
7792   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7793 }
7794 
7795 /// Get a direct memory input to behave well as an indirect operand.
7796 /// This may introduce stores, hence the need for a \p Chain.
7797 /// \return The (possibly updated) chain.
7798 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7799                                         SDISelAsmOperandInfo &OpInfo,
7800                                         SelectionDAG &DAG) {
7801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7802 
7803   // If we don't have an indirect input, put it in the constpool if we can,
7804   // otherwise spill it to a stack slot.
7805   // TODO: This isn't quite right. We need to handle these according to
7806   // the addressing mode that the constraint wants. Also, this may take
7807   // an additional register for the computation and we don't want that
7808   // either.
7809 
7810   // If the operand is a float, integer, or vector constant, spill to a
7811   // constant pool entry to get its address.
7812   const Value *OpVal = OpInfo.CallOperandVal;
7813   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7814       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7815     OpInfo.CallOperand = DAG.getConstantPool(
7816         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7817     return Chain;
7818   }
7819 
7820   // Otherwise, create a stack slot and emit a store to it before the asm.
7821   Type *Ty = OpVal->getType();
7822   auto &DL = DAG.getDataLayout();
7823   uint64_t TySize = DL.getTypeAllocSize(Ty);
7824   unsigned Align = DL.getPrefTypeAlignment(Ty);
7825   MachineFunction &MF = DAG.getMachineFunction();
7826   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7827   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7828   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7829                             MachinePointerInfo::getFixedStack(MF, SSFI),
7830                             TLI.getMemValueType(DL, Ty));
7831   OpInfo.CallOperand = StackSlot;
7832 
7833   return Chain;
7834 }
7835 
7836 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7837 /// specified operand.  We prefer to assign virtual registers, to allow the
7838 /// register allocator to handle the assignment process.  However, if the asm
7839 /// uses features that we can't model on machineinstrs, we have SDISel do the
7840 /// allocation.  This produces generally horrible, but correct, code.
7841 ///
7842 ///   OpInfo describes the operand
7843 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7844 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7845                                  SDISelAsmOperandInfo &OpInfo,
7846                                  SDISelAsmOperandInfo &RefOpInfo) {
7847   LLVMContext &Context = *DAG.getContext();
7848   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7849 
7850   MachineFunction &MF = DAG.getMachineFunction();
7851   SmallVector<unsigned, 4> Regs;
7852   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7853 
7854   // No work to do for memory operations.
7855   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7856     return;
7857 
7858   // If this is a constraint for a single physreg, or a constraint for a
7859   // register class, find it.
7860   unsigned AssignedReg;
7861   const TargetRegisterClass *RC;
7862   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7863       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7864   // RC is unset only on failure. Return immediately.
7865   if (!RC)
7866     return;
7867 
7868   // Get the actual register value type.  This is important, because the user
7869   // may have asked for (e.g.) the AX register in i32 type.  We need to
7870   // remember that AX is actually i16 to get the right extension.
7871   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7872 
7873   if (OpInfo.ConstraintVT != MVT::Other) {
7874     // If this is an FP operand in an integer register (or visa versa), or more
7875     // generally if the operand value disagrees with the register class we plan
7876     // to stick it in, fix the operand type.
7877     //
7878     // If this is an input value, the bitcast to the new type is done now.
7879     // Bitcast for output value is done at the end of visitInlineAsm().
7880     if ((OpInfo.Type == InlineAsm::isOutput ||
7881          OpInfo.Type == InlineAsm::isInput) &&
7882         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7883       // Try to convert to the first EVT that the reg class contains.  If the
7884       // types are identical size, use a bitcast to convert (e.g. two differing
7885       // vector types).  Note: output bitcast is done at the end of
7886       // visitInlineAsm().
7887       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7888         // Exclude indirect inputs while they are unsupported because the code
7889         // to perform the load is missing and thus OpInfo.CallOperand still
7890         // refers to the input address rather than the pointed-to value.
7891         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7892           OpInfo.CallOperand =
7893               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7894         OpInfo.ConstraintVT = RegVT;
7895         // If the operand is an FP value and we want it in integer registers,
7896         // use the corresponding integer type. This turns an f64 value into
7897         // i64, which can be passed with two i32 values on a 32-bit machine.
7898       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7899         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7900         if (OpInfo.Type == InlineAsm::isInput)
7901           OpInfo.CallOperand =
7902               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7903         OpInfo.ConstraintVT = VT;
7904       }
7905     }
7906   }
7907 
7908   // No need to allocate a matching input constraint since the constraint it's
7909   // matching to has already been allocated.
7910   if (OpInfo.isMatchingInputConstraint())
7911     return;
7912 
7913   EVT ValueVT = OpInfo.ConstraintVT;
7914   if (OpInfo.ConstraintVT == MVT::Other)
7915     ValueVT = RegVT;
7916 
7917   // Initialize NumRegs.
7918   unsigned NumRegs = 1;
7919   if (OpInfo.ConstraintVT != MVT::Other)
7920     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7921 
7922   // If this is a constraint for a specific physical register, like {r17},
7923   // assign it now.
7924 
7925   // If this associated to a specific register, initialize iterator to correct
7926   // place. If virtual, make sure we have enough registers
7927 
7928   // Initialize iterator if necessary
7929   TargetRegisterClass::iterator I = RC->begin();
7930   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7931 
7932   // Do not check for single registers.
7933   if (AssignedReg) {
7934       for (; *I != AssignedReg; ++I)
7935         assert(I != RC->end() && "AssignedReg should be member of RC");
7936   }
7937 
7938   for (; NumRegs; --NumRegs, ++I) {
7939     assert(I != RC->end() && "Ran out of registers to allocate!");
7940     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7941     Regs.push_back(R);
7942   }
7943 
7944   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7945 }
7946 
7947 static unsigned
7948 findMatchingInlineAsmOperand(unsigned OperandNo,
7949                              const std::vector<SDValue> &AsmNodeOperands) {
7950   // Scan until we find the definition we already emitted of this operand.
7951   unsigned CurOp = InlineAsm::Op_FirstOperand;
7952   for (; OperandNo; --OperandNo) {
7953     // Advance to the next operand.
7954     unsigned OpFlag =
7955         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7956     assert((InlineAsm::isRegDefKind(OpFlag) ||
7957             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7958             InlineAsm::isMemKind(OpFlag)) &&
7959            "Skipped past definitions?");
7960     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7961   }
7962   return CurOp;
7963 }
7964 
7965 namespace {
7966 
7967 class ExtraFlags {
7968   unsigned Flags = 0;
7969 
7970 public:
7971   explicit ExtraFlags(const CallBase &Call) {
7972     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue());
7973     if (IA->hasSideEffects())
7974       Flags |= InlineAsm::Extra_HasSideEffects;
7975     if (IA->isAlignStack())
7976       Flags |= InlineAsm::Extra_IsAlignStack;
7977     if (Call.isConvergent())
7978       Flags |= InlineAsm::Extra_IsConvergent;
7979     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7980   }
7981 
7982   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7983     // Ideally, we would only check against memory constraints.  However, the
7984     // meaning of an Other constraint can be target-specific and we can't easily
7985     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7986     // for Other constraints as well.
7987     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7988         OpInfo.ConstraintType == TargetLowering::C_Other) {
7989       if (OpInfo.Type == InlineAsm::isInput)
7990         Flags |= InlineAsm::Extra_MayLoad;
7991       else if (OpInfo.Type == InlineAsm::isOutput)
7992         Flags |= InlineAsm::Extra_MayStore;
7993       else if (OpInfo.Type == InlineAsm::isClobber)
7994         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7995     }
7996   }
7997 
7998   unsigned get() const { return Flags; }
7999 };
8000 
8001 } // end anonymous namespace
8002 
8003 /// visitInlineAsm - Handle a call to an InlineAsm object.
8004 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8005   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue());
8006 
8007   /// ConstraintOperands - Information about all of the constraints.
8008   SDISelAsmOperandInfoVector ConstraintOperands;
8009 
8010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8011   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8012       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8013 
8014   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8015   // AsmDialect, MayLoad, MayStore).
8016   bool HasSideEffect = IA->hasSideEffects();
8017   ExtraFlags ExtraInfo(Call);
8018 
8019   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8020   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8021   unsigned NumMatchingOps = 0;
8022   for (auto &T : TargetConstraints) {
8023     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8024     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8025 
8026     // Compute the value type for each operand.
8027     if (OpInfo.Type == InlineAsm::isInput ||
8028         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8029       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8030 
8031       // Process the call argument. BasicBlocks are labels, currently appearing
8032       // only in asm's.
8033       if (isa<CallBrInst>(Call) &&
8034           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8035                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8036                         NumMatchingOps) &&
8037           (NumMatchingOps == 0 ||
8038            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8039                         NumMatchingOps))) {
8040         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8041         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8042         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8043       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8044         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8045       } else {
8046         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8047       }
8048 
8049       OpInfo.ConstraintVT =
8050           OpInfo
8051               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8052               .getSimpleVT();
8053     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8054       // The return value of the call is this value.  As such, there is no
8055       // corresponding argument.
8056       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8057       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8058         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8059             DAG.getDataLayout(), STy->getElementType(ResNo));
8060       } else {
8061         assert(ResNo == 0 && "Asm only has one result!");
8062         OpInfo.ConstraintVT =
8063             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8064       }
8065       ++ResNo;
8066     } else {
8067       OpInfo.ConstraintVT = MVT::Other;
8068     }
8069 
8070     if (OpInfo.hasMatchingInput())
8071       ++NumMatchingOps;
8072 
8073     if (!HasSideEffect)
8074       HasSideEffect = OpInfo.hasMemory(TLI);
8075 
8076     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8077     // FIXME: Could we compute this on OpInfo rather than T?
8078 
8079     // Compute the constraint code and ConstraintType to use.
8080     TLI.ComputeConstraintToUse(T, SDValue());
8081 
8082     if (T.ConstraintType == TargetLowering::C_Immediate &&
8083         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8084       // We've delayed emitting a diagnostic like the "n" constraint because
8085       // inlining could cause an integer showing up.
8086       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8087                                           "' expects an integer constant "
8088                                           "expression");
8089 
8090     ExtraInfo.update(T);
8091   }
8092 
8093 
8094   // We won't need to flush pending loads if this asm doesn't touch
8095   // memory and is nonvolatile.
8096   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8097 
8098   bool IsCallBr = isa<CallBrInst>(Call);
8099   if (IsCallBr) {
8100     // If this is a callbr we need to flush pending exports since inlineasm_br
8101     // is a terminator. We need to do this before nodes are glued to
8102     // the inlineasm_br node.
8103     Chain = getControlRoot();
8104   }
8105 
8106   // Second pass over the constraints: compute which constraint option to use.
8107   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8108     // If this is an output operand with a matching input operand, look up the
8109     // matching input. If their types mismatch, e.g. one is an integer, the
8110     // other is floating point, or their sizes are different, flag it as an
8111     // error.
8112     if (OpInfo.hasMatchingInput()) {
8113       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8114       patchMatchingInput(OpInfo, Input, DAG);
8115     }
8116 
8117     // Compute the constraint code and ConstraintType to use.
8118     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8119 
8120     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8121         OpInfo.Type == InlineAsm::isClobber)
8122       continue;
8123 
8124     // If this is a memory input, and if the operand is not indirect, do what we
8125     // need to provide an address for the memory input.
8126     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8127         !OpInfo.isIndirect) {
8128       assert((OpInfo.isMultipleAlternative ||
8129               (OpInfo.Type == InlineAsm::isInput)) &&
8130              "Can only indirectify direct input operands!");
8131 
8132       // Memory operands really want the address of the value.
8133       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8134 
8135       // There is no longer a Value* corresponding to this operand.
8136       OpInfo.CallOperandVal = nullptr;
8137 
8138       // It is now an indirect operand.
8139       OpInfo.isIndirect = true;
8140     }
8141 
8142   }
8143 
8144   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8145   std::vector<SDValue> AsmNodeOperands;
8146   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8147   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8148       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8149 
8150   // If we have a !srcloc metadata node associated with it, we want to attach
8151   // this to the ultimately generated inline asm machineinstr.  To do this, we
8152   // pass in the third operand as this (potentially null) inline asm MDNode.
8153   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8154   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8155 
8156   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8157   // bits as operand 3.
8158   AsmNodeOperands.push_back(DAG.getTargetConstant(
8159       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8160 
8161   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8162   // this, assign virtual and physical registers for inputs and otput.
8163   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8164     // Assign Registers.
8165     SDISelAsmOperandInfo &RefOpInfo =
8166         OpInfo.isMatchingInputConstraint()
8167             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8168             : OpInfo;
8169     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8170 
8171     auto DetectWriteToReservedRegister = [&]() {
8172       const MachineFunction &MF = DAG.getMachineFunction();
8173       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8174       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8175         if (Register::isPhysicalRegister(Reg) &&
8176             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8177           const char *RegName = TRI.getName(Reg);
8178           emitInlineAsmError(CS, "write to reserved register '" +
8179                                      Twine(RegName) + "'");
8180           return true;
8181         }
8182       }
8183       return false;
8184     };
8185 
8186     switch (OpInfo.Type) {
8187     case InlineAsm::isOutput:
8188       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8189         unsigned ConstraintID =
8190             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8191         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8192                "Failed to convert memory constraint code to constraint id.");
8193 
8194         // Add information to the INLINEASM node to know about this output.
8195         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8196         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8197         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8198                                                         MVT::i32));
8199         AsmNodeOperands.push_back(OpInfo.CallOperand);
8200       } else {
8201         // Otherwise, this outputs to a register (directly for C_Register /
8202         // C_RegisterClass, and a target-defined fashion for
8203         // C_Immediate/C_Other). Find a register that we can use.
8204         if (OpInfo.AssignedRegs.Regs.empty()) {
8205           emitInlineAsmError(
8206               Call, "couldn't allocate output register for constraint '" +
8207                         Twine(OpInfo.ConstraintCode) + "'");
8208           return;
8209         }
8210 
8211         if (DetectWriteToReservedRegister())
8212           return;
8213 
8214         // Add information to the INLINEASM node to know that this register is
8215         // set.
8216         OpInfo.AssignedRegs.AddInlineAsmOperands(
8217             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8218                                   : InlineAsm::Kind_RegDef,
8219             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8220       }
8221       break;
8222 
8223     case InlineAsm::isInput: {
8224       SDValue InOperandVal = OpInfo.CallOperand;
8225 
8226       if (OpInfo.isMatchingInputConstraint()) {
8227         // If this is required to match an output register we have already set,
8228         // just use its register.
8229         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8230                                                   AsmNodeOperands);
8231         unsigned OpFlag =
8232           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8233         if (InlineAsm::isRegDefKind(OpFlag) ||
8234             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8235           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8236           if (OpInfo.isIndirect) {
8237             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8238             emitInlineAsmError(Call, "inline asm not supported yet: "
8239                                      "don't know how to handle tied "
8240                                      "indirect register inputs");
8241             return;
8242           }
8243 
8244           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8245           SmallVector<unsigned, 4> Regs;
8246 
8247           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8248             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8249             MachineRegisterInfo &RegInfo =
8250                 DAG.getMachineFunction().getRegInfo();
8251             for (unsigned i = 0; i != NumRegs; ++i)
8252               Regs.push_back(RegInfo.createVirtualRegister(RC));
8253           } else {
8254             emitInlineAsmError(Call,
8255                                "inline asm error: This value type register "
8256                                "class is not natively supported!");
8257             return;
8258           }
8259 
8260           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8261 
8262           SDLoc dl = getCurSDLoc();
8263           // Use the produced MatchedRegs object to
8264           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8265           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8266                                            true, OpInfo.getMatchedOperand(), dl,
8267                                            DAG, AsmNodeOperands);
8268           break;
8269         }
8270 
8271         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8272         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8273                "Unexpected number of operands");
8274         // Add information to the INLINEASM node to know about this input.
8275         // See InlineAsm.h isUseOperandTiedToDef.
8276         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8277         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8278                                                     OpInfo.getMatchedOperand());
8279         AsmNodeOperands.push_back(DAG.getTargetConstant(
8280             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8281         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8282         break;
8283       }
8284 
8285       // Treat indirect 'X' constraint as memory.
8286       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8287           OpInfo.isIndirect)
8288         OpInfo.ConstraintType = TargetLowering::C_Memory;
8289 
8290       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8291           OpInfo.ConstraintType == TargetLowering::C_Other) {
8292         std::vector<SDValue> Ops;
8293         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8294                                           Ops, DAG);
8295         if (Ops.empty()) {
8296           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8297             if (isa<ConstantSDNode>(InOperandVal)) {
8298               emitInlineAsmError(Call, "value out of range for constraint '" +
8299                                            Twine(OpInfo.ConstraintCode) + "'");
8300               return;
8301             }
8302 
8303           emitInlineAsmError(Call,
8304                              "invalid operand for inline asm constraint '" +
8305                                  Twine(OpInfo.ConstraintCode) + "'");
8306           return;
8307         }
8308 
8309         // Add information to the INLINEASM node to know about this input.
8310         unsigned ResOpType =
8311           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8312         AsmNodeOperands.push_back(DAG.getTargetConstant(
8313             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8314         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8315         break;
8316       }
8317 
8318       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8319         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8320         assert(InOperandVal.getValueType() ==
8321                    TLI.getPointerTy(DAG.getDataLayout()) &&
8322                "Memory operands expect pointer values");
8323 
8324         unsigned ConstraintID =
8325             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8326         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8327                "Failed to convert memory constraint code to constraint id.");
8328 
8329         // Add information to the INLINEASM node to know about this input.
8330         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8331         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8332         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8333                                                         getCurSDLoc(),
8334                                                         MVT::i32));
8335         AsmNodeOperands.push_back(InOperandVal);
8336         break;
8337       }
8338 
8339       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8340               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8341              "Unknown constraint type!");
8342 
8343       // TODO: Support this.
8344       if (OpInfo.isIndirect) {
8345         emitInlineAsmError(
8346             Call, "Don't know how to handle indirect register inputs yet "
8347                   "for constraint '" +
8348                       Twine(OpInfo.ConstraintCode) + "'");
8349         return;
8350       }
8351 
8352       // Copy the input into the appropriate registers.
8353       if (OpInfo.AssignedRegs.Regs.empty()) {
8354         emitInlineAsmError(Call,
8355                            "couldn't allocate input reg for constraint '" +
8356                                Twine(OpInfo.ConstraintCode) + "'");
8357         return;
8358       }
8359 
8360       if (DetectWriteToReservedRegister())
8361         return;
8362 
8363       SDLoc dl = getCurSDLoc();
8364 
8365       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8366                                         &Call);
8367 
8368       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8369                                                dl, DAG, AsmNodeOperands);
8370       break;
8371     }
8372     case InlineAsm::isClobber:
8373       // Add the clobbered value to the operand list, so that the register
8374       // allocator is aware that the physreg got clobbered.
8375       if (!OpInfo.AssignedRegs.Regs.empty())
8376         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8377                                                  false, 0, getCurSDLoc(), DAG,
8378                                                  AsmNodeOperands);
8379       break;
8380     }
8381   }
8382 
8383   // Finish up input operands.  Set the input chain and add the flag last.
8384   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8385   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8386 
8387   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8388   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8389                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8390   Flag = Chain.getValue(1);
8391 
8392   // Do additional work to generate outputs.
8393 
8394   SmallVector<EVT, 1> ResultVTs;
8395   SmallVector<SDValue, 1> ResultValues;
8396   SmallVector<SDValue, 8> OutChains;
8397 
8398   llvm::Type *CallResultType = Call.getType();
8399   ArrayRef<Type *> ResultTypes;
8400   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8401     ResultTypes = StructResult->elements();
8402   else if (!CallResultType->isVoidTy())
8403     ResultTypes = makeArrayRef(CallResultType);
8404 
8405   auto CurResultType = ResultTypes.begin();
8406   auto handleRegAssign = [&](SDValue V) {
8407     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8408     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8409     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8410     ++CurResultType;
8411     // If the type of the inline asm call site return value is different but has
8412     // same size as the type of the asm output bitcast it.  One example of this
8413     // is for vectors with different width / number of elements.  This can
8414     // happen for register classes that can contain multiple different value
8415     // types.  The preg or vreg allocated may not have the same VT as was
8416     // expected.
8417     //
8418     // This can also happen for a return value that disagrees with the register
8419     // class it is put in, eg. a double in a general-purpose register on a
8420     // 32-bit machine.
8421     if (ResultVT != V.getValueType() &&
8422         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8423       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8424     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8425              V.getValueType().isInteger()) {
8426       // If a result value was tied to an input value, the computed result
8427       // may have a wider width than the expected result.  Extract the
8428       // relevant portion.
8429       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8430     }
8431     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8432     ResultVTs.push_back(ResultVT);
8433     ResultValues.push_back(V);
8434   };
8435 
8436   // Deal with output operands.
8437   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8438     if (OpInfo.Type == InlineAsm::isOutput) {
8439       SDValue Val;
8440       // Skip trivial output operands.
8441       if (OpInfo.AssignedRegs.Regs.empty())
8442         continue;
8443 
8444       switch (OpInfo.ConstraintType) {
8445       case TargetLowering::C_Register:
8446       case TargetLowering::C_RegisterClass:
8447         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8448                                                   Chain, &Flag, &Call);
8449         break;
8450       case TargetLowering::C_Immediate:
8451       case TargetLowering::C_Other:
8452         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8453                                               OpInfo, DAG);
8454         break;
8455       case TargetLowering::C_Memory:
8456         break; // Already handled.
8457       case TargetLowering::C_Unknown:
8458         assert(false && "Unexpected unknown constraint");
8459       }
8460 
8461       // Indirect output manifest as stores. Record output chains.
8462       if (OpInfo.isIndirect) {
8463         const Value *Ptr = OpInfo.CallOperandVal;
8464         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8465         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8466                                      MachinePointerInfo(Ptr));
8467         OutChains.push_back(Store);
8468       } else {
8469         // generate CopyFromRegs to associated registers.
8470         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8471         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8472           for (const SDValue &V : Val->op_values())
8473             handleRegAssign(V);
8474         } else
8475           handleRegAssign(Val);
8476       }
8477     }
8478   }
8479 
8480   // Set results.
8481   if (!ResultValues.empty()) {
8482     assert(CurResultType == ResultTypes.end() &&
8483            "Mismatch in number of ResultTypes");
8484     assert(ResultValues.size() == ResultTypes.size() &&
8485            "Mismatch in number of output operands in asm result");
8486 
8487     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8488                             DAG.getVTList(ResultVTs), ResultValues);
8489     setValue(&Call, V);
8490   }
8491 
8492   // Collect store chains.
8493   if (!OutChains.empty())
8494     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8495 
8496   // Only Update Root if inline assembly has a memory effect.
8497   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8498     DAG.setRoot(Chain);
8499 }
8500 
8501 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8502                                              const Twine &Message) {
8503   LLVMContext &Ctx = *DAG.getContext();
8504   Ctx.emitError(&Call, Message);
8505 
8506   // Make sure we leave the DAG in a valid state
8507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8508   SmallVector<EVT, 1> ValueVTs;
8509   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8510 
8511   if (ValueVTs.empty())
8512     return;
8513 
8514   SmallVector<SDValue, 1> Ops;
8515   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8516     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8517 
8518   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8519 }
8520 
8521 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8522   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8523                           MVT::Other, getRoot(),
8524                           getValue(I.getArgOperand(0)),
8525                           DAG.getSrcValue(I.getArgOperand(0))));
8526 }
8527 
8528 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8530   const DataLayout &DL = DAG.getDataLayout();
8531   SDValue V = DAG.getVAArg(
8532       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8533       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8534       DL.getABITypeAlignment(I.getType()));
8535   DAG.setRoot(V.getValue(1));
8536 
8537   if (I.getType()->isPointerTy())
8538     V = DAG.getPtrExtOrTrunc(
8539         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8540   setValue(&I, V);
8541 }
8542 
8543 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8544   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8545                           MVT::Other, getRoot(),
8546                           getValue(I.getArgOperand(0)),
8547                           DAG.getSrcValue(I.getArgOperand(0))));
8548 }
8549 
8550 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8551   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8552                           MVT::Other, getRoot(),
8553                           getValue(I.getArgOperand(0)),
8554                           getValue(I.getArgOperand(1)),
8555                           DAG.getSrcValue(I.getArgOperand(0)),
8556                           DAG.getSrcValue(I.getArgOperand(1))));
8557 }
8558 
8559 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8560                                                     const Instruction &I,
8561                                                     SDValue Op) {
8562   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8563   if (!Range)
8564     return Op;
8565 
8566   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8567   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8568     return Op;
8569 
8570   APInt Lo = CR.getUnsignedMin();
8571   if (!Lo.isMinValue())
8572     return Op;
8573 
8574   APInt Hi = CR.getUnsignedMax();
8575   unsigned Bits = std::max(Hi.getActiveBits(),
8576                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8577 
8578   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8579 
8580   SDLoc SL = getCurSDLoc();
8581 
8582   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8583                              DAG.getValueType(SmallVT));
8584   unsigned NumVals = Op.getNode()->getNumValues();
8585   if (NumVals == 1)
8586     return ZExt;
8587 
8588   SmallVector<SDValue, 4> Ops;
8589 
8590   Ops.push_back(ZExt);
8591   for (unsigned I = 1; I != NumVals; ++I)
8592     Ops.push_back(Op.getValue(I));
8593 
8594   return DAG.getMergeValues(Ops, SL);
8595 }
8596 
8597 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8598 /// the call being lowered.
8599 ///
8600 /// This is a helper for lowering intrinsics that follow a target calling
8601 /// convention or require stack pointer adjustment. Only a subset of the
8602 /// intrinsic's operands need to participate in the calling convention.
8603 void SelectionDAGBuilder::populateCallLoweringInfo(
8604     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8605     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8606     bool IsPatchPoint) {
8607   TargetLowering::ArgListTy Args;
8608   Args.reserve(NumArgs);
8609 
8610   // Populate the argument list.
8611   // Attributes for args start at offset 1, after the return attribute.
8612   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8613        ArgI != ArgE; ++ArgI) {
8614     const Value *V = Call->getOperand(ArgI);
8615 
8616     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8617 
8618     TargetLowering::ArgListEntry Entry;
8619     Entry.Node = getValue(V);
8620     Entry.Ty = V->getType();
8621     Entry.setAttributes(Call, ArgI);
8622     Args.push_back(Entry);
8623   }
8624 
8625   CLI.setDebugLoc(getCurSDLoc())
8626       .setChain(getRoot())
8627       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8628       .setDiscardResult(Call->use_empty())
8629       .setIsPatchPoint(IsPatchPoint);
8630 }
8631 
8632 /// Add a stack map intrinsic call's live variable operands to a stackmap
8633 /// or patchpoint target node's operand list.
8634 ///
8635 /// Constants are converted to TargetConstants purely as an optimization to
8636 /// avoid constant materialization and register allocation.
8637 ///
8638 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8639 /// generate addess computation nodes, and so FinalizeISel can convert the
8640 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8641 /// address materialization and register allocation, but may also be required
8642 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8643 /// alloca in the entry block, then the runtime may assume that the alloca's
8644 /// StackMap location can be read immediately after compilation and that the
8645 /// location is valid at any point during execution (this is similar to the
8646 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8647 /// only available in a register, then the runtime would need to trap when
8648 /// execution reaches the StackMap in order to read the alloca's location.
8649 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8650                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8651                                 SelectionDAGBuilder &Builder) {
8652   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8653     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8654     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8655       Ops.push_back(
8656         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8657       Ops.push_back(
8658         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8659     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8660       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8661       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8662           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8663     } else
8664       Ops.push_back(OpVal);
8665   }
8666 }
8667 
8668 /// Lower llvm.experimental.stackmap directly to its target opcode.
8669 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8670   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8671   //                                  [live variables...])
8672 
8673   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8674 
8675   SDValue Chain, InFlag, Callee, NullPtr;
8676   SmallVector<SDValue, 32> Ops;
8677 
8678   SDLoc DL = getCurSDLoc();
8679   Callee = getValue(CI.getCalledValue());
8680   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8681 
8682   // The stackmap intrinsic only records the live variables (the arguments
8683   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8684   // intrinsic, this won't be lowered to a function call. This means we don't
8685   // have to worry about calling conventions and target specific lowering code.
8686   // Instead we perform the call lowering right here.
8687   //
8688   // chain, flag = CALLSEQ_START(chain, 0, 0)
8689   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8690   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8691   //
8692   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8693   InFlag = Chain.getValue(1);
8694 
8695   // Add the <id> and <numBytes> constants.
8696   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8697   Ops.push_back(DAG.getTargetConstant(
8698                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8699   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8700   Ops.push_back(DAG.getTargetConstant(
8701                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8702                   MVT::i32));
8703 
8704   // Push live variables for the stack map.
8705   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8706 
8707   // We are not pushing any register mask info here on the operands list,
8708   // because the stackmap doesn't clobber anything.
8709 
8710   // Push the chain and the glue flag.
8711   Ops.push_back(Chain);
8712   Ops.push_back(InFlag);
8713 
8714   // Create the STACKMAP node.
8715   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8716   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8717   Chain = SDValue(SM, 0);
8718   InFlag = Chain.getValue(1);
8719 
8720   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8721 
8722   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8723 
8724   // Set the root to the target-lowered call chain.
8725   DAG.setRoot(Chain);
8726 
8727   // Inform the Frame Information that we have a stackmap in this function.
8728   FuncInfo.MF->getFrameInfo().setHasStackMap();
8729 }
8730 
8731 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8732 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8733                                           const BasicBlock *EHPadBB) {
8734   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8735   //                                                 i32 <numBytes>,
8736   //                                                 i8* <target>,
8737   //                                                 i32 <numArgs>,
8738   //                                                 [Args...],
8739   //                                                 [live variables...])
8740 
8741   CallingConv::ID CC = CB.getCallingConv();
8742   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8743   bool HasDef = !CB.getType()->isVoidTy();
8744   SDLoc dl = getCurSDLoc();
8745   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8746 
8747   // Handle immediate and symbolic callees.
8748   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8749     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8750                                    /*isTarget=*/true);
8751   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8752     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8753                                          SDLoc(SymbolicCallee),
8754                                          SymbolicCallee->getValueType(0));
8755 
8756   // Get the real number of arguments participating in the call <numArgs>
8757   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8758   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8759 
8760   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8761   // Intrinsics include all meta-operands up to but not including CC.
8762   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8763   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8764          "Not enough arguments provided to the patchpoint intrinsic");
8765 
8766   // For AnyRegCC the arguments are lowered later on manually.
8767   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8768   Type *ReturnTy =
8769       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8770 
8771   TargetLowering::CallLoweringInfo CLI(DAG);
8772   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8773                            ReturnTy, true);
8774   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8775 
8776   SDNode *CallEnd = Result.second.getNode();
8777   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8778     CallEnd = CallEnd->getOperand(0).getNode();
8779 
8780   /// Get a call instruction from the call sequence chain.
8781   /// Tail calls are not allowed.
8782   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8783          "Expected a callseq node.");
8784   SDNode *Call = CallEnd->getOperand(0).getNode();
8785   bool HasGlue = Call->getGluedNode();
8786 
8787   // Replace the target specific call node with the patchable intrinsic.
8788   SmallVector<SDValue, 8> Ops;
8789 
8790   // Add the <id> and <numBytes> constants.
8791   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8792   Ops.push_back(DAG.getTargetConstant(
8793                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8794   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8795   Ops.push_back(DAG.getTargetConstant(
8796                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8797                   MVT::i32));
8798 
8799   // Add the callee.
8800   Ops.push_back(Callee);
8801 
8802   // Adjust <numArgs> to account for any arguments that have been passed on the
8803   // stack instead.
8804   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8805   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8806   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8807   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8808 
8809   // Add the calling convention
8810   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8811 
8812   // Add the arguments we omitted previously. The register allocator should
8813   // place these in any free register.
8814   if (IsAnyRegCC)
8815     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8816       Ops.push_back(getValue(CB.getArgOperand(i)));
8817 
8818   // Push the arguments from the call instruction up to the register mask.
8819   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8820   Ops.append(Call->op_begin() + 2, e);
8821 
8822   // Push live variables for the stack map.
8823   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8824 
8825   // Push the register mask info.
8826   if (HasGlue)
8827     Ops.push_back(*(Call->op_end()-2));
8828   else
8829     Ops.push_back(*(Call->op_end()-1));
8830 
8831   // Push the chain (this is originally the first operand of the call, but
8832   // becomes now the last or second to last operand).
8833   Ops.push_back(*(Call->op_begin()));
8834 
8835   // Push the glue flag (last operand).
8836   if (HasGlue)
8837     Ops.push_back(*(Call->op_end()-1));
8838 
8839   SDVTList NodeTys;
8840   if (IsAnyRegCC && HasDef) {
8841     // Create the return types based on the intrinsic definition
8842     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8843     SmallVector<EVT, 3> ValueVTs;
8844     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8845     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8846 
8847     // There is always a chain and a glue type at the end
8848     ValueVTs.push_back(MVT::Other);
8849     ValueVTs.push_back(MVT::Glue);
8850     NodeTys = DAG.getVTList(ValueVTs);
8851   } else
8852     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8853 
8854   // Replace the target specific call node with a PATCHPOINT node.
8855   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8856                                          dl, NodeTys, Ops);
8857 
8858   // Update the NodeMap.
8859   if (HasDef) {
8860     if (IsAnyRegCC)
8861       setValue(&CB, SDValue(MN, 0));
8862     else
8863       setValue(&CB, Result.first);
8864   }
8865 
8866   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8867   // call sequence. Furthermore the location of the chain and glue can change
8868   // when the AnyReg calling convention is used and the intrinsic returns a
8869   // value.
8870   if (IsAnyRegCC && HasDef) {
8871     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8872     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8873     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8874   } else
8875     DAG.ReplaceAllUsesWith(Call, MN);
8876   DAG.DeleteNode(Call);
8877 
8878   // Inform the Frame Information that we have a patchpoint in this function.
8879   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8880 }
8881 
8882 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8883                                             unsigned Intrinsic) {
8884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8885   SDValue Op1 = getValue(I.getArgOperand(0));
8886   SDValue Op2;
8887   if (I.getNumArgOperands() > 1)
8888     Op2 = getValue(I.getArgOperand(1));
8889   SDLoc dl = getCurSDLoc();
8890   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8891   SDValue Res;
8892   FastMathFlags FMF;
8893   if (isa<FPMathOperator>(I))
8894     FMF = I.getFastMathFlags();
8895 
8896   switch (Intrinsic) {
8897   case Intrinsic::experimental_vector_reduce_v2_fadd:
8898     if (FMF.allowReassoc())
8899       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8900                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8901     else
8902       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8903     break;
8904   case Intrinsic::experimental_vector_reduce_v2_fmul:
8905     if (FMF.allowReassoc())
8906       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8907                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8908     else
8909       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8910     break;
8911   case Intrinsic::experimental_vector_reduce_add:
8912     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8913     break;
8914   case Intrinsic::experimental_vector_reduce_mul:
8915     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8916     break;
8917   case Intrinsic::experimental_vector_reduce_and:
8918     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8919     break;
8920   case Intrinsic::experimental_vector_reduce_or:
8921     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8922     break;
8923   case Intrinsic::experimental_vector_reduce_xor:
8924     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8925     break;
8926   case Intrinsic::experimental_vector_reduce_smax:
8927     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8928     break;
8929   case Intrinsic::experimental_vector_reduce_smin:
8930     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8931     break;
8932   case Intrinsic::experimental_vector_reduce_umax:
8933     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8934     break;
8935   case Intrinsic::experimental_vector_reduce_umin:
8936     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8937     break;
8938   case Intrinsic::experimental_vector_reduce_fmax:
8939     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8940     break;
8941   case Intrinsic::experimental_vector_reduce_fmin:
8942     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8943     break;
8944   default:
8945     llvm_unreachable("Unhandled vector reduce intrinsic");
8946   }
8947   setValue(&I, Res);
8948 }
8949 
8950 /// Returns an AttributeList representing the attributes applied to the return
8951 /// value of the given call.
8952 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8953   SmallVector<Attribute::AttrKind, 2> Attrs;
8954   if (CLI.RetSExt)
8955     Attrs.push_back(Attribute::SExt);
8956   if (CLI.RetZExt)
8957     Attrs.push_back(Attribute::ZExt);
8958   if (CLI.IsInReg)
8959     Attrs.push_back(Attribute::InReg);
8960 
8961   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8962                             Attrs);
8963 }
8964 
8965 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8966 /// implementation, which just calls LowerCall.
8967 /// FIXME: When all targets are
8968 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8969 std::pair<SDValue, SDValue>
8970 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8971   // Handle the incoming return values from the call.
8972   CLI.Ins.clear();
8973   Type *OrigRetTy = CLI.RetTy;
8974   SmallVector<EVT, 4> RetTys;
8975   SmallVector<uint64_t, 4> Offsets;
8976   auto &DL = CLI.DAG.getDataLayout();
8977   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8978 
8979   if (CLI.IsPostTypeLegalization) {
8980     // If we are lowering a libcall after legalization, split the return type.
8981     SmallVector<EVT, 4> OldRetTys;
8982     SmallVector<uint64_t, 4> OldOffsets;
8983     RetTys.swap(OldRetTys);
8984     Offsets.swap(OldOffsets);
8985 
8986     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8987       EVT RetVT = OldRetTys[i];
8988       uint64_t Offset = OldOffsets[i];
8989       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8990       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8991       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8992       RetTys.append(NumRegs, RegisterVT);
8993       for (unsigned j = 0; j != NumRegs; ++j)
8994         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8995     }
8996   }
8997 
8998   SmallVector<ISD::OutputArg, 4> Outs;
8999   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9000 
9001   bool CanLowerReturn =
9002       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9003                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9004 
9005   SDValue DemoteStackSlot;
9006   int DemoteStackIdx = -100;
9007   if (!CanLowerReturn) {
9008     // FIXME: equivalent assert?
9009     // assert(!CS.hasInAllocaArgument() &&
9010     //        "sret demotion is incompatible with inalloca");
9011     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9012     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9013     MachineFunction &MF = CLI.DAG.getMachineFunction();
9014     DemoteStackIdx =
9015         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9016     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9017                                               DL.getAllocaAddrSpace());
9018 
9019     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9020     ArgListEntry Entry;
9021     Entry.Node = DemoteStackSlot;
9022     Entry.Ty = StackSlotPtrType;
9023     Entry.IsSExt = false;
9024     Entry.IsZExt = false;
9025     Entry.IsInReg = false;
9026     Entry.IsSRet = true;
9027     Entry.IsNest = false;
9028     Entry.IsByVal = false;
9029     Entry.IsReturned = false;
9030     Entry.IsSwiftSelf = false;
9031     Entry.IsSwiftError = false;
9032     Entry.IsCFGuardTarget = false;
9033     Entry.Alignment = Alignment;
9034     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9035     CLI.NumFixedArgs += 1;
9036     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9037 
9038     // sret demotion isn't compatible with tail-calls, since the sret argument
9039     // points into the callers stack frame.
9040     CLI.IsTailCall = false;
9041   } else {
9042     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9043         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9044     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9045       ISD::ArgFlagsTy Flags;
9046       if (NeedsRegBlock) {
9047         Flags.setInConsecutiveRegs();
9048         if (I == RetTys.size() - 1)
9049           Flags.setInConsecutiveRegsLast();
9050       }
9051       EVT VT = RetTys[I];
9052       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9053                                                      CLI.CallConv, VT);
9054       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9055                                                        CLI.CallConv, VT);
9056       for (unsigned i = 0; i != NumRegs; ++i) {
9057         ISD::InputArg MyFlags;
9058         MyFlags.Flags = Flags;
9059         MyFlags.VT = RegisterVT;
9060         MyFlags.ArgVT = VT;
9061         MyFlags.Used = CLI.IsReturnValueUsed;
9062         if (CLI.RetTy->isPointerTy()) {
9063           MyFlags.Flags.setPointer();
9064           MyFlags.Flags.setPointerAddrSpace(
9065               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9066         }
9067         if (CLI.RetSExt)
9068           MyFlags.Flags.setSExt();
9069         if (CLI.RetZExt)
9070           MyFlags.Flags.setZExt();
9071         if (CLI.IsInReg)
9072           MyFlags.Flags.setInReg();
9073         CLI.Ins.push_back(MyFlags);
9074       }
9075     }
9076   }
9077 
9078   // We push in swifterror return as the last element of CLI.Ins.
9079   ArgListTy &Args = CLI.getArgs();
9080   if (supportSwiftError()) {
9081     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9082       if (Args[i].IsSwiftError) {
9083         ISD::InputArg MyFlags;
9084         MyFlags.VT = getPointerTy(DL);
9085         MyFlags.ArgVT = EVT(getPointerTy(DL));
9086         MyFlags.Flags.setSwiftError();
9087         CLI.Ins.push_back(MyFlags);
9088       }
9089     }
9090   }
9091 
9092   // Handle all of the outgoing arguments.
9093   CLI.Outs.clear();
9094   CLI.OutVals.clear();
9095   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9096     SmallVector<EVT, 4> ValueVTs;
9097     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9098     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9099     Type *FinalType = Args[i].Ty;
9100     if (Args[i].IsByVal)
9101       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9102     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9103         FinalType, CLI.CallConv, CLI.IsVarArg);
9104     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9105          ++Value) {
9106       EVT VT = ValueVTs[Value];
9107       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9108       SDValue Op = SDValue(Args[i].Node.getNode(),
9109                            Args[i].Node.getResNo() + Value);
9110       ISD::ArgFlagsTy Flags;
9111 
9112       // Certain targets (such as MIPS), may have a different ABI alignment
9113       // for a type depending on the context. Give the target a chance to
9114       // specify the alignment it wants.
9115       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9116 
9117       if (Args[i].Ty->isPointerTy()) {
9118         Flags.setPointer();
9119         Flags.setPointerAddrSpace(
9120             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9121       }
9122       if (Args[i].IsZExt)
9123         Flags.setZExt();
9124       if (Args[i].IsSExt)
9125         Flags.setSExt();
9126       if (Args[i].IsInReg) {
9127         // If we are using vectorcall calling convention, a structure that is
9128         // passed InReg - is surely an HVA
9129         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9130             isa<StructType>(FinalType)) {
9131           // The first value of a structure is marked
9132           if (0 == Value)
9133             Flags.setHvaStart();
9134           Flags.setHva();
9135         }
9136         // Set InReg Flag
9137         Flags.setInReg();
9138       }
9139       if (Args[i].IsSRet)
9140         Flags.setSRet();
9141       if (Args[i].IsSwiftSelf)
9142         Flags.setSwiftSelf();
9143       if (Args[i].IsSwiftError)
9144         Flags.setSwiftError();
9145       if (Args[i].IsCFGuardTarget)
9146         Flags.setCFGuardTarget();
9147       if (Args[i].IsByVal)
9148         Flags.setByVal();
9149       if (Args[i].IsInAlloca) {
9150         Flags.setInAlloca();
9151         // Set the byval flag for CCAssignFn callbacks that don't know about
9152         // inalloca.  This way we can know how many bytes we should've allocated
9153         // and how many bytes a callee cleanup function will pop.  If we port
9154         // inalloca to more targets, we'll have to add custom inalloca handling
9155         // in the various CC lowering callbacks.
9156         Flags.setByVal();
9157       }
9158       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9159         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9160         Type *ElementTy = Ty->getElementType();
9161 
9162         unsigned FrameSize = DL.getTypeAllocSize(
9163             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9164         Flags.setByValSize(FrameSize);
9165 
9166         // info is not there but there are cases it cannot get right.
9167         Align FrameAlign;
9168         if (auto MA = Args[i].Alignment)
9169           FrameAlign = *MA;
9170         else
9171           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9172         Flags.setByValAlign(FrameAlign);
9173       }
9174       if (Args[i].IsNest)
9175         Flags.setNest();
9176       if (NeedsRegBlock)
9177         Flags.setInConsecutiveRegs();
9178       Flags.setOrigAlign(OriginalAlignment);
9179 
9180       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9181                                                  CLI.CallConv, VT);
9182       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9183                                                         CLI.CallConv, VT);
9184       SmallVector<SDValue, 4> Parts(NumParts);
9185       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9186 
9187       if (Args[i].IsSExt)
9188         ExtendKind = ISD::SIGN_EXTEND;
9189       else if (Args[i].IsZExt)
9190         ExtendKind = ISD::ZERO_EXTEND;
9191 
9192       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9193       // for now.
9194       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9195           CanLowerReturn) {
9196         assert((CLI.RetTy == Args[i].Ty ||
9197                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9198                  CLI.RetTy->getPointerAddressSpace() ==
9199                      Args[i].Ty->getPointerAddressSpace())) &&
9200                RetTys.size() == NumValues && "unexpected use of 'returned'");
9201         // Before passing 'returned' to the target lowering code, ensure that
9202         // either the register MVT and the actual EVT are the same size or that
9203         // the return value and argument are extended in the same way; in these
9204         // cases it's safe to pass the argument register value unchanged as the
9205         // return register value (although it's at the target's option whether
9206         // to do so)
9207         // TODO: allow code generation to take advantage of partially preserved
9208         // registers rather than clobbering the entire register when the
9209         // parameter extension method is not compatible with the return
9210         // extension method
9211         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9212             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9213              CLI.RetZExt == Args[i].IsZExt))
9214           Flags.setReturned();
9215       }
9216 
9217       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9218                      CLI.CallConv, ExtendKind);
9219 
9220       for (unsigned j = 0; j != NumParts; ++j) {
9221         // if it isn't first piece, alignment must be 1
9222         // For scalable vectors the scalable part is currently handled
9223         // by individual targets, so we just use the known minimum size here.
9224         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9225                     i < CLI.NumFixedArgs, i,
9226                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9227         if (NumParts > 1 && j == 0)
9228           MyFlags.Flags.setSplit();
9229         else if (j != 0) {
9230           MyFlags.Flags.setOrigAlign(Align(1));
9231           if (j == NumParts - 1)
9232             MyFlags.Flags.setSplitEnd();
9233         }
9234 
9235         CLI.Outs.push_back(MyFlags);
9236         CLI.OutVals.push_back(Parts[j]);
9237       }
9238 
9239       if (NeedsRegBlock && Value == NumValues - 1)
9240         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9241     }
9242   }
9243 
9244   SmallVector<SDValue, 4> InVals;
9245   CLI.Chain = LowerCall(CLI, InVals);
9246 
9247   // Update CLI.InVals to use outside of this function.
9248   CLI.InVals = InVals;
9249 
9250   // Verify that the target's LowerCall behaved as expected.
9251   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9252          "LowerCall didn't return a valid chain!");
9253   assert((!CLI.IsTailCall || InVals.empty()) &&
9254          "LowerCall emitted a return value for a tail call!");
9255   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9256          "LowerCall didn't emit the correct number of values!");
9257 
9258   // For a tail call, the return value is merely live-out and there aren't
9259   // any nodes in the DAG representing it. Return a special value to
9260   // indicate that a tail call has been emitted and no more Instructions
9261   // should be processed in the current block.
9262   if (CLI.IsTailCall) {
9263     CLI.DAG.setRoot(CLI.Chain);
9264     return std::make_pair(SDValue(), SDValue());
9265   }
9266 
9267 #ifndef NDEBUG
9268   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9269     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9270     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9271            "LowerCall emitted a value with the wrong type!");
9272   }
9273 #endif
9274 
9275   SmallVector<SDValue, 4> ReturnValues;
9276   if (!CanLowerReturn) {
9277     // The instruction result is the result of loading from the
9278     // hidden sret parameter.
9279     SmallVector<EVT, 1> PVTs;
9280     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9281 
9282     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9283     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9284     EVT PtrVT = PVTs[0];
9285 
9286     unsigned NumValues = RetTys.size();
9287     ReturnValues.resize(NumValues);
9288     SmallVector<SDValue, 4> Chains(NumValues);
9289 
9290     // An aggregate return value cannot wrap around the address space, so
9291     // offsets to its parts don't wrap either.
9292     SDNodeFlags Flags;
9293     Flags.setNoUnsignedWrap(true);
9294 
9295     for (unsigned i = 0; i < NumValues; ++i) {
9296       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9297                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9298                                                         PtrVT), Flags);
9299       SDValue L = CLI.DAG.getLoad(
9300           RetTys[i], CLI.DL, CLI.Chain, Add,
9301           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9302                                             DemoteStackIdx, Offsets[i]),
9303           /* Alignment = */ 1);
9304       ReturnValues[i] = L;
9305       Chains[i] = L.getValue(1);
9306     }
9307 
9308     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9309   } else {
9310     // Collect the legal value parts into potentially illegal values
9311     // that correspond to the original function's return values.
9312     Optional<ISD::NodeType> AssertOp;
9313     if (CLI.RetSExt)
9314       AssertOp = ISD::AssertSext;
9315     else if (CLI.RetZExt)
9316       AssertOp = ISD::AssertZext;
9317     unsigned CurReg = 0;
9318     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9319       EVT VT = RetTys[I];
9320       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9321                                                      CLI.CallConv, VT);
9322       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9323                                                        CLI.CallConv, VT);
9324 
9325       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9326                                               NumRegs, RegisterVT, VT, nullptr,
9327                                               CLI.CallConv, AssertOp));
9328       CurReg += NumRegs;
9329     }
9330 
9331     // For a function returning void, there is no return value. We can't create
9332     // such a node, so we just return a null return value in that case. In
9333     // that case, nothing will actually look at the value.
9334     if (ReturnValues.empty())
9335       return std::make_pair(SDValue(), CLI.Chain);
9336   }
9337 
9338   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9339                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9340   return std::make_pair(Res, CLI.Chain);
9341 }
9342 
9343 void TargetLowering::LowerOperationWrapper(SDNode *N,
9344                                            SmallVectorImpl<SDValue> &Results,
9345                                            SelectionDAG &DAG) const {
9346   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9347     Results.push_back(Res);
9348 }
9349 
9350 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9351   llvm_unreachable("LowerOperation not implemented for this target!");
9352 }
9353 
9354 void
9355 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9356   SDValue Op = getNonRegisterValue(V);
9357   assert((Op.getOpcode() != ISD::CopyFromReg ||
9358           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9359          "Copy from a reg to the same reg!");
9360   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9361 
9362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9363   // If this is an InlineAsm we have to match the registers required, not the
9364   // notional registers required by the type.
9365 
9366   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9367                    None); // This is not an ABI copy.
9368   SDValue Chain = DAG.getEntryNode();
9369 
9370   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9371                               FuncInfo.PreferredExtendType.end())
9372                                  ? ISD::ANY_EXTEND
9373                                  : FuncInfo.PreferredExtendType[V];
9374   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9375   PendingExports.push_back(Chain);
9376 }
9377 
9378 #include "llvm/CodeGen/SelectionDAGISel.h"
9379 
9380 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9381 /// entry block, return true.  This includes arguments used by switches, since
9382 /// the switch may expand into multiple basic blocks.
9383 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9384   // With FastISel active, we may be splitting blocks, so force creation
9385   // of virtual registers for all non-dead arguments.
9386   if (FastISel)
9387     return A->use_empty();
9388 
9389   const BasicBlock &Entry = A->getParent()->front();
9390   for (const User *U : A->users())
9391     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9392       return false;  // Use not in entry block.
9393 
9394   return true;
9395 }
9396 
9397 using ArgCopyElisionMapTy =
9398     DenseMap<const Argument *,
9399              std::pair<const AllocaInst *, const StoreInst *>>;
9400 
9401 /// Scan the entry block of the function in FuncInfo for arguments that look
9402 /// like copies into a local alloca. Record any copied arguments in
9403 /// ArgCopyElisionCandidates.
9404 static void
9405 findArgumentCopyElisionCandidates(const DataLayout &DL,
9406                                   FunctionLoweringInfo *FuncInfo,
9407                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9408   // Record the state of every static alloca used in the entry block. Argument
9409   // allocas are all used in the entry block, so we need approximately as many
9410   // entries as we have arguments.
9411   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9412   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9413   unsigned NumArgs = FuncInfo->Fn->arg_size();
9414   StaticAllocas.reserve(NumArgs * 2);
9415 
9416   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9417     if (!V)
9418       return nullptr;
9419     V = V->stripPointerCasts();
9420     const auto *AI = dyn_cast<AllocaInst>(V);
9421     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9422       return nullptr;
9423     auto Iter = StaticAllocas.insert({AI, Unknown});
9424     return &Iter.first->second;
9425   };
9426 
9427   // Look for stores of arguments to static allocas. Look through bitcasts and
9428   // GEPs to handle type coercions, as long as the alloca is fully initialized
9429   // by the store. Any non-store use of an alloca escapes it and any subsequent
9430   // unanalyzed store might write it.
9431   // FIXME: Handle structs initialized with multiple stores.
9432   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9433     // Look for stores, and handle non-store uses conservatively.
9434     const auto *SI = dyn_cast<StoreInst>(&I);
9435     if (!SI) {
9436       // We will look through cast uses, so ignore them completely.
9437       if (I.isCast())
9438         continue;
9439       // Ignore debug info intrinsics, they don't escape or store to allocas.
9440       if (isa<DbgInfoIntrinsic>(I))
9441         continue;
9442       // This is an unknown instruction. Assume it escapes or writes to all
9443       // static alloca operands.
9444       for (const Use &U : I.operands()) {
9445         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9446           *Info = StaticAllocaInfo::Clobbered;
9447       }
9448       continue;
9449     }
9450 
9451     // If the stored value is a static alloca, mark it as escaped.
9452     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9453       *Info = StaticAllocaInfo::Clobbered;
9454 
9455     // Check if the destination is a static alloca.
9456     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9457     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9458     if (!Info)
9459       continue;
9460     const AllocaInst *AI = cast<AllocaInst>(Dst);
9461 
9462     // Skip allocas that have been initialized or clobbered.
9463     if (*Info != StaticAllocaInfo::Unknown)
9464       continue;
9465 
9466     // Check if the stored value is an argument, and that this store fully
9467     // initializes the alloca. Don't elide copies from the same argument twice.
9468     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9469     const auto *Arg = dyn_cast<Argument>(Val);
9470     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9471         Arg->getType()->isEmptyTy() ||
9472         DL.getTypeStoreSize(Arg->getType()) !=
9473             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9474         ArgCopyElisionCandidates.count(Arg)) {
9475       *Info = StaticAllocaInfo::Clobbered;
9476       continue;
9477     }
9478 
9479     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9480                       << '\n');
9481 
9482     // Mark this alloca and store for argument copy elision.
9483     *Info = StaticAllocaInfo::Elidable;
9484     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9485 
9486     // Stop scanning if we've seen all arguments. This will happen early in -O0
9487     // builds, which is useful, because -O0 builds have large entry blocks and
9488     // many allocas.
9489     if (ArgCopyElisionCandidates.size() == NumArgs)
9490       break;
9491   }
9492 }
9493 
9494 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9495 /// ArgVal is a load from a suitable fixed stack object.
9496 static void tryToElideArgumentCopy(
9497     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9498     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9499     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9500     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9501     SDValue ArgVal, bool &ArgHasUses) {
9502   // Check if this is a load from a fixed stack object.
9503   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9504   if (!LNode)
9505     return;
9506   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9507   if (!FINode)
9508     return;
9509 
9510   // Check that the fixed stack object is the right size and alignment.
9511   // Look at the alignment that the user wrote on the alloca instead of looking
9512   // at the stack object.
9513   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9514   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9515   const AllocaInst *AI = ArgCopyIter->second.first;
9516   int FixedIndex = FINode->getIndex();
9517   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9518   int OldIndex = AllocaIndex;
9519   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9520   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9521     LLVM_DEBUG(
9522         dbgs() << "  argument copy elision failed due to bad fixed stack "
9523                   "object size\n");
9524     return;
9525   }
9526   Align RequiredAlignment = AI->getAlign().getValueOr(
9527       FuncInfo.MF->getDataLayout().getABITypeAlign(AI->getAllocatedType()));
9528   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9529     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9530                          "greater than stack argument alignment ("
9531                       << DebugStr(RequiredAlignment) << " vs "
9532                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9533     return;
9534   }
9535 
9536   // Perform the elision. Delete the old stack object and replace its only use
9537   // in the variable info map. Mark the stack object as mutable.
9538   LLVM_DEBUG({
9539     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9540            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9541            << '\n';
9542   });
9543   MFI.RemoveStackObject(OldIndex);
9544   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9545   AllocaIndex = FixedIndex;
9546   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9547   Chains.push_back(ArgVal.getValue(1));
9548 
9549   // Avoid emitting code for the store implementing the copy.
9550   const StoreInst *SI = ArgCopyIter->second.second;
9551   ElidedArgCopyInstrs.insert(SI);
9552 
9553   // Check for uses of the argument again so that we can avoid exporting ArgVal
9554   // if it is't used by anything other than the store.
9555   for (const Value *U : Arg.users()) {
9556     if (U != SI) {
9557       ArgHasUses = true;
9558       break;
9559     }
9560   }
9561 }
9562 
9563 void SelectionDAGISel::LowerArguments(const Function &F) {
9564   SelectionDAG &DAG = SDB->DAG;
9565   SDLoc dl = SDB->getCurSDLoc();
9566   const DataLayout &DL = DAG.getDataLayout();
9567   SmallVector<ISD::InputArg, 16> Ins;
9568 
9569   if (!FuncInfo->CanLowerReturn) {
9570     // Put in an sret pointer parameter before all the other parameters.
9571     SmallVector<EVT, 1> ValueVTs;
9572     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9573                     F.getReturnType()->getPointerTo(
9574                         DAG.getDataLayout().getAllocaAddrSpace()),
9575                     ValueVTs);
9576 
9577     // NOTE: Assuming that a pointer will never break down to more than one VT
9578     // or one register.
9579     ISD::ArgFlagsTy Flags;
9580     Flags.setSRet();
9581     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9582     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9583                          ISD::InputArg::NoArgIndex, 0);
9584     Ins.push_back(RetArg);
9585   }
9586 
9587   // Look for stores of arguments to static allocas. Mark such arguments with a
9588   // flag to ask the target to give us the memory location of that argument if
9589   // available.
9590   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9591   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9592                                     ArgCopyElisionCandidates);
9593 
9594   // Set up the incoming argument description vector.
9595   for (const Argument &Arg : F.args()) {
9596     unsigned ArgNo = Arg.getArgNo();
9597     SmallVector<EVT, 4> ValueVTs;
9598     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9599     bool isArgValueUsed = !Arg.use_empty();
9600     unsigned PartBase = 0;
9601     Type *FinalType = Arg.getType();
9602     if (Arg.hasAttribute(Attribute::ByVal))
9603       FinalType = Arg.getParamByValType();
9604     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9605         FinalType, F.getCallingConv(), F.isVarArg());
9606     for (unsigned Value = 0, NumValues = ValueVTs.size();
9607          Value != NumValues; ++Value) {
9608       EVT VT = ValueVTs[Value];
9609       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9610       ISD::ArgFlagsTy Flags;
9611 
9612       // Certain targets (such as MIPS), may have a different ABI alignment
9613       // for a type depending on the context. Give the target a chance to
9614       // specify the alignment it wants.
9615       const Align OriginalAlignment(
9616           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9617 
9618       if (Arg.getType()->isPointerTy()) {
9619         Flags.setPointer();
9620         Flags.setPointerAddrSpace(
9621             cast<PointerType>(Arg.getType())->getAddressSpace());
9622       }
9623       if (Arg.hasAttribute(Attribute::ZExt))
9624         Flags.setZExt();
9625       if (Arg.hasAttribute(Attribute::SExt))
9626         Flags.setSExt();
9627       if (Arg.hasAttribute(Attribute::InReg)) {
9628         // If we are using vectorcall calling convention, a structure that is
9629         // passed InReg - is surely an HVA
9630         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9631             isa<StructType>(Arg.getType())) {
9632           // The first value of a structure is marked
9633           if (0 == Value)
9634             Flags.setHvaStart();
9635           Flags.setHva();
9636         }
9637         // Set InReg Flag
9638         Flags.setInReg();
9639       }
9640       if (Arg.hasAttribute(Attribute::StructRet))
9641         Flags.setSRet();
9642       if (Arg.hasAttribute(Attribute::SwiftSelf))
9643         Flags.setSwiftSelf();
9644       if (Arg.hasAttribute(Attribute::SwiftError))
9645         Flags.setSwiftError();
9646       if (Arg.hasAttribute(Attribute::ByVal))
9647         Flags.setByVal();
9648       if (Arg.hasAttribute(Attribute::InAlloca)) {
9649         Flags.setInAlloca();
9650         // Set the byval flag for CCAssignFn callbacks that don't know about
9651         // inalloca.  This way we can know how many bytes we should've allocated
9652         // and how many bytes a callee cleanup function will pop.  If we port
9653         // inalloca to more targets, we'll have to add custom inalloca handling
9654         // in the various CC lowering callbacks.
9655         Flags.setByVal();
9656       }
9657       if (F.getCallingConv() == CallingConv::X86_INTR) {
9658         // IA Interrupt passes frame (1st parameter) by value in the stack.
9659         if (ArgNo == 0)
9660           Flags.setByVal();
9661       }
9662       if (Flags.isByVal() || Flags.isInAlloca()) {
9663         Type *ElementTy = Arg.getParamByValType();
9664 
9665         // For ByVal, size and alignment should be passed from FE.  BE will
9666         // guess if this info is not there but there are cases it cannot get
9667         // right.
9668         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9669         Flags.setByValSize(FrameSize);
9670 
9671         unsigned FrameAlign;
9672         if (Arg.getParamAlignment())
9673           FrameAlign = Arg.getParamAlignment();
9674         else
9675           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9676         Flags.setByValAlign(Align(FrameAlign));
9677       }
9678       if (Arg.hasAttribute(Attribute::Nest))
9679         Flags.setNest();
9680       if (NeedsRegBlock)
9681         Flags.setInConsecutiveRegs();
9682       Flags.setOrigAlign(OriginalAlignment);
9683       if (ArgCopyElisionCandidates.count(&Arg))
9684         Flags.setCopyElisionCandidate();
9685       if (Arg.hasAttribute(Attribute::Returned))
9686         Flags.setReturned();
9687 
9688       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9689           *CurDAG->getContext(), F.getCallingConv(), VT);
9690       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9691           *CurDAG->getContext(), F.getCallingConv(), VT);
9692       for (unsigned i = 0; i != NumRegs; ++i) {
9693         // For scalable vectors, use the minimum size; individual targets
9694         // are responsible for handling scalable vector arguments and
9695         // return values.
9696         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9697                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9698         if (NumRegs > 1 && i == 0)
9699           MyFlags.Flags.setSplit();
9700         // if it isn't first piece, alignment must be 1
9701         else if (i > 0) {
9702           MyFlags.Flags.setOrigAlign(Align(1));
9703           if (i == NumRegs - 1)
9704             MyFlags.Flags.setSplitEnd();
9705         }
9706         Ins.push_back(MyFlags);
9707       }
9708       if (NeedsRegBlock && Value == NumValues - 1)
9709         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9710       PartBase += VT.getStoreSize().getKnownMinSize();
9711     }
9712   }
9713 
9714   // Call the target to set up the argument values.
9715   SmallVector<SDValue, 8> InVals;
9716   SDValue NewRoot = TLI->LowerFormalArguments(
9717       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9718 
9719   // Verify that the target's LowerFormalArguments behaved as expected.
9720   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9721          "LowerFormalArguments didn't return a valid chain!");
9722   assert(InVals.size() == Ins.size() &&
9723          "LowerFormalArguments didn't emit the correct number of values!");
9724   LLVM_DEBUG({
9725     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9726       assert(InVals[i].getNode() &&
9727              "LowerFormalArguments emitted a null value!");
9728       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9729              "LowerFormalArguments emitted a value with the wrong type!");
9730     }
9731   });
9732 
9733   // Update the DAG with the new chain value resulting from argument lowering.
9734   DAG.setRoot(NewRoot);
9735 
9736   // Set up the argument values.
9737   unsigned i = 0;
9738   if (!FuncInfo->CanLowerReturn) {
9739     // Create a virtual register for the sret pointer, and put in a copy
9740     // from the sret argument into it.
9741     SmallVector<EVT, 1> ValueVTs;
9742     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9743                     F.getReturnType()->getPointerTo(
9744                         DAG.getDataLayout().getAllocaAddrSpace()),
9745                     ValueVTs);
9746     MVT VT = ValueVTs[0].getSimpleVT();
9747     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9748     Optional<ISD::NodeType> AssertOp = None;
9749     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9750                                         nullptr, F.getCallingConv(), AssertOp);
9751 
9752     MachineFunction& MF = SDB->DAG.getMachineFunction();
9753     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9754     Register SRetReg =
9755         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9756     FuncInfo->DemoteRegister = SRetReg;
9757     NewRoot =
9758         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9759     DAG.setRoot(NewRoot);
9760 
9761     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9762     ++i;
9763   }
9764 
9765   SmallVector<SDValue, 4> Chains;
9766   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9767   for (const Argument &Arg : F.args()) {
9768     SmallVector<SDValue, 4> ArgValues;
9769     SmallVector<EVT, 4> ValueVTs;
9770     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9771     unsigned NumValues = ValueVTs.size();
9772     if (NumValues == 0)
9773       continue;
9774 
9775     bool ArgHasUses = !Arg.use_empty();
9776 
9777     // Elide the copying store if the target loaded this argument from a
9778     // suitable fixed stack object.
9779     if (Ins[i].Flags.isCopyElisionCandidate()) {
9780       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9781                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9782                              InVals[i], ArgHasUses);
9783     }
9784 
9785     // If this argument is unused then remember its value. It is used to generate
9786     // debugging information.
9787     bool isSwiftErrorArg =
9788         TLI->supportSwiftError() &&
9789         Arg.hasAttribute(Attribute::SwiftError);
9790     if (!ArgHasUses && !isSwiftErrorArg) {
9791       SDB->setUnusedArgValue(&Arg, InVals[i]);
9792 
9793       // Also remember any frame index for use in FastISel.
9794       if (FrameIndexSDNode *FI =
9795           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9796         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9797     }
9798 
9799     for (unsigned Val = 0; Val != NumValues; ++Val) {
9800       EVT VT = ValueVTs[Val];
9801       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9802                                                       F.getCallingConv(), VT);
9803       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9804           *CurDAG->getContext(), F.getCallingConv(), VT);
9805 
9806       // Even an apparent 'unused' swifterror argument needs to be returned. So
9807       // we do generate a copy for it that can be used on return from the
9808       // function.
9809       if (ArgHasUses || isSwiftErrorArg) {
9810         Optional<ISD::NodeType> AssertOp;
9811         if (Arg.hasAttribute(Attribute::SExt))
9812           AssertOp = ISD::AssertSext;
9813         else if (Arg.hasAttribute(Attribute::ZExt))
9814           AssertOp = ISD::AssertZext;
9815 
9816         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9817                                              PartVT, VT, nullptr,
9818                                              F.getCallingConv(), AssertOp));
9819       }
9820 
9821       i += NumParts;
9822     }
9823 
9824     // We don't need to do anything else for unused arguments.
9825     if (ArgValues.empty())
9826       continue;
9827 
9828     // Note down frame index.
9829     if (FrameIndexSDNode *FI =
9830         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9831       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9832 
9833     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9834                                      SDB->getCurSDLoc());
9835 
9836     SDB->setValue(&Arg, Res);
9837     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9838       // We want to associate the argument with the frame index, among
9839       // involved operands, that correspond to the lowest address. The
9840       // getCopyFromParts function, called earlier, is swapping the order of
9841       // the operands to BUILD_PAIR depending on endianness. The result of
9842       // that swapping is that the least significant bits of the argument will
9843       // be in the first operand of the BUILD_PAIR node, and the most
9844       // significant bits will be in the second operand.
9845       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9846       if (LoadSDNode *LNode =
9847           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9848         if (FrameIndexSDNode *FI =
9849             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9850           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9851     }
9852 
9853     // Analyses past this point are naive and don't expect an assertion.
9854     if (Res.getOpcode() == ISD::AssertZext)
9855       Res = Res.getOperand(0);
9856 
9857     // Update the SwiftErrorVRegDefMap.
9858     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9859       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9860       if (Register::isVirtualRegister(Reg))
9861         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9862                                    Reg);
9863     }
9864 
9865     // If this argument is live outside of the entry block, insert a copy from
9866     // wherever we got it to the vreg that other BB's will reference it as.
9867     if (Res.getOpcode() == ISD::CopyFromReg) {
9868       // If we can, though, try to skip creating an unnecessary vreg.
9869       // FIXME: This isn't very clean... it would be nice to make this more
9870       // general.
9871       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9872       if (Register::isVirtualRegister(Reg)) {
9873         FuncInfo->ValueMap[&Arg] = Reg;
9874         continue;
9875       }
9876     }
9877     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9878       FuncInfo->InitializeRegForValue(&Arg);
9879       SDB->CopyToExportRegsIfNeeded(&Arg);
9880     }
9881   }
9882 
9883   if (!Chains.empty()) {
9884     Chains.push_back(NewRoot);
9885     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9886   }
9887 
9888   DAG.setRoot(NewRoot);
9889 
9890   assert(i == InVals.size() && "Argument register count mismatch!");
9891 
9892   // If any argument copy elisions occurred and we have debug info, update the
9893   // stale frame indices used in the dbg.declare variable info table.
9894   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9895   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9896     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9897       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9898       if (I != ArgCopyElisionFrameIndexMap.end())
9899         VI.Slot = I->second;
9900     }
9901   }
9902 
9903   // Finally, if the target has anything special to do, allow it to do so.
9904   emitFunctionEntryCode();
9905 }
9906 
9907 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9908 /// ensure constants are generated when needed.  Remember the virtual registers
9909 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9910 /// directly add them, because expansion might result in multiple MBB's for one
9911 /// BB.  As such, the start of the BB might correspond to a different MBB than
9912 /// the end.
9913 void
9914 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9915   const Instruction *TI = LLVMBB->getTerminator();
9916 
9917   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9918 
9919   // Check PHI nodes in successors that expect a value to be available from this
9920   // block.
9921   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9922     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9923     if (!isa<PHINode>(SuccBB->begin())) continue;
9924     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9925 
9926     // If this terminator has multiple identical successors (common for
9927     // switches), only handle each succ once.
9928     if (!SuccsHandled.insert(SuccMBB).second)
9929       continue;
9930 
9931     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9932 
9933     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9934     // nodes and Machine PHI nodes, but the incoming operands have not been
9935     // emitted yet.
9936     for (const PHINode &PN : SuccBB->phis()) {
9937       // Ignore dead phi's.
9938       if (PN.use_empty())
9939         continue;
9940 
9941       // Skip empty types
9942       if (PN.getType()->isEmptyTy())
9943         continue;
9944 
9945       unsigned Reg;
9946       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9947 
9948       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9949         unsigned &RegOut = ConstantsOut[C];
9950         if (RegOut == 0) {
9951           RegOut = FuncInfo.CreateRegs(C);
9952           CopyValueToVirtualRegister(C, RegOut);
9953         }
9954         Reg = RegOut;
9955       } else {
9956         DenseMap<const Value *, Register>::iterator I =
9957           FuncInfo.ValueMap.find(PHIOp);
9958         if (I != FuncInfo.ValueMap.end())
9959           Reg = I->second;
9960         else {
9961           assert(isa<AllocaInst>(PHIOp) &&
9962                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9963                  "Didn't codegen value into a register!??");
9964           Reg = FuncInfo.CreateRegs(PHIOp);
9965           CopyValueToVirtualRegister(PHIOp, Reg);
9966         }
9967       }
9968 
9969       // Remember that this register needs to added to the machine PHI node as
9970       // the input for this MBB.
9971       SmallVector<EVT, 4> ValueVTs;
9972       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9973       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9974       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9975         EVT VT = ValueVTs[vti];
9976         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9977         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9978           FuncInfo.PHINodesToUpdate.push_back(
9979               std::make_pair(&*MBBI++, Reg + i));
9980         Reg += NumRegisters;
9981       }
9982     }
9983   }
9984 
9985   ConstantsOut.clear();
9986 }
9987 
9988 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9989 /// is 0.
9990 MachineBasicBlock *
9991 SelectionDAGBuilder::StackProtectorDescriptor::
9992 AddSuccessorMBB(const BasicBlock *BB,
9993                 MachineBasicBlock *ParentMBB,
9994                 bool IsLikely,
9995                 MachineBasicBlock *SuccMBB) {
9996   // If SuccBB has not been created yet, create it.
9997   if (!SuccMBB) {
9998     MachineFunction *MF = ParentMBB->getParent();
9999     MachineFunction::iterator BBI(ParentMBB);
10000     SuccMBB = MF->CreateMachineBasicBlock(BB);
10001     MF->insert(++BBI, SuccMBB);
10002   }
10003   // Add it as a successor of ParentMBB.
10004   ParentMBB->addSuccessor(
10005       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10006   return SuccMBB;
10007 }
10008 
10009 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10010   MachineFunction::iterator I(MBB);
10011   if (++I == FuncInfo.MF->end())
10012     return nullptr;
10013   return &*I;
10014 }
10015 
10016 /// During lowering new call nodes can be created (such as memset, etc.).
10017 /// Those will become new roots of the current DAG, but complications arise
10018 /// when they are tail calls. In such cases, the call lowering will update
10019 /// the root, but the builder still needs to know that a tail call has been
10020 /// lowered in order to avoid generating an additional return.
10021 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10022   // If the node is null, we do have a tail call.
10023   if (MaybeTC.getNode() != nullptr)
10024     DAG.setRoot(MaybeTC);
10025   else
10026     HasTailCall = true;
10027 }
10028 
10029 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10030                                         MachineBasicBlock *SwitchMBB,
10031                                         MachineBasicBlock *DefaultMBB) {
10032   MachineFunction *CurMF = FuncInfo.MF;
10033   MachineBasicBlock *NextMBB = nullptr;
10034   MachineFunction::iterator BBI(W.MBB);
10035   if (++BBI != FuncInfo.MF->end())
10036     NextMBB = &*BBI;
10037 
10038   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10039 
10040   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10041 
10042   if (Size == 2 && W.MBB == SwitchMBB) {
10043     // If any two of the cases has the same destination, and if one value
10044     // is the same as the other, but has one bit unset that the other has set,
10045     // use bit manipulation to do two compares at once.  For example:
10046     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10047     // TODO: This could be extended to merge any 2 cases in switches with 3
10048     // cases.
10049     // TODO: Handle cases where W.CaseBB != SwitchBB.
10050     CaseCluster &Small = *W.FirstCluster;
10051     CaseCluster &Big = *W.LastCluster;
10052 
10053     if (Small.Low == Small.High && Big.Low == Big.High &&
10054         Small.MBB == Big.MBB) {
10055       const APInt &SmallValue = Small.Low->getValue();
10056       const APInt &BigValue = Big.Low->getValue();
10057 
10058       // Check that there is only one bit different.
10059       APInt CommonBit = BigValue ^ SmallValue;
10060       if (CommonBit.isPowerOf2()) {
10061         SDValue CondLHS = getValue(Cond);
10062         EVT VT = CondLHS.getValueType();
10063         SDLoc DL = getCurSDLoc();
10064 
10065         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10066                                  DAG.getConstant(CommonBit, DL, VT));
10067         SDValue Cond = DAG.getSetCC(
10068             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10069             ISD::SETEQ);
10070 
10071         // Update successor info.
10072         // Both Small and Big will jump to Small.BB, so we sum up the
10073         // probabilities.
10074         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10075         if (BPI)
10076           addSuccessorWithProb(
10077               SwitchMBB, DefaultMBB,
10078               // The default destination is the first successor in IR.
10079               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10080         else
10081           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10082 
10083         // Insert the true branch.
10084         SDValue BrCond =
10085             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10086                         DAG.getBasicBlock(Small.MBB));
10087         // Insert the false branch.
10088         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10089                              DAG.getBasicBlock(DefaultMBB));
10090 
10091         DAG.setRoot(BrCond);
10092         return;
10093       }
10094     }
10095   }
10096 
10097   if (TM.getOptLevel() != CodeGenOpt::None) {
10098     // Here, we order cases by probability so the most likely case will be
10099     // checked first. However, two clusters can have the same probability in
10100     // which case their relative ordering is non-deterministic. So we use Low
10101     // as a tie-breaker as clusters are guaranteed to never overlap.
10102     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10103                [](const CaseCluster &a, const CaseCluster &b) {
10104       return a.Prob != b.Prob ?
10105              a.Prob > b.Prob :
10106              a.Low->getValue().slt(b.Low->getValue());
10107     });
10108 
10109     // Rearrange the case blocks so that the last one falls through if possible
10110     // without changing the order of probabilities.
10111     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10112       --I;
10113       if (I->Prob > W.LastCluster->Prob)
10114         break;
10115       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10116         std::swap(*I, *W.LastCluster);
10117         break;
10118       }
10119     }
10120   }
10121 
10122   // Compute total probability.
10123   BranchProbability DefaultProb = W.DefaultProb;
10124   BranchProbability UnhandledProbs = DefaultProb;
10125   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10126     UnhandledProbs += I->Prob;
10127 
10128   MachineBasicBlock *CurMBB = W.MBB;
10129   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10130     bool FallthroughUnreachable = false;
10131     MachineBasicBlock *Fallthrough;
10132     if (I == W.LastCluster) {
10133       // For the last cluster, fall through to the default destination.
10134       Fallthrough = DefaultMBB;
10135       FallthroughUnreachable = isa<UnreachableInst>(
10136           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10137     } else {
10138       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10139       CurMF->insert(BBI, Fallthrough);
10140       // Put Cond in a virtual register to make it available from the new blocks.
10141       ExportFromCurrentBlock(Cond);
10142     }
10143     UnhandledProbs -= I->Prob;
10144 
10145     switch (I->Kind) {
10146       case CC_JumpTable: {
10147         // FIXME: Optimize away range check based on pivot comparisons.
10148         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10149         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10150 
10151         // The jump block hasn't been inserted yet; insert it here.
10152         MachineBasicBlock *JumpMBB = JT->MBB;
10153         CurMF->insert(BBI, JumpMBB);
10154 
10155         auto JumpProb = I->Prob;
10156         auto FallthroughProb = UnhandledProbs;
10157 
10158         // If the default statement is a target of the jump table, we evenly
10159         // distribute the default probability to successors of CurMBB. Also
10160         // update the probability on the edge from JumpMBB to Fallthrough.
10161         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10162                                               SE = JumpMBB->succ_end();
10163              SI != SE; ++SI) {
10164           if (*SI == DefaultMBB) {
10165             JumpProb += DefaultProb / 2;
10166             FallthroughProb -= DefaultProb / 2;
10167             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10168             JumpMBB->normalizeSuccProbs();
10169             break;
10170           }
10171         }
10172 
10173         if (FallthroughUnreachable) {
10174           // Skip the range check if the fallthrough block is unreachable.
10175           JTH->OmitRangeCheck = true;
10176         }
10177 
10178         if (!JTH->OmitRangeCheck)
10179           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10180         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10181         CurMBB->normalizeSuccProbs();
10182 
10183         // The jump table header will be inserted in our current block, do the
10184         // range check, and fall through to our fallthrough block.
10185         JTH->HeaderBB = CurMBB;
10186         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10187 
10188         // If we're in the right place, emit the jump table header right now.
10189         if (CurMBB == SwitchMBB) {
10190           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10191           JTH->Emitted = true;
10192         }
10193         break;
10194       }
10195       case CC_BitTests: {
10196         // FIXME: Optimize away range check based on pivot comparisons.
10197         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10198 
10199         // The bit test blocks haven't been inserted yet; insert them here.
10200         for (BitTestCase &BTC : BTB->Cases)
10201           CurMF->insert(BBI, BTC.ThisBB);
10202 
10203         // Fill in fields of the BitTestBlock.
10204         BTB->Parent = CurMBB;
10205         BTB->Default = Fallthrough;
10206 
10207         BTB->DefaultProb = UnhandledProbs;
10208         // If the cases in bit test don't form a contiguous range, we evenly
10209         // distribute the probability on the edge to Fallthrough to two
10210         // successors of CurMBB.
10211         if (!BTB->ContiguousRange) {
10212           BTB->Prob += DefaultProb / 2;
10213           BTB->DefaultProb -= DefaultProb / 2;
10214         }
10215 
10216         if (FallthroughUnreachable) {
10217           // Skip the range check if the fallthrough block is unreachable.
10218           BTB->OmitRangeCheck = true;
10219         }
10220 
10221         // If we're in the right place, emit the bit test header right now.
10222         if (CurMBB == SwitchMBB) {
10223           visitBitTestHeader(*BTB, SwitchMBB);
10224           BTB->Emitted = true;
10225         }
10226         break;
10227       }
10228       case CC_Range: {
10229         const Value *RHS, *LHS, *MHS;
10230         ISD::CondCode CC;
10231         if (I->Low == I->High) {
10232           // Check Cond == I->Low.
10233           CC = ISD::SETEQ;
10234           LHS = Cond;
10235           RHS=I->Low;
10236           MHS = nullptr;
10237         } else {
10238           // Check I->Low <= Cond <= I->High.
10239           CC = ISD::SETLE;
10240           LHS = I->Low;
10241           MHS = Cond;
10242           RHS = I->High;
10243         }
10244 
10245         // If Fallthrough is unreachable, fold away the comparison.
10246         if (FallthroughUnreachable)
10247           CC = ISD::SETTRUE;
10248 
10249         // The false probability is the sum of all unhandled cases.
10250         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10251                      getCurSDLoc(), I->Prob, UnhandledProbs);
10252 
10253         if (CurMBB == SwitchMBB)
10254           visitSwitchCase(CB, SwitchMBB);
10255         else
10256           SL->SwitchCases.push_back(CB);
10257 
10258         break;
10259       }
10260     }
10261     CurMBB = Fallthrough;
10262   }
10263 }
10264 
10265 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10266                                               CaseClusterIt First,
10267                                               CaseClusterIt Last) {
10268   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10269     if (X.Prob != CC.Prob)
10270       return X.Prob > CC.Prob;
10271 
10272     // Ties are broken by comparing the case value.
10273     return X.Low->getValue().slt(CC.Low->getValue());
10274   });
10275 }
10276 
10277 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10278                                         const SwitchWorkListItem &W,
10279                                         Value *Cond,
10280                                         MachineBasicBlock *SwitchMBB) {
10281   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10282          "Clusters not sorted?");
10283 
10284   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10285 
10286   // Balance the tree based on branch probabilities to create a near-optimal (in
10287   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10288   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10289   CaseClusterIt LastLeft = W.FirstCluster;
10290   CaseClusterIt FirstRight = W.LastCluster;
10291   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10292   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10293 
10294   // Move LastLeft and FirstRight towards each other from opposite directions to
10295   // find a partitioning of the clusters which balances the probability on both
10296   // sides. If LeftProb and RightProb are equal, alternate which side is
10297   // taken to ensure 0-probability nodes are distributed evenly.
10298   unsigned I = 0;
10299   while (LastLeft + 1 < FirstRight) {
10300     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10301       LeftProb += (++LastLeft)->Prob;
10302     else
10303       RightProb += (--FirstRight)->Prob;
10304     I++;
10305   }
10306 
10307   while (true) {
10308     // Our binary search tree differs from a typical BST in that ours can have up
10309     // to three values in each leaf. The pivot selection above doesn't take that
10310     // into account, which means the tree might require more nodes and be less
10311     // efficient. We compensate for this here.
10312 
10313     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10314     unsigned NumRight = W.LastCluster - FirstRight + 1;
10315 
10316     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10317       // If one side has less than 3 clusters, and the other has more than 3,
10318       // consider taking a cluster from the other side.
10319 
10320       if (NumLeft < NumRight) {
10321         // Consider moving the first cluster on the right to the left side.
10322         CaseCluster &CC = *FirstRight;
10323         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10324         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10325         if (LeftSideRank <= RightSideRank) {
10326           // Moving the cluster to the left does not demote it.
10327           ++LastLeft;
10328           ++FirstRight;
10329           continue;
10330         }
10331       } else {
10332         assert(NumRight < NumLeft);
10333         // Consider moving the last element on the left to the right side.
10334         CaseCluster &CC = *LastLeft;
10335         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10336         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10337         if (RightSideRank <= LeftSideRank) {
10338           // Moving the cluster to the right does not demot it.
10339           --LastLeft;
10340           --FirstRight;
10341           continue;
10342         }
10343       }
10344     }
10345     break;
10346   }
10347 
10348   assert(LastLeft + 1 == FirstRight);
10349   assert(LastLeft >= W.FirstCluster);
10350   assert(FirstRight <= W.LastCluster);
10351 
10352   // Use the first element on the right as pivot since we will make less-than
10353   // comparisons against it.
10354   CaseClusterIt PivotCluster = FirstRight;
10355   assert(PivotCluster > W.FirstCluster);
10356   assert(PivotCluster <= W.LastCluster);
10357 
10358   CaseClusterIt FirstLeft = W.FirstCluster;
10359   CaseClusterIt LastRight = W.LastCluster;
10360 
10361   const ConstantInt *Pivot = PivotCluster->Low;
10362 
10363   // New blocks will be inserted immediately after the current one.
10364   MachineFunction::iterator BBI(W.MBB);
10365   ++BBI;
10366 
10367   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10368   // we can branch to its destination directly if it's squeezed exactly in
10369   // between the known lower bound and Pivot - 1.
10370   MachineBasicBlock *LeftMBB;
10371   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10372       FirstLeft->Low == W.GE &&
10373       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10374     LeftMBB = FirstLeft->MBB;
10375   } else {
10376     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10377     FuncInfo.MF->insert(BBI, LeftMBB);
10378     WorkList.push_back(
10379         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10380     // Put Cond in a virtual register to make it available from the new blocks.
10381     ExportFromCurrentBlock(Cond);
10382   }
10383 
10384   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10385   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10386   // directly if RHS.High equals the current upper bound.
10387   MachineBasicBlock *RightMBB;
10388   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10389       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10390     RightMBB = FirstRight->MBB;
10391   } else {
10392     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10393     FuncInfo.MF->insert(BBI, RightMBB);
10394     WorkList.push_back(
10395         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10396     // Put Cond in a virtual register to make it available from the new blocks.
10397     ExportFromCurrentBlock(Cond);
10398   }
10399 
10400   // Create the CaseBlock record that will be used to lower the branch.
10401   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10402                getCurSDLoc(), LeftProb, RightProb);
10403 
10404   if (W.MBB == SwitchMBB)
10405     visitSwitchCase(CB, SwitchMBB);
10406   else
10407     SL->SwitchCases.push_back(CB);
10408 }
10409 
10410 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10411 // from the swith statement.
10412 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10413                                             BranchProbability PeeledCaseProb) {
10414   if (PeeledCaseProb == BranchProbability::getOne())
10415     return BranchProbability::getZero();
10416   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10417 
10418   uint32_t Numerator = CaseProb.getNumerator();
10419   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10420   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10421 }
10422 
10423 // Try to peel the top probability case if it exceeds the threshold.
10424 // Return current MachineBasicBlock for the switch statement if the peeling
10425 // does not occur.
10426 // If the peeling is performed, return the newly created MachineBasicBlock
10427 // for the peeled switch statement. Also update Clusters to remove the peeled
10428 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10429 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10430     const SwitchInst &SI, CaseClusterVector &Clusters,
10431     BranchProbability &PeeledCaseProb) {
10432   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10433   // Don't perform if there is only one cluster or optimizing for size.
10434   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10435       TM.getOptLevel() == CodeGenOpt::None ||
10436       SwitchMBB->getParent()->getFunction().hasMinSize())
10437     return SwitchMBB;
10438 
10439   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10440   unsigned PeeledCaseIndex = 0;
10441   bool SwitchPeeled = false;
10442   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10443     CaseCluster &CC = Clusters[Index];
10444     if (CC.Prob < TopCaseProb)
10445       continue;
10446     TopCaseProb = CC.Prob;
10447     PeeledCaseIndex = Index;
10448     SwitchPeeled = true;
10449   }
10450   if (!SwitchPeeled)
10451     return SwitchMBB;
10452 
10453   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10454                     << TopCaseProb << "\n");
10455 
10456   // Record the MBB for the peeled switch statement.
10457   MachineFunction::iterator BBI(SwitchMBB);
10458   ++BBI;
10459   MachineBasicBlock *PeeledSwitchMBB =
10460       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10461   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10462 
10463   ExportFromCurrentBlock(SI.getCondition());
10464   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10465   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10466                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10467   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10468 
10469   Clusters.erase(PeeledCaseIt);
10470   for (CaseCluster &CC : Clusters) {
10471     LLVM_DEBUG(
10472         dbgs() << "Scale the probablity for one cluster, before scaling: "
10473                << CC.Prob << "\n");
10474     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10475     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10476   }
10477   PeeledCaseProb = TopCaseProb;
10478   return PeeledSwitchMBB;
10479 }
10480 
10481 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10482   // Extract cases from the switch.
10483   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10484   CaseClusterVector Clusters;
10485   Clusters.reserve(SI.getNumCases());
10486   for (auto I : SI.cases()) {
10487     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10488     const ConstantInt *CaseVal = I.getCaseValue();
10489     BranchProbability Prob =
10490         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10491             : BranchProbability(1, SI.getNumCases() + 1);
10492     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10493   }
10494 
10495   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10496 
10497   // Cluster adjacent cases with the same destination. We do this at all
10498   // optimization levels because it's cheap to do and will make codegen faster
10499   // if there are many clusters.
10500   sortAndRangeify(Clusters);
10501 
10502   // The branch probablity of the peeled case.
10503   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10504   MachineBasicBlock *PeeledSwitchMBB =
10505       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10506 
10507   // If there is only the default destination, jump there directly.
10508   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10509   if (Clusters.empty()) {
10510     assert(PeeledSwitchMBB == SwitchMBB);
10511     SwitchMBB->addSuccessor(DefaultMBB);
10512     if (DefaultMBB != NextBlock(SwitchMBB)) {
10513       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10514                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10515     }
10516     return;
10517   }
10518 
10519   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10520   SL->findBitTestClusters(Clusters, &SI);
10521 
10522   LLVM_DEBUG({
10523     dbgs() << "Case clusters: ";
10524     for (const CaseCluster &C : Clusters) {
10525       if (C.Kind == CC_JumpTable)
10526         dbgs() << "JT:";
10527       if (C.Kind == CC_BitTests)
10528         dbgs() << "BT:";
10529 
10530       C.Low->getValue().print(dbgs(), true);
10531       if (C.Low != C.High) {
10532         dbgs() << '-';
10533         C.High->getValue().print(dbgs(), true);
10534       }
10535       dbgs() << ' ';
10536     }
10537     dbgs() << '\n';
10538   });
10539 
10540   assert(!Clusters.empty());
10541   SwitchWorkList WorkList;
10542   CaseClusterIt First = Clusters.begin();
10543   CaseClusterIt Last = Clusters.end() - 1;
10544   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10545   // Scale the branchprobability for DefaultMBB if the peel occurs and
10546   // DefaultMBB is not replaced.
10547   if (PeeledCaseProb != BranchProbability::getZero() &&
10548       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10549     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10550   WorkList.push_back(
10551       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10552 
10553   while (!WorkList.empty()) {
10554     SwitchWorkListItem W = WorkList.back();
10555     WorkList.pop_back();
10556     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10557 
10558     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10559         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10560       // For optimized builds, lower large range as a balanced binary tree.
10561       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10562       continue;
10563     }
10564 
10565     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10566   }
10567 }
10568 
10569 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10570   SmallVector<EVT, 4> ValueVTs;
10571   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10572                   ValueVTs);
10573   unsigned NumValues = ValueVTs.size();
10574   if (NumValues == 0) return;
10575 
10576   SmallVector<SDValue, 4> Values(NumValues);
10577   SDValue Op = getValue(I.getOperand(0));
10578 
10579   for (unsigned i = 0; i != NumValues; ++i)
10580     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10581                             SDValue(Op.getNode(), Op.getResNo() + i));
10582 
10583   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10584                            DAG.getVTList(ValueVTs), Values));
10585 }
10586