xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 1ee6ec2bf370fbd1d93f34c8b56741a9d3f22ed2)
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 *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1401   SDValue Result;
1402 
1403   if (It != FuncInfo.ValueMap.end()) {
1404     unsigned 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 *, unsigned>::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 
2949 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2950   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2951 
2952   // Update machine-CFG edges with unique successors.
2953   SmallSet<BasicBlock*, 32> Done;
2954   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2955     BasicBlock *BB = I.getSuccessor(i);
2956     bool Inserted = Done.insert(BB).second;
2957     if (!Inserted)
2958         continue;
2959 
2960     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2961     addSuccessorWithProb(IndirectBrMBB, Succ);
2962   }
2963   IndirectBrMBB->normalizeSuccProbs();
2964 
2965   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2966                           MVT::Other, getControlRoot(),
2967                           getValue(I.getAddress())));
2968 }
2969 
2970 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2971   if (!DAG.getTarget().Options.TrapUnreachable)
2972     return;
2973 
2974   // We may be able to ignore unreachable behind a noreturn call.
2975   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2976     const BasicBlock &BB = *I.getParent();
2977     if (&I != &BB.front()) {
2978       BasicBlock::const_iterator PredI =
2979         std::prev(BasicBlock::const_iterator(&I));
2980       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2981         if (Call->doesNotReturn())
2982           return;
2983       }
2984     }
2985   }
2986 
2987   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2988 }
2989 
2990 void SelectionDAGBuilder::visitFSub(const User &I) {
2991   // -0.0 - X --> fneg
2992   Type *Ty = I.getType();
2993   if (isa<Constant>(I.getOperand(0)) &&
2994       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2995     SDValue Op2 = getValue(I.getOperand(1));
2996     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2997                              Op2.getValueType(), Op2));
2998     return;
2999   }
3000 
3001   visitBinary(I, ISD::FSUB);
3002 }
3003 
3004 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3005   SDNodeFlags Flags;
3006 
3007   SDValue Op = getValue(I.getOperand(0));
3008   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3009                                     Op, Flags);
3010   setValue(&I, UnNodeValue);
3011 }
3012 
3013 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3014   SDNodeFlags Flags;
3015   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3016     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3017     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3018   }
3019   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3020     Flags.setExact(ExactOp->isExact());
3021   }
3022 
3023   SDValue Op1 = getValue(I.getOperand(0));
3024   SDValue Op2 = getValue(I.getOperand(1));
3025   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3026                                      Op1, Op2, Flags);
3027   setValue(&I, BinNodeValue);
3028 }
3029 
3030 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3031   SDValue Op1 = getValue(I.getOperand(0));
3032   SDValue Op2 = getValue(I.getOperand(1));
3033 
3034   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3035       Op1.getValueType(), DAG.getDataLayout());
3036 
3037   // Coerce the shift amount to the right type if we can.
3038   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3039     unsigned ShiftSize = ShiftTy.getSizeInBits();
3040     unsigned Op2Size = Op2.getValueSizeInBits();
3041     SDLoc DL = getCurSDLoc();
3042 
3043     // If the operand is smaller than the shift count type, promote it.
3044     if (ShiftSize > Op2Size)
3045       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3046 
3047     // If the operand is larger than the shift count type but the shift
3048     // count type has enough bits to represent any shift value, truncate
3049     // it now. This is a common case and it exposes the truncate to
3050     // optimization early.
3051     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3052       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3053     // Otherwise we'll need to temporarily settle for some other convenient
3054     // type.  Type legalization will make adjustments once the shiftee is split.
3055     else
3056       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3057   }
3058 
3059   bool nuw = false;
3060   bool nsw = false;
3061   bool exact = false;
3062 
3063   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3064 
3065     if (const OverflowingBinaryOperator *OFBinOp =
3066             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3067       nuw = OFBinOp->hasNoUnsignedWrap();
3068       nsw = OFBinOp->hasNoSignedWrap();
3069     }
3070     if (const PossiblyExactOperator *ExactOp =
3071             dyn_cast<const PossiblyExactOperator>(&I))
3072       exact = ExactOp->isExact();
3073   }
3074   SDNodeFlags Flags;
3075   Flags.setExact(exact);
3076   Flags.setNoSignedWrap(nsw);
3077   Flags.setNoUnsignedWrap(nuw);
3078   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3079                             Flags);
3080   setValue(&I, Res);
3081 }
3082 
3083 void SelectionDAGBuilder::visitSDiv(const User &I) {
3084   SDValue Op1 = getValue(I.getOperand(0));
3085   SDValue Op2 = getValue(I.getOperand(1));
3086 
3087   SDNodeFlags Flags;
3088   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3089                  cast<PossiblyExactOperator>(&I)->isExact());
3090   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3091                            Op2, Flags));
3092 }
3093 
3094 void SelectionDAGBuilder::visitICmp(const User &I) {
3095   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3096   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3097     predicate = IC->getPredicate();
3098   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3099     predicate = ICmpInst::Predicate(IC->getPredicate());
3100   SDValue Op1 = getValue(I.getOperand(0));
3101   SDValue Op2 = getValue(I.getOperand(1));
3102   ISD::CondCode Opcode = getICmpCondCode(predicate);
3103 
3104   auto &TLI = DAG.getTargetLoweringInfo();
3105   EVT MemVT =
3106       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3107 
3108   // If a pointer's DAG type is larger than its memory type then the DAG values
3109   // are zero-extended. This breaks signed comparisons so truncate back to the
3110   // underlying type before doing the compare.
3111   if (Op1.getValueType() != MemVT) {
3112     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3113     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3114   }
3115 
3116   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3117                                                         I.getType());
3118   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3119 }
3120 
3121 void SelectionDAGBuilder::visitFCmp(const User &I) {
3122   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3123   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3124     predicate = FC->getPredicate();
3125   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3126     predicate = FCmpInst::Predicate(FC->getPredicate());
3127   SDValue Op1 = getValue(I.getOperand(0));
3128   SDValue Op2 = getValue(I.getOperand(1));
3129 
3130   ISD::CondCode Condition = getFCmpCondCode(predicate);
3131   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3132   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3133     Condition = getFCmpCodeWithoutNaN(Condition);
3134 
3135   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3136                                                         I.getType());
3137   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3138 }
3139 
3140 // Check if the condition of the select has one use or two users that are both
3141 // selects with the same condition.
3142 static bool hasOnlySelectUsers(const Value *Cond) {
3143   return llvm::all_of(Cond->users(), [](const Value *V) {
3144     return isa<SelectInst>(V);
3145   });
3146 }
3147 
3148 void SelectionDAGBuilder::visitSelect(const User &I) {
3149   SmallVector<EVT, 4> ValueVTs;
3150   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3151                   ValueVTs);
3152   unsigned NumValues = ValueVTs.size();
3153   if (NumValues == 0) return;
3154 
3155   SmallVector<SDValue, 4> Values(NumValues);
3156   SDValue Cond     = getValue(I.getOperand(0));
3157   SDValue LHSVal   = getValue(I.getOperand(1));
3158   SDValue RHSVal   = getValue(I.getOperand(2));
3159   SmallVector<SDValue, 1> BaseOps(1, Cond);
3160   ISD::NodeType OpCode =
3161       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3162 
3163   bool IsUnaryAbs = false;
3164 
3165   // Min/max matching is only viable if all output VTs are the same.
3166   if (is_splat(ValueVTs)) {
3167     EVT VT = ValueVTs[0];
3168     LLVMContext &Ctx = *DAG.getContext();
3169     auto &TLI = DAG.getTargetLoweringInfo();
3170 
3171     // We care about the legality of the operation after it has been type
3172     // legalized.
3173     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3174       VT = TLI.getTypeToTransformTo(Ctx, VT);
3175 
3176     // If the vselect is legal, assume we want to leave this as a vector setcc +
3177     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3178     // min/max is legal on the scalar type.
3179     bool UseScalarMinMax = VT.isVector() &&
3180       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3181 
3182     Value *LHS, *RHS;
3183     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3184     ISD::NodeType Opc = ISD::DELETED_NODE;
3185     switch (SPR.Flavor) {
3186     case SPF_UMAX:    Opc = ISD::UMAX; break;
3187     case SPF_UMIN:    Opc = ISD::UMIN; break;
3188     case SPF_SMAX:    Opc = ISD::SMAX; break;
3189     case SPF_SMIN:    Opc = ISD::SMIN; break;
3190     case SPF_FMINNUM:
3191       switch (SPR.NaNBehavior) {
3192       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3193       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3194       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3195       case SPNB_RETURNS_ANY: {
3196         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3197           Opc = ISD::FMINNUM;
3198         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3199           Opc = ISD::FMINIMUM;
3200         else if (UseScalarMinMax)
3201           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3202             ISD::FMINNUM : ISD::FMINIMUM;
3203         break;
3204       }
3205       }
3206       break;
3207     case SPF_FMAXNUM:
3208       switch (SPR.NaNBehavior) {
3209       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3210       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3211       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3212       case SPNB_RETURNS_ANY:
3213 
3214         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3215           Opc = ISD::FMAXNUM;
3216         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3217           Opc = ISD::FMAXIMUM;
3218         else if (UseScalarMinMax)
3219           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3220             ISD::FMAXNUM : ISD::FMAXIMUM;
3221         break;
3222       }
3223       break;
3224     case SPF_ABS:
3225       IsUnaryAbs = true;
3226       Opc = ISD::ABS;
3227       break;
3228     case SPF_NABS:
3229       // TODO: we need to produce sub(0, abs(X)).
3230     default: break;
3231     }
3232 
3233     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3234         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3235          (UseScalarMinMax &&
3236           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3237         // If the underlying comparison instruction is used by any other
3238         // instruction, the consumed instructions won't be destroyed, so it is
3239         // not profitable to convert to a min/max.
3240         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3241       OpCode = Opc;
3242       LHSVal = getValue(LHS);
3243       RHSVal = getValue(RHS);
3244       BaseOps.clear();
3245     }
3246 
3247     if (IsUnaryAbs) {
3248       OpCode = Opc;
3249       LHSVal = getValue(LHS);
3250       BaseOps.clear();
3251     }
3252   }
3253 
3254   if (IsUnaryAbs) {
3255     for (unsigned i = 0; i != NumValues; ++i) {
3256       Values[i] =
3257           DAG.getNode(OpCode, getCurSDLoc(),
3258                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3259                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3260     }
3261   } else {
3262     for (unsigned i = 0; i != NumValues; ++i) {
3263       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3264       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3265       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3266       Values[i] = DAG.getNode(
3267           OpCode, getCurSDLoc(),
3268           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3269     }
3270   }
3271 
3272   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3273                            DAG.getVTList(ValueVTs), Values));
3274 }
3275 
3276 void SelectionDAGBuilder::visitTrunc(const User &I) {
3277   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3278   SDValue N = getValue(I.getOperand(0));
3279   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3280                                                         I.getType());
3281   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3282 }
3283 
3284 void SelectionDAGBuilder::visitZExt(const User &I) {
3285   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3286   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3287   SDValue N = getValue(I.getOperand(0));
3288   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3289                                                         I.getType());
3290   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3291 }
3292 
3293 void SelectionDAGBuilder::visitSExt(const User &I) {
3294   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3295   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3296   SDValue N = getValue(I.getOperand(0));
3297   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3298                                                         I.getType());
3299   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3300 }
3301 
3302 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3303   // FPTrunc is never a no-op cast, no need to check
3304   SDValue N = getValue(I.getOperand(0));
3305   SDLoc dl = getCurSDLoc();
3306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3307   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3308   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3309                            DAG.getTargetConstant(
3310                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3311 }
3312 
3313 void SelectionDAGBuilder::visitFPExt(const User &I) {
3314   // FPExt is never a no-op cast, no need to check
3315   SDValue N = getValue(I.getOperand(0));
3316   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3317                                                         I.getType());
3318   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3319 }
3320 
3321 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3322   // FPToUI is never a no-op cast, no need to check
3323   SDValue N = getValue(I.getOperand(0));
3324   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3325                                                         I.getType());
3326   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3327 }
3328 
3329 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3330   // FPToSI is never a no-op cast, no need to check
3331   SDValue N = getValue(I.getOperand(0));
3332   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3333                                                         I.getType());
3334   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3335 }
3336 
3337 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3338   // UIToFP is never a no-op cast, no need to check
3339   SDValue N = getValue(I.getOperand(0));
3340   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3341                                                         I.getType());
3342   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3343 }
3344 
3345 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3346   // SIToFP is never a no-op cast, no need to check
3347   SDValue N = getValue(I.getOperand(0));
3348   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3349                                                         I.getType());
3350   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3351 }
3352 
3353 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3354   // What to do depends on the size of the integer and the size of the pointer.
3355   // We can either truncate, zero extend, or no-op, accordingly.
3356   SDValue N = getValue(I.getOperand(0));
3357   auto &TLI = DAG.getTargetLoweringInfo();
3358   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3359                                                         I.getType());
3360   EVT PtrMemVT =
3361       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3362   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3363   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3364   setValue(&I, N);
3365 }
3366 
3367 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3368   // What to do depends on the size of the integer and the size of the pointer.
3369   // We can either truncate, zero extend, or no-op, accordingly.
3370   SDValue N = getValue(I.getOperand(0));
3371   auto &TLI = DAG.getTargetLoweringInfo();
3372   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3373   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3374   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3375   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3376   setValue(&I, N);
3377 }
3378 
3379 void SelectionDAGBuilder::visitBitCast(const User &I) {
3380   SDValue N = getValue(I.getOperand(0));
3381   SDLoc dl = getCurSDLoc();
3382   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3383                                                         I.getType());
3384 
3385   // BitCast assures us that source and destination are the same size so this is
3386   // either a BITCAST or a no-op.
3387   if (DestVT != N.getValueType())
3388     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3389                              DestVT, N)); // convert types.
3390   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3391   // might fold any kind of constant expression to an integer constant and that
3392   // is not what we are looking for. Only recognize a bitcast of a genuine
3393   // constant integer as an opaque constant.
3394   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3395     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3396                                  /*isOpaque*/true));
3397   else
3398     setValue(&I, N);            // noop cast.
3399 }
3400 
3401 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3403   const Value *SV = I.getOperand(0);
3404   SDValue N = getValue(SV);
3405   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3406 
3407   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3408   unsigned DestAS = I.getType()->getPointerAddressSpace();
3409 
3410   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3411     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3412 
3413   setValue(&I, N);
3414 }
3415 
3416 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3418   SDValue InVec = getValue(I.getOperand(0));
3419   SDValue InVal = getValue(I.getOperand(1));
3420   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3421                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3422   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3423                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3424                            InVec, InVal, InIdx));
3425 }
3426 
3427 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3429   SDValue InVec = getValue(I.getOperand(0));
3430   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3431                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3432   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3433                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3434                            InVec, InIdx));
3435 }
3436 
3437 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3438   SDValue Src1 = getValue(I.getOperand(0));
3439   SDValue Src2 = getValue(I.getOperand(1));
3440   ArrayRef<int> Mask;
3441   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3442     Mask = SVI->getShuffleMask();
3443   else
3444     Mask = cast<ConstantExpr>(I).getShuffleMask();
3445   SDLoc DL = getCurSDLoc();
3446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3447   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3448   EVT SrcVT = Src1.getValueType();
3449   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3450 
3451   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3452       VT.isScalableVector()) {
3453     // Canonical splat form of first element of first input vector.
3454     SDValue FirstElt =
3455         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3456                     DAG.getVectorIdxConstant(0, DL));
3457     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3458     return;
3459   }
3460 
3461   // For now, we only handle splats for scalable vectors.
3462   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3463   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3464   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3465 
3466   unsigned MaskNumElts = Mask.size();
3467 
3468   if (SrcNumElts == MaskNumElts) {
3469     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3470     return;
3471   }
3472 
3473   // Normalize the shuffle vector since mask and vector length don't match.
3474   if (SrcNumElts < MaskNumElts) {
3475     // Mask is longer than the source vectors. We can use concatenate vector to
3476     // make the mask and vectors lengths match.
3477 
3478     if (MaskNumElts % SrcNumElts == 0) {
3479       // Mask length is a multiple of the source vector length.
3480       // Check if the shuffle is some kind of concatenation of the input
3481       // vectors.
3482       unsigned NumConcat = MaskNumElts / SrcNumElts;
3483       bool IsConcat = true;
3484       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3485       for (unsigned i = 0; i != MaskNumElts; ++i) {
3486         int Idx = Mask[i];
3487         if (Idx < 0)
3488           continue;
3489         // Ensure the indices in each SrcVT sized piece are sequential and that
3490         // the same source is used for the whole piece.
3491         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3492             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3493              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3494           IsConcat = false;
3495           break;
3496         }
3497         // Remember which source this index came from.
3498         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3499       }
3500 
3501       // The shuffle is concatenating multiple vectors together. Just emit
3502       // a CONCAT_VECTORS operation.
3503       if (IsConcat) {
3504         SmallVector<SDValue, 8> ConcatOps;
3505         for (auto Src : ConcatSrcs) {
3506           if (Src < 0)
3507             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3508           else if (Src == 0)
3509             ConcatOps.push_back(Src1);
3510           else
3511             ConcatOps.push_back(Src2);
3512         }
3513         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3514         return;
3515       }
3516     }
3517 
3518     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3519     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3520     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3521                                     PaddedMaskNumElts);
3522 
3523     // Pad both vectors with undefs to make them the same length as the mask.
3524     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3525 
3526     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3527     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3528     MOps1[0] = Src1;
3529     MOps2[0] = Src2;
3530 
3531     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3532     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3533 
3534     // Readjust mask for new input vector length.
3535     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3536     for (unsigned i = 0; i != MaskNumElts; ++i) {
3537       int Idx = Mask[i];
3538       if (Idx >= (int)SrcNumElts)
3539         Idx -= SrcNumElts - PaddedMaskNumElts;
3540       MappedOps[i] = Idx;
3541     }
3542 
3543     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3544 
3545     // If the concatenated vector was padded, extract a subvector with the
3546     // correct number of elements.
3547     if (MaskNumElts != PaddedMaskNumElts)
3548       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3549                            DAG.getVectorIdxConstant(0, DL));
3550 
3551     setValue(&I, Result);
3552     return;
3553   }
3554 
3555   if (SrcNumElts > MaskNumElts) {
3556     // Analyze the access pattern of the vector to see if we can extract
3557     // two subvectors and do the shuffle.
3558     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3559     bool CanExtract = true;
3560     for (int Idx : Mask) {
3561       unsigned Input = 0;
3562       if (Idx < 0)
3563         continue;
3564 
3565       if (Idx >= (int)SrcNumElts) {
3566         Input = 1;
3567         Idx -= SrcNumElts;
3568       }
3569 
3570       // If all the indices come from the same MaskNumElts sized portion of
3571       // the sources we can use extract. Also make sure the extract wouldn't
3572       // extract past the end of the source.
3573       int NewStartIdx = alignDown(Idx, MaskNumElts);
3574       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3575           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3576         CanExtract = false;
3577       // Make sure we always update StartIdx as we use it to track if all
3578       // elements are undef.
3579       StartIdx[Input] = NewStartIdx;
3580     }
3581 
3582     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3583       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3584       return;
3585     }
3586     if (CanExtract) {
3587       // Extract appropriate subvector and generate a vector shuffle
3588       for (unsigned Input = 0; Input < 2; ++Input) {
3589         SDValue &Src = Input == 0 ? Src1 : Src2;
3590         if (StartIdx[Input] < 0)
3591           Src = DAG.getUNDEF(VT);
3592         else {
3593           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3594                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3595         }
3596       }
3597 
3598       // Calculate new mask.
3599       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3600       for (int &Idx : MappedOps) {
3601         if (Idx >= (int)SrcNumElts)
3602           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3603         else if (Idx >= 0)
3604           Idx -= StartIdx[0];
3605       }
3606 
3607       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3608       return;
3609     }
3610   }
3611 
3612   // We can't use either concat vectors or extract subvectors so fall back to
3613   // replacing the shuffle with extract and build vector.
3614   // to insert and build vector.
3615   EVT EltVT = VT.getVectorElementType();
3616   SmallVector<SDValue,8> Ops;
3617   for (int Idx : Mask) {
3618     SDValue Res;
3619 
3620     if (Idx < 0) {
3621       Res = DAG.getUNDEF(EltVT);
3622     } else {
3623       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3624       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3625 
3626       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3627                         DAG.getVectorIdxConstant(Idx, DL));
3628     }
3629 
3630     Ops.push_back(Res);
3631   }
3632 
3633   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3634 }
3635 
3636 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3637   ArrayRef<unsigned> Indices;
3638   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3639     Indices = IV->getIndices();
3640   else
3641     Indices = cast<ConstantExpr>(&I)->getIndices();
3642 
3643   const Value *Op0 = I.getOperand(0);
3644   const Value *Op1 = I.getOperand(1);
3645   Type *AggTy = I.getType();
3646   Type *ValTy = Op1->getType();
3647   bool IntoUndef = isa<UndefValue>(Op0);
3648   bool FromUndef = isa<UndefValue>(Op1);
3649 
3650   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3651 
3652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3653   SmallVector<EVT, 4> AggValueVTs;
3654   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3655   SmallVector<EVT, 4> ValValueVTs;
3656   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3657 
3658   unsigned NumAggValues = AggValueVTs.size();
3659   unsigned NumValValues = ValValueVTs.size();
3660   SmallVector<SDValue, 4> Values(NumAggValues);
3661 
3662   // Ignore an insertvalue that produces an empty object
3663   if (!NumAggValues) {
3664     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3665     return;
3666   }
3667 
3668   SDValue Agg = getValue(Op0);
3669   unsigned i = 0;
3670   // Copy the beginning value(s) from the original aggregate.
3671   for (; i != LinearIndex; ++i)
3672     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3673                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3674   // Copy values from the inserted value(s).
3675   if (NumValValues) {
3676     SDValue Val = getValue(Op1);
3677     for (; i != LinearIndex + NumValValues; ++i)
3678       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3679                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3680   }
3681   // Copy remaining value(s) from the original aggregate.
3682   for (; i != NumAggValues; ++i)
3683     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3684                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3685 
3686   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3687                            DAG.getVTList(AggValueVTs), Values));
3688 }
3689 
3690 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3691   ArrayRef<unsigned> Indices;
3692   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3693     Indices = EV->getIndices();
3694   else
3695     Indices = cast<ConstantExpr>(&I)->getIndices();
3696 
3697   const Value *Op0 = I.getOperand(0);
3698   Type *AggTy = Op0->getType();
3699   Type *ValTy = I.getType();
3700   bool OutOfUndef = isa<UndefValue>(Op0);
3701 
3702   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3703 
3704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3705   SmallVector<EVT, 4> ValValueVTs;
3706   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3707 
3708   unsigned NumValValues = ValValueVTs.size();
3709 
3710   // Ignore a extractvalue that produces an empty object
3711   if (!NumValValues) {
3712     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3713     return;
3714   }
3715 
3716   SmallVector<SDValue, 4> Values(NumValValues);
3717 
3718   SDValue Agg = getValue(Op0);
3719   // Copy out the selected value(s).
3720   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3721     Values[i - LinearIndex] =
3722       OutOfUndef ?
3723         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3724         SDValue(Agg.getNode(), Agg.getResNo() + i);
3725 
3726   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3727                            DAG.getVTList(ValValueVTs), Values));
3728 }
3729 
3730 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3731   Value *Op0 = I.getOperand(0);
3732   // Note that the pointer operand may be a vector of pointers. Take the scalar
3733   // element which holds a pointer.
3734   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3735   SDValue N = getValue(Op0);
3736   SDLoc dl = getCurSDLoc();
3737   auto &TLI = DAG.getTargetLoweringInfo();
3738   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3739   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3740 
3741   // Normalize Vector GEP - all scalar operands should be converted to the
3742   // splat vector.
3743   bool IsVectorGEP = I.getType()->isVectorTy();
3744   ElementCount VectorElementCount = IsVectorGEP ?
3745     I.getType()->getVectorElementCount() : ElementCount(0, false);
3746 
3747   if (IsVectorGEP && !N.getValueType().isVector()) {
3748     LLVMContext &Context = *DAG.getContext();
3749     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3750     if (VectorElementCount.Scalable)
3751       N = DAG.getSplatVector(VT, dl, N);
3752     else
3753       N = DAG.getSplatBuildVector(VT, dl, N);
3754   }
3755 
3756   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3757        GTI != E; ++GTI) {
3758     const Value *Idx = GTI.getOperand();
3759     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3760       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3761       if (Field) {
3762         // N = N + Offset
3763         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3764 
3765         // In an inbounds GEP with an offset that is nonnegative even when
3766         // interpreted as signed, assume there is no unsigned overflow.
3767         SDNodeFlags Flags;
3768         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3769           Flags.setNoUnsignedWrap(true);
3770 
3771         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3772                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3773       }
3774     } else {
3775       // IdxSize is the width of the arithmetic according to IR semantics.
3776       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3777       // (and fix up the result later).
3778       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3779       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3780       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3781       // We intentionally mask away the high bits here; ElementSize may not
3782       // fit in IdxTy.
3783       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3784       bool ElementScalable = ElementSize.isScalable();
3785 
3786       // If this is a scalar constant or a splat vector of constants,
3787       // handle it quickly.
3788       const auto *C = dyn_cast<Constant>(Idx);
3789       if (C && isa<VectorType>(C->getType()))
3790         C = C->getSplatValue();
3791 
3792       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3793       if (CI && CI->isZero())
3794         continue;
3795       if (CI && !ElementScalable) {
3796         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3797         LLVMContext &Context = *DAG.getContext();
3798         SDValue OffsVal;
3799         if (IsVectorGEP)
3800           OffsVal = DAG.getConstant(
3801               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3802         else
3803           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3804 
3805         // In an inbounds GEP with an offset that is nonnegative even when
3806         // interpreted as signed, assume there is no unsigned overflow.
3807         SDNodeFlags Flags;
3808         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3809           Flags.setNoUnsignedWrap(true);
3810 
3811         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3812 
3813         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3814         continue;
3815       }
3816 
3817       // N = N + Idx * ElementMul;
3818       SDValue IdxN = getValue(Idx);
3819 
3820       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3821         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3822                                   VectorElementCount);
3823         if (VectorElementCount.Scalable)
3824           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3825         else
3826           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3827       }
3828 
3829       // If the index is smaller or larger than intptr_t, truncate or extend
3830       // it.
3831       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3832 
3833       if (ElementScalable) {
3834         EVT VScaleTy = N.getValueType().getScalarType();
3835         SDValue VScale = DAG.getNode(
3836             ISD::VSCALE, dl, VScaleTy,
3837             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3838         if (IsVectorGEP)
3839           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3840         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3841       } else {
3842         // If this is a multiply by a power of two, turn it into a shl
3843         // immediately.  This is a very common case.
3844         if (ElementMul != 1) {
3845           if (ElementMul.isPowerOf2()) {
3846             unsigned Amt = ElementMul.logBase2();
3847             IdxN = DAG.getNode(ISD::SHL, dl,
3848                                N.getValueType(), IdxN,
3849                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3850           } else {
3851             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3852                                             IdxN.getValueType());
3853             IdxN = DAG.getNode(ISD::MUL, dl,
3854                                N.getValueType(), IdxN, Scale);
3855           }
3856         }
3857       }
3858 
3859       N = DAG.getNode(ISD::ADD, dl,
3860                       N.getValueType(), N, IdxN);
3861     }
3862   }
3863 
3864   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3865     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3866 
3867   setValue(&I, N);
3868 }
3869 
3870 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3871   // If this is a fixed sized alloca in the entry block of the function,
3872   // allocate it statically on the stack.
3873   if (FuncInfo.StaticAllocaMap.count(&I))
3874     return;   // getValue will auto-populate this.
3875 
3876   SDLoc dl = getCurSDLoc();
3877   Type *Ty = I.getAllocatedType();
3878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3879   auto &DL = DAG.getDataLayout();
3880   uint64_t TySize = DL.getTypeAllocSize(Ty);
3881   MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign());
3882 
3883   SDValue AllocSize = getValue(I.getArraySize());
3884 
3885   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3886   if (AllocSize.getValueType() != IntPtr)
3887     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3888 
3889   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3890                           AllocSize,
3891                           DAG.getConstant(TySize, dl, IntPtr));
3892 
3893   // Handle alignment.  If the requested alignment is less than or equal to
3894   // the stack alignment, ignore it.  If the size is greater than or equal to
3895   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3896   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3897   if (Alignment <= StackAlign)
3898     Alignment = None;
3899 
3900   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3901   // Round the size of the allocation up to the stack alignment size
3902   // by add SA-1 to the size. This doesn't overflow because we're computing
3903   // an address inside an alloca.
3904   SDNodeFlags Flags;
3905   Flags.setNoUnsignedWrap(true);
3906   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3907                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3908 
3909   // Mask out the low bits for alignment purposes.
3910   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3911                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3912 
3913   SDValue Ops[] = {
3914       getRoot(), AllocSize,
3915       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3916   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3917   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3918   setValue(&I, DSA);
3919   DAG.setRoot(DSA.getValue(1));
3920 
3921   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3922 }
3923 
3924 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3925   if (I.isAtomic())
3926     return visitAtomicLoad(I);
3927 
3928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3929   const Value *SV = I.getOperand(0);
3930   if (TLI.supportSwiftError()) {
3931     // Swifterror values can come from either a function parameter with
3932     // swifterror attribute or an alloca with swifterror attribute.
3933     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3934       if (Arg->hasSwiftErrorAttr())
3935         return visitLoadFromSwiftError(I);
3936     }
3937 
3938     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3939       if (Alloca->isSwiftError())
3940         return visitLoadFromSwiftError(I);
3941     }
3942   }
3943 
3944   SDValue Ptr = getValue(SV);
3945 
3946   Type *Ty = I.getType();
3947   unsigned Alignment = I.getAlignment();
3948 
3949   AAMDNodes AAInfo;
3950   I.getAAMetadata(AAInfo);
3951   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3952 
3953   SmallVector<EVT, 4> ValueVTs, MemVTs;
3954   SmallVector<uint64_t, 4> Offsets;
3955   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3956   unsigned NumValues = ValueVTs.size();
3957   if (NumValues == 0)
3958     return;
3959 
3960   bool isVolatile = I.isVolatile();
3961 
3962   SDValue Root;
3963   bool ConstantMemory = false;
3964   if (isVolatile)
3965     // Serialize volatile loads with other side effects.
3966     Root = getRoot();
3967   else if (NumValues > MaxParallelChains)
3968     Root = getMemoryRoot();
3969   else if (AA &&
3970            AA->pointsToConstantMemory(MemoryLocation(
3971                SV,
3972                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3973                AAInfo))) {
3974     // Do not serialize (non-volatile) loads of constant memory with anything.
3975     Root = DAG.getEntryNode();
3976     ConstantMemory = true;
3977   } else {
3978     // Do not serialize non-volatile loads against each other.
3979     Root = DAG.getRoot();
3980   }
3981 
3982   SDLoc dl = getCurSDLoc();
3983 
3984   if (isVolatile)
3985     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3986 
3987   // An aggregate load cannot wrap around the address space, so offsets to its
3988   // parts don't wrap either.
3989   SDNodeFlags Flags;
3990   Flags.setNoUnsignedWrap(true);
3991 
3992   SmallVector<SDValue, 4> Values(NumValues);
3993   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3994   EVT PtrVT = Ptr.getValueType();
3995 
3996   MachineMemOperand::Flags MMOFlags
3997     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
3998 
3999   unsigned ChainI = 0;
4000   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4001     // Serializing loads here may result in excessive register pressure, and
4002     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4003     // could recover a bit by hoisting nodes upward in the chain by recognizing
4004     // they are side-effect free or do not alias. The optimizer should really
4005     // avoid this case by converting large object/array copies to llvm.memcpy
4006     // (MaxParallelChains should always remain as failsafe).
4007     if (ChainI == MaxParallelChains) {
4008       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4009       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4010                                   makeArrayRef(Chains.data(), ChainI));
4011       Root = Chain;
4012       ChainI = 0;
4013     }
4014     SDValue A = DAG.getNode(ISD::ADD, dl,
4015                             PtrVT, Ptr,
4016                             DAG.getConstant(Offsets[i], dl, PtrVT),
4017                             Flags);
4018 
4019     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4020                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4021                             MMOFlags, AAInfo, Ranges);
4022     Chains[ChainI] = L.getValue(1);
4023 
4024     if (MemVTs[i] != ValueVTs[i])
4025       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4026 
4027     Values[i] = L;
4028   }
4029 
4030   if (!ConstantMemory) {
4031     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4032                                 makeArrayRef(Chains.data(), ChainI));
4033     if (isVolatile)
4034       DAG.setRoot(Chain);
4035     else
4036       PendingLoads.push_back(Chain);
4037   }
4038 
4039   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4040                            DAG.getVTList(ValueVTs), Values));
4041 }
4042 
4043 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4044   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4045          "call visitStoreToSwiftError when backend supports swifterror");
4046 
4047   SmallVector<EVT, 4> ValueVTs;
4048   SmallVector<uint64_t, 4> Offsets;
4049   const Value *SrcV = I.getOperand(0);
4050   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4051                   SrcV->getType(), ValueVTs, &Offsets);
4052   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4053          "expect a single EVT for swifterror");
4054 
4055   SDValue Src = getValue(SrcV);
4056   // Create a virtual register, then update the virtual register.
4057   Register VReg =
4058       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4059   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4060   // Chain can be getRoot or getControlRoot.
4061   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4062                                       SDValue(Src.getNode(), Src.getResNo()));
4063   DAG.setRoot(CopyNode);
4064 }
4065 
4066 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4067   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4068          "call visitLoadFromSwiftError when backend supports swifterror");
4069 
4070   assert(!I.isVolatile() &&
4071          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4072          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4073          "Support volatile, non temporal, invariant for load_from_swift_error");
4074 
4075   const Value *SV = I.getOperand(0);
4076   Type *Ty = I.getType();
4077   AAMDNodes AAInfo;
4078   I.getAAMetadata(AAInfo);
4079   assert(
4080       (!AA ||
4081        !AA->pointsToConstantMemory(MemoryLocation(
4082            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4083            AAInfo))) &&
4084       "load_from_swift_error should not be constant memory");
4085 
4086   SmallVector<EVT, 4> ValueVTs;
4087   SmallVector<uint64_t, 4> Offsets;
4088   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4089                   ValueVTs, &Offsets);
4090   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4091          "expect a single EVT for swifterror");
4092 
4093   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4094   SDValue L = DAG.getCopyFromReg(
4095       getRoot(), getCurSDLoc(),
4096       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4097 
4098   setValue(&I, L);
4099 }
4100 
4101 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4102   if (I.isAtomic())
4103     return visitAtomicStore(I);
4104 
4105   const Value *SrcV = I.getOperand(0);
4106   const Value *PtrV = I.getOperand(1);
4107 
4108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4109   if (TLI.supportSwiftError()) {
4110     // Swifterror values can come from either a function parameter with
4111     // swifterror attribute or an alloca with swifterror attribute.
4112     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4113       if (Arg->hasSwiftErrorAttr())
4114         return visitStoreToSwiftError(I);
4115     }
4116 
4117     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4118       if (Alloca->isSwiftError())
4119         return visitStoreToSwiftError(I);
4120     }
4121   }
4122 
4123   SmallVector<EVT, 4> ValueVTs, MemVTs;
4124   SmallVector<uint64_t, 4> Offsets;
4125   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4126                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4127   unsigned NumValues = ValueVTs.size();
4128   if (NumValues == 0)
4129     return;
4130 
4131   // Get the lowered operands. Note that we do this after
4132   // checking if NumResults is zero, because with zero results
4133   // the operands won't have values in the map.
4134   SDValue Src = getValue(SrcV);
4135   SDValue Ptr = getValue(PtrV);
4136 
4137   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4138   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4139   SDLoc dl = getCurSDLoc();
4140   unsigned Alignment = I.getAlignment();
4141   AAMDNodes AAInfo;
4142   I.getAAMetadata(AAInfo);
4143 
4144   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4145 
4146   // An aggregate load cannot wrap around the address space, so offsets to its
4147   // parts don't wrap either.
4148   SDNodeFlags Flags;
4149   Flags.setNoUnsignedWrap(true);
4150 
4151   unsigned ChainI = 0;
4152   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4153     // See visitLoad comments.
4154     if (ChainI == MaxParallelChains) {
4155       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4156                                   makeArrayRef(Chains.data(), ChainI));
4157       Root = Chain;
4158       ChainI = 0;
4159     }
4160     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4161     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4162     if (MemVTs[i] != ValueVTs[i])
4163       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4164     SDValue St =
4165         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4166                      Alignment, MMOFlags, AAInfo);
4167     Chains[ChainI] = St;
4168   }
4169 
4170   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4171                                   makeArrayRef(Chains.data(), ChainI));
4172   DAG.setRoot(StoreNode);
4173 }
4174 
4175 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4176                                            bool IsCompressing) {
4177   SDLoc sdl = getCurSDLoc();
4178 
4179   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4180                                MaybeAlign &Alignment) {
4181     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4182     Src0 = I.getArgOperand(0);
4183     Ptr = I.getArgOperand(1);
4184     Alignment =
4185         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4186     Mask = I.getArgOperand(3);
4187   };
4188   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4189                                     MaybeAlign &Alignment) {
4190     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4191     Src0 = I.getArgOperand(0);
4192     Ptr = I.getArgOperand(1);
4193     Mask = I.getArgOperand(2);
4194     Alignment = None;
4195   };
4196 
4197   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4198   MaybeAlign Alignment;
4199   if (IsCompressing)
4200     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4201   else
4202     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4203 
4204   SDValue Ptr = getValue(PtrOperand);
4205   SDValue Src0 = getValue(Src0Operand);
4206   SDValue Mask = getValue(MaskOperand);
4207   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4208 
4209   EVT VT = Src0.getValueType();
4210   if (!Alignment)
4211     Alignment = DAG.getEVTAlign(VT);
4212 
4213   AAMDNodes AAInfo;
4214   I.getAAMetadata(AAInfo);
4215 
4216   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4217       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4218       // TODO: Make MachineMemOperands aware of scalable
4219       // vectors.
4220       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4221   SDValue StoreNode =
4222       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4223                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4224   DAG.setRoot(StoreNode);
4225   setValue(&I, StoreNode);
4226 }
4227 
4228 // Get a uniform base for the Gather/Scatter intrinsic.
4229 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4230 // We try to represent it as a base pointer + vector of indices.
4231 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4232 // The first operand of the GEP may be a single pointer or a vector of pointers
4233 // Example:
4234 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4235 //  or
4236 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4237 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4238 //
4239 // When the first GEP operand is a single pointer - it is the uniform base we
4240 // are looking for. If first operand of the GEP is a splat vector - we
4241 // extract the splat value and use it as a uniform base.
4242 // In all other cases the function returns 'false'.
4243 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4244                            ISD::MemIndexType &IndexType, SDValue &Scale,
4245                            SelectionDAGBuilder *SDB) {
4246   SelectionDAG& DAG = SDB->DAG;
4247   LLVMContext &Context = *DAG.getContext();
4248 
4249   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4250   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4251   if (!GEP)
4252     return false;
4253 
4254   const Value *BasePtr = GEP->getPointerOperand();
4255   if (BasePtr->getType()->isVectorTy()) {
4256     BasePtr = getSplatValue(BasePtr);
4257     if (!BasePtr)
4258       return false;
4259   }
4260 
4261   unsigned FinalIndex = GEP->getNumOperands() - 1;
4262   Value *IndexVal = GEP->getOperand(FinalIndex);
4263   gep_type_iterator GTI = gep_type_begin(*GEP);
4264 
4265   // Ensure all the other indices are 0.
4266   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4267     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4268     if (!C)
4269       return false;
4270     if (isa<VectorType>(C->getType()))
4271       C = C->getSplatValue();
4272     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4273     if (!CI || !CI->isZero())
4274       return false;
4275   }
4276 
4277   // The operands of the GEP may be defined in another basic block.
4278   // In this case we'll not find nodes for the operands.
4279   if (!SDB->findValue(BasePtr))
4280     return false;
4281   Constant *C = dyn_cast<Constant>(IndexVal);
4282   if (!C && !SDB->findValue(IndexVal))
4283     return false;
4284 
4285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4286   const DataLayout &DL = DAG.getDataLayout();
4287   StructType *STy = GTI.getStructTypeOrNull();
4288 
4289   if (STy) {
4290     const StructLayout *SL = DL.getStructLayout(STy);
4291     unsigned Field = cast<Constant>(IndexVal)->getUniqueInteger().getZExtValue();
4292     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4293     Index = DAG.getConstant(SL->getElementOffset(Field),
4294                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4295   } else {
4296     Scale = DAG.getTargetConstant(
4297                 DL.getTypeAllocSize(GEP->getResultElementType()),
4298                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4299     Index = SDB->getValue(IndexVal);
4300   }
4301   Base = SDB->getValue(BasePtr);
4302   IndexType = ISD::SIGNED_SCALED;
4303 
4304   if (STy || !Index.getValueType().isVector()) {
4305     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4306     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4307     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4308   }
4309   return true;
4310 }
4311 
4312 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4313   SDLoc sdl = getCurSDLoc();
4314 
4315   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4316   const Value *Ptr = I.getArgOperand(1);
4317   SDValue Src0 = getValue(I.getArgOperand(0));
4318   SDValue Mask = getValue(I.getArgOperand(3));
4319   EVT VT = Src0.getValueType();
4320   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4321   if (!Alignment)
4322     Alignment = DAG.getEVTAlign(VT);
4323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4324 
4325   AAMDNodes AAInfo;
4326   I.getAAMetadata(AAInfo);
4327 
4328   SDValue Base;
4329   SDValue Index;
4330   ISD::MemIndexType IndexType;
4331   SDValue Scale;
4332   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this);
4333 
4334   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4335   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4336       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4337       // TODO: Make MachineMemOperands aware of scalable
4338       // vectors.
4339       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4340   if (!UniformBase) {
4341     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4342     Index = getValue(Ptr);
4343     IndexType = ISD::SIGNED_SCALED;
4344     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4345   }
4346   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4347   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4348                                          Ops, MMO, IndexType);
4349   DAG.setRoot(Scatter);
4350   setValue(&I, Scatter);
4351 }
4352 
4353 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4354   SDLoc sdl = getCurSDLoc();
4355 
4356   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4357                               MaybeAlign &Alignment) {
4358     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4359     Ptr = I.getArgOperand(0);
4360     Alignment =
4361         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4362     Mask = I.getArgOperand(2);
4363     Src0 = I.getArgOperand(3);
4364   };
4365   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4366                                  MaybeAlign &Alignment) {
4367     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4368     Ptr = I.getArgOperand(0);
4369     Alignment = None;
4370     Mask = I.getArgOperand(1);
4371     Src0 = I.getArgOperand(2);
4372   };
4373 
4374   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4375   MaybeAlign Alignment;
4376   if (IsExpanding)
4377     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4378   else
4379     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4380 
4381   SDValue Ptr = getValue(PtrOperand);
4382   SDValue Src0 = getValue(Src0Operand);
4383   SDValue Mask = getValue(MaskOperand);
4384   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4385 
4386   EVT VT = Src0.getValueType();
4387   if (!Alignment)
4388     Alignment = DAG.getEVTAlign(VT);
4389 
4390   AAMDNodes AAInfo;
4391   I.getAAMetadata(AAInfo);
4392   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4393 
4394   // Do not serialize masked loads of constant memory with anything.
4395   MemoryLocation ML;
4396   if (VT.isScalableVector())
4397     ML = MemoryLocation(PtrOperand);
4398   else
4399     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4400                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4401                            AAInfo);
4402   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4403 
4404   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4405 
4406   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4407       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4408       // TODO: Make MachineMemOperands aware of scalable
4409       // vectors.
4410       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4411 
4412   SDValue Load =
4413       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4414                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4415   if (AddToChain)
4416     PendingLoads.push_back(Load.getValue(1));
4417   setValue(&I, Load);
4418 }
4419 
4420 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4421   SDLoc sdl = getCurSDLoc();
4422 
4423   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4424   const Value *Ptr = I.getArgOperand(0);
4425   SDValue Src0 = getValue(I.getArgOperand(3));
4426   SDValue Mask = getValue(I.getArgOperand(2));
4427 
4428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4429   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4430   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4431   if (!Alignment)
4432     Alignment = DAG.getEVTAlign(VT);
4433 
4434   AAMDNodes AAInfo;
4435   I.getAAMetadata(AAInfo);
4436   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4437 
4438   SDValue Root = DAG.getRoot();
4439   SDValue Base;
4440   SDValue Index;
4441   ISD::MemIndexType IndexType;
4442   SDValue Scale;
4443   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this);
4444   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4445   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4446       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4447       // TODO: Make MachineMemOperands aware of scalable
4448       // vectors.
4449       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4450 
4451   if (!UniformBase) {
4452     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4453     Index = getValue(Ptr);
4454     IndexType = ISD::SIGNED_SCALED;
4455     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4456   }
4457   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4458   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4459                                        Ops, MMO, IndexType);
4460 
4461   PendingLoads.push_back(Gather.getValue(1));
4462   setValue(&I, Gather);
4463 }
4464 
4465 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4466   SDLoc dl = getCurSDLoc();
4467   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4468   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4469   SyncScope::ID SSID = I.getSyncScopeID();
4470 
4471   SDValue InChain = getRoot();
4472 
4473   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4474   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4475 
4476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4477   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4478 
4479   MachineFunction &MF = DAG.getMachineFunction();
4480   MachineMemOperand *MMO = MF.getMachineMemOperand(
4481       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4482       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4483       FailureOrdering);
4484 
4485   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4486                                    dl, MemVT, VTs, InChain,
4487                                    getValue(I.getPointerOperand()),
4488                                    getValue(I.getCompareOperand()),
4489                                    getValue(I.getNewValOperand()), MMO);
4490 
4491   SDValue OutChain = L.getValue(2);
4492 
4493   setValue(&I, L);
4494   DAG.setRoot(OutChain);
4495 }
4496 
4497 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4498   SDLoc dl = getCurSDLoc();
4499   ISD::NodeType NT;
4500   switch (I.getOperation()) {
4501   default: llvm_unreachable("Unknown atomicrmw operation");
4502   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4503   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4504   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4505   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4506   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4507   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4508   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4509   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4510   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4511   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4512   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4513   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4514   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4515   }
4516   AtomicOrdering Ordering = I.getOrdering();
4517   SyncScope::ID SSID = I.getSyncScopeID();
4518 
4519   SDValue InChain = getRoot();
4520 
4521   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4523   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4524 
4525   MachineFunction &MF = DAG.getMachineFunction();
4526   MachineMemOperand *MMO = MF.getMachineMemOperand(
4527       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4528       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4529 
4530   SDValue L =
4531     DAG.getAtomic(NT, dl, MemVT, InChain,
4532                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4533                   MMO);
4534 
4535   SDValue OutChain = L.getValue(1);
4536 
4537   setValue(&I, L);
4538   DAG.setRoot(OutChain);
4539 }
4540 
4541 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4542   SDLoc dl = getCurSDLoc();
4543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4544   SDValue Ops[3];
4545   Ops[0] = getRoot();
4546   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4547                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4548   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4549                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4550   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4551 }
4552 
4553 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4554   SDLoc dl = getCurSDLoc();
4555   AtomicOrdering Order = I.getOrdering();
4556   SyncScope::ID SSID = I.getSyncScopeID();
4557 
4558   SDValue InChain = getRoot();
4559 
4560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4561   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4562   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4563 
4564   if (!TLI.supportsUnalignedAtomics() &&
4565       I.getAlignment() < MemVT.getSizeInBits() / 8)
4566     report_fatal_error("Cannot generate unaligned atomic load");
4567 
4568   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4569 
4570   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4571       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4572       I.getAlign().getValueOr(DAG.getEVTAlign(MemVT)), AAMDNodes(), nullptr,
4573       SSID, Order);
4574 
4575   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4576 
4577   SDValue Ptr = getValue(I.getPointerOperand());
4578 
4579   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4580     // TODO: Once this is better exercised by tests, it should be merged with
4581     // the normal path for loads to prevent future divergence.
4582     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4583     if (MemVT != VT)
4584       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4585 
4586     setValue(&I, L);
4587     SDValue OutChain = L.getValue(1);
4588     if (!I.isUnordered())
4589       DAG.setRoot(OutChain);
4590     else
4591       PendingLoads.push_back(OutChain);
4592     return;
4593   }
4594 
4595   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4596                             Ptr, MMO);
4597 
4598   SDValue OutChain = L.getValue(1);
4599   if (MemVT != VT)
4600     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4601 
4602   setValue(&I, L);
4603   DAG.setRoot(OutChain);
4604 }
4605 
4606 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4607   SDLoc dl = getCurSDLoc();
4608 
4609   AtomicOrdering Ordering = I.getOrdering();
4610   SyncScope::ID SSID = I.getSyncScopeID();
4611 
4612   SDValue InChain = getRoot();
4613 
4614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4615   EVT MemVT =
4616       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4617 
4618   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4619     report_fatal_error("Cannot generate unaligned atomic store");
4620 
4621   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4622 
4623   MachineFunction &MF = DAG.getMachineFunction();
4624   MachineMemOperand *MMO = MF.getMachineMemOperand(
4625       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4626       *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4627 
4628   SDValue Val = getValue(I.getValueOperand());
4629   if (Val.getValueType() != MemVT)
4630     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4631   SDValue Ptr = getValue(I.getPointerOperand());
4632 
4633   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4634     // TODO: Once this is better exercised by tests, it should be merged with
4635     // the normal path for stores to prevent future divergence.
4636     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4637     DAG.setRoot(S);
4638     return;
4639   }
4640   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4641                                    Ptr, Val, MMO);
4642 
4643 
4644   DAG.setRoot(OutChain);
4645 }
4646 
4647 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4648 /// node.
4649 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4650                                                unsigned Intrinsic) {
4651   // Ignore the callsite's attributes. A specific call site may be marked with
4652   // readnone, but the lowering code will expect the chain based on the
4653   // definition.
4654   const Function *F = I.getCalledFunction();
4655   bool HasChain = !F->doesNotAccessMemory();
4656   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4657 
4658   // Build the operand list.
4659   SmallVector<SDValue, 8> Ops;
4660   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4661     if (OnlyLoad) {
4662       // We don't need to serialize loads against other loads.
4663       Ops.push_back(DAG.getRoot());
4664     } else {
4665       Ops.push_back(getRoot());
4666     }
4667   }
4668 
4669   // Info is set by getTgtMemInstrinsic
4670   TargetLowering::IntrinsicInfo Info;
4671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4672   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4673                                                DAG.getMachineFunction(),
4674                                                Intrinsic);
4675 
4676   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4677   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4678       Info.opc == ISD::INTRINSIC_W_CHAIN)
4679     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4680                                         TLI.getPointerTy(DAG.getDataLayout())));
4681 
4682   // Add all operands of the call to the operand list.
4683   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4684     const Value *Arg = I.getArgOperand(i);
4685     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4686       Ops.push_back(getValue(Arg));
4687       continue;
4688     }
4689 
4690     // Use TargetConstant instead of a regular constant for immarg.
4691     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4692     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4693       assert(CI->getBitWidth() <= 64 &&
4694              "large intrinsic immediates not handled");
4695       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4696     } else {
4697       Ops.push_back(
4698           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4699     }
4700   }
4701 
4702   SmallVector<EVT, 4> ValueVTs;
4703   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4704 
4705   if (HasChain)
4706     ValueVTs.push_back(MVT::Other);
4707 
4708   SDVTList VTs = DAG.getVTList(ValueVTs);
4709 
4710   // Create the node.
4711   SDValue Result;
4712   if (IsTgtIntrinsic) {
4713     // This is target intrinsic that touches memory
4714     AAMDNodes AAInfo;
4715     I.getAAMetadata(AAInfo);
4716     Result = DAG.getMemIntrinsicNode(
4717         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4718         MachinePointerInfo(Info.ptrVal, Info.offset),
4719         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4720   } else if (!HasChain) {
4721     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4722   } else if (!I.getType()->isVoidTy()) {
4723     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4724   } else {
4725     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4726   }
4727 
4728   if (HasChain) {
4729     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4730     if (OnlyLoad)
4731       PendingLoads.push_back(Chain);
4732     else
4733       DAG.setRoot(Chain);
4734   }
4735 
4736   if (!I.getType()->isVoidTy()) {
4737     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4738       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4739       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4740     } else
4741       Result = lowerRangeToAssertZExt(DAG, I, Result);
4742 
4743     setValue(&I, Result);
4744   }
4745 }
4746 
4747 /// GetSignificand - Get the significand and build it into a floating-point
4748 /// number with exponent of 1:
4749 ///
4750 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4751 ///
4752 /// where Op is the hexadecimal representation of floating point value.
4753 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4754   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4755                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4756   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4757                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4758   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4759 }
4760 
4761 /// GetExponent - Get the exponent:
4762 ///
4763 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4764 ///
4765 /// where Op is the hexadecimal representation of floating point value.
4766 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4767                            const TargetLowering &TLI, const SDLoc &dl) {
4768   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4769                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4770   SDValue t1 = DAG.getNode(
4771       ISD::SRL, dl, MVT::i32, t0,
4772       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4773   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4774                            DAG.getConstant(127, dl, MVT::i32));
4775   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4776 }
4777 
4778 /// getF32Constant - Get 32-bit floating point constant.
4779 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4780                               const SDLoc &dl) {
4781   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4782                            MVT::f32);
4783 }
4784 
4785 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4786                                        SelectionDAG &DAG) {
4787   // TODO: What fast-math-flags should be set on the floating-point nodes?
4788 
4789   //   IntegerPartOfX = ((int32_t)(t0);
4790   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4791 
4792   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4793   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4794   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4795 
4796   //   IntegerPartOfX <<= 23;
4797   IntegerPartOfX = DAG.getNode(
4798       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4799       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4800                                   DAG.getDataLayout())));
4801 
4802   SDValue TwoToFractionalPartOfX;
4803   if (LimitFloatPrecision <= 6) {
4804     // For floating-point precision of 6:
4805     //
4806     //   TwoToFractionalPartOfX =
4807     //     0.997535578f +
4808     //       (0.735607626f + 0.252464424f * x) * x;
4809     //
4810     // error 0.0144103317, which is 6 bits
4811     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4812                              getF32Constant(DAG, 0x3e814304, dl));
4813     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4814                              getF32Constant(DAG, 0x3f3c50c8, dl));
4815     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4816     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4817                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4818   } else if (LimitFloatPrecision <= 12) {
4819     // For floating-point precision of 12:
4820     //
4821     //   TwoToFractionalPartOfX =
4822     //     0.999892986f +
4823     //       (0.696457318f +
4824     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4825     //
4826     // error 0.000107046256, which is 13 to 14 bits
4827     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4828                              getF32Constant(DAG, 0x3da235e3, dl));
4829     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4830                              getF32Constant(DAG, 0x3e65b8f3, dl));
4831     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4832     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4833                              getF32Constant(DAG, 0x3f324b07, dl));
4834     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4835     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4836                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4837   } else { // LimitFloatPrecision <= 18
4838     // For floating-point precision of 18:
4839     //
4840     //   TwoToFractionalPartOfX =
4841     //     0.999999982f +
4842     //       (0.693148872f +
4843     //         (0.240227044f +
4844     //           (0.554906021e-1f +
4845     //             (0.961591928e-2f +
4846     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4847     // error 2.47208000*10^(-7), which is better than 18 bits
4848     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4849                              getF32Constant(DAG, 0x3924b03e, dl));
4850     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4851                              getF32Constant(DAG, 0x3ab24b87, dl));
4852     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4853     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4854                              getF32Constant(DAG, 0x3c1d8c17, dl));
4855     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4856     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4857                              getF32Constant(DAG, 0x3d634a1d, dl));
4858     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4859     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4860                              getF32Constant(DAG, 0x3e75fe14, dl));
4861     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4862     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4863                               getF32Constant(DAG, 0x3f317234, dl));
4864     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4865     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4866                                          getF32Constant(DAG, 0x3f800000, dl));
4867   }
4868 
4869   // Add the exponent into the result in integer domain.
4870   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4871   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4872                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4873 }
4874 
4875 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4876 /// limited-precision mode.
4877 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4878                          const TargetLowering &TLI) {
4879   if (Op.getValueType() == MVT::f32 &&
4880       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4881 
4882     // Put the exponent in the right bit position for later addition to the
4883     // final result:
4884     //
4885     // t0 = Op * log2(e)
4886 
4887     // TODO: What fast-math-flags should be set here?
4888     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4889                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4890     return getLimitedPrecisionExp2(t0, dl, DAG);
4891   }
4892 
4893   // No special expansion.
4894   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4895 }
4896 
4897 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4898 /// limited-precision mode.
4899 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4900                          const TargetLowering &TLI) {
4901   // TODO: What fast-math-flags should be set on the floating-point nodes?
4902 
4903   if (Op.getValueType() == MVT::f32 &&
4904       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4905     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4906 
4907     // Scale the exponent by log(2).
4908     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4909     SDValue LogOfExponent =
4910         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4911                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4912 
4913     // Get the significand and build it into a floating-point number with
4914     // exponent of 1.
4915     SDValue X = GetSignificand(DAG, Op1, dl);
4916 
4917     SDValue LogOfMantissa;
4918     if (LimitFloatPrecision <= 6) {
4919       // For floating-point precision of 6:
4920       //
4921       //   LogofMantissa =
4922       //     -1.1609546f +
4923       //       (1.4034025f - 0.23903021f * x) * x;
4924       //
4925       // error 0.0034276066, which is better than 8 bits
4926       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4927                                getF32Constant(DAG, 0xbe74c456, dl));
4928       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4929                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4930       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4931       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4932                                   getF32Constant(DAG, 0x3f949a29, dl));
4933     } else if (LimitFloatPrecision <= 12) {
4934       // For floating-point precision of 12:
4935       //
4936       //   LogOfMantissa =
4937       //     -1.7417939f +
4938       //       (2.8212026f +
4939       //         (-1.4699568f +
4940       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4941       //
4942       // error 0.000061011436, which is 14 bits
4943       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4944                                getF32Constant(DAG, 0xbd67b6d6, dl));
4945       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4946                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4947       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4948       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4949                                getF32Constant(DAG, 0x3fbc278b, dl));
4950       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4951       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4952                                getF32Constant(DAG, 0x40348e95, dl));
4953       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4954       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4955                                   getF32Constant(DAG, 0x3fdef31a, dl));
4956     } else { // LimitFloatPrecision <= 18
4957       // For floating-point precision of 18:
4958       //
4959       //   LogOfMantissa =
4960       //     -2.1072184f +
4961       //       (4.2372794f +
4962       //         (-3.7029485f +
4963       //           (2.2781945f +
4964       //             (-0.87823314f +
4965       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4966       //
4967       // error 0.0000023660568, which is better than 18 bits
4968       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4969                                getF32Constant(DAG, 0xbc91e5ac, dl));
4970       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4971                                getF32Constant(DAG, 0x3e4350aa, dl));
4972       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4973       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4974                                getF32Constant(DAG, 0x3f60d3e3, dl));
4975       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4976       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4977                                getF32Constant(DAG, 0x4011cdf0, dl));
4978       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4979       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4980                                getF32Constant(DAG, 0x406cfd1c, dl));
4981       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4982       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4983                                getF32Constant(DAG, 0x408797cb, dl));
4984       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4985       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4986                                   getF32Constant(DAG, 0x4006dcab, dl));
4987     }
4988 
4989     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4990   }
4991 
4992   // No special expansion.
4993   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4994 }
4995 
4996 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4997 /// limited-precision mode.
4998 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4999                           const TargetLowering &TLI) {
5000   // TODO: What fast-math-flags should be set on the floating-point nodes?
5001 
5002   if (Op.getValueType() == MVT::f32 &&
5003       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5004     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5005 
5006     // Get the exponent.
5007     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5008 
5009     // Get the significand and build it into a floating-point number with
5010     // exponent of 1.
5011     SDValue X = GetSignificand(DAG, Op1, dl);
5012 
5013     // Different possible minimax approximations of significand in
5014     // floating-point for various degrees of accuracy over [1,2].
5015     SDValue Log2ofMantissa;
5016     if (LimitFloatPrecision <= 6) {
5017       // For floating-point precision of 6:
5018       //
5019       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5020       //
5021       // error 0.0049451742, which is more than 7 bits
5022       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5023                                getF32Constant(DAG, 0xbeb08fe0, dl));
5024       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5025                                getF32Constant(DAG, 0x40019463, dl));
5026       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5027       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5028                                    getF32Constant(DAG, 0x3fd6633d, dl));
5029     } else if (LimitFloatPrecision <= 12) {
5030       // For floating-point precision of 12:
5031       //
5032       //   Log2ofMantissa =
5033       //     -2.51285454f +
5034       //       (4.07009056f +
5035       //         (-2.12067489f +
5036       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5037       //
5038       // error 0.0000876136000, which is better than 13 bits
5039       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5040                                getF32Constant(DAG, 0xbda7262e, dl));
5041       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5042                                getF32Constant(DAG, 0x3f25280b, dl));
5043       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5044       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5045                                getF32Constant(DAG, 0x4007b923, dl));
5046       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5047       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5048                                getF32Constant(DAG, 0x40823e2f, dl));
5049       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5050       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5051                                    getF32Constant(DAG, 0x4020d29c, dl));
5052     } else { // LimitFloatPrecision <= 18
5053       // For floating-point precision of 18:
5054       //
5055       //   Log2ofMantissa =
5056       //     -3.0400495f +
5057       //       (6.1129976f +
5058       //         (-5.3420409f +
5059       //           (3.2865683f +
5060       //             (-1.2669343f +
5061       //               (0.27515199f -
5062       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5063       //
5064       // error 0.0000018516, which is better than 18 bits
5065       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5066                                getF32Constant(DAG, 0xbcd2769e, dl));
5067       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5068                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5069       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5070       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5071                                getF32Constant(DAG, 0x3fa22ae7, dl));
5072       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5073       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5074                                getF32Constant(DAG, 0x40525723, dl));
5075       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5076       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5077                                getF32Constant(DAG, 0x40aaf200, dl));
5078       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5079       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5080                                getF32Constant(DAG, 0x40c39dad, dl));
5081       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5082       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5083                                    getF32Constant(DAG, 0x4042902c, dl));
5084     }
5085 
5086     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5087   }
5088 
5089   // No special expansion.
5090   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5091 }
5092 
5093 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5094 /// limited-precision mode.
5095 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5096                            const TargetLowering &TLI) {
5097   // TODO: What fast-math-flags should be set on the floating-point nodes?
5098 
5099   if (Op.getValueType() == MVT::f32 &&
5100       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5101     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5102 
5103     // Scale the exponent by log10(2) [0.30102999f].
5104     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5105     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5106                                         getF32Constant(DAG, 0x3e9a209a, dl));
5107 
5108     // Get the significand and build it into a floating-point number with
5109     // exponent of 1.
5110     SDValue X = GetSignificand(DAG, Op1, dl);
5111 
5112     SDValue Log10ofMantissa;
5113     if (LimitFloatPrecision <= 6) {
5114       // For floating-point precision of 6:
5115       //
5116       //   Log10ofMantissa =
5117       //     -0.50419619f +
5118       //       (0.60948995f - 0.10380950f * x) * x;
5119       //
5120       // error 0.0014886165, which is 6 bits
5121       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5122                                getF32Constant(DAG, 0xbdd49a13, dl));
5123       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5124                                getF32Constant(DAG, 0x3f1c0789, dl));
5125       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5126       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5127                                     getF32Constant(DAG, 0x3f011300, dl));
5128     } else if (LimitFloatPrecision <= 12) {
5129       // For floating-point precision of 12:
5130       //
5131       //   Log10ofMantissa =
5132       //     -0.64831180f +
5133       //       (0.91751397f +
5134       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5135       //
5136       // error 0.00019228036, which is better than 12 bits
5137       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5138                                getF32Constant(DAG, 0x3d431f31, dl));
5139       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5140                                getF32Constant(DAG, 0x3ea21fb2, dl));
5141       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5142       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5143                                getF32Constant(DAG, 0x3f6ae232, dl));
5144       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5145       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5146                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5147     } else { // LimitFloatPrecision <= 18
5148       // For floating-point precision of 18:
5149       //
5150       //   Log10ofMantissa =
5151       //     -0.84299375f +
5152       //       (1.5327582f +
5153       //         (-1.0688956f +
5154       //           (0.49102474f +
5155       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5156       //
5157       // error 0.0000037995730, which is better than 18 bits
5158       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5159                                getF32Constant(DAG, 0x3c5d51ce, dl));
5160       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5161                                getF32Constant(DAG, 0x3e00685a, dl));
5162       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5163       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5164                                getF32Constant(DAG, 0x3efb6798, dl));
5165       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5166       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5167                                getF32Constant(DAG, 0x3f88d192, dl));
5168       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5169       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5170                                getF32Constant(DAG, 0x3fc4316c, dl));
5171       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5172       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5173                                     getF32Constant(DAG, 0x3f57ce70, dl));
5174     }
5175 
5176     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5177   }
5178 
5179   // No special expansion.
5180   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5181 }
5182 
5183 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5184 /// limited-precision mode.
5185 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5186                           const TargetLowering &TLI) {
5187   if (Op.getValueType() == MVT::f32 &&
5188       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5189     return getLimitedPrecisionExp2(Op, dl, DAG);
5190 
5191   // No special expansion.
5192   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5193 }
5194 
5195 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5196 /// limited-precision mode with x == 10.0f.
5197 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5198                          SelectionDAG &DAG, const TargetLowering &TLI) {
5199   bool IsExp10 = false;
5200   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5201       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5202     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5203       APFloat Ten(10.0f);
5204       IsExp10 = LHSC->isExactlyValue(Ten);
5205     }
5206   }
5207 
5208   // TODO: What fast-math-flags should be set on the FMUL node?
5209   if (IsExp10) {
5210     // Put the exponent in the right bit position for later addition to the
5211     // final result:
5212     //
5213     //   #define LOG2OF10 3.3219281f
5214     //   t0 = Op * LOG2OF10;
5215     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5216                              getF32Constant(DAG, 0x40549a78, dl));
5217     return getLimitedPrecisionExp2(t0, dl, DAG);
5218   }
5219 
5220   // No special expansion.
5221   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5222 }
5223 
5224 /// ExpandPowI - Expand a llvm.powi intrinsic.
5225 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5226                           SelectionDAG &DAG) {
5227   // If RHS is a constant, we can expand this out to a multiplication tree,
5228   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5229   // optimizing for size, we only want to do this if the expansion would produce
5230   // a small number of multiplies, otherwise we do the full expansion.
5231   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5232     // Get the exponent as a positive value.
5233     unsigned Val = RHSC->getSExtValue();
5234     if ((int)Val < 0) Val = -Val;
5235 
5236     // powi(x, 0) -> 1.0
5237     if (Val == 0)
5238       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5239 
5240     bool OptForSize = DAG.shouldOptForSize();
5241     if (!OptForSize ||
5242         // If optimizing for size, don't insert too many multiplies.
5243         // This inserts up to 5 multiplies.
5244         countPopulation(Val) + Log2_32(Val) < 7) {
5245       // We use the simple binary decomposition method to generate the multiply
5246       // sequence.  There are more optimal ways to do this (for example,
5247       // powi(x,15) generates one more multiply than it should), but this has
5248       // the benefit of being both really simple and much better than a libcall.
5249       SDValue Res;  // Logically starts equal to 1.0
5250       SDValue CurSquare = LHS;
5251       // TODO: Intrinsics should have fast-math-flags that propagate to these
5252       // nodes.
5253       while (Val) {
5254         if (Val & 1) {
5255           if (Res.getNode())
5256             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5257           else
5258             Res = CurSquare;  // 1.0*CurSquare.
5259         }
5260 
5261         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5262                                 CurSquare, CurSquare);
5263         Val >>= 1;
5264       }
5265 
5266       // If the original was negative, invert the result, producing 1/(x*x*x).
5267       if (RHSC->getSExtValue() < 0)
5268         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5269                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5270       return Res;
5271     }
5272   }
5273 
5274   // Otherwise, expand to a libcall.
5275   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5276 }
5277 
5278 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5279                             SDValue LHS, SDValue RHS, SDValue Scale,
5280                             SelectionDAG &DAG, const TargetLowering &TLI) {
5281   EVT VT = LHS.getValueType();
5282   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5283   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5284   LLVMContext &Ctx = *DAG.getContext();
5285 
5286   // If the type is legal but the operation isn't, this node might survive all
5287   // the way to operation legalization. If we end up there and we do not have
5288   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5289   // node.
5290 
5291   // Coax the legalizer into expanding the node during type legalization instead
5292   // by bumping the size by one bit. This will force it to Promote, enabling the
5293   // early expansion and avoiding the need to expand later.
5294 
5295   // We don't have to do this if Scale is 0; that can always be expanded, unless
5296   // it's a saturating signed operation. Those can experience true integer
5297   // division overflow, a case which we must avoid.
5298 
5299   // FIXME: We wouldn't have to do this (or any of the early
5300   // expansion/promotion) if it was possible to expand a libcall of an
5301   // illegal type during operation legalization. But it's not, so things
5302   // get a bit hacky.
5303   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5304   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5305       (TLI.isTypeLegal(VT) ||
5306        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5307     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5308         Opcode, VT, ScaleInt);
5309     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5310       EVT PromVT;
5311       if (VT.isScalarInteger())
5312         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5313       else if (VT.isVector()) {
5314         PromVT = VT.getVectorElementType();
5315         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5316         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5317       } else
5318         llvm_unreachable("Wrong VT for DIVFIX?");
5319       if (Signed) {
5320         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5321         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5322       } else {
5323         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5324         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5325       }
5326       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5327       // For saturating operations, we need to shift up the LHS to get the
5328       // proper saturation width, and then shift down again afterwards.
5329       if (Saturating)
5330         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5331                           DAG.getConstant(1, DL, ShiftTy));
5332       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5333       if (Saturating)
5334         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5335                           DAG.getConstant(1, DL, ShiftTy));
5336       return DAG.getZExtOrTrunc(Res, DL, VT);
5337     }
5338   }
5339 
5340   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5341 }
5342 
5343 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5344 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5345 static void
5346 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5347                      const SDValue &N) {
5348   switch (N.getOpcode()) {
5349   case ISD::CopyFromReg: {
5350     SDValue Op = N.getOperand(1);
5351     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5352                       Op.getValueType().getSizeInBits());
5353     return;
5354   }
5355   case ISD::BITCAST:
5356   case ISD::AssertZext:
5357   case ISD::AssertSext:
5358   case ISD::TRUNCATE:
5359     getUnderlyingArgRegs(Regs, N.getOperand(0));
5360     return;
5361   case ISD::BUILD_PAIR:
5362   case ISD::BUILD_VECTOR:
5363   case ISD::CONCAT_VECTORS:
5364     for (SDValue Op : N->op_values())
5365       getUnderlyingArgRegs(Regs, Op);
5366     return;
5367   default:
5368     return;
5369   }
5370 }
5371 
5372 /// If the DbgValueInst is a dbg_value of a function argument, create the
5373 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5374 /// instruction selection, they will be inserted to the entry BB.
5375 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5376     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5377     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5378   const Argument *Arg = dyn_cast<Argument>(V);
5379   if (!Arg)
5380     return false;
5381 
5382   if (!IsDbgDeclare) {
5383     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5384     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5385     // the entry block.
5386     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5387     if (!IsInEntryBlock)
5388       return false;
5389 
5390     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5391     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5392     // variable that also is a param.
5393     //
5394     // Although, if we are at the top of the entry block already, we can still
5395     // emit using ArgDbgValue. This might catch some situations when the
5396     // dbg.value refers to an argument that isn't used in the entry block, so
5397     // any CopyToReg node would be optimized out and the only way to express
5398     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5399     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5400     // we should only emit as ArgDbgValue if the Variable is an argument to the
5401     // current function, and the dbg.value intrinsic is found in the entry
5402     // block.
5403     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5404         !DL->getInlinedAt();
5405     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5406     if (!IsInPrologue && !VariableIsFunctionInputArg)
5407       return false;
5408 
5409     // Here we assume that a function argument on IR level only can be used to
5410     // describe one input parameter on source level. If we for example have
5411     // source code like this
5412     //
5413     //    struct A { long x, y; };
5414     //    void foo(struct A a, long b) {
5415     //      ...
5416     //      b = a.x;
5417     //      ...
5418     //    }
5419     //
5420     // and IR like this
5421     //
5422     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5423     //  entry:
5424     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5425     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5426     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5427     //    ...
5428     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5429     //    ...
5430     //
5431     // then the last dbg.value is describing a parameter "b" using a value that
5432     // is an argument. But since we already has used %a1 to describe a parameter
5433     // we should not handle that last dbg.value here (that would result in an
5434     // incorrect hoisting of the DBG_VALUE to the function entry).
5435     // Notice that we allow one dbg.value per IR level argument, to accommodate
5436     // for the situation with fragments above.
5437     if (VariableIsFunctionInputArg) {
5438       unsigned ArgNo = Arg->getArgNo();
5439       if (ArgNo >= FuncInfo.DescribedArgs.size())
5440         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5441       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5442         return false;
5443       FuncInfo.DescribedArgs.set(ArgNo);
5444     }
5445   }
5446 
5447   MachineFunction &MF = DAG.getMachineFunction();
5448   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5449 
5450   bool IsIndirect = false;
5451   Optional<MachineOperand> Op;
5452   // Some arguments' frame index is recorded during argument lowering.
5453   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5454   if (FI != std::numeric_limits<int>::max())
5455     Op = MachineOperand::CreateFI(FI);
5456 
5457   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5458   if (!Op && N.getNode()) {
5459     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5460     Register Reg;
5461     if (ArgRegsAndSizes.size() == 1)
5462       Reg = ArgRegsAndSizes.front().first;
5463 
5464     if (Reg && Reg.isVirtual()) {
5465       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5466       Register PR = RegInfo.getLiveInPhysReg(Reg);
5467       if (PR)
5468         Reg = PR;
5469     }
5470     if (Reg) {
5471       Op = MachineOperand::CreateReg(Reg, false);
5472       IsIndirect = IsDbgDeclare;
5473     }
5474   }
5475 
5476   if (!Op && N.getNode()) {
5477     // Check if frame index is available.
5478     SDValue LCandidate = peekThroughBitcasts(N);
5479     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5480       if (FrameIndexSDNode *FINode =
5481           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5482         Op = MachineOperand::CreateFI(FINode->getIndex());
5483   }
5484 
5485   if (!Op) {
5486     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5487     auto splitMultiRegDbgValue
5488       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5489       unsigned Offset = 0;
5490       for (auto RegAndSize : SplitRegs) {
5491         // If the expression is already a fragment, the current register
5492         // offset+size might extend beyond the fragment. In this case, only
5493         // the register bits that are inside the fragment are relevant.
5494         int RegFragmentSizeInBits = RegAndSize.second;
5495         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5496           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5497           // The register is entirely outside the expression fragment,
5498           // so is irrelevant for debug info.
5499           if (Offset >= ExprFragmentSizeInBits)
5500             break;
5501           // The register is partially outside the expression fragment, only
5502           // the low bits within the fragment are relevant for debug info.
5503           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5504             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5505           }
5506         }
5507 
5508         auto FragmentExpr = DIExpression::createFragmentExpression(
5509             Expr, Offset, RegFragmentSizeInBits);
5510         Offset += RegAndSize.second;
5511         // If a valid fragment expression cannot be created, the variable's
5512         // correct value cannot be determined and so it is set as Undef.
5513         if (!FragmentExpr) {
5514           SDDbgValue *SDV = DAG.getConstantDbgValue(
5515               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5516           DAG.AddDbgValue(SDV, nullptr, false);
5517           continue;
5518         }
5519         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5520         FuncInfo.ArgDbgValues.push_back(
5521           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5522                   RegAndSize.first, Variable, *FragmentExpr));
5523       }
5524     };
5525 
5526     // Check if ValueMap has reg number.
5527     DenseMap<const Value *, unsigned>::const_iterator
5528       VMI = FuncInfo.ValueMap.find(V);
5529     if (VMI != FuncInfo.ValueMap.end()) {
5530       const auto &TLI = DAG.getTargetLoweringInfo();
5531       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5532                        V->getType(), getABIRegCopyCC(V));
5533       if (RFV.occupiesMultipleRegs()) {
5534         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5535         return true;
5536       }
5537 
5538       Op = MachineOperand::CreateReg(VMI->second, false);
5539       IsIndirect = IsDbgDeclare;
5540     } else if (ArgRegsAndSizes.size() > 1) {
5541       // This was split due to the calling convention, and no virtual register
5542       // mapping exists for the value.
5543       splitMultiRegDbgValue(ArgRegsAndSizes);
5544       return true;
5545     }
5546   }
5547 
5548   if (!Op)
5549     return false;
5550 
5551   assert(Variable->isValidLocationForIntrinsic(DL) &&
5552          "Expected inlined-at fields to agree");
5553   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5554   FuncInfo.ArgDbgValues.push_back(
5555       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5556               *Op, Variable, Expr));
5557 
5558   return true;
5559 }
5560 
5561 /// Return the appropriate SDDbgValue based on N.
5562 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5563                                              DILocalVariable *Variable,
5564                                              DIExpression *Expr,
5565                                              const DebugLoc &dl,
5566                                              unsigned DbgSDNodeOrder) {
5567   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5568     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5569     // stack slot locations.
5570     //
5571     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5572     // debug values here after optimization:
5573     //
5574     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5575     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5576     //
5577     // Both describe the direct values of their associated variables.
5578     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5579                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5580   }
5581   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5582                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5583 }
5584 
5585 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5586   switch (Intrinsic) {
5587   case Intrinsic::smul_fix:
5588     return ISD::SMULFIX;
5589   case Intrinsic::umul_fix:
5590     return ISD::UMULFIX;
5591   case Intrinsic::smul_fix_sat:
5592     return ISD::SMULFIXSAT;
5593   case Intrinsic::umul_fix_sat:
5594     return ISD::UMULFIXSAT;
5595   case Intrinsic::sdiv_fix:
5596     return ISD::SDIVFIX;
5597   case Intrinsic::udiv_fix:
5598     return ISD::UDIVFIX;
5599   case Intrinsic::sdiv_fix_sat:
5600     return ISD::SDIVFIXSAT;
5601   case Intrinsic::udiv_fix_sat:
5602     return ISD::UDIVFIXSAT;
5603   default:
5604     llvm_unreachable("Unhandled fixed point intrinsic");
5605   }
5606 }
5607 
5608 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5609                                            const char *FunctionName) {
5610   assert(FunctionName && "FunctionName must not be nullptr");
5611   SDValue Callee = DAG.getExternalSymbol(
5612       FunctionName,
5613       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5614   LowerCallTo(&I, Callee, I.isTailCall());
5615 }
5616 
5617 /// Lower the call to the specified intrinsic function.
5618 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5619                                              unsigned Intrinsic) {
5620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5621   SDLoc sdl = getCurSDLoc();
5622   DebugLoc dl = getCurDebugLoc();
5623   SDValue Res;
5624 
5625   switch (Intrinsic) {
5626   default:
5627     // By default, turn this into a target intrinsic node.
5628     visitTargetIntrinsic(I, Intrinsic);
5629     return;
5630   case Intrinsic::vscale: {
5631     match(&I, m_VScale(DAG.getDataLayout()));
5632     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5633     setValue(&I,
5634              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5635     return;
5636   }
5637   case Intrinsic::vastart:  visitVAStart(I); return;
5638   case Intrinsic::vaend:    visitVAEnd(I); return;
5639   case Intrinsic::vacopy:   visitVACopy(I); return;
5640   case Intrinsic::returnaddress:
5641     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5642                              TLI.getPointerTy(DAG.getDataLayout()),
5643                              getValue(I.getArgOperand(0))));
5644     return;
5645   case Intrinsic::addressofreturnaddress:
5646     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5647                              TLI.getPointerTy(DAG.getDataLayout())));
5648     return;
5649   case Intrinsic::sponentry:
5650     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5651                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5652     return;
5653   case Intrinsic::frameaddress:
5654     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5655                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5656                              getValue(I.getArgOperand(0))));
5657     return;
5658   case Intrinsic::read_register: {
5659     Value *Reg = I.getArgOperand(0);
5660     SDValue Chain = getRoot();
5661     SDValue RegName =
5662         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5663     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5664     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5665       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5666     setValue(&I, Res);
5667     DAG.setRoot(Res.getValue(1));
5668     return;
5669   }
5670   case Intrinsic::write_register: {
5671     Value *Reg = I.getArgOperand(0);
5672     Value *RegValue = I.getArgOperand(1);
5673     SDValue Chain = getRoot();
5674     SDValue RegName =
5675         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5676     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5677                             RegName, getValue(RegValue)));
5678     return;
5679   }
5680   case Intrinsic::memcpy: {
5681     const auto &MCI = cast<MemCpyInst>(I);
5682     SDValue Op1 = getValue(I.getArgOperand(0));
5683     SDValue Op2 = getValue(I.getArgOperand(1));
5684     SDValue Op3 = getValue(I.getArgOperand(2));
5685     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5686     Align DstAlign = MCI.getDestAlign().valueOrOne();
5687     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5688     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5689     bool isVol = MCI.isVolatile();
5690     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5691     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5692     // node.
5693     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5694     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5695                                /* AlwaysInline */ false, isTC,
5696                                MachinePointerInfo(I.getArgOperand(0)),
5697                                MachinePointerInfo(I.getArgOperand(1)));
5698     updateDAGForMaybeTailCall(MC);
5699     return;
5700   }
5701   case Intrinsic::memcpy_inline: {
5702     const auto &MCI = cast<MemCpyInlineInst>(I);
5703     SDValue Dst = getValue(I.getArgOperand(0));
5704     SDValue Src = getValue(I.getArgOperand(1));
5705     SDValue Size = getValue(I.getArgOperand(2));
5706     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5707     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5708     Align DstAlign = MCI.getDestAlign().valueOrOne();
5709     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5710     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5711     bool isVol = MCI.isVolatile();
5712     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5713     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5714     // node.
5715     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5716                                /* AlwaysInline */ true, isTC,
5717                                MachinePointerInfo(I.getArgOperand(0)),
5718                                MachinePointerInfo(I.getArgOperand(1)));
5719     updateDAGForMaybeTailCall(MC);
5720     return;
5721   }
5722   case Intrinsic::memset: {
5723     const auto &MSI = cast<MemSetInst>(I);
5724     SDValue Op1 = getValue(I.getArgOperand(0));
5725     SDValue Op2 = getValue(I.getArgOperand(1));
5726     SDValue Op3 = getValue(I.getArgOperand(2));
5727     // @llvm.memset defines 0 and 1 to both mean no alignment.
5728     Align Alignment = MSI.getDestAlign().valueOrOne();
5729     bool isVol = MSI.isVolatile();
5730     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5731     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5732     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5733                                MachinePointerInfo(I.getArgOperand(0)));
5734     updateDAGForMaybeTailCall(MS);
5735     return;
5736   }
5737   case Intrinsic::memmove: {
5738     const auto &MMI = cast<MemMoveInst>(I);
5739     SDValue Op1 = getValue(I.getArgOperand(0));
5740     SDValue Op2 = getValue(I.getArgOperand(1));
5741     SDValue Op3 = getValue(I.getArgOperand(2));
5742     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5743     Align DstAlign = MMI.getDestAlign().valueOrOne();
5744     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5745     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5746     bool isVol = MMI.isVolatile();
5747     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5748     // FIXME: Support passing different dest/src alignments to the memmove DAG
5749     // node.
5750     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5751     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5752                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5753                                 MachinePointerInfo(I.getArgOperand(1)));
5754     updateDAGForMaybeTailCall(MM);
5755     return;
5756   }
5757   case Intrinsic::memcpy_element_unordered_atomic: {
5758     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5759     SDValue Dst = getValue(MI.getRawDest());
5760     SDValue Src = getValue(MI.getRawSource());
5761     SDValue Length = getValue(MI.getLength());
5762 
5763     unsigned DstAlign = MI.getDestAlignment();
5764     unsigned SrcAlign = MI.getSourceAlignment();
5765     Type *LengthTy = MI.getLength()->getType();
5766     unsigned ElemSz = MI.getElementSizeInBytes();
5767     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5768     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5769                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5770                                      MachinePointerInfo(MI.getRawDest()),
5771                                      MachinePointerInfo(MI.getRawSource()));
5772     updateDAGForMaybeTailCall(MC);
5773     return;
5774   }
5775   case Intrinsic::memmove_element_unordered_atomic: {
5776     auto &MI = cast<AtomicMemMoveInst>(I);
5777     SDValue Dst = getValue(MI.getRawDest());
5778     SDValue Src = getValue(MI.getRawSource());
5779     SDValue Length = getValue(MI.getLength());
5780 
5781     unsigned DstAlign = MI.getDestAlignment();
5782     unsigned SrcAlign = MI.getSourceAlignment();
5783     Type *LengthTy = MI.getLength()->getType();
5784     unsigned ElemSz = MI.getElementSizeInBytes();
5785     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5786     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5787                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5788                                       MachinePointerInfo(MI.getRawDest()),
5789                                       MachinePointerInfo(MI.getRawSource()));
5790     updateDAGForMaybeTailCall(MC);
5791     return;
5792   }
5793   case Intrinsic::memset_element_unordered_atomic: {
5794     auto &MI = cast<AtomicMemSetInst>(I);
5795     SDValue Dst = getValue(MI.getRawDest());
5796     SDValue Val = getValue(MI.getValue());
5797     SDValue Length = getValue(MI.getLength());
5798 
5799     unsigned DstAlign = MI.getDestAlignment();
5800     Type *LengthTy = MI.getLength()->getType();
5801     unsigned ElemSz = MI.getElementSizeInBytes();
5802     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5803     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5804                                      LengthTy, ElemSz, isTC,
5805                                      MachinePointerInfo(MI.getRawDest()));
5806     updateDAGForMaybeTailCall(MC);
5807     return;
5808   }
5809   case Intrinsic::dbg_addr:
5810   case Intrinsic::dbg_declare: {
5811     const auto &DI = cast<DbgVariableIntrinsic>(I);
5812     DILocalVariable *Variable = DI.getVariable();
5813     DIExpression *Expression = DI.getExpression();
5814     dropDanglingDebugInfo(Variable, Expression);
5815     assert(Variable && "Missing variable");
5816     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5817                       << "\n");
5818     // Check if address has undef value.
5819     const Value *Address = DI.getVariableLocation();
5820     if (!Address || isa<UndefValue>(Address) ||
5821         (Address->use_empty() && !isa<Argument>(Address))) {
5822       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5823                         << " (bad/undef/unused-arg address)\n");
5824       return;
5825     }
5826 
5827     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5828 
5829     // Check if this variable can be described by a frame index, typically
5830     // either as a static alloca or a byval parameter.
5831     int FI = std::numeric_limits<int>::max();
5832     if (const auto *AI =
5833             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5834       if (AI->isStaticAlloca()) {
5835         auto I = FuncInfo.StaticAllocaMap.find(AI);
5836         if (I != FuncInfo.StaticAllocaMap.end())
5837           FI = I->second;
5838       }
5839     } else if (const auto *Arg = dyn_cast<Argument>(
5840                    Address->stripInBoundsConstantOffsets())) {
5841       FI = FuncInfo.getArgumentFrameIndex(Arg);
5842     }
5843 
5844     // llvm.dbg.addr is control dependent and always generates indirect
5845     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5846     // the MachineFunction variable table.
5847     if (FI != std::numeric_limits<int>::max()) {
5848       if (Intrinsic == Intrinsic::dbg_addr) {
5849         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5850             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5851         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5852       } else {
5853         LLVM_DEBUG(dbgs() << "Skipping " << DI
5854                           << " (variable info stashed in MF side table)\n");
5855       }
5856       return;
5857     }
5858 
5859     SDValue &N = NodeMap[Address];
5860     if (!N.getNode() && isa<Argument>(Address))
5861       // Check unused arguments map.
5862       N = UnusedArgNodeMap[Address];
5863     SDDbgValue *SDV;
5864     if (N.getNode()) {
5865       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5866         Address = BCI->getOperand(0);
5867       // Parameters are handled specially.
5868       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5869       if (isParameter && FINode) {
5870         // Byval parameter. We have a frame index at this point.
5871         SDV =
5872             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5873                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5874       } else if (isa<Argument>(Address)) {
5875         // Address is an argument, so try to emit its dbg value using
5876         // virtual register info from the FuncInfo.ValueMap.
5877         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5878         return;
5879       } else {
5880         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5881                               true, dl, SDNodeOrder);
5882       }
5883       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5884     } else {
5885       // If Address is an argument then try to emit its dbg value using
5886       // virtual register info from the FuncInfo.ValueMap.
5887       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5888                                     N)) {
5889         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5890                           << " (could not emit func-arg dbg_value)\n");
5891       }
5892     }
5893     return;
5894   }
5895   case Intrinsic::dbg_label: {
5896     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5897     DILabel *Label = DI.getLabel();
5898     assert(Label && "Missing label");
5899 
5900     SDDbgLabel *SDV;
5901     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5902     DAG.AddDbgLabel(SDV);
5903     return;
5904   }
5905   case Intrinsic::dbg_value: {
5906     const DbgValueInst &DI = cast<DbgValueInst>(I);
5907     assert(DI.getVariable() && "Missing variable");
5908 
5909     DILocalVariable *Variable = DI.getVariable();
5910     DIExpression *Expression = DI.getExpression();
5911     dropDanglingDebugInfo(Variable, Expression);
5912     const Value *V = DI.getValue();
5913     if (!V)
5914       return;
5915 
5916     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5917         SDNodeOrder))
5918       return;
5919 
5920     // TODO: Dangling debug info will eventually either be resolved or produce
5921     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5922     // between the original dbg.value location and its resolved DBG_VALUE, which
5923     // we should ideally fill with an extra Undef DBG_VALUE.
5924 
5925     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5926     return;
5927   }
5928 
5929   case Intrinsic::eh_typeid_for: {
5930     // Find the type id for the given typeinfo.
5931     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5932     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5933     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5934     setValue(&I, Res);
5935     return;
5936   }
5937 
5938   case Intrinsic::eh_return_i32:
5939   case Intrinsic::eh_return_i64:
5940     DAG.getMachineFunction().setCallsEHReturn(true);
5941     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5942                             MVT::Other,
5943                             getControlRoot(),
5944                             getValue(I.getArgOperand(0)),
5945                             getValue(I.getArgOperand(1))));
5946     return;
5947   case Intrinsic::eh_unwind_init:
5948     DAG.getMachineFunction().setCallsUnwindInit(true);
5949     return;
5950   case Intrinsic::eh_dwarf_cfa:
5951     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5952                              TLI.getPointerTy(DAG.getDataLayout()),
5953                              getValue(I.getArgOperand(0))));
5954     return;
5955   case Intrinsic::eh_sjlj_callsite: {
5956     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5957     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5958     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5959     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5960 
5961     MMI.setCurrentCallSite(CI->getZExtValue());
5962     return;
5963   }
5964   case Intrinsic::eh_sjlj_functioncontext: {
5965     // Get and store the index of the function context.
5966     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5967     AllocaInst *FnCtx =
5968       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5969     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5970     MFI.setFunctionContextIndex(FI);
5971     return;
5972   }
5973   case Intrinsic::eh_sjlj_setjmp: {
5974     SDValue Ops[2];
5975     Ops[0] = getRoot();
5976     Ops[1] = getValue(I.getArgOperand(0));
5977     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5978                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5979     setValue(&I, Op.getValue(0));
5980     DAG.setRoot(Op.getValue(1));
5981     return;
5982   }
5983   case Intrinsic::eh_sjlj_longjmp:
5984     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5985                             getRoot(), getValue(I.getArgOperand(0))));
5986     return;
5987   case Intrinsic::eh_sjlj_setup_dispatch:
5988     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5989                             getRoot()));
5990     return;
5991   case Intrinsic::masked_gather:
5992     visitMaskedGather(I);
5993     return;
5994   case Intrinsic::masked_load:
5995     visitMaskedLoad(I);
5996     return;
5997   case Intrinsic::masked_scatter:
5998     visitMaskedScatter(I);
5999     return;
6000   case Intrinsic::masked_store:
6001     visitMaskedStore(I);
6002     return;
6003   case Intrinsic::masked_expandload:
6004     visitMaskedLoad(I, true /* IsExpanding */);
6005     return;
6006   case Intrinsic::masked_compressstore:
6007     visitMaskedStore(I, true /* IsCompressing */);
6008     return;
6009   case Intrinsic::powi:
6010     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6011                             getValue(I.getArgOperand(1)), DAG));
6012     return;
6013   case Intrinsic::log:
6014     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6015     return;
6016   case Intrinsic::log2:
6017     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6018     return;
6019   case Intrinsic::log10:
6020     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6021     return;
6022   case Intrinsic::exp:
6023     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6024     return;
6025   case Intrinsic::exp2:
6026     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6027     return;
6028   case Intrinsic::pow:
6029     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6030                            getValue(I.getArgOperand(1)), DAG, TLI));
6031     return;
6032   case Intrinsic::sqrt:
6033   case Intrinsic::fabs:
6034   case Intrinsic::sin:
6035   case Intrinsic::cos:
6036   case Intrinsic::floor:
6037   case Intrinsic::ceil:
6038   case Intrinsic::trunc:
6039   case Intrinsic::rint:
6040   case Intrinsic::nearbyint:
6041   case Intrinsic::round:
6042   case Intrinsic::canonicalize: {
6043     unsigned Opcode;
6044     switch (Intrinsic) {
6045     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6046     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6047     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6048     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6049     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6050     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6051     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6052     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6053     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6054     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6055     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6056     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6057     }
6058 
6059     setValue(&I, DAG.getNode(Opcode, sdl,
6060                              getValue(I.getArgOperand(0)).getValueType(),
6061                              getValue(I.getArgOperand(0))));
6062     return;
6063   }
6064   case Intrinsic::lround:
6065   case Intrinsic::llround:
6066   case Intrinsic::lrint:
6067   case Intrinsic::llrint: {
6068     unsigned Opcode;
6069     switch (Intrinsic) {
6070     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6071     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6072     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6073     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6074     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6075     }
6076 
6077     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6078     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6079                              getValue(I.getArgOperand(0))));
6080     return;
6081   }
6082   case Intrinsic::minnum:
6083     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6084                              getValue(I.getArgOperand(0)).getValueType(),
6085                              getValue(I.getArgOperand(0)),
6086                              getValue(I.getArgOperand(1))));
6087     return;
6088   case Intrinsic::maxnum:
6089     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6090                              getValue(I.getArgOperand(0)).getValueType(),
6091                              getValue(I.getArgOperand(0)),
6092                              getValue(I.getArgOperand(1))));
6093     return;
6094   case Intrinsic::minimum:
6095     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6096                              getValue(I.getArgOperand(0)).getValueType(),
6097                              getValue(I.getArgOperand(0)),
6098                              getValue(I.getArgOperand(1))));
6099     return;
6100   case Intrinsic::maximum:
6101     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6102                              getValue(I.getArgOperand(0)).getValueType(),
6103                              getValue(I.getArgOperand(0)),
6104                              getValue(I.getArgOperand(1))));
6105     return;
6106   case Intrinsic::copysign:
6107     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6108                              getValue(I.getArgOperand(0)).getValueType(),
6109                              getValue(I.getArgOperand(0)),
6110                              getValue(I.getArgOperand(1))));
6111     return;
6112   case Intrinsic::fma:
6113     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6114                              getValue(I.getArgOperand(0)).getValueType(),
6115                              getValue(I.getArgOperand(0)),
6116                              getValue(I.getArgOperand(1)),
6117                              getValue(I.getArgOperand(2))));
6118     return;
6119 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6120   case Intrinsic::INTRINSIC:
6121 #include "llvm/IR/ConstrainedOps.def"
6122     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6123     return;
6124   case Intrinsic::fmuladd: {
6125     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6126     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6127         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6128       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6129                                getValue(I.getArgOperand(0)).getValueType(),
6130                                getValue(I.getArgOperand(0)),
6131                                getValue(I.getArgOperand(1)),
6132                                getValue(I.getArgOperand(2))));
6133     } else {
6134       // TODO: Intrinsic calls should have fast-math-flags.
6135       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6136                                 getValue(I.getArgOperand(0)).getValueType(),
6137                                 getValue(I.getArgOperand(0)),
6138                                 getValue(I.getArgOperand(1)));
6139       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6140                                 getValue(I.getArgOperand(0)).getValueType(),
6141                                 Mul,
6142                                 getValue(I.getArgOperand(2)));
6143       setValue(&I, Add);
6144     }
6145     return;
6146   }
6147   case Intrinsic::convert_to_fp16:
6148     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6149                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6150                                          getValue(I.getArgOperand(0)),
6151                                          DAG.getTargetConstant(0, sdl,
6152                                                                MVT::i32))));
6153     return;
6154   case Intrinsic::convert_from_fp16:
6155     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6156                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6157                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6158                                          getValue(I.getArgOperand(0)))));
6159     return;
6160   case Intrinsic::pcmarker: {
6161     SDValue Tmp = getValue(I.getArgOperand(0));
6162     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6163     return;
6164   }
6165   case Intrinsic::readcyclecounter: {
6166     SDValue Op = getRoot();
6167     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6168                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6169     setValue(&I, Res);
6170     DAG.setRoot(Res.getValue(1));
6171     return;
6172   }
6173   case Intrinsic::bitreverse:
6174     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6175                              getValue(I.getArgOperand(0)).getValueType(),
6176                              getValue(I.getArgOperand(0))));
6177     return;
6178   case Intrinsic::bswap:
6179     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6180                              getValue(I.getArgOperand(0)).getValueType(),
6181                              getValue(I.getArgOperand(0))));
6182     return;
6183   case Intrinsic::cttz: {
6184     SDValue Arg = getValue(I.getArgOperand(0));
6185     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6186     EVT Ty = Arg.getValueType();
6187     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6188                              sdl, Ty, Arg));
6189     return;
6190   }
6191   case Intrinsic::ctlz: {
6192     SDValue Arg = getValue(I.getArgOperand(0));
6193     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6194     EVT Ty = Arg.getValueType();
6195     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6196                              sdl, Ty, Arg));
6197     return;
6198   }
6199   case Intrinsic::ctpop: {
6200     SDValue Arg = getValue(I.getArgOperand(0));
6201     EVT Ty = Arg.getValueType();
6202     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6203     return;
6204   }
6205   case Intrinsic::fshl:
6206   case Intrinsic::fshr: {
6207     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6208     SDValue X = getValue(I.getArgOperand(0));
6209     SDValue Y = getValue(I.getArgOperand(1));
6210     SDValue Z = getValue(I.getArgOperand(2));
6211     EVT VT = X.getValueType();
6212     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6213     SDValue Zero = DAG.getConstant(0, sdl, VT);
6214     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6215 
6216     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6217     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6218       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6219       return;
6220     }
6221 
6222     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6223     // avoid the select that is necessary in the general case to filter out
6224     // the 0-shift possibility that leads to UB.
6225     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6226       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6227       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6228         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6229         return;
6230       }
6231 
6232       // Some targets only rotate one way. Try the opposite direction.
6233       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6234       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6235         // Negate the shift amount because it is safe to ignore the high bits.
6236         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6237         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6238         return;
6239       }
6240 
6241       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6242       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6243       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6244       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6245       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6246       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6247       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6248       return;
6249     }
6250 
6251     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6252     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6253     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6254     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6255     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6256     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6257 
6258     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6259     // and that is undefined. We must compare and select to avoid UB.
6260     EVT CCVT = MVT::i1;
6261     if (VT.isVector())
6262       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6263 
6264     // For fshl, 0-shift returns the 1st arg (X).
6265     // For fshr, 0-shift returns the 2nd arg (Y).
6266     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6267     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6268     return;
6269   }
6270   case Intrinsic::sadd_sat: {
6271     SDValue Op1 = getValue(I.getArgOperand(0));
6272     SDValue Op2 = getValue(I.getArgOperand(1));
6273     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6274     return;
6275   }
6276   case Intrinsic::uadd_sat: {
6277     SDValue Op1 = getValue(I.getArgOperand(0));
6278     SDValue Op2 = getValue(I.getArgOperand(1));
6279     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6280     return;
6281   }
6282   case Intrinsic::ssub_sat: {
6283     SDValue Op1 = getValue(I.getArgOperand(0));
6284     SDValue Op2 = getValue(I.getArgOperand(1));
6285     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6286     return;
6287   }
6288   case Intrinsic::usub_sat: {
6289     SDValue Op1 = getValue(I.getArgOperand(0));
6290     SDValue Op2 = getValue(I.getArgOperand(1));
6291     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6292     return;
6293   }
6294   case Intrinsic::smul_fix:
6295   case Intrinsic::umul_fix:
6296   case Intrinsic::smul_fix_sat:
6297   case Intrinsic::umul_fix_sat: {
6298     SDValue Op1 = getValue(I.getArgOperand(0));
6299     SDValue Op2 = getValue(I.getArgOperand(1));
6300     SDValue Op3 = getValue(I.getArgOperand(2));
6301     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6302                              Op1.getValueType(), Op1, Op2, Op3));
6303     return;
6304   }
6305   case Intrinsic::sdiv_fix:
6306   case Intrinsic::udiv_fix:
6307   case Intrinsic::sdiv_fix_sat:
6308   case Intrinsic::udiv_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, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6313                               Op1, Op2, Op3, DAG, TLI));
6314     return;
6315   }
6316   case Intrinsic::stacksave: {
6317     SDValue Op = getRoot();
6318     Res = DAG.getNode(
6319         ISD::STACKSAVE, sdl,
6320         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6321     setValue(&I, Res);
6322     DAG.setRoot(Res.getValue(1));
6323     return;
6324   }
6325   case Intrinsic::stackrestore:
6326     Res = getValue(I.getArgOperand(0));
6327     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6328     return;
6329   case Intrinsic::get_dynamic_area_offset: {
6330     SDValue Op = getRoot();
6331     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6332     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6333     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6334     // target.
6335     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6336       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6337                          " intrinsic!");
6338     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6339                       Op);
6340     DAG.setRoot(Op);
6341     setValue(&I, Res);
6342     return;
6343   }
6344   case Intrinsic::stackguard: {
6345     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6346     MachineFunction &MF = DAG.getMachineFunction();
6347     const Module &M = *MF.getFunction().getParent();
6348     SDValue Chain = getRoot();
6349     if (TLI.useLoadStackGuardNode()) {
6350       Res = getLoadStackGuard(DAG, sdl, Chain);
6351     } else {
6352       const Value *Global = TLI.getSDagStackGuard(M);
6353       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6354       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6355                         MachinePointerInfo(Global, 0), Align,
6356                         MachineMemOperand::MOVolatile);
6357     }
6358     if (TLI.useStackGuardXorFP())
6359       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6360     DAG.setRoot(Chain);
6361     setValue(&I, Res);
6362     return;
6363   }
6364   case Intrinsic::stackprotector: {
6365     // Emit code into the DAG to store the stack guard onto the stack.
6366     MachineFunction &MF = DAG.getMachineFunction();
6367     MachineFrameInfo &MFI = MF.getFrameInfo();
6368     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6369     SDValue Src, Chain = getRoot();
6370 
6371     if (TLI.useLoadStackGuardNode())
6372       Src = getLoadStackGuard(DAG, sdl, Chain);
6373     else
6374       Src = getValue(I.getArgOperand(0));   // The guard's value.
6375 
6376     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6377 
6378     int FI = FuncInfo.StaticAllocaMap[Slot];
6379     MFI.setStackProtectorIndex(FI);
6380 
6381     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6382 
6383     // Store the stack protector onto the stack.
6384     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6385                                                  DAG.getMachineFunction(), FI),
6386                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6387     setValue(&I, Res);
6388     DAG.setRoot(Res);
6389     return;
6390   }
6391   case Intrinsic::objectsize:
6392     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6393 
6394   case Intrinsic::is_constant:
6395     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6396 
6397   case Intrinsic::annotation:
6398   case Intrinsic::ptr_annotation:
6399   case Intrinsic::launder_invariant_group:
6400   case Intrinsic::strip_invariant_group:
6401     // Drop the intrinsic, but forward the value
6402     setValue(&I, getValue(I.getOperand(0)));
6403     return;
6404   case Intrinsic::assume:
6405   case Intrinsic::var_annotation:
6406   case Intrinsic::sideeffect:
6407     // Discard annotate attributes, assumptions, and artificial side-effects.
6408     return;
6409 
6410   case Intrinsic::codeview_annotation: {
6411     // Emit a label associated with this metadata.
6412     MachineFunction &MF = DAG.getMachineFunction();
6413     MCSymbol *Label =
6414         MF.getMMI().getContext().createTempSymbol("annotation", true);
6415     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6416     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6417     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6418     DAG.setRoot(Res);
6419     return;
6420   }
6421 
6422   case Intrinsic::init_trampoline: {
6423     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6424 
6425     SDValue Ops[6];
6426     Ops[0] = getRoot();
6427     Ops[1] = getValue(I.getArgOperand(0));
6428     Ops[2] = getValue(I.getArgOperand(1));
6429     Ops[3] = getValue(I.getArgOperand(2));
6430     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6431     Ops[5] = DAG.getSrcValue(F);
6432 
6433     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6434 
6435     DAG.setRoot(Res);
6436     return;
6437   }
6438   case Intrinsic::adjust_trampoline:
6439     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6440                              TLI.getPointerTy(DAG.getDataLayout()),
6441                              getValue(I.getArgOperand(0))));
6442     return;
6443   case Intrinsic::gcroot: {
6444     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6445            "only valid in functions with gc specified, enforced by Verifier");
6446     assert(GFI && "implied by previous");
6447     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6448     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6449 
6450     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6451     GFI->addStackRoot(FI->getIndex(), TypeMap);
6452     return;
6453   }
6454   case Intrinsic::gcread:
6455   case Intrinsic::gcwrite:
6456     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6457   case Intrinsic::flt_rounds:
6458     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6459     setValue(&I, Res);
6460     DAG.setRoot(Res.getValue(1));
6461     return;
6462 
6463   case Intrinsic::expect:
6464     // Just replace __builtin_expect(exp, c) with EXP.
6465     setValue(&I, getValue(I.getArgOperand(0)));
6466     return;
6467 
6468   case Intrinsic::debugtrap:
6469   case Intrinsic::trap: {
6470     StringRef TrapFuncName =
6471         I.getAttributes()
6472             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6473             .getValueAsString();
6474     if (TrapFuncName.empty()) {
6475       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6476         ISD::TRAP : ISD::DEBUGTRAP;
6477       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6478       return;
6479     }
6480     TargetLowering::ArgListTy Args;
6481 
6482     TargetLowering::CallLoweringInfo CLI(DAG);
6483     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6484         CallingConv::C, I.getType(),
6485         DAG.getExternalSymbol(TrapFuncName.data(),
6486                               TLI.getPointerTy(DAG.getDataLayout())),
6487         std::move(Args));
6488 
6489     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6490     DAG.setRoot(Result.second);
6491     return;
6492   }
6493 
6494   case Intrinsic::uadd_with_overflow:
6495   case Intrinsic::sadd_with_overflow:
6496   case Intrinsic::usub_with_overflow:
6497   case Intrinsic::ssub_with_overflow:
6498   case Intrinsic::umul_with_overflow:
6499   case Intrinsic::smul_with_overflow: {
6500     ISD::NodeType Op;
6501     switch (Intrinsic) {
6502     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6503     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6504     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6505     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6506     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6507     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6508     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6509     }
6510     SDValue Op1 = getValue(I.getArgOperand(0));
6511     SDValue Op2 = getValue(I.getArgOperand(1));
6512 
6513     EVT ResultVT = Op1.getValueType();
6514     EVT OverflowVT = MVT::i1;
6515     if (ResultVT.isVector())
6516       OverflowVT = EVT::getVectorVT(
6517           *Context, OverflowVT, ResultVT.getVectorNumElements());
6518 
6519     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6520     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6521     return;
6522   }
6523   case Intrinsic::prefetch: {
6524     SDValue Ops[5];
6525     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6526     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6527     Ops[0] = DAG.getRoot();
6528     Ops[1] = getValue(I.getArgOperand(0));
6529     Ops[2] = getValue(I.getArgOperand(1));
6530     Ops[3] = getValue(I.getArgOperand(2));
6531     Ops[4] = getValue(I.getArgOperand(3));
6532     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6533                                              DAG.getVTList(MVT::Other), Ops,
6534                                              EVT::getIntegerVT(*Context, 8),
6535                                              MachinePointerInfo(I.getArgOperand(0)),
6536                                              0, /* align */
6537                                              Flags);
6538 
6539     // Chain the prefetch in parallell with any pending loads, to stay out of
6540     // the way of later optimizations.
6541     PendingLoads.push_back(Result);
6542     Result = getRoot();
6543     DAG.setRoot(Result);
6544     return;
6545   }
6546   case Intrinsic::lifetime_start:
6547   case Intrinsic::lifetime_end: {
6548     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6549     // Stack coloring is not enabled in O0, discard region information.
6550     if (TM.getOptLevel() == CodeGenOpt::None)
6551       return;
6552 
6553     const int64_t ObjectSize =
6554         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6555     Value *const ObjectPtr = I.getArgOperand(1);
6556     SmallVector<const Value *, 4> Allocas;
6557     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6558 
6559     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6560            E = Allocas.end(); Object != E; ++Object) {
6561       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6562 
6563       // Could not find an Alloca.
6564       if (!LifetimeObject)
6565         continue;
6566 
6567       // First check that the Alloca is static, otherwise it won't have a
6568       // valid frame index.
6569       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6570       if (SI == FuncInfo.StaticAllocaMap.end())
6571         return;
6572 
6573       const int FrameIndex = SI->second;
6574       int64_t Offset;
6575       if (GetPointerBaseWithConstantOffset(
6576               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6577         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6578       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6579                                 Offset);
6580       DAG.setRoot(Res);
6581     }
6582     return;
6583   }
6584   case Intrinsic::invariant_start:
6585     // Discard region information.
6586     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6587     return;
6588   case Intrinsic::invariant_end:
6589     // Discard region information.
6590     return;
6591   case Intrinsic::clear_cache:
6592     /// FunctionName may be null.
6593     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6594       lowerCallToExternalSymbol(I, FunctionName);
6595     return;
6596   case Intrinsic::donothing:
6597     // ignore
6598     return;
6599   case Intrinsic::experimental_stackmap:
6600     visitStackmap(I);
6601     return;
6602   case Intrinsic::experimental_patchpoint_void:
6603   case Intrinsic::experimental_patchpoint_i64:
6604     visitPatchpoint(&I);
6605     return;
6606   case Intrinsic::experimental_gc_statepoint:
6607     LowerStatepoint(ImmutableStatepoint(&I));
6608     return;
6609   case Intrinsic::experimental_gc_result:
6610     visitGCResult(cast<GCResultInst>(I));
6611     return;
6612   case Intrinsic::experimental_gc_relocate:
6613     visitGCRelocate(cast<GCRelocateInst>(I));
6614     return;
6615   case Intrinsic::instrprof_increment:
6616     llvm_unreachable("instrprof failed to lower an increment");
6617   case Intrinsic::instrprof_value_profile:
6618     llvm_unreachable("instrprof failed to lower a value profiling call");
6619   case Intrinsic::localescape: {
6620     MachineFunction &MF = DAG.getMachineFunction();
6621     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6622 
6623     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6624     // is the same on all targets.
6625     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6626       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6627       if (isa<ConstantPointerNull>(Arg))
6628         continue; // Skip null pointers. They represent a hole in index space.
6629       AllocaInst *Slot = cast<AllocaInst>(Arg);
6630       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6631              "can only escape static allocas");
6632       int FI = FuncInfo.StaticAllocaMap[Slot];
6633       MCSymbol *FrameAllocSym =
6634           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6635               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6636       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6637               TII->get(TargetOpcode::LOCAL_ESCAPE))
6638           .addSym(FrameAllocSym)
6639           .addFrameIndex(FI);
6640     }
6641 
6642     return;
6643   }
6644 
6645   case Intrinsic::localrecover: {
6646     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6647     MachineFunction &MF = DAG.getMachineFunction();
6648     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6649 
6650     // Get the symbol that defines the frame offset.
6651     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6652     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6653     unsigned IdxVal =
6654         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6655     MCSymbol *FrameAllocSym =
6656         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6657             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6658 
6659     // Create a MCSymbol for the label to avoid any target lowering
6660     // that would make this PC relative.
6661     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6662     SDValue OffsetVal =
6663         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6664 
6665     // Add the offset to the FP.
6666     Value *FP = I.getArgOperand(1);
6667     SDValue FPVal = getValue(FP);
6668     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6669     setValue(&I, Add);
6670 
6671     return;
6672   }
6673 
6674   case Intrinsic::eh_exceptionpointer:
6675   case Intrinsic::eh_exceptioncode: {
6676     // Get the exception pointer vreg, copy from it, and resize it to fit.
6677     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6678     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6679     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6680     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6681     SDValue N =
6682         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6683     if (Intrinsic == Intrinsic::eh_exceptioncode)
6684       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6685     setValue(&I, N);
6686     return;
6687   }
6688   case Intrinsic::xray_customevent: {
6689     // Here we want to make sure that the intrinsic behaves as if it has a
6690     // specific calling convention, and only for x86_64.
6691     // FIXME: Support other platforms later.
6692     const auto &Triple = DAG.getTarget().getTargetTriple();
6693     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6694       return;
6695 
6696     SDLoc DL = getCurSDLoc();
6697     SmallVector<SDValue, 8> Ops;
6698 
6699     // We want to say that we always want the arguments in registers.
6700     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6701     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6702     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6703     SDValue Chain = getRoot();
6704     Ops.push_back(LogEntryVal);
6705     Ops.push_back(StrSizeVal);
6706     Ops.push_back(Chain);
6707 
6708     // We need to enforce the calling convention for the callsite, so that
6709     // argument ordering is enforced correctly, and that register allocation can
6710     // see that some registers may be assumed clobbered and have to preserve
6711     // them across calls to the intrinsic.
6712     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6713                                            DL, NodeTys, Ops);
6714     SDValue patchableNode = SDValue(MN, 0);
6715     DAG.setRoot(patchableNode);
6716     setValue(&I, patchableNode);
6717     return;
6718   }
6719   case Intrinsic::xray_typedevent: {
6720     // Here we want to make sure that the intrinsic behaves as if it has a
6721     // specific calling convention, and only for x86_64.
6722     // FIXME: Support other platforms later.
6723     const auto &Triple = DAG.getTarget().getTargetTriple();
6724     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6725       return;
6726 
6727     SDLoc DL = getCurSDLoc();
6728     SmallVector<SDValue, 8> Ops;
6729 
6730     // We want to say that we always want the arguments in registers.
6731     // It's unclear to me how manipulating the selection DAG here forces callers
6732     // to provide arguments in registers instead of on the stack.
6733     SDValue LogTypeId = getValue(I.getArgOperand(0));
6734     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6735     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6736     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6737     SDValue Chain = getRoot();
6738     Ops.push_back(LogTypeId);
6739     Ops.push_back(LogEntryVal);
6740     Ops.push_back(StrSizeVal);
6741     Ops.push_back(Chain);
6742 
6743     // We need to enforce the calling convention for the callsite, so that
6744     // argument ordering is enforced correctly, and that register allocation can
6745     // see that some registers may be assumed clobbered and have to preserve
6746     // them across calls to the intrinsic.
6747     MachineSDNode *MN = DAG.getMachineNode(
6748         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6749     SDValue patchableNode = SDValue(MN, 0);
6750     DAG.setRoot(patchableNode);
6751     setValue(&I, patchableNode);
6752     return;
6753   }
6754   case Intrinsic::experimental_deoptimize:
6755     LowerDeoptimizeCall(&I);
6756     return;
6757 
6758   case Intrinsic::experimental_vector_reduce_v2_fadd:
6759   case Intrinsic::experimental_vector_reduce_v2_fmul:
6760   case Intrinsic::experimental_vector_reduce_add:
6761   case Intrinsic::experimental_vector_reduce_mul:
6762   case Intrinsic::experimental_vector_reduce_and:
6763   case Intrinsic::experimental_vector_reduce_or:
6764   case Intrinsic::experimental_vector_reduce_xor:
6765   case Intrinsic::experimental_vector_reduce_smax:
6766   case Intrinsic::experimental_vector_reduce_smin:
6767   case Intrinsic::experimental_vector_reduce_umax:
6768   case Intrinsic::experimental_vector_reduce_umin:
6769   case Intrinsic::experimental_vector_reduce_fmax:
6770   case Intrinsic::experimental_vector_reduce_fmin:
6771     visitVectorReduce(I, Intrinsic);
6772     return;
6773 
6774   case Intrinsic::icall_branch_funnel: {
6775     SmallVector<SDValue, 16> Ops;
6776     Ops.push_back(getValue(I.getArgOperand(0)));
6777 
6778     int64_t Offset;
6779     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6780         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6781     if (!Base)
6782       report_fatal_error(
6783           "llvm.icall.branch.funnel operand must be a GlobalValue");
6784     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6785 
6786     struct BranchFunnelTarget {
6787       int64_t Offset;
6788       SDValue Target;
6789     };
6790     SmallVector<BranchFunnelTarget, 8> Targets;
6791 
6792     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6793       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6794           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6795       if (ElemBase != Base)
6796         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6797                            "to the same GlobalValue");
6798 
6799       SDValue Val = getValue(I.getArgOperand(Op + 1));
6800       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6801       if (!GA)
6802         report_fatal_error(
6803             "llvm.icall.branch.funnel operand must be a GlobalValue");
6804       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6805                                      GA->getGlobal(), getCurSDLoc(),
6806                                      Val.getValueType(), GA->getOffset())});
6807     }
6808     llvm::sort(Targets,
6809                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6810                  return T1.Offset < T2.Offset;
6811                });
6812 
6813     for (auto &T : Targets) {
6814       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6815       Ops.push_back(T.Target);
6816     }
6817 
6818     Ops.push_back(DAG.getRoot()); // Chain
6819     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6820                                  getCurSDLoc(), MVT::Other, Ops),
6821               0);
6822     DAG.setRoot(N);
6823     setValue(&I, N);
6824     HasTailCall = true;
6825     return;
6826   }
6827 
6828   case Intrinsic::wasm_landingpad_index:
6829     // Information this intrinsic contained has been transferred to
6830     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6831     // delete it now.
6832     return;
6833 
6834   case Intrinsic::aarch64_settag:
6835   case Intrinsic::aarch64_settag_zero: {
6836     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6837     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6838     SDValue Val = TSI.EmitTargetCodeForSetTag(
6839         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6840         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6841         ZeroMemory);
6842     DAG.setRoot(Val);
6843     setValue(&I, Val);
6844     return;
6845   }
6846   case Intrinsic::ptrmask: {
6847     SDValue Ptr = getValue(I.getOperand(0));
6848     SDValue Const = getValue(I.getOperand(1));
6849 
6850     EVT DestVT =
6851         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6852 
6853     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6854                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6855     return;
6856   }
6857   }
6858 }
6859 
6860 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6861     const ConstrainedFPIntrinsic &FPI) {
6862   SDLoc sdl = getCurSDLoc();
6863 
6864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6865   SmallVector<EVT, 4> ValueVTs;
6866   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6867   ValueVTs.push_back(MVT::Other); // Out chain
6868 
6869   // We do not need to serialize constrained FP intrinsics against
6870   // each other or against (nonvolatile) loads, so they can be
6871   // chained like loads.
6872   SDValue Chain = DAG.getRoot();
6873   SmallVector<SDValue, 4> Opers;
6874   Opers.push_back(Chain);
6875   if (FPI.isUnaryOp()) {
6876     Opers.push_back(getValue(FPI.getArgOperand(0)));
6877   } else if (FPI.isTernaryOp()) {
6878     Opers.push_back(getValue(FPI.getArgOperand(0)));
6879     Opers.push_back(getValue(FPI.getArgOperand(1)));
6880     Opers.push_back(getValue(FPI.getArgOperand(2)));
6881   } else {
6882     Opers.push_back(getValue(FPI.getArgOperand(0)));
6883     Opers.push_back(getValue(FPI.getArgOperand(1)));
6884   }
6885 
6886   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6887     assert(Result.getNode()->getNumValues() == 2);
6888 
6889     // Push node to the appropriate list so that future instructions can be
6890     // chained up correctly.
6891     SDValue OutChain = Result.getValue(1);
6892     switch (EB) {
6893     case fp::ExceptionBehavior::ebIgnore:
6894       // The only reason why ebIgnore nodes still need to be chained is that
6895       // they might depend on the current rounding mode, and therefore must
6896       // not be moved across instruction that may change that mode.
6897       LLVM_FALLTHROUGH;
6898     case fp::ExceptionBehavior::ebMayTrap:
6899       // These must not be moved across calls or instructions that may change
6900       // floating-point exception masks.
6901       PendingConstrainedFP.push_back(OutChain);
6902       break;
6903     case fp::ExceptionBehavior::ebStrict:
6904       // These must not be moved across calls or instructions that may change
6905       // floating-point exception masks or read floating-point exception flags.
6906       // In addition, they cannot be optimized out even if unused.
6907       PendingConstrainedFPStrict.push_back(OutChain);
6908       break;
6909     }
6910   };
6911 
6912   SDVTList VTs = DAG.getVTList(ValueVTs);
6913   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6914 
6915   SDNodeFlags Flags;
6916   if (EB == fp::ExceptionBehavior::ebIgnore)
6917     Flags.setNoFPExcept(true);
6918 
6919   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6920     Flags.copyFMF(*FPOp);
6921 
6922   unsigned Opcode;
6923   switch (FPI.getIntrinsicID()) {
6924   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6925 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6926   case Intrinsic::INTRINSIC:                                                   \
6927     Opcode = ISD::STRICT_##DAGN;                                               \
6928     break;
6929 #include "llvm/IR/ConstrainedOps.def"
6930   case Intrinsic::experimental_constrained_fmuladd: {
6931     Opcode = ISD::STRICT_FMA;
6932     // Break fmuladd into fmul and fadd.
6933     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6934         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6935                                         ValueVTs[0])) {
6936       Opers.pop_back();
6937       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6938       pushOutChain(Mul, EB);
6939       Opcode = ISD::STRICT_FADD;
6940       Opers.clear();
6941       Opers.push_back(Mul.getValue(1));
6942       Opers.push_back(Mul.getValue(0));
6943       Opers.push_back(getValue(FPI.getArgOperand(2)));
6944     }
6945     break;
6946   }
6947   }
6948 
6949   // A few strict DAG nodes carry additional operands that are not
6950   // set up by the default code above.
6951   switch (Opcode) {
6952   default: break;
6953   case ISD::STRICT_FP_ROUND:
6954     Opers.push_back(
6955         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6956     break;
6957   case ISD::STRICT_FSETCC:
6958   case ISD::STRICT_FSETCCS: {
6959     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6960     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6961     break;
6962   }
6963   }
6964 
6965   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
6966   pushOutChain(Result, EB);
6967 
6968   SDValue FPResult = Result.getValue(0);
6969   setValue(&FPI, FPResult);
6970 }
6971 
6972 std::pair<SDValue, SDValue>
6973 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6974                                     const BasicBlock *EHPadBB) {
6975   MachineFunction &MF = DAG.getMachineFunction();
6976   MachineModuleInfo &MMI = MF.getMMI();
6977   MCSymbol *BeginLabel = nullptr;
6978 
6979   if (EHPadBB) {
6980     // Insert a label before the invoke call to mark the try range.  This can be
6981     // used to detect deletion of the invoke via the MachineModuleInfo.
6982     BeginLabel = MMI.getContext().createTempSymbol();
6983 
6984     // For SjLj, keep track of which landing pads go with which invokes
6985     // so as to maintain the ordering of pads in the LSDA.
6986     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6987     if (CallSiteIndex) {
6988       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6989       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6990 
6991       // Now that the call site is handled, stop tracking it.
6992       MMI.setCurrentCallSite(0);
6993     }
6994 
6995     // Both PendingLoads and PendingExports must be flushed here;
6996     // this call might not return.
6997     (void)getRoot();
6998     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6999 
7000     CLI.setChain(getRoot());
7001   }
7002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7003   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7004 
7005   assert((CLI.IsTailCall || Result.second.getNode()) &&
7006          "Non-null chain expected with non-tail call!");
7007   assert((Result.second.getNode() || !Result.first.getNode()) &&
7008          "Null value expected with tail call!");
7009 
7010   if (!Result.second.getNode()) {
7011     // As a special case, a null chain means that a tail call has been emitted
7012     // and the DAG root is already updated.
7013     HasTailCall = true;
7014 
7015     // Since there's no actual continuation from this block, nothing can be
7016     // relying on us setting vregs for them.
7017     PendingExports.clear();
7018   } else {
7019     DAG.setRoot(Result.second);
7020   }
7021 
7022   if (EHPadBB) {
7023     // Insert a label at the end of the invoke call to mark the try range.  This
7024     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7025     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7026     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7027 
7028     // Inform MachineModuleInfo of range.
7029     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7030     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7031     // actually use outlined funclets and their LSDA info style.
7032     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7033       assert(CLI.CS);
7034       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7035       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7036                                 BeginLabel, EndLabel);
7037     } else if (!isScopedEHPersonality(Pers)) {
7038       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7039     }
7040   }
7041 
7042   return Result;
7043 }
7044 
7045 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7046                                       bool isTailCall,
7047                                       const BasicBlock *EHPadBB) {
7048   auto &DL = DAG.getDataLayout();
7049   FunctionType *FTy = CS.getFunctionType();
7050   Type *RetTy = CS.getType();
7051 
7052   TargetLowering::ArgListTy Args;
7053   Args.reserve(CS.arg_size());
7054 
7055   const Value *SwiftErrorVal = nullptr;
7056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7057 
7058   if (isTailCall) {
7059     // Avoid emitting tail calls in functions with the disable-tail-calls
7060     // attribute.
7061     auto *Caller = CS.getInstruction()->getParent()->getParent();
7062     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7063         "true")
7064       isTailCall = false;
7065 
7066     // We can't tail call inside a function with a swifterror argument. Lowering
7067     // does not support this yet. It would have to move into the swifterror
7068     // register before the call.
7069     if (TLI.supportSwiftError() &&
7070         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7071       isTailCall = false;
7072   }
7073 
7074   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7075        i != e; ++i) {
7076     TargetLowering::ArgListEntry Entry;
7077     const Value *V = *i;
7078 
7079     // Skip empty types
7080     if (V->getType()->isEmptyTy())
7081       continue;
7082 
7083     SDValue ArgNode = getValue(V);
7084     Entry.Node = ArgNode; Entry.Ty = V->getType();
7085 
7086     Entry.setAttributes(&CS, i - CS.arg_begin());
7087 
7088     // Use swifterror virtual register as input to the call.
7089     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7090       SwiftErrorVal = V;
7091       // We find the virtual register for the actual swifterror argument.
7092       // Instead of using the Value, we use the virtual register instead.
7093       Entry.Node = DAG.getRegister(
7094           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7095           EVT(TLI.getPointerTy(DL)));
7096     }
7097 
7098     Args.push_back(Entry);
7099 
7100     // If we have an explicit sret argument that is an Instruction, (i.e., it
7101     // might point to function-local memory), we can't meaningfully tail-call.
7102     if (Entry.IsSRet && isa<Instruction>(V))
7103       isTailCall = false;
7104   }
7105 
7106   // If call site has a cfguardtarget operand bundle, create and add an
7107   // additional ArgListEntry.
7108   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7109     TargetLowering::ArgListEntry Entry;
7110     Value *V = Bundle->Inputs[0];
7111     SDValue ArgNode = getValue(V);
7112     Entry.Node = ArgNode;
7113     Entry.Ty = V->getType();
7114     Entry.IsCFGuardTarget = true;
7115     Args.push_back(Entry);
7116   }
7117 
7118   // Check if target-independent constraints permit a tail call here.
7119   // Target-dependent constraints are checked within TLI->LowerCallTo.
7120   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7121     isTailCall = false;
7122 
7123   // Disable tail calls if there is an swifterror argument. Targets have not
7124   // been updated to support tail calls.
7125   if (TLI.supportSwiftError() && SwiftErrorVal)
7126     isTailCall = false;
7127 
7128   TargetLowering::CallLoweringInfo CLI(DAG);
7129   CLI.setDebugLoc(getCurSDLoc())
7130       .setChain(getRoot())
7131       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7132       .setTailCall(isTailCall)
7133       .setConvergent(CS.isConvergent());
7134   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7135 
7136   if (Result.first.getNode()) {
7137     const Instruction *Inst = CS.getInstruction();
7138     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7139     setValue(Inst, Result.first);
7140   }
7141 
7142   // The last element of CLI.InVals has the SDValue for swifterror return.
7143   // Here we copy it to a virtual register and update SwiftErrorMap for
7144   // book-keeping.
7145   if (SwiftErrorVal && TLI.supportSwiftError()) {
7146     // Get the last element of InVals.
7147     SDValue Src = CLI.InVals.back();
7148     Register VReg = SwiftError.getOrCreateVRegDefAt(
7149         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7150     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7151     DAG.setRoot(CopyNode);
7152   }
7153 }
7154 
7155 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7156                              SelectionDAGBuilder &Builder) {
7157   // Check to see if this load can be trivially constant folded, e.g. if the
7158   // input is from a string literal.
7159   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7160     // Cast pointer to the type we really want to load.
7161     Type *LoadTy =
7162         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7163     if (LoadVT.isVector())
7164       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7165 
7166     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7167                                          PointerType::getUnqual(LoadTy));
7168 
7169     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7170             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7171       return Builder.getValue(LoadCst);
7172   }
7173 
7174   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7175   // still constant memory, the input chain can be the entry node.
7176   SDValue Root;
7177   bool ConstantMemory = false;
7178 
7179   // Do not serialize (non-volatile) loads of constant memory with anything.
7180   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7181     Root = Builder.DAG.getEntryNode();
7182     ConstantMemory = true;
7183   } else {
7184     // Do not serialize non-volatile loads against each other.
7185     Root = Builder.DAG.getRoot();
7186   }
7187 
7188   SDValue Ptr = Builder.getValue(PtrVal);
7189   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7190                                         Ptr, MachinePointerInfo(PtrVal),
7191                                         /* Alignment = */ 1);
7192 
7193   if (!ConstantMemory)
7194     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7195   return LoadVal;
7196 }
7197 
7198 /// Record the value for an instruction that produces an integer result,
7199 /// converting the type where necessary.
7200 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7201                                                   SDValue Value,
7202                                                   bool IsSigned) {
7203   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7204                                                     I.getType(), true);
7205   if (IsSigned)
7206     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7207   else
7208     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7209   setValue(&I, Value);
7210 }
7211 
7212 /// See if we can lower a memcmp call into an optimized form. If so, return
7213 /// true and lower it. Otherwise return false, and it will be lowered like a
7214 /// normal call.
7215 /// The caller already checked that \p I calls the appropriate LibFunc with a
7216 /// correct prototype.
7217 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7218   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7219   const Value *Size = I.getArgOperand(2);
7220   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7221   if (CSize && CSize->getZExtValue() == 0) {
7222     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7223                                                           I.getType(), true);
7224     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7225     return true;
7226   }
7227 
7228   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7229   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7230       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7231       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7232   if (Res.first.getNode()) {
7233     processIntegerCallValue(I, Res.first, true);
7234     PendingLoads.push_back(Res.second);
7235     return true;
7236   }
7237 
7238   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7239   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7240   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7241     return false;
7242 
7243   // If the target has a fast compare for the given size, it will return a
7244   // preferred load type for that size. Require that the load VT is legal and
7245   // that the target supports unaligned loads of that type. Otherwise, return
7246   // INVALID.
7247   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7248     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7249     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7250     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7251       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7252       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7253       // TODO: Check alignment of src and dest ptrs.
7254       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7255       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7256       if (!TLI.isTypeLegal(LVT) ||
7257           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7258           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7259         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7260     }
7261 
7262     return LVT;
7263   };
7264 
7265   // This turns into unaligned loads. We only do this if the target natively
7266   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7267   // we'll only produce a small number of byte loads.
7268   MVT LoadVT;
7269   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7270   switch (NumBitsToCompare) {
7271   default:
7272     return false;
7273   case 16:
7274     LoadVT = MVT::i16;
7275     break;
7276   case 32:
7277     LoadVT = MVT::i32;
7278     break;
7279   case 64:
7280   case 128:
7281   case 256:
7282     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7283     break;
7284   }
7285 
7286   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7287     return false;
7288 
7289   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7290   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7291 
7292   // Bitcast to a wide integer type if the loads are vectors.
7293   if (LoadVT.isVector()) {
7294     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7295     LoadL = DAG.getBitcast(CmpVT, LoadL);
7296     LoadR = DAG.getBitcast(CmpVT, LoadR);
7297   }
7298 
7299   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7300   processIntegerCallValue(I, Cmp, false);
7301   return true;
7302 }
7303 
7304 /// See if we can lower a memchr call into an optimized form. If so, return
7305 /// true and lower it. Otherwise return false, and it will be lowered like a
7306 /// normal call.
7307 /// The caller already checked that \p I calls the appropriate LibFunc with a
7308 /// correct prototype.
7309 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7310   const Value *Src = I.getArgOperand(0);
7311   const Value *Char = I.getArgOperand(1);
7312   const Value *Length = I.getArgOperand(2);
7313 
7314   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7315   std::pair<SDValue, SDValue> Res =
7316     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7317                                 getValue(Src), getValue(Char), getValue(Length),
7318                                 MachinePointerInfo(Src));
7319   if (Res.first.getNode()) {
7320     setValue(&I, Res.first);
7321     PendingLoads.push_back(Res.second);
7322     return true;
7323   }
7324 
7325   return false;
7326 }
7327 
7328 /// See if we can lower a mempcpy call into an optimized form. If so, return
7329 /// true and lower it. Otherwise return false, and it will be lowered like a
7330 /// normal call.
7331 /// The caller already checked that \p I calls the appropriate LibFunc with a
7332 /// correct prototype.
7333 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7334   SDValue Dst = getValue(I.getArgOperand(0));
7335   SDValue Src = getValue(I.getArgOperand(1));
7336   SDValue Size = getValue(I.getArgOperand(2));
7337 
7338   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7339   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7340   // DAG::getMemcpy needs Alignment to be defined.
7341   Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign));
7342 
7343   bool isVol = false;
7344   SDLoc sdl = getCurSDLoc();
7345 
7346   // In the mempcpy context we need to pass in a false value for isTailCall
7347   // because the return pointer needs to be adjusted by the size of
7348   // the copied memory.
7349   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7350   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7351                              /*isTailCall=*/false,
7352                              MachinePointerInfo(I.getArgOperand(0)),
7353                              MachinePointerInfo(I.getArgOperand(1)));
7354   assert(MC.getNode() != nullptr &&
7355          "** memcpy should not be lowered as TailCall in mempcpy context **");
7356   DAG.setRoot(MC);
7357 
7358   // Check if Size needs to be truncated or extended.
7359   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7360 
7361   // Adjust return pointer to point just past the last dst byte.
7362   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7363                                     Dst, Size);
7364   setValue(&I, DstPlusSize);
7365   return true;
7366 }
7367 
7368 /// See if we can lower a strcpy call into an optimized form.  If so, return
7369 /// true and lower it, otherwise return false and it will be lowered like a
7370 /// normal call.
7371 /// The caller already checked that \p I calls the appropriate LibFunc with a
7372 /// correct prototype.
7373 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7374   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7375 
7376   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7377   std::pair<SDValue, SDValue> Res =
7378     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7379                                 getValue(Arg0), getValue(Arg1),
7380                                 MachinePointerInfo(Arg0),
7381                                 MachinePointerInfo(Arg1), isStpcpy);
7382   if (Res.first.getNode()) {
7383     setValue(&I, Res.first);
7384     DAG.setRoot(Res.second);
7385     return true;
7386   }
7387 
7388   return false;
7389 }
7390 
7391 /// See if we can lower a strcmp call into an optimized form.  If so, return
7392 /// true and lower it, otherwise return false and it will be lowered like a
7393 /// normal call.
7394 /// The caller already checked that \p I calls the appropriate LibFunc with a
7395 /// correct prototype.
7396 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7397   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7398 
7399   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7400   std::pair<SDValue, SDValue> Res =
7401     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7402                                 getValue(Arg0), getValue(Arg1),
7403                                 MachinePointerInfo(Arg0),
7404                                 MachinePointerInfo(Arg1));
7405   if (Res.first.getNode()) {
7406     processIntegerCallValue(I, Res.first, true);
7407     PendingLoads.push_back(Res.second);
7408     return true;
7409   }
7410 
7411   return false;
7412 }
7413 
7414 /// See if we can lower a strlen call into an optimized form.  If so, return
7415 /// true and lower it, otherwise return false and it will be lowered like a
7416 /// normal call.
7417 /// The caller already checked that \p I calls the appropriate LibFunc with a
7418 /// correct prototype.
7419 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7420   const Value *Arg0 = I.getArgOperand(0);
7421 
7422   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7423   std::pair<SDValue, SDValue> Res =
7424     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7425                                 getValue(Arg0), MachinePointerInfo(Arg0));
7426   if (Res.first.getNode()) {
7427     processIntegerCallValue(I, Res.first, false);
7428     PendingLoads.push_back(Res.second);
7429     return true;
7430   }
7431 
7432   return false;
7433 }
7434 
7435 /// See if we can lower a strnlen call into an optimized form.  If so, return
7436 /// true and lower it, otherwise return false and it will be lowered like a
7437 /// normal call.
7438 /// The caller already checked that \p I calls the appropriate LibFunc with a
7439 /// correct prototype.
7440 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7441   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7442 
7443   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7444   std::pair<SDValue, SDValue> Res =
7445     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7446                                  getValue(Arg0), getValue(Arg1),
7447                                  MachinePointerInfo(Arg0));
7448   if (Res.first.getNode()) {
7449     processIntegerCallValue(I, Res.first, false);
7450     PendingLoads.push_back(Res.second);
7451     return true;
7452   }
7453 
7454   return false;
7455 }
7456 
7457 /// See if we can lower a unary floating-point operation into an SDNode with
7458 /// the specified Opcode.  If so, return true and lower it, otherwise return
7459 /// false and it will be lowered like a normal call.
7460 /// The caller already checked that \p I calls the appropriate LibFunc with a
7461 /// correct prototype.
7462 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7463                                               unsigned Opcode) {
7464   // We already checked this call's prototype; verify it doesn't modify errno.
7465   if (!I.onlyReadsMemory())
7466     return false;
7467 
7468   SDValue Tmp = getValue(I.getArgOperand(0));
7469   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7470   return true;
7471 }
7472 
7473 /// See if we can lower a binary floating-point operation into an SDNode with
7474 /// the specified Opcode. If so, return true and lower it. Otherwise return
7475 /// false, and it will be lowered like a normal call.
7476 /// The caller already checked that \p I calls the appropriate LibFunc with a
7477 /// correct prototype.
7478 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7479                                                unsigned Opcode) {
7480   // We already checked this call's prototype; verify it doesn't modify errno.
7481   if (!I.onlyReadsMemory())
7482     return false;
7483 
7484   SDValue Tmp0 = getValue(I.getArgOperand(0));
7485   SDValue Tmp1 = getValue(I.getArgOperand(1));
7486   EVT VT = Tmp0.getValueType();
7487   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7488   return true;
7489 }
7490 
7491 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7492   // Handle inline assembly differently.
7493   if (isa<InlineAsm>(I.getCalledValue())) {
7494     visitInlineAsm(&I);
7495     return;
7496   }
7497 
7498   if (Function *F = I.getCalledFunction()) {
7499     if (F->isDeclaration()) {
7500       // Is this an LLVM intrinsic or a target-specific intrinsic?
7501       unsigned IID = F->getIntrinsicID();
7502       if (!IID)
7503         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7504           IID = II->getIntrinsicID(F);
7505 
7506       if (IID) {
7507         visitIntrinsicCall(I, IID);
7508         return;
7509       }
7510     }
7511 
7512     // Check for well-known libc/libm calls.  If the function is internal, it
7513     // can't be a library call.  Don't do the check if marked as nobuiltin for
7514     // some reason or the call site requires strict floating point semantics.
7515     LibFunc Func;
7516     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7517         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7518         LibInfo->hasOptimizedCodeGen(Func)) {
7519       switch (Func) {
7520       default: break;
7521       case LibFunc_copysign:
7522       case LibFunc_copysignf:
7523       case LibFunc_copysignl:
7524         // We already checked this call's prototype; verify it doesn't modify
7525         // errno.
7526         if (I.onlyReadsMemory()) {
7527           SDValue LHS = getValue(I.getArgOperand(0));
7528           SDValue RHS = getValue(I.getArgOperand(1));
7529           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7530                                    LHS.getValueType(), LHS, RHS));
7531           return;
7532         }
7533         break;
7534       case LibFunc_fabs:
7535       case LibFunc_fabsf:
7536       case LibFunc_fabsl:
7537         if (visitUnaryFloatCall(I, ISD::FABS))
7538           return;
7539         break;
7540       case LibFunc_fmin:
7541       case LibFunc_fminf:
7542       case LibFunc_fminl:
7543         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7544           return;
7545         break;
7546       case LibFunc_fmax:
7547       case LibFunc_fmaxf:
7548       case LibFunc_fmaxl:
7549         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7550           return;
7551         break;
7552       case LibFunc_sin:
7553       case LibFunc_sinf:
7554       case LibFunc_sinl:
7555         if (visitUnaryFloatCall(I, ISD::FSIN))
7556           return;
7557         break;
7558       case LibFunc_cos:
7559       case LibFunc_cosf:
7560       case LibFunc_cosl:
7561         if (visitUnaryFloatCall(I, ISD::FCOS))
7562           return;
7563         break;
7564       case LibFunc_sqrt:
7565       case LibFunc_sqrtf:
7566       case LibFunc_sqrtl:
7567       case LibFunc_sqrt_finite:
7568       case LibFunc_sqrtf_finite:
7569       case LibFunc_sqrtl_finite:
7570         if (visitUnaryFloatCall(I, ISD::FSQRT))
7571           return;
7572         break;
7573       case LibFunc_floor:
7574       case LibFunc_floorf:
7575       case LibFunc_floorl:
7576         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7577           return;
7578         break;
7579       case LibFunc_nearbyint:
7580       case LibFunc_nearbyintf:
7581       case LibFunc_nearbyintl:
7582         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7583           return;
7584         break;
7585       case LibFunc_ceil:
7586       case LibFunc_ceilf:
7587       case LibFunc_ceill:
7588         if (visitUnaryFloatCall(I, ISD::FCEIL))
7589           return;
7590         break;
7591       case LibFunc_rint:
7592       case LibFunc_rintf:
7593       case LibFunc_rintl:
7594         if (visitUnaryFloatCall(I, ISD::FRINT))
7595           return;
7596         break;
7597       case LibFunc_round:
7598       case LibFunc_roundf:
7599       case LibFunc_roundl:
7600         if (visitUnaryFloatCall(I, ISD::FROUND))
7601           return;
7602         break;
7603       case LibFunc_trunc:
7604       case LibFunc_truncf:
7605       case LibFunc_truncl:
7606         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7607           return;
7608         break;
7609       case LibFunc_log2:
7610       case LibFunc_log2f:
7611       case LibFunc_log2l:
7612         if (visitUnaryFloatCall(I, ISD::FLOG2))
7613           return;
7614         break;
7615       case LibFunc_exp2:
7616       case LibFunc_exp2f:
7617       case LibFunc_exp2l:
7618         if (visitUnaryFloatCall(I, ISD::FEXP2))
7619           return;
7620         break;
7621       case LibFunc_memcmp:
7622         if (visitMemCmpCall(I))
7623           return;
7624         break;
7625       case LibFunc_mempcpy:
7626         if (visitMemPCpyCall(I))
7627           return;
7628         break;
7629       case LibFunc_memchr:
7630         if (visitMemChrCall(I))
7631           return;
7632         break;
7633       case LibFunc_strcpy:
7634         if (visitStrCpyCall(I, false))
7635           return;
7636         break;
7637       case LibFunc_stpcpy:
7638         if (visitStrCpyCall(I, true))
7639           return;
7640         break;
7641       case LibFunc_strcmp:
7642         if (visitStrCmpCall(I))
7643           return;
7644         break;
7645       case LibFunc_strlen:
7646         if (visitStrLenCall(I))
7647           return;
7648         break;
7649       case LibFunc_strnlen:
7650         if (visitStrNLenCall(I))
7651           return;
7652         break;
7653       }
7654     }
7655   }
7656 
7657   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7658   // have to do anything here to lower funclet bundles.
7659   // CFGuardTarget bundles are lowered in LowerCallTo.
7660   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7661                                         LLVMContext::OB_funclet,
7662                                         LLVMContext::OB_cfguardtarget}) &&
7663          "Cannot lower calls with arbitrary operand bundles!");
7664 
7665   SDValue Callee = getValue(I.getCalledValue());
7666 
7667   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7668     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7669   else
7670     // Check if we can potentially perform a tail call. More detailed checking
7671     // is be done within LowerCallTo, after more information about the call is
7672     // known.
7673     LowerCallTo(&I, Callee, I.isTailCall());
7674 }
7675 
7676 namespace {
7677 
7678 /// AsmOperandInfo - This contains information for each constraint that we are
7679 /// lowering.
7680 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7681 public:
7682   /// CallOperand - If this is the result output operand or a clobber
7683   /// this is null, otherwise it is the incoming operand to the CallInst.
7684   /// This gets modified as the asm is processed.
7685   SDValue CallOperand;
7686 
7687   /// AssignedRegs - If this is a register or register class operand, this
7688   /// contains the set of register corresponding to the operand.
7689   RegsForValue AssignedRegs;
7690 
7691   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7692     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7693   }
7694 
7695   /// Whether or not this operand accesses memory
7696   bool hasMemory(const TargetLowering &TLI) const {
7697     // Indirect operand accesses access memory.
7698     if (isIndirect)
7699       return true;
7700 
7701     for (const auto &Code : Codes)
7702       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7703         return true;
7704 
7705     return false;
7706   }
7707 
7708   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7709   /// corresponds to.  If there is no Value* for this operand, it returns
7710   /// MVT::Other.
7711   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7712                            const DataLayout &DL) const {
7713     if (!CallOperandVal) return MVT::Other;
7714 
7715     if (isa<BasicBlock>(CallOperandVal))
7716       return TLI.getPointerTy(DL);
7717 
7718     llvm::Type *OpTy = CallOperandVal->getType();
7719 
7720     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7721     // If this is an indirect operand, the operand is a pointer to the
7722     // accessed type.
7723     if (isIndirect) {
7724       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7725       if (!PtrTy)
7726         report_fatal_error("Indirect operand for inline asm not a pointer!");
7727       OpTy = PtrTy->getElementType();
7728     }
7729 
7730     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7731     if (StructType *STy = dyn_cast<StructType>(OpTy))
7732       if (STy->getNumElements() == 1)
7733         OpTy = STy->getElementType(0);
7734 
7735     // If OpTy is not a single value, it may be a struct/union that we
7736     // can tile with integers.
7737     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7738       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7739       switch (BitSize) {
7740       default: break;
7741       case 1:
7742       case 8:
7743       case 16:
7744       case 32:
7745       case 64:
7746       case 128:
7747         OpTy = IntegerType::get(Context, BitSize);
7748         break;
7749       }
7750     }
7751 
7752     return TLI.getValueType(DL, OpTy, true);
7753   }
7754 };
7755 
7756 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7757 
7758 } // end anonymous namespace
7759 
7760 /// Make sure that the output operand \p OpInfo and its corresponding input
7761 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7762 /// out).
7763 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7764                                SDISelAsmOperandInfo &MatchingOpInfo,
7765                                SelectionDAG &DAG) {
7766   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7767     return;
7768 
7769   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7770   const auto &TLI = DAG.getTargetLoweringInfo();
7771 
7772   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7773       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7774                                        OpInfo.ConstraintVT);
7775   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7776       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7777                                        MatchingOpInfo.ConstraintVT);
7778   if ((OpInfo.ConstraintVT.isInteger() !=
7779        MatchingOpInfo.ConstraintVT.isInteger()) ||
7780       (MatchRC.second != InputRC.second)) {
7781     // FIXME: error out in a more elegant fashion
7782     report_fatal_error("Unsupported asm: input constraint"
7783                        " with a matching output constraint of"
7784                        " incompatible type!");
7785   }
7786   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7787 }
7788 
7789 /// Get a direct memory input to behave well as an indirect operand.
7790 /// This may introduce stores, hence the need for a \p Chain.
7791 /// \return The (possibly updated) chain.
7792 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7793                                         SDISelAsmOperandInfo &OpInfo,
7794                                         SelectionDAG &DAG) {
7795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7796 
7797   // If we don't have an indirect input, put it in the constpool if we can,
7798   // otherwise spill it to a stack slot.
7799   // TODO: This isn't quite right. We need to handle these according to
7800   // the addressing mode that the constraint wants. Also, this may take
7801   // an additional register for the computation and we don't want that
7802   // either.
7803 
7804   // If the operand is a float, integer, or vector constant, spill to a
7805   // constant pool entry to get its address.
7806   const Value *OpVal = OpInfo.CallOperandVal;
7807   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7808       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7809     OpInfo.CallOperand = DAG.getConstantPool(
7810         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7811     return Chain;
7812   }
7813 
7814   // Otherwise, create a stack slot and emit a store to it before the asm.
7815   Type *Ty = OpVal->getType();
7816   auto &DL = DAG.getDataLayout();
7817   uint64_t TySize = DL.getTypeAllocSize(Ty);
7818   unsigned Align = DL.getPrefTypeAlignment(Ty);
7819   MachineFunction &MF = DAG.getMachineFunction();
7820   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7821   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7822   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7823                             MachinePointerInfo::getFixedStack(MF, SSFI),
7824                             TLI.getMemValueType(DL, Ty));
7825   OpInfo.CallOperand = StackSlot;
7826 
7827   return Chain;
7828 }
7829 
7830 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7831 /// specified operand.  We prefer to assign virtual registers, to allow the
7832 /// register allocator to handle the assignment process.  However, if the asm
7833 /// uses features that we can't model on machineinstrs, we have SDISel do the
7834 /// allocation.  This produces generally horrible, but correct, code.
7835 ///
7836 ///   OpInfo describes the operand
7837 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7838 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7839                                  SDISelAsmOperandInfo &OpInfo,
7840                                  SDISelAsmOperandInfo &RefOpInfo) {
7841   LLVMContext &Context = *DAG.getContext();
7842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7843 
7844   MachineFunction &MF = DAG.getMachineFunction();
7845   SmallVector<unsigned, 4> Regs;
7846   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7847 
7848   // No work to do for memory operations.
7849   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7850     return;
7851 
7852   // If this is a constraint for a single physreg, or a constraint for a
7853   // register class, find it.
7854   unsigned AssignedReg;
7855   const TargetRegisterClass *RC;
7856   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7857       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7858   // RC is unset only on failure. Return immediately.
7859   if (!RC)
7860     return;
7861 
7862   // Get the actual register value type.  This is important, because the user
7863   // may have asked for (e.g.) the AX register in i32 type.  We need to
7864   // remember that AX is actually i16 to get the right extension.
7865   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7866 
7867   if (OpInfo.ConstraintVT != MVT::Other) {
7868     // If this is an FP operand in an integer register (or visa versa), or more
7869     // generally if the operand value disagrees with the register class we plan
7870     // to stick it in, fix the operand type.
7871     //
7872     // If this is an input value, the bitcast to the new type is done now.
7873     // Bitcast for output value is done at the end of visitInlineAsm().
7874     if ((OpInfo.Type == InlineAsm::isOutput ||
7875          OpInfo.Type == InlineAsm::isInput) &&
7876         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7877       // Try to convert to the first EVT that the reg class contains.  If the
7878       // types are identical size, use a bitcast to convert (e.g. two differing
7879       // vector types).  Note: output bitcast is done at the end of
7880       // visitInlineAsm().
7881       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7882         // Exclude indirect inputs while they are unsupported because the code
7883         // to perform the load is missing and thus OpInfo.CallOperand still
7884         // refers to the input address rather than the pointed-to value.
7885         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7886           OpInfo.CallOperand =
7887               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7888         OpInfo.ConstraintVT = RegVT;
7889         // If the operand is an FP value and we want it in integer registers,
7890         // use the corresponding integer type. This turns an f64 value into
7891         // i64, which can be passed with two i32 values on a 32-bit machine.
7892       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7893         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7894         if (OpInfo.Type == InlineAsm::isInput)
7895           OpInfo.CallOperand =
7896               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7897         OpInfo.ConstraintVT = VT;
7898       }
7899     }
7900   }
7901 
7902   // No need to allocate a matching input constraint since the constraint it's
7903   // matching to has already been allocated.
7904   if (OpInfo.isMatchingInputConstraint())
7905     return;
7906 
7907   EVT ValueVT = OpInfo.ConstraintVT;
7908   if (OpInfo.ConstraintVT == MVT::Other)
7909     ValueVT = RegVT;
7910 
7911   // Initialize NumRegs.
7912   unsigned NumRegs = 1;
7913   if (OpInfo.ConstraintVT != MVT::Other)
7914     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7915 
7916   // If this is a constraint for a specific physical register, like {r17},
7917   // assign it now.
7918 
7919   // If this associated to a specific register, initialize iterator to correct
7920   // place. If virtual, make sure we have enough registers
7921 
7922   // Initialize iterator if necessary
7923   TargetRegisterClass::iterator I = RC->begin();
7924   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7925 
7926   // Do not check for single registers.
7927   if (AssignedReg) {
7928       for (; *I != AssignedReg; ++I)
7929         assert(I != RC->end() && "AssignedReg should be member of RC");
7930   }
7931 
7932   for (; NumRegs; --NumRegs, ++I) {
7933     assert(I != RC->end() && "Ran out of registers to allocate!");
7934     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7935     Regs.push_back(R);
7936   }
7937 
7938   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7939 }
7940 
7941 static unsigned
7942 findMatchingInlineAsmOperand(unsigned OperandNo,
7943                              const std::vector<SDValue> &AsmNodeOperands) {
7944   // Scan until we find the definition we already emitted of this operand.
7945   unsigned CurOp = InlineAsm::Op_FirstOperand;
7946   for (; OperandNo; --OperandNo) {
7947     // Advance to the next operand.
7948     unsigned OpFlag =
7949         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7950     assert((InlineAsm::isRegDefKind(OpFlag) ||
7951             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7952             InlineAsm::isMemKind(OpFlag)) &&
7953            "Skipped past definitions?");
7954     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7955   }
7956   return CurOp;
7957 }
7958 
7959 namespace {
7960 
7961 class ExtraFlags {
7962   unsigned Flags = 0;
7963 
7964 public:
7965   explicit ExtraFlags(ImmutableCallSite CS) {
7966     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7967     if (IA->hasSideEffects())
7968       Flags |= InlineAsm::Extra_HasSideEffects;
7969     if (IA->isAlignStack())
7970       Flags |= InlineAsm::Extra_IsAlignStack;
7971     if (CS.isConvergent())
7972       Flags |= InlineAsm::Extra_IsConvergent;
7973     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7974   }
7975 
7976   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7977     // Ideally, we would only check against memory constraints.  However, the
7978     // meaning of an Other constraint can be target-specific and we can't easily
7979     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7980     // for Other constraints as well.
7981     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7982         OpInfo.ConstraintType == TargetLowering::C_Other) {
7983       if (OpInfo.Type == InlineAsm::isInput)
7984         Flags |= InlineAsm::Extra_MayLoad;
7985       else if (OpInfo.Type == InlineAsm::isOutput)
7986         Flags |= InlineAsm::Extra_MayStore;
7987       else if (OpInfo.Type == InlineAsm::isClobber)
7988         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7989     }
7990   }
7991 
7992   unsigned get() const { return Flags; }
7993 };
7994 
7995 } // end anonymous namespace
7996 
7997 /// visitInlineAsm - Handle a call to an InlineAsm object.
7998 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7999   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8000 
8001   /// ConstraintOperands - Information about all of the constraints.
8002   SDISelAsmOperandInfoVector ConstraintOperands;
8003 
8004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8005   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8006       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8007 
8008   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8009   // AsmDialect, MayLoad, MayStore).
8010   bool HasSideEffect = IA->hasSideEffects();
8011   ExtraFlags ExtraInfo(CS);
8012 
8013   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8014   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8015   unsigned NumMatchingOps = 0;
8016   for (auto &T : TargetConstraints) {
8017     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8018     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8019 
8020     // Compute the value type for each operand.
8021     if (OpInfo.Type == InlineAsm::isInput ||
8022         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8023       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8024 
8025       // Process the call argument. BasicBlocks are labels, currently appearing
8026       // only in asm's.
8027       const Instruction *I = CS.getInstruction();
8028       if (isa<CallBrInst>(I) &&
8029           ArgNo - 1 >= (cast<CallBrInst>(I)->getNumArgOperands() -
8030                         cast<CallBrInst>(I)->getNumIndirectDests() -
8031                         NumMatchingOps) &&
8032           (NumMatchingOps == 0 ||
8033            ArgNo - 1 < (cast<CallBrInst>(I)->getNumArgOperands() -
8034                         NumMatchingOps))) {
8035         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8036         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8037         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8038       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8039         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8040       } else {
8041         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8042       }
8043 
8044       OpInfo.ConstraintVT =
8045           OpInfo
8046               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8047               .getSimpleVT();
8048     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8049       // The return value of the call is this value.  As such, there is no
8050       // corresponding argument.
8051       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8052       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8053         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8054             DAG.getDataLayout(), STy->getElementType(ResNo));
8055       } else {
8056         assert(ResNo == 0 && "Asm only has one result!");
8057         OpInfo.ConstraintVT =
8058             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8059       }
8060       ++ResNo;
8061     } else {
8062       OpInfo.ConstraintVT = MVT::Other;
8063     }
8064 
8065     if (OpInfo.hasMatchingInput())
8066       ++NumMatchingOps;
8067 
8068     if (!HasSideEffect)
8069       HasSideEffect = OpInfo.hasMemory(TLI);
8070 
8071     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8072     // FIXME: Could we compute this on OpInfo rather than T?
8073 
8074     // Compute the constraint code and ConstraintType to use.
8075     TLI.ComputeConstraintToUse(T, SDValue());
8076 
8077     if (T.ConstraintType == TargetLowering::C_Immediate &&
8078         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8079       // We've delayed emitting a diagnostic like the "n" constraint because
8080       // inlining could cause an integer showing up.
8081       return emitInlineAsmError(
8082           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8083                   "integer constant expression");
8084 
8085     ExtraInfo.update(T);
8086   }
8087 
8088 
8089   // We won't need to flush pending loads if this asm doesn't touch
8090   // memory and is nonvolatile.
8091   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8092 
8093   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8094   if (IsCallBr) {
8095     // If this is a callbr we need to flush pending exports since inlineasm_br
8096     // is a terminator. We need to do this before nodes are glued to
8097     // the inlineasm_br node.
8098     Chain = getControlRoot();
8099   }
8100 
8101   // Second pass over the constraints: compute which constraint option to use.
8102   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8103     // If this is an output operand with a matching input operand, look up the
8104     // matching input. If their types mismatch, e.g. one is an integer, the
8105     // other is floating point, or their sizes are different, flag it as an
8106     // error.
8107     if (OpInfo.hasMatchingInput()) {
8108       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8109       patchMatchingInput(OpInfo, Input, DAG);
8110     }
8111 
8112     // Compute the constraint code and ConstraintType to use.
8113     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8114 
8115     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8116         OpInfo.Type == InlineAsm::isClobber)
8117       continue;
8118 
8119     // If this is a memory input, and if the operand is not indirect, do what we
8120     // need to provide an address for the memory input.
8121     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8122         !OpInfo.isIndirect) {
8123       assert((OpInfo.isMultipleAlternative ||
8124               (OpInfo.Type == InlineAsm::isInput)) &&
8125              "Can only indirectify direct input operands!");
8126 
8127       // Memory operands really want the address of the value.
8128       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8129 
8130       // There is no longer a Value* corresponding to this operand.
8131       OpInfo.CallOperandVal = nullptr;
8132 
8133       // It is now an indirect operand.
8134       OpInfo.isIndirect = true;
8135     }
8136 
8137   }
8138 
8139   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8140   std::vector<SDValue> AsmNodeOperands;
8141   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8142   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8143       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8144 
8145   // If we have a !srcloc metadata node associated with it, we want to attach
8146   // this to the ultimately generated inline asm machineinstr.  To do this, we
8147   // pass in the third operand as this (potentially null) inline asm MDNode.
8148   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8149   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8150 
8151   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8152   // bits as operand 3.
8153   AsmNodeOperands.push_back(DAG.getTargetConstant(
8154       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8155 
8156   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8157   // this, assign virtual and physical registers for inputs and otput.
8158   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8159     // Assign Registers.
8160     SDISelAsmOperandInfo &RefOpInfo =
8161         OpInfo.isMatchingInputConstraint()
8162             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8163             : OpInfo;
8164     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8165 
8166     switch (OpInfo.Type) {
8167     case InlineAsm::isOutput:
8168       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8169         unsigned ConstraintID =
8170             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8171         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8172                "Failed to convert memory constraint code to constraint id.");
8173 
8174         // Add information to the INLINEASM node to know about this output.
8175         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8176         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8177         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8178                                                         MVT::i32));
8179         AsmNodeOperands.push_back(OpInfo.CallOperand);
8180       } else {
8181         // Otherwise, this outputs to a register (directly for C_Register /
8182         // C_RegisterClass, and a target-defined fashion for
8183         // C_Immediate/C_Other). Find a register that we can use.
8184         if (OpInfo.AssignedRegs.Regs.empty()) {
8185           emitInlineAsmError(
8186               CS, "couldn't allocate output register for constraint '" +
8187                       Twine(OpInfo.ConstraintCode) + "'");
8188           return;
8189         }
8190 
8191         // Add information to the INLINEASM node to know that this register is
8192         // set.
8193         OpInfo.AssignedRegs.AddInlineAsmOperands(
8194             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8195                                   : InlineAsm::Kind_RegDef,
8196             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8197       }
8198       break;
8199 
8200     case InlineAsm::isInput: {
8201       SDValue InOperandVal = OpInfo.CallOperand;
8202 
8203       if (OpInfo.isMatchingInputConstraint()) {
8204         // If this is required to match an output register we have already set,
8205         // just use its register.
8206         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8207                                                   AsmNodeOperands);
8208         unsigned OpFlag =
8209           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8210         if (InlineAsm::isRegDefKind(OpFlag) ||
8211             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8212           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8213           if (OpInfo.isIndirect) {
8214             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8215             emitInlineAsmError(CS, "inline asm not supported yet:"
8216                                    " don't know how to handle tied "
8217                                    "indirect register inputs");
8218             return;
8219           }
8220 
8221           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8222           SmallVector<unsigned, 4> Regs;
8223 
8224           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8225             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8226             MachineRegisterInfo &RegInfo =
8227                 DAG.getMachineFunction().getRegInfo();
8228             for (unsigned i = 0; i != NumRegs; ++i)
8229               Regs.push_back(RegInfo.createVirtualRegister(RC));
8230           } else {
8231             emitInlineAsmError(CS, "inline asm error: This value type register "
8232                                    "class is not natively supported!");
8233             return;
8234           }
8235 
8236           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8237 
8238           SDLoc dl = getCurSDLoc();
8239           // Use the produced MatchedRegs object to
8240           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8241                                     CS.getInstruction());
8242           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8243                                            true, OpInfo.getMatchedOperand(), dl,
8244                                            DAG, AsmNodeOperands);
8245           break;
8246         }
8247 
8248         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8249         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8250                "Unexpected number of operands");
8251         // Add information to the INLINEASM node to know about this input.
8252         // See InlineAsm.h isUseOperandTiedToDef.
8253         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8254         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8255                                                     OpInfo.getMatchedOperand());
8256         AsmNodeOperands.push_back(DAG.getTargetConstant(
8257             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8258         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8259         break;
8260       }
8261 
8262       // Treat indirect 'X' constraint as memory.
8263       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8264           OpInfo.isIndirect)
8265         OpInfo.ConstraintType = TargetLowering::C_Memory;
8266 
8267       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8268           OpInfo.ConstraintType == TargetLowering::C_Other) {
8269         std::vector<SDValue> Ops;
8270         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8271                                           Ops, DAG);
8272         if (Ops.empty()) {
8273           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8274             if (isa<ConstantSDNode>(InOperandVal)) {
8275               emitInlineAsmError(CS, "value out of range for constraint '" +
8276                                  Twine(OpInfo.ConstraintCode) + "'");
8277               return;
8278             }
8279 
8280           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8281                                      Twine(OpInfo.ConstraintCode) + "'");
8282           return;
8283         }
8284 
8285         // Add information to the INLINEASM node to know about this input.
8286         unsigned ResOpType =
8287           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8288         AsmNodeOperands.push_back(DAG.getTargetConstant(
8289             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8290         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8291         break;
8292       }
8293 
8294       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8295         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8296         assert(InOperandVal.getValueType() ==
8297                    TLI.getPointerTy(DAG.getDataLayout()) &&
8298                "Memory operands expect pointer values");
8299 
8300         unsigned ConstraintID =
8301             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8302         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8303                "Failed to convert memory constraint code to constraint id.");
8304 
8305         // Add information to the INLINEASM node to know about this input.
8306         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8307         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8308         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8309                                                         getCurSDLoc(),
8310                                                         MVT::i32));
8311         AsmNodeOperands.push_back(InOperandVal);
8312         break;
8313       }
8314 
8315       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8316               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8317              "Unknown constraint type!");
8318 
8319       // TODO: Support this.
8320       if (OpInfo.isIndirect) {
8321         emitInlineAsmError(
8322             CS, "Don't know how to handle indirect register inputs yet "
8323                 "for constraint '" +
8324                     Twine(OpInfo.ConstraintCode) + "'");
8325         return;
8326       }
8327 
8328       // Copy the input into the appropriate registers.
8329       if (OpInfo.AssignedRegs.Regs.empty()) {
8330         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8331                                    Twine(OpInfo.ConstraintCode) + "'");
8332         return;
8333       }
8334 
8335       SDLoc dl = getCurSDLoc();
8336 
8337       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8338                                         Chain, &Flag, CS.getInstruction());
8339 
8340       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8341                                                dl, DAG, AsmNodeOperands);
8342       break;
8343     }
8344     case InlineAsm::isClobber:
8345       // Add the clobbered value to the operand list, so that the register
8346       // allocator is aware that the physreg got clobbered.
8347       if (!OpInfo.AssignedRegs.Regs.empty())
8348         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8349                                                  false, 0, getCurSDLoc(), DAG,
8350                                                  AsmNodeOperands);
8351       break;
8352     }
8353   }
8354 
8355   // Finish up input operands.  Set the input chain and add the flag last.
8356   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8357   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8358 
8359   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8360   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8361                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8362   Flag = Chain.getValue(1);
8363 
8364   // Do additional work to generate outputs.
8365 
8366   SmallVector<EVT, 1> ResultVTs;
8367   SmallVector<SDValue, 1> ResultValues;
8368   SmallVector<SDValue, 8> OutChains;
8369 
8370   llvm::Type *CSResultType = CS.getType();
8371   ArrayRef<Type *> ResultTypes;
8372   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8373     ResultTypes = StructResult->elements();
8374   else if (!CSResultType->isVoidTy())
8375     ResultTypes = makeArrayRef(CSResultType);
8376 
8377   auto CurResultType = ResultTypes.begin();
8378   auto handleRegAssign = [&](SDValue V) {
8379     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8380     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8381     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8382     ++CurResultType;
8383     // If the type of the inline asm call site return value is different but has
8384     // same size as the type of the asm output bitcast it.  One example of this
8385     // is for vectors with different width / number of elements.  This can
8386     // happen for register classes that can contain multiple different value
8387     // types.  The preg or vreg allocated may not have the same VT as was
8388     // expected.
8389     //
8390     // This can also happen for a return value that disagrees with the register
8391     // class it is put in, eg. a double in a general-purpose register on a
8392     // 32-bit machine.
8393     if (ResultVT != V.getValueType() &&
8394         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8395       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8396     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8397              V.getValueType().isInteger()) {
8398       // If a result value was tied to an input value, the computed result
8399       // may have a wider width than the expected result.  Extract the
8400       // relevant portion.
8401       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8402     }
8403     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8404     ResultVTs.push_back(ResultVT);
8405     ResultValues.push_back(V);
8406   };
8407 
8408   // Deal with output operands.
8409   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8410     if (OpInfo.Type == InlineAsm::isOutput) {
8411       SDValue Val;
8412       // Skip trivial output operands.
8413       if (OpInfo.AssignedRegs.Regs.empty())
8414         continue;
8415 
8416       switch (OpInfo.ConstraintType) {
8417       case TargetLowering::C_Register:
8418       case TargetLowering::C_RegisterClass:
8419         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8420             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8421         break;
8422       case TargetLowering::C_Immediate:
8423       case TargetLowering::C_Other:
8424         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8425                                               OpInfo, DAG);
8426         break;
8427       case TargetLowering::C_Memory:
8428         break; // Already handled.
8429       case TargetLowering::C_Unknown:
8430         assert(false && "Unexpected unknown constraint");
8431       }
8432 
8433       // Indirect output manifest as stores. Record output chains.
8434       if (OpInfo.isIndirect) {
8435         const Value *Ptr = OpInfo.CallOperandVal;
8436         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8437         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8438                                      MachinePointerInfo(Ptr));
8439         OutChains.push_back(Store);
8440       } else {
8441         // generate CopyFromRegs to associated registers.
8442         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8443         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8444           for (const SDValue &V : Val->op_values())
8445             handleRegAssign(V);
8446         } else
8447           handleRegAssign(Val);
8448       }
8449     }
8450   }
8451 
8452   // Set results.
8453   if (!ResultValues.empty()) {
8454     assert(CurResultType == ResultTypes.end() &&
8455            "Mismatch in number of ResultTypes");
8456     assert(ResultValues.size() == ResultTypes.size() &&
8457            "Mismatch in number of output operands in asm result");
8458 
8459     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8460                             DAG.getVTList(ResultVTs), ResultValues);
8461     setValue(CS.getInstruction(), V);
8462   }
8463 
8464   // Collect store chains.
8465   if (!OutChains.empty())
8466     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8467 
8468   // Only Update Root if inline assembly has a memory effect.
8469   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8470     DAG.setRoot(Chain);
8471 }
8472 
8473 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8474                                              const Twine &Message) {
8475   LLVMContext &Ctx = *DAG.getContext();
8476   Ctx.emitError(CS.getInstruction(), Message);
8477 
8478   // Make sure we leave the DAG in a valid state
8479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8480   SmallVector<EVT, 1> ValueVTs;
8481   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8482 
8483   if (ValueVTs.empty())
8484     return;
8485 
8486   SmallVector<SDValue, 1> Ops;
8487   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8488     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8489 
8490   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8491 }
8492 
8493 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8494   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8495                           MVT::Other, getRoot(),
8496                           getValue(I.getArgOperand(0)),
8497                           DAG.getSrcValue(I.getArgOperand(0))));
8498 }
8499 
8500 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8502   const DataLayout &DL = DAG.getDataLayout();
8503   SDValue V = DAG.getVAArg(
8504       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8505       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8506       DL.getABITypeAlignment(I.getType()));
8507   DAG.setRoot(V.getValue(1));
8508 
8509   if (I.getType()->isPointerTy())
8510     V = DAG.getPtrExtOrTrunc(
8511         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8512   setValue(&I, V);
8513 }
8514 
8515 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8516   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8517                           MVT::Other, getRoot(),
8518                           getValue(I.getArgOperand(0)),
8519                           DAG.getSrcValue(I.getArgOperand(0))));
8520 }
8521 
8522 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8523   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8524                           MVT::Other, getRoot(),
8525                           getValue(I.getArgOperand(0)),
8526                           getValue(I.getArgOperand(1)),
8527                           DAG.getSrcValue(I.getArgOperand(0)),
8528                           DAG.getSrcValue(I.getArgOperand(1))));
8529 }
8530 
8531 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8532                                                     const Instruction &I,
8533                                                     SDValue Op) {
8534   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8535   if (!Range)
8536     return Op;
8537 
8538   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8539   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8540     return Op;
8541 
8542   APInt Lo = CR.getUnsignedMin();
8543   if (!Lo.isMinValue())
8544     return Op;
8545 
8546   APInt Hi = CR.getUnsignedMax();
8547   unsigned Bits = std::max(Hi.getActiveBits(),
8548                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8549 
8550   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8551 
8552   SDLoc SL = getCurSDLoc();
8553 
8554   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8555                              DAG.getValueType(SmallVT));
8556   unsigned NumVals = Op.getNode()->getNumValues();
8557   if (NumVals == 1)
8558     return ZExt;
8559 
8560   SmallVector<SDValue, 4> Ops;
8561 
8562   Ops.push_back(ZExt);
8563   for (unsigned I = 1; I != NumVals; ++I)
8564     Ops.push_back(Op.getValue(I));
8565 
8566   return DAG.getMergeValues(Ops, SL);
8567 }
8568 
8569 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8570 /// the call being lowered.
8571 ///
8572 /// This is a helper for lowering intrinsics that follow a target calling
8573 /// convention or require stack pointer adjustment. Only a subset of the
8574 /// intrinsic's operands need to participate in the calling convention.
8575 void SelectionDAGBuilder::populateCallLoweringInfo(
8576     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8577     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8578     bool IsPatchPoint) {
8579   TargetLowering::ArgListTy Args;
8580   Args.reserve(NumArgs);
8581 
8582   // Populate the argument list.
8583   // Attributes for args start at offset 1, after the return attribute.
8584   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8585        ArgI != ArgE; ++ArgI) {
8586     const Value *V = Call->getOperand(ArgI);
8587 
8588     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8589 
8590     TargetLowering::ArgListEntry Entry;
8591     Entry.Node = getValue(V);
8592     Entry.Ty = V->getType();
8593     Entry.setAttributes(Call, ArgI);
8594     Args.push_back(Entry);
8595   }
8596 
8597   CLI.setDebugLoc(getCurSDLoc())
8598       .setChain(getRoot())
8599       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8600       .setDiscardResult(Call->use_empty())
8601       .setIsPatchPoint(IsPatchPoint);
8602 }
8603 
8604 /// Add a stack map intrinsic call's live variable operands to a stackmap
8605 /// or patchpoint target node's operand list.
8606 ///
8607 /// Constants are converted to TargetConstants purely as an optimization to
8608 /// avoid constant materialization and register allocation.
8609 ///
8610 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8611 /// generate addess computation nodes, and so FinalizeISel can convert the
8612 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8613 /// address materialization and register allocation, but may also be required
8614 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8615 /// alloca in the entry block, then the runtime may assume that the alloca's
8616 /// StackMap location can be read immediately after compilation and that the
8617 /// location is valid at any point during execution (this is similar to the
8618 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8619 /// only available in a register, then the runtime would need to trap when
8620 /// execution reaches the StackMap in order to read the alloca's location.
8621 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8622                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8623                                 SelectionDAGBuilder &Builder) {
8624   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8625     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8626     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8627       Ops.push_back(
8628         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8629       Ops.push_back(
8630         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8631     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8632       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8633       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8634           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8635     } else
8636       Ops.push_back(OpVal);
8637   }
8638 }
8639 
8640 /// Lower llvm.experimental.stackmap directly to its target opcode.
8641 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8642   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8643   //                                  [live variables...])
8644 
8645   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8646 
8647   SDValue Chain, InFlag, Callee, NullPtr;
8648   SmallVector<SDValue, 32> Ops;
8649 
8650   SDLoc DL = getCurSDLoc();
8651   Callee = getValue(CI.getCalledValue());
8652   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8653 
8654   // The stackmap intrinsic only records the live variables (the arguments
8655   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8656   // intrinsic, this won't be lowered to a function call. This means we don't
8657   // have to worry about calling conventions and target specific lowering code.
8658   // Instead we perform the call lowering right here.
8659   //
8660   // chain, flag = CALLSEQ_START(chain, 0, 0)
8661   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8662   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8663   //
8664   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8665   InFlag = Chain.getValue(1);
8666 
8667   // Add the <id> and <numBytes> constants.
8668   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8669   Ops.push_back(DAG.getTargetConstant(
8670                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8671   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8672   Ops.push_back(DAG.getTargetConstant(
8673                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8674                   MVT::i32));
8675 
8676   // Push live variables for the stack map.
8677   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8678 
8679   // We are not pushing any register mask info here on the operands list,
8680   // because the stackmap doesn't clobber anything.
8681 
8682   // Push the chain and the glue flag.
8683   Ops.push_back(Chain);
8684   Ops.push_back(InFlag);
8685 
8686   // Create the STACKMAP node.
8687   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8688   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8689   Chain = SDValue(SM, 0);
8690   InFlag = Chain.getValue(1);
8691 
8692   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8693 
8694   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8695 
8696   // Set the root to the target-lowered call chain.
8697   DAG.setRoot(Chain);
8698 
8699   // Inform the Frame Information that we have a stackmap in this function.
8700   FuncInfo.MF->getFrameInfo().setHasStackMap();
8701 }
8702 
8703 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8704 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8705                                           const BasicBlock *EHPadBB) {
8706   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8707   //                                                 i32 <numBytes>,
8708   //                                                 i8* <target>,
8709   //                                                 i32 <numArgs>,
8710   //                                                 [Args...],
8711   //                                                 [live variables...])
8712 
8713   CallingConv::ID CC = CS.getCallingConv();
8714   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8715   bool HasDef = !CS->getType()->isVoidTy();
8716   SDLoc dl = getCurSDLoc();
8717   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8718 
8719   // Handle immediate and symbolic callees.
8720   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8721     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8722                                    /*isTarget=*/true);
8723   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8724     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8725                                          SDLoc(SymbolicCallee),
8726                                          SymbolicCallee->getValueType(0));
8727 
8728   // Get the real number of arguments participating in the call <numArgs>
8729   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8730   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8731 
8732   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8733   // Intrinsics include all meta-operands up to but not including CC.
8734   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8735   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8736          "Not enough arguments provided to the patchpoint intrinsic");
8737 
8738   // For AnyRegCC the arguments are lowered later on manually.
8739   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8740   Type *ReturnTy =
8741     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8742 
8743   TargetLowering::CallLoweringInfo CLI(DAG);
8744   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8745                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8746   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8747 
8748   SDNode *CallEnd = Result.second.getNode();
8749   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8750     CallEnd = CallEnd->getOperand(0).getNode();
8751 
8752   /// Get a call instruction from the call sequence chain.
8753   /// Tail calls are not allowed.
8754   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8755          "Expected a callseq node.");
8756   SDNode *Call = CallEnd->getOperand(0).getNode();
8757   bool HasGlue = Call->getGluedNode();
8758 
8759   // Replace the target specific call node with the patchable intrinsic.
8760   SmallVector<SDValue, 8> Ops;
8761 
8762   // Add the <id> and <numBytes> constants.
8763   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8764   Ops.push_back(DAG.getTargetConstant(
8765                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8766   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8767   Ops.push_back(DAG.getTargetConstant(
8768                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8769                   MVT::i32));
8770 
8771   // Add the callee.
8772   Ops.push_back(Callee);
8773 
8774   // Adjust <numArgs> to account for any arguments that have been passed on the
8775   // stack instead.
8776   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8777   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8778   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8779   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8780 
8781   // Add the calling convention
8782   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8783 
8784   // Add the arguments we omitted previously. The register allocator should
8785   // place these in any free register.
8786   if (IsAnyRegCC)
8787     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8788       Ops.push_back(getValue(CS.getArgument(i)));
8789 
8790   // Push the arguments from the call instruction up to the register mask.
8791   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8792   Ops.append(Call->op_begin() + 2, e);
8793 
8794   // Push live variables for the stack map.
8795   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8796 
8797   // Push the register mask info.
8798   if (HasGlue)
8799     Ops.push_back(*(Call->op_end()-2));
8800   else
8801     Ops.push_back(*(Call->op_end()-1));
8802 
8803   // Push the chain (this is originally the first operand of the call, but
8804   // becomes now the last or second to last operand).
8805   Ops.push_back(*(Call->op_begin()));
8806 
8807   // Push the glue flag (last operand).
8808   if (HasGlue)
8809     Ops.push_back(*(Call->op_end()-1));
8810 
8811   SDVTList NodeTys;
8812   if (IsAnyRegCC && HasDef) {
8813     // Create the return types based on the intrinsic definition
8814     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8815     SmallVector<EVT, 3> ValueVTs;
8816     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8817     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8818 
8819     // There is always a chain and a glue type at the end
8820     ValueVTs.push_back(MVT::Other);
8821     ValueVTs.push_back(MVT::Glue);
8822     NodeTys = DAG.getVTList(ValueVTs);
8823   } else
8824     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8825 
8826   // Replace the target specific call node with a PATCHPOINT node.
8827   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8828                                          dl, NodeTys, Ops);
8829 
8830   // Update the NodeMap.
8831   if (HasDef) {
8832     if (IsAnyRegCC)
8833       setValue(CS.getInstruction(), SDValue(MN, 0));
8834     else
8835       setValue(CS.getInstruction(), Result.first);
8836   }
8837 
8838   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8839   // call sequence. Furthermore the location of the chain and glue can change
8840   // when the AnyReg calling convention is used and the intrinsic returns a
8841   // value.
8842   if (IsAnyRegCC && HasDef) {
8843     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8844     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8845     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8846   } else
8847     DAG.ReplaceAllUsesWith(Call, MN);
8848   DAG.DeleteNode(Call);
8849 
8850   // Inform the Frame Information that we have a patchpoint in this function.
8851   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8852 }
8853 
8854 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8855                                             unsigned Intrinsic) {
8856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8857   SDValue Op1 = getValue(I.getArgOperand(0));
8858   SDValue Op2;
8859   if (I.getNumArgOperands() > 1)
8860     Op2 = getValue(I.getArgOperand(1));
8861   SDLoc dl = getCurSDLoc();
8862   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8863   SDValue Res;
8864   FastMathFlags FMF;
8865   if (isa<FPMathOperator>(I))
8866     FMF = I.getFastMathFlags();
8867 
8868   switch (Intrinsic) {
8869   case Intrinsic::experimental_vector_reduce_v2_fadd:
8870     if (FMF.allowReassoc())
8871       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8872                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8873     else
8874       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8875     break;
8876   case Intrinsic::experimental_vector_reduce_v2_fmul:
8877     if (FMF.allowReassoc())
8878       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8879                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8880     else
8881       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8882     break;
8883   case Intrinsic::experimental_vector_reduce_add:
8884     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8885     break;
8886   case Intrinsic::experimental_vector_reduce_mul:
8887     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8888     break;
8889   case Intrinsic::experimental_vector_reduce_and:
8890     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8891     break;
8892   case Intrinsic::experimental_vector_reduce_or:
8893     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8894     break;
8895   case Intrinsic::experimental_vector_reduce_xor:
8896     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8897     break;
8898   case Intrinsic::experimental_vector_reduce_smax:
8899     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8900     break;
8901   case Intrinsic::experimental_vector_reduce_smin:
8902     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8903     break;
8904   case Intrinsic::experimental_vector_reduce_umax:
8905     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8906     break;
8907   case Intrinsic::experimental_vector_reduce_umin:
8908     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8909     break;
8910   case Intrinsic::experimental_vector_reduce_fmax:
8911     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8912     break;
8913   case Intrinsic::experimental_vector_reduce_fmin:
8914     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8915     break;
8916   default:
8917     llvm_unreachable("Unhandled vector reduce intrinsic");
8918   }
8919   setValue(&I, Res);
8920 }
8921 
8922 /// Returns an AttributeList representing the attributes applied to the return
8923 /// value of the given call.
8924 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8925   SmallVector<Attribute::AttrKind, 2> Attrs;
8926   if (CLI.RetSExt)
8927     Attrs.push_back(Attribute::SExt);
8928   if (CLI.RetZExt)
8929     Attrs.push_back(Attribute::ZExt);
8930   if (CLI.IsInReg)
8931     Attrs.push_back(Attribute::InReg);
8932 
8933   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8934                             Attrs);
8935 }
8936 
8937 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8938 /// implementation, which just calls LowerCall.
8939 /// FIXME: When all targets are
8940 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8941 std::pair<SDValue, SDValue>
8942 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8943   // Handle the incoming return values from the call.
8944   CLI.Ins.clear();
8945   Type *OrigRetTy = CLI.RetTy;
8946   SmallVector<EVT, 4> RetTys;
8947   SmallVector<uint64_t, 4> Offsets;
8948   auto &DL = CLI.DAG.getDataLayout();
8949   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8950 
8951   if (CLI.IsPostTypeLegalization) {
8952     // If we are lowering a libcall after legalization, split the return type.
8953     SmallVector<EVT, 4> OldRetTys;
8954     SmallVector<uint64_t, 4> OldOffsets;
8955     RetTys.swap(OldRetTys);
8956     Offsets.swap(OldOffsets);
8957 
8958     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8959       EVT RetVT = OldRetTys[i];
8960       uint64_t Offset = OldOffsets[i];
8961       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8962       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8963       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8964       RetTys.append(NumRegs, RegisterVT);
8965       for (unsigned j = 0; j != NumRegs; ++j)
8966         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8967     }
8968   }
8969 
8970   SmallVector<ISD::OutputArg, 4> Outs;
8971   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8972 
8973   bool CanLowerReturn =
8974       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8975                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8976 
8977   SDValue DemoteStackSlot;
8978   int DemoteStackIdx = -100;
8979   if (!CanLowerReturn) {
8980     // FIXME: equivalent assert?
8981     // assert(!CS.hasInAllocaArgument() &&
8982     //        "sret demotion is incompatible with inalloca");
8983     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8984     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8985     MachineFunction &MF = CLI.DAG.getMachineFunction();
8986     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8987     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8988                                               DL.getAllocaAddrSpace());
8989 
8990     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8991     ArgListEntry Entry;
8992     Entry.Node = DemoteStackSlot;
8993     Entry.Ty = StackSlotPtrType;
8994     Entry.IsSExt = false;
8995     Entry.IsZExt = false;
8996     Entry.IsInReg = false;
8997     Entry.IsSRet = true;
8998     Entry.IsNest = false;
8999     Entry.IsByVal = false;
9000     Entry.IsReturned = false;
9001     Entry.IsSwiftSelf = false;
9002     Entry.IsSwiftError = false;
9003     Entry.IsCFGuardTarget = false;
9004     Entry.Alignment = Align;
9005     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9006     CLI.NumFixedArgs += 1;
9007     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9008 
9009     // sret demotion isn't compatible with tail-calls, since the sret argument
9010     // points into the callers stack frame.
9011     CLI.IsTailCall = false;
9012   } else {
9013     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9014         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9015     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9016       ISD::ArgFlagsTy Flags;
9017       if (NeedsRegBlock) {
9018         Flags.setInConsecutiveRegs();
9019         if (I == RetTys.size() - 1)
9020           Flags.setInConsecutiveRegsLast();
9021       }
9022       EVT VT = RetTys[I];
9023       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9024                                                      CLI.CallConv, VT);
9025       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9026                                                        CLI.CallConv, VT);
9027       for (unsigned i = 0; i != NumRegs; ++i) {
9028         ISD::InputArg MyFlags;
9029         MyFlags.Flags = Flags;
9030         MyFlags.VT = RegisterVT;
9031         MyFlags.ArgVT = VT;
9032         MyFlags.Used = CLI.IsReturnValueUsed;
9033         if (CLI.RetTy->isPointerTy()) {
9034           MyFlags.Flags.setPointer();
9035           MyFlags.Flags.setPointerAddrSpace(
9036               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9037         }
9038         if (CLI.RetSExt)
9039           MyFlags.Flags.setSExt();
9040         if (CLI.RetZExt)
9041           MyFlags.Flags.setZExt();
9042         if (CLI.IsInReg)
9043           MyFlags.Flags.setInReg();
9044         CLI.Ins.push_back(MyFlags);
9045       }
9046     }
9047   }
9048 
9049   // We push in swifterror return as the last element of CLI.Ins.
9050   ArgListTy &Args = CLI.getArgs();
9051   if (supportSwiftError()) {
9052     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9053       if (Args[i].IsSwiftError) {
9054         ISD::InputArg MyFlags;
9055         MyFlags.VT = getPointerTy(DL);
9056         MyFlags.ArgVT = EVT(getPointerTy(DL));
9057         MyFlags.Flags.setSwiftError();
9058         CLI.Ins.push_back(MyFlags);
9059       }
9060     }
9061   }
9062 
9063   // Handle all of the outgoing arguments.
9064   CLI.Outs.clear();
9065   CLI.OutVals.clear();
9066   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9067     SmallVector<EVT, 4> ValueVTs;
9068     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9069     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9070     Type *FinalType = Args[i].Ty;
9071     if (Args[i].IsByVal)
9072       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9073     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9074         FinalType, CLI.CallConv, CLI.IsVarArg);
9075     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9076          ++Value) {
9077       EVT VT = ValueVTs[Value];
9078       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9079       SDValue Op = SDValue(Args[i].Node.getNode(),
9080                            Args[i].Node.getResNo() + Value);
9081       ISD::ArgFlagsTy Flags;
9082 
9083       // Certain targets (such as MIPS), may have a different ABI alignment
9084       // for a type depending on the context. Give the target a chance to
9085       // specify the alignment it wants.
9086       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9087 
9088       if (Args[i].Ty->isPointerTy()) {
9089         Flags.setPointer();
9090         Flags.setPointerAddrSpace(
9091             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9092       }
9093       if (Args[i].IsZExt)
9094         Flags.setZExt();
9095       if (Args[i].IsSExt)
9096         Flags.setSExt();
9097       if (Args[i].IsInReg) {
9098         // If we are using vectorcall calling convention, a structure that is
9099         // passed InReg - is surely an HVA
9100         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9101             isa<StructType>(FinalType)) {
9102           // The first value of a structure is marked
9103           if (0 == Value)
9104             Flags.setHvaStart();
9105           Flags.setHva();
9106         }
9107         // Set InReg Flag
9108         Flags.setInReg();
9109       }
9110       if (Args[i].IsSRet)
9111         Flags.setSRet();
9112       if (Args[i].IsSwiftSelf)
9113         Flags.setSwiftSelf();
9114       if (Args[i].IsSwiftError)
9115         Flags.setSwiftError();
9116       if (Args[i].IsCFGuardTarget)
9117         Flags.setCFGuardTarget();
9118       if (Args[i].IsByVal)
9119         Flags.setByVal();
9120       if (Args[i].IsInAlloca) {
9121         Flags.setInAlloca();
9122         // Set the byval flag for CCAssignFn callbacks that don't know about
9123         // inalloca.  This way we can know how many bytes we should've allocated
9124         // and how many bytes a callee cleanup function will pop.  If we port
9125         // inalloca to more targets, we'll have to add custom inalloca handling
9126         // in the various CC lowering callbacks.
9127         Flags.setByVal();
9128       }
9129       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9130         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9131         Type *ElementTy = Ty->getElementType();
9132 
9133         unsigned FrameSize = DL.getTypeAllocSize(
9134             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9135         Flags.setByValSize(FrameSize);
9136 
9137         // info is not there but there are cases it cannot get right.
9138         unsigned FrameAlign;
9139         if (Args[i].Alignment)
9140           FrameAlign = Args[i].Alignment;
9141         else
9142           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9143         Flags.setByValAlign(Align(FrameAlign));
9144       }
9145       if (Args[i].IsNest)
9146         Flags.setNest();
9147       if (NeedsRegBlock)
9148         Flags.setInConsecutiveRegs();
9149       Flags.setOrigAlign(OriginalAlignment);
9150 
9151       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9152                                                  CLI.CallConv, VT);
9153       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9154                                                         CLI.CallConv, VT);
9155       SmallVector<SDValue, 4> Parts(NumParts);
9156       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9157 
9158       if (Args[i].IsSExt)
9159         ExtendKind = ISD::SIGN_EXTEND;
9160       else if (Args[i].IsZExt)
9161         ExtendKind = ISD::ZERO_EXTEND;
9162 
9163       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9164       // for now.
9165       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9166           CanLowerReturn) {
9167         assert((CLI.RetTy == Args[i].Ty ||
9168                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9169                  CLI.RetTy->getPointerAddressSpace() ==
9170                      Args[i].Ty->getPointerAddressSpace())) &&
9171                RetTys.size() == NumValues && "unexpected use of 'returned'");
9172         // Before passing 'returned' to the target lowering code, ensure that
9173         // either the register MVT and the actual EVT are the same size or that
9174         // the return value and argument are extended in the same way; in these
9175         // cases it's safe to pass the argument register value unchanged as the
9176         // return register value (although it's at the target's option whether
9177         // to do so)
9178         // TODO: allow code generation to take advantage of partially preserved
9179         // registers rather than clobbering the entire register when the
9180         // parameter extension method is not compatible with the return
9181         // extension method
9182         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9183             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9184              CLI.RetZExt == Args[i].IsZExt))
9185           Flags.setReturned();
9186       }
9187 
9188       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9189                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9190 
9191       for (unsigned j = 0; j != NumParts; ++j) {
9192         // if it isn't first piece, alignment must be 1
9193         // For scalable vectors the scalable part is currently handled
9194         // by individual targets, so we just use the known minimum size here.
9195         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9196                     i < CLI.NumFixedArgs, i,
9197                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9198         if (NumParts > 1 && j == 0)
9199           MyFlags.Flags.setSplit();
9200         else if (j != 0) {
9201           MyFlags.Flags.setOrigAlign(Align(1));
9202           if (j == NumParts - 1)
9203             MyFlags.Flags.setSplitEnd();
9204         }
9205 
9206         CLI.Outs.push_back(MyFlags);
9207         CLI.OutVals.push_back(Parts[j]);
9208       }
9209 
9210       if (NeedsRegBlock && Value == NumValues - 1)
9211         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9212     }
9213   }
9214 
9215   SmallVector<SDValue, 4> InVals;
9216   CLI.Chain = LowerCall(CLI, InVals);
9217 
9218   // Update CLI.InVals to use outside of this function.
9219   CLI.InVals = InVals;
9220 
9221   // Verify that the target's LowerCall behaved as expected.
9222   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9223          "LowerCall didn't return a valid chain!");
9224   assert((!CLI.IsTailCall || InVals.empty()) &&
9225          "LowerCall emitted a return value for a tail call!");
9226   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9227          "LowerCall didn't emit the correct number of values!");
9228 
9229   // For a tail call, the return value is merely live-out and there aren't
9230   // any nodes in the DAG representing it. Return a special value to
9231   // indicate that a tail call has been emitted and no more Instructions
9232   // should be processed in the current block.
9233   if (CLI.IsTailCall) {
9234     CLI.DAG.setRoot(CLI.Chain);
9235     return std::make_pair(SDValue(), SDValue());
9236   }
9237 
9238 #ifndef NDEBUG
9239   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9240     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9241     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9242            "LowerCall emitted a value with the wrong type!");
9243   }
9244 #endif
9245 
9246   SmallVector<SDValue, 4> ReturnValues;
9247   if (!CanLowerReturn) {
9248     // The instruction result is the result of loading from the
9249     // hidden sret parameter.
9250     SmallVector<EVT, 1> PVTs;
9251     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9252 
9253     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9254     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9255     EVT PtrVT = PVTs[0];
9256 
9257     unsigned NumValues = RetTys.size();
9258     ReturnValues.resize(NumValues);
9259     SmallVector<SDValue, 4> Chains(NumValues);
9260 
9261     // An aggregate return value cannot wrap around the address space, so
9262     // offsets to its parts don't wrap either.
9263     SDNodeFlags Flags;
9264     Flags.setNoUnsignedWrap(true);
9265 
9266     for (unsigned i = 0; i < NumValues; ++i) {
9267       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9268                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9269                                                         PtrVT), Flags);
9270       SDValue L = CLI.DAG.getLoad(
9271           RetTys[i], CLI.DL, CLI.Chain, Add,
9272           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9273                                             DemoteStackIdx, Offsets[i]),
9274           /* Alignment = */ 1);
9275       ReturnValues[i] = L;
9276       Chains[i] = L.getValue(1);
9277     }
9278 
9279     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9280   } else {
9281     // Collect the legal value parts into potentially illegal values
9282     // that correspond to the original function's return values.
9283     Optional<ISD::NodeType> AssertOp;
9284     if (CLI.RetSExt)
9285       AssertOp = ISD::AssertSext;
9286     else if (CLI.RetZExt)
9287       AssertOp = ISD::AssertZext;
9288     unsigned CurReg = 0;
9289     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9290       EVT VT = RetTys[I];
9291       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9292                                                      CLI.CallConv, VT);
9293       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9294                                                        CLI.CallConv, VT);
9295 
9296       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9297                                               NumRegs, RegisterVT, VT, nullptr,
9298                                               CLI.CallConv, AssertOp));
9299       CurReg += NumRegs;
9300     }
9301 
9302     // For a function returning void, there is no return value. We can't create
9303     // such a node, so we just return a null return value in that case. In
9304     // that case, nothing will actually look at the value.
9305     if (ReturnValues.empty())
9306       return std::make_pair(SDValue(), CLI.Chain);
9307   }
9308 
9309   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9310                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9311   return std::make_pair(Res, CLI.Chain);
9312 }
9313 
9314 void TargetLowering::LowerOperationWrapper(SDNode *N,
9315                                            SmallVectorImpl<SDValue> &Results,
9316                                            SelectionDAG &DAG) const {
9317   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9318     Results.push_back(Res);
9319 }
9320 
9321 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9322   llvm_unreachable("LowerOperation not implemented for this target!");
9323 }
9324 
9325 void
9326 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9327   SDValue Op = getNonRegisterValue(V);
9328   assert((Op.getOpcode() != ISD::CopyFromReg ||
9329           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9330          "Copy from a reg to the same reg!");
9331   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9332 
9333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9334   // If this is an InlineAsm we have to match the registers required, not the
9335   // notional registers required by the type.
9336 
9337   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9338                    None); // This is not an ABI copy.
9339   SDValue Chain = DAG.getEntryNode();
9340 
9341   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9342                               FuncInfo.PreferredExtendType.end())
9343                                  ? ISD::ANY_EXTEND
9344                                  : FuncInfo.PreferredExtendType[V];
9345   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9346   PendingExports.push_back(Chain);
9347 }
9348 
9349 #include "llvm/CodeGen/SelectionDAGISel.h"
9350 
9351 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9352 /// entry block, return true.  This includes arguments used by switches, since
9353 /// the switch may expand into multiple basic blocks.
9354 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9355   // With FastISel active, we may be splitting blocks, so force creation
9356   // of virtual registers for all non-dead arguments.
9357   if (FastISel)
9358     return A->use_empty();
9359 
9360   const BasicBlock &Entry = A->getParent()->front();
9361   for (const User *U : A->users())
9362     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9363       return false;  // Use not in entry block.
9364 
9365   return true;
9366 }
9367 
9368 using ArgCopyElisionMapTy =
9369     DenseMap<const Argument *,
9370              std::pair<const AllocaInst *, const StoreInst *>>;
9371 
9372 /// Scan the entry block of the function in FuncInfo for arguments that look
9373 /// like copies into a local alloca. Record any copied arguments in
9374 /// ArgCopyElisionCandidates.
9375 static void
9376 findArgumentCopyElisionCandidates(const DataLayout &DL,
9377                                   FunctionLoweringInfo *FuncInfo,
9378                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9379   // Record the state of every static alloca used in the entry block. Argument
9380   // allocas are all used in the entry block, so we need approximately as many
9381   // entries as we have arguments.
9382   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9383   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9384   unsigned NumArgs = FuncInfo->Fn->arg_size();
9385   StaticAllocas.reserve(NumArgs * 2);
9386 
9387   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9388     if (!V)
9389       return nullptr;
9390     V = V->stripPointerCasts();
9391     const auto *AI = dyn_cast<AllocaInst>(V);
9392     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9393       return nullptr;
9394     auto Iter = StaticAllocas.insert({AI, Unknown});
9395     return &Iter.first->second;
9396   };
9397 
9398   // Look for stores of arguments to static allocas. Look through bitcasts and
9399   // GEPs to handle type coercions, as long as the alloca is fully initialized
9400   // by the store. Any non-store use of an alloca escapes it and any subsequent
9401   // unanalyzed store might write it.
9402   // FIXME: Handle structs initialized with multiple stores.
9403   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9404     // Look for stores, and handle non-store uses conservatively.
9405     const auto *SI = dyn_cast<StoreInst>(&I);
9406     if (!SI) {
9407       // We will look through cast uses, so ignore them completely.
9408       if (I.isCast())
9409         continue;
9410       // Ignore debug info intrinsics, they don't escape or store to allocas.
9411       if (isa<DbgInfoIntrinsic>(I))
9412         continue;
9413       // This is an unknown instruction. Assume it escapes or writes to all
9414       // static alloca operands.
9415       for (const Use &U : I.operands()) {
9416         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9417           *Info = StaticAllocaInfo::Clobbered;
9418       }
9419       continue;
9420     }
9421 
9422     // If the stored value is a static alloca, mark it as escaped.
9423     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9424       *Info = StaticAllocaInfo::Clobbered;
9425 
9426     // Check if the destination is a static alloca.
9427     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9428     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9429     if (!Info)
9430       continue;
9431     const AllocaInst *AI = cast<AllocaInst>(Dst);
9432 
9433     // Skip allocas that have been initialized or clobbered.
9434     if (*Info != StaticAllocaInfo::Unknown)
9435       continue;
9436 
9437     // Check if the stored value is an argument, and that this store fully
9438     // initializes the alloca. Don't elide copies from the same argument twice.
9439     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9440     const auto *Arg = dyn_cast<Argument>(Val);
9441     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9442         Arg->getType()->isEmptyTy() ||
9443         DL.getTypeStoreSize(Arg->getType()) !=
9444             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9445         ArgCopyElisionCandidates.count(Arg)) {
9446       *Info = StaticAllocaInfo::Clobbered;
9447       continue;
9448     }
9449 
9450     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9451                       << '\n');
9452 
9453     // Mark this alloca and store for argument copy elision.
9454     *Info = StaticAllocaInfo::Elidable;
9455     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9456 
9457     // Stop scanning if we've seen all arguments. This will happen early in -O0
9458     // builds, which is useful, because -O0 builds have large entry blocks and
9459     // many allocas.
9460     if (ArgCopyElisionCandidates.size() == NumArgs)
9461       break;
9462   }
9463 }
9464 
9465 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9466 /// ArgVal is a load from a suitable fixed stack object.
9467 static void tryToElideArgumentCopy(
9468     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9469     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9470     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9471     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9472     SDValue ArgVal, bool &ArgHasUses) {
9473   // Check if this is a load from a fixed stack object.
9474   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9475   if (!LNode)
9476     return;
9477   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9478   if (!FINode)
9479     return;
9480 
9481   // Check that the fixed stack object is the right size and alignment.
9482   // Look at the alignment that the user wrote on the alloca instead of looking
9483   // at the stack object.
9484   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9485   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9486   const AllocaInst *AI = ArgCopyIter->second.first;
9487   int FixedIndex = FINode->getIndex();
9488   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9489   int OldIndex = AllocaIndex;
9490   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9491   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9492     LLVM_DEBUG(
9493         dbgs() << "  argument copy elision failed due to bad fixed stack "
9494                   "object size\n");
9495     return;
9496   }
9497   unsigned RequiredAlignment = AI->getAlignment();
9498   if (!RequiredAlignment) {
9499     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9500         AI->getAllocatedType());
9501   }
9502   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9503     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9504                          "greater than stack argument alignment ("
9505                       << RequiredAlignment << " vs "
9506                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9507     return;
9508   }
9509 
9510   // Perform the elision. Delete the old stack object and replace its only use
9511   // in the variable info map. Mark the stack object as mutable.
9512   LLVM_DEBUG({
9513     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9514            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9515            << '\n';
9516   });
9517   MFI.RemoveStackObject(OldIndex);
9518   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9519   AllocaIndex = FixedIndex;
9520   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9521   Chains.push_back(ArgVal.getValue(1));
9522 
9523   // Avoid emitting code for the store implementing the copy.
9524   const StoreInst *SI = ArgCopyIter->second.second;
9525   ElidedArgCopyInstrs.insert(SI);
9526 
9527   // Check for uses of the argument again so that we can avoid exporting ArgVal
9528   // if it is't used by anything other than the store.
9529   for (const Value *U : Arg.users()) {
9530     if (U != SI) {
9531       ArgHasUses = true;
9532       break;
9533     }
9534   }
9535 }
9536 
9537 void SelectionDAGISel::LowerArguments(const Function &F) {
9538   SelectionDAG &DAG = SDB->DAG;
9539   SDLoc dl = SDB->getCurSDLoc();
9540   const DataLayout &DL = DAG.getDataLayout();
9541   SmallVector<ISD::InputArg, 16> Ins;
9542 
9543   if (!FuncInfo->CanLowerReturn) {
9544     // Put in an sret pointer parameter before all the other parameters.
9545     SmallVector<EVT, 1> ValueVTs;
9546     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9547                     F.getReturnType()->getPointerTo(
9548                         DAG.getDataLayout().getAllocaAddrSpace()),
9549                     ValueVTs);
9550 
9551     // NOTE: Assuming that a pointer will never break down to more than one VT
9552     // or one register.
9553     ISD::ArgFlagsTy Flags;
9554     Flags.setSRet();
9555     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9556     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9557                          ISD::InputArg::NoArgIndex, 0);
9558     Ins.push_back(RetArg);
9559   }
9560 
9561   // Look for stores of arguments to static allocas. Mark such arguments with a
9562   // flag to ask the target to give us the memory location of that argument if
9563   // available.
9564   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9565   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9566                                     ArgCopyElisionCandidates);
9567 
9568   // Set up the incoming argument description vector.
9569   for (const Argument &Arg : F.args()) {
9570     unsigned ArgNo = Arg.getArgNo();
9571     SmallVector<EVT, 4> ValueVTs;
9572     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9573     bool isArgValueUsed = !Arg.use_empty();
9574     unsigned PartBase = 0;
9575     Type *FinalType = Arg.getType();
9576     if (Arg.hasAttribute(Attribute::ByVal))
9577       FinalType = Arg.getParamByValType();
9578     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9579         FinalType, F.getCallingConv(), F.isVarArg());
9580     for (unsigned Value = 0, NumValues = ValueVTs.size();
9581          Value != NumValues; ++Value) {
9582       EVT VT = ValueVTs[Value];
9583       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9584       ISD::ArgFlagsTy Flags;
9585 
9586       // Certain targets (such as MIPS), may have a different ABI alignment
9587       // for a type depending on the context. Give the target a chance to
9588       // specify the alignment it wants.
9589       const Align OriginalAlignment(
9590           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9591 
9592       if (Arg.getType()->isPointerTy()) {
9593         Flags.setPointer();
9594         Flags.setPointerAddrSpace(
9595             cast<PointerType>(Arg.getType())->getAddressSpace());
9596       }
9597       if (Arg.hasAttribute(Attribute::ZExt))
9598         Flags.setZExt();
9599       if (Arg.hasAttribute(Attribute::SExt))
9600         Flags.setSExt();
9601       if (Arg.hasAttribute(Attribute::InReg)) {
9602         // If we are using vectorcall calling convention, a structure that is
9603         // passed InReg - is surely an HVA
9604         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9605             isa<StructType>(Arg.getType())) {
9606           // The first value of a structure is marked
9607           if (0 == Value)
9608             Flags.setHvaStart();
9609           Flags.setHva();
9610         }
9611         // Set InReg Flag
9612         Flags.setInReg();
9613       }
9614       if (Arg.hasAttribute(Attribute::StructRet))
9615         Flags.setSRet();
9616       if (Arg.hasAttribute(Attribute::SwiftSelf))
9617         Flags.setSwiftSelf();
9618       if (Arg.hasAttribute(Attribute::SwiftError))
9619         Flags.setSwiftError();
9620       if (Arg.hasAttribute(Attribute::ByVal))
9621         Flags.setByVal();
9622       if (Arg.hasAttribute(Attribute::InAlloca)) {
9623         Flags.setInAlloca();
9624         // Set the byval flag for CCAssignFn callbacks that don't know about
9625         // inalloca.  This way we can know how many bytes we should've allocated
9626         // and how many bytes a callee cleanup function will pop.  If we port
9627         // inalloca to more targets, we'll have to add custom inalloca handling
9628         // in the various CC lowering callbacks.
9629         Flags.setByVal();
9630       }
9631       if (F.getCallingConv() == CallingConv::X86_INTR) {
9632         // IA Interrupt passes frame (1st parameter) by value in the stack.
9633         if (ArgNo == 0)
9634           Flags.setByVal();
9635       }
9636       if (Flags.isByVal() || Flags.isInAlloca()) {
9637         Type *ElementTy = Arg.getParamByValType();
9638 
9639         // For ByVal, size and alignment should be passed from FE.  BE will
9640         // guess if this info is not there but there are cases it cannot get
9641         // right.
9642         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9643         Flags.setByValSize(FrameSize);
9644 
9645         unsigned FrameAlign;
9646         if (Arg.getParamAlignment())
9647           FrameAlign = Arg.getParamAlignment();
9648         else
9649           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9650         Flags.setByValAlign(Align(FrameAlign));
9651       }
9652       if (Arg.hasAttribute(Attribute::Nest))
9653         Flags.setNest();
9654       if (NeedsRegBlock)
9655         Flags.setInConsecutiveRegs();
9656       Flags.setOrigAlign(OriginalAlignment);
9657       if (ArgCopyElisionCandidates.count(&Arg))
9658         Flags.setCopyElisionCandidate();
9659       if (Arg.hasAttribute(Attribute::Returned))
9660         Flags.setReturned();
9661 
9662       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9663           *CurDAG->getContext(), F.getCallingConv(), VT);
9664       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9665           *CurDAG->getContext(), F.getCallingConv(), VT);
9666       for (unsigned i = 0; i != NumRegs; ++i) {
9667         // For scalable vectors, use the minimum size; individual targets
9668         // are responsible for handling scalable vector arguments and
9669         // return values.
9670         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9671                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9672         if (NumRegs > 1 && i == 0)
9673           MyFlags.Flags.setSplit();
9674         // if it isn't first piece, alignment must be 1
9675         else if (i > 0) {
9676           MyFlags.Flags.setOrigAlign(Align(1));
9677           if (i == NumRegs - 1)
9678             MyFlags.Flags.setSplitEnd();
9679         }
9680         Ins.push_back(MyFlags);
9681       }
9682       if (NeedsRegBlock && Value == NumValues - 1)
9683         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9684       PartBase += VT.getStoreSize().getKnownMinSize();
9685     }
9686   }
9687 
9688   // Call the target to set up the argument values.
9689   SmallVector<SDValue, 8> InVals;
9690   SDValue NewRoot = TLI->LowerFormalArguments(
9691       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9692 
9693   // Verify that the target's LowerFormalArguments behaved as expected.
9694   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9695          "LowerFormalArguments didn't return a valid chain!");
9696   assert(InVals.size() == Ins.size() &&
9697          "LowerFormalArguments didn't emit the correct number of values!");
9698   LLVM_DEBUG({
9699     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9700       assert(InVals[i].getNode() &&
9701              "LowerFormalArguments emitted a null value!");
9702       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9703              "LowerFormalArguments emitted a value with the wrong type!");
9704     }
9705   });
9706 
9707   // Update the DAG with the new chain value resulting from argument lowering.
9708   DAG.setRoot(NewRoot);
9709 
9710   // Set up the argument values.
9711   unsigned i = 0;
9712   if (!FuncInfo->CanLowerReturn) {
9713     // Create a virtual register for the sret pointer, and put in a copy
9714     // from the sret argument into it.
9715     SmallVector<EVT, 1> ValueVTs;
9716     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9717                     F.getReturnType()->getPointerTo(
9718                         DAG.getDataLayout().getAllocaAddrSpace()),
9719                     ValueVTs);
9720     MVT VT = ValueVTs[0].getSimpleVT();
9721     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9722     Optional<ISD::NodeType> AssertOp = None;
9723     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9724                                         nullptr, F.getCallingConv(), AssertOp);
9725 
9726     MachineFunction& MF = SDB->DAG.getMachineFunction();
9727     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9728     Register SRetReg =
9729         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9730     FuncInfo->DemoteRegister = SRetReg;
9731     NewRoot =
9732         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9733     DAG.setRoot(NewRoot);
9734 
9735     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9736     ++i;
9737   }
9738 
9739   SmallVector<SDValue, 4> Chains;
9740   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9741   for (const Argument &Arg : F.args()) {
9742     SmallVector<SDValue, 4> ArgValues;
9743     SmallVector<EVT, 4> ValueVTs;
9744     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9745     unsigned NumValues = ValueVTs.size();
9746     if (NumValues == 0)
9747       continue;
9748 
9749     bool ArgHasUses = !Arg.use_empty();
9750 
9751     // Elide the copying store if the target loaded this argument from a
9752     // suitable fixed stack object.
9753     if (Ins[i].Flags.isCopyElisionCandidate()) {
9754       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9755                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9756                              InVals[i], ArgHasUses);
9757     }
9758 
9759     // If this argument is unused then remember its value. It is used to generate
9760     // debugging information.
9761     bool isSwiftErrorArg =
9762         TLI->supportSwiftError() &&
9763         Arg.hasAttribute(Attribute::SwiftError);
9764     if (!ArgHasUses && !isSwiftErrorArg) {
9765       SDB->setUnusedArgValue(&Arg, InVals[i]);
9766 
9767       // Also remember any frame index for use in FastISel.
9768       if (FrameIndexSDNode *FI =
9769           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9770         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9771     }
9772 
9773     for (unsigned Val = 0; Val != NumValues; ++Val) {
9774       EVT VT = ValueVTs[Val];
9775       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9776                                                       F.getCallingConv(), VT);
9777       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9778           *CurDAG->getContext(), F.getCallingConv(), VT);
9779 
9780       // Even an apparent 'unused' swifterror argument needs to be returned. So
9781       // we do generate a copy for it that can be used on return from the
9782       // function.
9783       if (ArgHasUses || isSwiftErrorArg) {
9784         Optional<ISD::NodeType> AssertOp;
9785         if (Arg.hasAttribute(Attribute::SExt))
9786           AssertOp = ISD::AssertSext;
9787         else if (Arg.hasAttribute(Attribute::ZExt))
9788           AssertOp = ISD::AssertZext;
9789 
9790         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9791                                              PartVT, VT, nullptr,
9792                                              F.getCallingConv(), AssertOp));
9793       }
9794 
9795       i += NumParts;
9796     }
9797 
9798     // We don't need to do anything else for unused arguments.
9799     if (ArgValues.empty())
9800       continue;
9801 
9802     // Note down frame index.
9803     if (FrameIndexSDNode *FI =
9804         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9805       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9806 
9807     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9808                                      SDB->getCurSDLoc());
9809 
9810     SDB->setValue(&Arg, Res);
9811     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9812       // We want to associate the argument with the frame index, among
9813       // involved operands, that correspond to the lowest address. The
9814       // getCopyFromParts function, called earlier, is swapping the order of
9815       // the operands to BUILD_PAIR depending on endianness. The result of
9816       // that swapping is that the least significant bits of the argument will
9817       // be in the first operand of the BUILD_PAIR node, and the most
9818       // significant bits will be in the second operand.
9819       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9820       if (LoadSDNode *LNode =
9821           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9822         if (FrameIndexSDNode *FI =
9823             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9824           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9825     }
9826 
9827     // Analyses past this point are naive and don't expect an assertion.
9828     if (Res.getOpcode() == ISD::AssertZext)
9829       Res = Res.getOperand(0);
9830 
9831     // Update the SwiftErrorVRegDefMap.
9832     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9833       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9834       if (Register::isVirtualRegister(Reg))
9835         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9836                                    Reg);
9837     }
9838 
9839     // If this argument is live outside of the entry block, insert a copy from
9840     // wherever we got it to the vreg that other BB's will reference it as.
9841     if (Res.getOpcode() == ISD::CopyFromReg) {
9842       // If we can, though, try to skip creating an unnecessary vreg.
9843       // FIXME: This isn't very clean... it would be nice to make this more
9844       // general.
9845       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9846       if (Register::isVirtualRegister(Reg)) {
9847         FuncInfo->ValueMap[&Arg] = Reg;
9848         continue;
9849       }
9850     }
9851     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9852       FuncInfo->InitializeRegForValue(&Arg);
9853       SDB->CopyToExportRegsIfNeeded(&Arg);
9854     }
9855   }
9856 
9857   if (!Chains.empty()) {
9858     Chains.push_back(NewRoot);
9859     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9860   }
9861 
9862   DAG.setRoot(NewRoot);
9863 
9864   assert(i == InVals.size() && "Argument register count mismatch!");
9865 
9866   // If any argument copy elisions occurred and we have debug info, update the
9867   // stale frame indices used in the dbg.declare variable info table.
9868   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9869   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9870     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9871       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9872       if (I != ArgCopyElisionFrameIndexMap.end())
9873         VI.Slot = I->second;
9874     }
9875   }
9876 
9877   // Finally, if the target has anything special to do, allow it to do so.
9878   emitFunctionEntryCode();
9879 }
9880 
9881 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9882 /// ensure constants are generated when needed.  Remember the virtual registers
9883 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9884 /// directly add them, because expansion might result in multiple MBB's for one
9885 /// BB.  As such, the start of the BB might correspond to a different MBB than
9886 /// the end.
9887 void
9888 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9889   const Instruction *TI = LLVMBB->getTerminator();
9890 
9891   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9892 
9893   // Check PHI nodes in successors that expect a value to be available from this
9894   // block.
9895   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9896     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9897     if (!isa<PHINode>(SuccBB->begin())) continue;
9898     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9899 
9900     // If this terminator has multiple identical successors (common for
9901     // switches), only handle each succ once.
9902     if (!SuccsHandled.insert(SuccMBB).second)
9903       continue;
9904 
9905     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9906 
9907     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9908     // nodes and Machine PHI nodes, but the incoming operands have not been
9909     // emitted yet.
9910     for (const PHINode &PN : SuccBB->phis()) {
9911       // Ignore dead phi's.
9912       if (PN.use_empty())
9913         continue;
9914 
9915       // Skip empty types
9916       if (PN.getType()->isEmptyTy())
9917         continue;
9918 
9919       unsigned Reg;
9920       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9921 
9922       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9923         unsigned &RegOut = ConstantsOut[C];
9924         if (RegOut == 0) {
9925           RegOut = FuncInfo.CreateRegs(C);
9926           CopyValueToVirtualRegister(C, RegOut);
9927         }
9928         Reg = RegOut;
9929       } else {
9930         DenseMap<const Value *, unsigned>::iterator I =
9931           FuncInfo.ValueMap.find(PHIOp);
9932         if (I != FuncInfo.ValueMap.end())
9933           Reg = I->second;
9934         else {
9935           assert(isa<AllocaInst>(PHIOp) &&
9936                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9937                  "Didn't codegen value into a register!??");
9938           Reg = FuncInfo.CreateRegs(PHIOp);
9939           CopyValueToVirtualRegister(PHIOp, Reg);
9940         }
9941       }
9942 
9943       // Remember that this register needs to added to the machine PHI node as
9944       // the input for this MBB.
9945       SmallVector<EVT, 4> ValueVTs;
9946       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9947       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9948       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9949         EVT VT = ValueVTs[vti];
9950         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9951         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9952           FuncInfo.PHINodesToUpdate.push_back(
9953               std::make_pair(&*MBBI++, Reg + i));
9954         Reg += NumRegisters;
9955       }
9956     }
9957   }
9958 
9959   ConstantsOut.clear();
9960 }
9961 
9962 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9963 /// is 0.
9964 MachineBasicBlock *
9965 SelectionDAGBuilder::StackProtectorDescriptor::
9966 AddSuccessorMBB(const BasicBlock *BB,
9967                 MachineBasicBlock *ParentMBB,
9968                 bool IsLikely,
9969                 MachineBasicBlock *SuccMBB) {
9970   // If SuccBB has not been created yet, create it.
9971   if (!SuccMBB) {
9972     MachineFunction *MF = ParentMBB->getParent();
9973     MachineFunction::iterator BBI(ParentMBB);
9974     SuccMBB = MF->CreateMachineBasicBlock(BB);
9975     MF->insert(++BBI, SuccMBB);
9976   }
9977   // Add it as a successor of ParentMBB.
9978   ParentMBB->addSuccessor(
9979       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9980   return SuccMBB;
9981 }
9982 
9983 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9984   MachineFunction::iterator I(MBB);
9985   if (++I == FuncInfo.MF->end())
9986     return nullptr;
9987   return &*I;
9988 }
9989 
9990 /// During lowering new call nodes can be created (such as memset, etc.).
9991 /// Those will become new roots of the current DAG, but complications arise
9992 /// when they are tail calls. In such cases, the call lowering will update
9993 /// the root, but the builder still needs to know that a tail call has been
9994 /// lowered in order to avoid generating an additional return.
9995 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9996   // If the node is null, we do have a tail call.
9997   if (MaybeTC.getNode() != nullptr)
9998     DAG.setRoot(MaybeTC);
9999   else
10000     HasTailCall = true;
10001 }
10002 
10003 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10004                                         MachineBasicBlock *SwitchMBB,
10005                                         MachineBasicBlock *DefaultMBB) {
10006   MachineFunction *CurMF = FuncInfo.MF;
10007   MachineBasicBlock *NextMBB = nullptr;
10008   MachineFunction::iterator BBI(W.MBB);
10009   if (++BBI != FuncInfo.MF->end())
10010     NextMBB = &*BBI;
10011 
10012   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10013 
10014   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10015 
10016   if (Size == 2 && W.MBB == SwitchMBB) {
10017     // If any two of the cases has the same destination, and if one value
10018     // is the same as the other, but has one bit unset that the other has set,
10019     // use bit manipulation to do two compares at once.  For example:
10020     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10021     // TODO: This could be extended to merge any 2 cases in switches with 3
10022     // cases.
10023     // TODO: Handle cases where W.CaseBB != SwitchBB.
10024     CaseCluster &Small = *W.FirstCluster;
10025     CaseCluster &Big = *W.LastCluster;
10026 
10027     if (Small.Low == Small.High && Big.Low == Big.High &&
10028         Small.MBB == Big.MBB) {
10029       const APInt &SmallValue = Small.Low->getValue();
10030       const APInt &BigValue = Big.Low->getValue();
10031 
10032       // Check that there is only one bit different.
10033       APInt CommonBit = BigValue ^ SmallValue;
10034       if (CommonBit.isPowerOf2()) {
10035         SDValue CondLHS = getValue(Cond);
10036         EVT VT = CondLHS.getValueType();
10037         SDLoc DL = getCurSDLoc();
10038 
10039         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10040                                  DAG.getConstant(CommonBit, DL, VT));
10041         SDValue Cond = DAG.getSetCC(
10042             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10043             ISD::SETEQ);
10044 
10045         // Update successor info.
10046         // Both Small and Big will jump to Small.BB, so we sum up the
10047         // probabilities.
10048         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10049         if (BPI)
10050           addSuccessorWithProb(
10051               SwitchMBB, DefaultMBB,
10052               // The default destination is the first successor in IR.
10053               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10054         else
10055           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10056 
10057         // Insert the true branch.
10058         SDValue BrCond =
10059             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10060                         DAG.getBasicBlock(Small.MBB));
10061         // Insert the false branch.
10062         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10063                              DAG.getBasicBlock(DefaultMBB));
10064 
10065         DAG.setRoot(BrCond);
10066         return;
10067       }
10068     }
10069   }
10070 
10071   if (TM.getOptLevel() != CodeGenOpt::None) {
10072     // Here, we order cases by probability so the most likely case will be
10073     // checked first. However, two clusters can have the same probability in
10074     // which case their relative ordering is non-deterministic. So we use Low
10075     // as a tie-breaker as clusters are guaranteed to never overlap.
10076     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10077                [](const CaseCluster &a, const CaseCluster &b) {
10078       return a.Prob != b.Prob ?
10079              a.Prob > b.Prob :
10080              a.Low->getValue().slt(b.Low->getValue());
10081     });
10082 
10083     // Rearrange the case blocks so that the last one falls through if possible
10084     // without changing the order of probabilities.
10085     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10086       --I;
10087       if (I->Prob > W.LastCluster->Prob)
10088         break;
10089       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10090         std::swap(*I, *W.LastCluster);
10091         break;
10092       }
10093     }
10094   }
10095 
10096   // Compute total probability.
10097   BranchProbability DefaultProb = W.DefaultProb;
10098   BranchProbability UnhandledProbs = DefaultProb;
10099   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10100     UnhandledProbs += I->Prob;
10101 
10102   MachineBasicBlock *CurMBB = W.MBB;
10103   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10104     bool FallthroughUnreachable = false;
10105     MachineBasicBlock *Fallthrough;
10106     if (I == W.LastCluster) {
10107       // For the last cluster, fall through to the default destination.
10108       Fallthrough = DefaultMBB;
10109       FallthroughUnreachable = isa<UnreachableInst>(
10110           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10111     } else {
10112       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10113       CurMF->insert(BBI, Fallthrough);
10114       // Put Cond in a virtual register to make it available from the new blocks.
10115       ExportFromCurrentBlock(Cond);
10116     }
10117     UnhandledProbs -= I->Prob;
10118 
10119     switch (I->Kind) {
10120       case CC_JumpTable: {
10121         // FIXME: Optimize away range check based on pivot comparisons.
10122         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10123         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10124 
10125         // The jump block hasn't been inserted yet; insert it here.
10126         MachineBasicBlock *JumpMBB = JT->MBB;
10127         CurMF->insert(BBI, JumpMBB);
10128 
10129         auto JumpProb = I->Prob;
10130         auto FallthroughProb = UnhandledProbs;
10131 
10132         // If the default statement is a target of the jump table, we evenly
10133         // distribute the default probability to successors of CurMBB. Also
10134         // update the probability on the edge from JumpMBB to Fallthrough.
10135         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10136                                               SE = JumpMBB->succ_end();
10137              SI != SE; ++SI) {
10138           if (*SI == DefaultMBB) {
10139             JumpProb += DefaultProb / 2;
10140             FallthroughProb -= DefaultProb / 2;
10141             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10142             JumpMBB->normalizeSuccProbs();
10143             break;
10144           }
10145         }
10146 
10147         if (FallthroughUnreachable) {
10148           // Skip the range check if the fallthrough block is unreachable.
10149           JTH->OmitRangeCheck = true;
10150         }
10151 
10152         if (!JTH->OmitRangeCheck)
10153           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10154         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10155         CurMBB->normalizeSuccProbs();
10156 
10157         // The jump table header will be inserted in our current block, do the
10158         // range check, and fall through to our fallthrough block.
10159         JTH->HeaderBB = CurMBB;
10160         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10161 
10162         // If we're in the right place, emit the jump table header right now.
10163         if (CurMBB == SwitchMBB) {
10164           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10165           JTH->Emitted = true;
10166         }
10167         break;
10168       }
10169       case CC_BitTests: {
10170         // FIXME: Optimize away range check based on pivot comparisons.
10171         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10172 
10173         // The bit test blocks haven't been inserted yet; insert them here.
10174         for (BitTestCase &BTC : BTB->Cases)
10175           CurMF->insert(BBI, BTC.ThisBB);
10176 
10177         // Fill in fields of the BitTestBlock.
10178         BTB->Parent = CurMBB;
10179         BTB->Default = Fallthrough;
10180 
10181         BTB->DefaultProb = UnhandledProbs;
10182         // If the cases in bit test don't form a contiguous range, we evenly
10183         // distribute the probability on the edge to Fallthrough to two
10184         // successors of CurMBB.
10185         if (!BTB->ContiguousRange) {
10186           BTB->Prob += DefaultProb / 2;
10187           BTB->DefaultProb -= DefaultProb / 2;
10188         }
10189 
10190         if (FallthroughUnreachable) {
10191           // Skip the range check if the fallthrough block is unreachable.
10192           BTB->OmitRangeCheck = true;
10193         }
10194 
10195         // If we're in the right place, emit the bit test header right now.
10196         if (CurMBB == SwitchMBB) {
10197           visitBitTestHeader(*BTB, SwitchMBB);
10198           BTB->Emitted = true;
10199         }
10200         break;
10201       }
10202       case CC_Range: {
10203         const Value *RHS, *LHS, *MHS;
10204         ISD::CondCode CC;
10205         if (I->Low == I->High) {
10206           // Check Cond == I->Low.
10207           CC = ISD::SETEQ;
10208           LHS = Cond;
10209           RHS=I->Low;
10210           MHS = nullptr;
10211         } else {
10212           // Check I->Low <= Cond <= I->High.
10213           CC = ISD::SETLE;
10214           LHS = I->Low;
10215           MHS = Cond;
10216           RHS = I->High;
10217         }
10218 
10219         // If Fallthrough is unreachable, fold away the comparison.
10220         if (FallthroughUnreachable)
10221           CC = ISD::SETTRUE;
10222 
10223         // The false probability is the sum of all unhandled cases.
10224         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10225                      getCurSDLoc(), I->Prob, UnhandledProbs);
10226 
10227         if (CurMBB == SwitchMBB)
10228           visitSwitchCase(CB, SwitchMBB);
10229         else
10230           SL->SwitchCases.push_back(CB);
10231 
10232         break;
10233       }
10234     }
10235     CurMBB = Fallthrough;
10236   }
10237 }
10238 
10239 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10240                                               CaseClusterIt First,
10241                                               CaseClusterIt Last) {
10242   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10243     if (X.Prob != CC.Prob)
10244       return X.Prob > CC.Prob;
10245 
10246     // Ties are broken by comparing the case value.
10247     return X.Low->getValue().slt(CC.Low->getValue());
10248   });
10249 }
10250 
10251 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10252                                         const SwitchWorkListItem &W,
10253                                         Value *Cond,
10254                                         MachineBasicBlock *SwitchMBB) {
10255   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10256          "Clusters not sorted?");
10257 
10258   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10259 
10260   // Balance the tree based on branch probabilities to create a near-optimal (in
10261   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10262   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10263   CaseClusterIt LastLeft = W.FirstCluster;
10264   CaseClusterIt FirstRight = W.LastCluster;
10265   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10266   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10267 
10268   // Move LastLeft and FirstRight towards each other from opposite directions to
10269   // find a partitioning of the clusters which balances the probability on both
10270   // sides. If LeftProb and RightProb are equal, alternate which side is
10271   // taken to ensure 0-probability nodes are distributed evenly.
10272   unsigned I = 0;
10273   while (LastLeft + 1 < FirstRight) {
10274     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10275       LeftProb += (++LastLeft)->Prob;
10276     else
10277       RightProb += (--FirstRight)->Prob;
10278     I++;
10279   }
10280 
10281   while (true) {
10282     // Our binary search tree differs from a typical BST in that ours can have up
10283     // to three values in each leaf. The pivot selection above doesn't take that
10284     // into account, which means the tree might require more nodes and be less
10285     // efficient. We compensate for this here.
10286 
10287     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10288     unsigned NumRight = W.LastCluster - FirstRight + 1;
10289 
10290     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10291       // If one side has less than 3 clusters, and the other has more than 3,
10292       // consider taking a cluster from the other side.
10293 
10294       if (NumLeft < NumRight) {
10295         // Consider moving the first cluster on the right to the left side.
10296         CaseCluster &CC = *FirstRight;
10297         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10298         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10299         if (LeftSideRank <= RightSideRank) {
10300           // Moving the cluster to the left does not demote it.
10301           ++LastLeft;
10302           ++FirstRight;
10303           continue;
10304         }
10305       } else {
10306         assert(NumRight < NumLeft);
10307         // Consider moving the last element on the left to the right side.
10308         CaseCluster &CC = *LastLeft;
10309         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10310         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10311         if (RightSideRank <= LeftSideRank) {
10312           // Moving the cluster to the right does not demot it.
10313           --LastLeft;
10314           --FirstRight;
10315           continue;
10316         }
10317       }
10318     }
10319     break;
10320   }
10321 
10322   assert(LastLeft + 1 == FirstRight);
10323   assert(LastLeft >= W.FirstCluster);
10324   assert(FirstRight <= W.LastCluster);
10325 
10326   // Use the first element on the right as pivot since we will make less-than
10327   // comparisons against it.
10328   CaseClusterIt PivotCluster = FirstRight;
10329   assert(PivotCluster > W.FirstCluster);
10330   assert(PivotCluster <= W.LastCluster);
10331 
10332   CaseClusterIt FirstLeft = W.FirstCluster;
10333   CaseClusterIt LastRight = W.LastCluster;
10334 
10335   const ConstantInt *Pivot = PivotCluster->Low;
10336 
10337   // New blocks will be inserted immediately after the current one.
10338   MachineFunction::iterator BBI(W.MBB);
10339   ++BBI;
10340 
10341   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10342   // we can branch to its destination directly if it's squeezed exactly in
10343   // between the known lower bound and Pivot - 1.
10344   MachineBasicBlock *LeftMBB;
10345   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10346       FirstLeft->Low == W.GE &&
10347       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10348     LeftMBB = FirstLeft->MBB;
10349   } else {
10350     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10351     FuncInfo.MF->insert(BBI, LeftMBB);
10352     WorkList.push_back(
10353         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10354     // Put Cond in a virtual register to make it available from the new blocks.
10355     ExportFromCurrentBlock(Cond);
10356   }
10357 
10358   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10359   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10360   // directly if RHS.High equals the current upper bound.
10361   MachineBasicBlock *RightMBB;
10362   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10363       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10364     RightMBB = FirstRight->MBB;
10365   } else {
10366     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10367     FuncInfo.MF->insert(BBI, RightMBB);
10368     WorkList.push_back(
10369         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10370     // Put Cond in a virtual register to make it available from the new blocks.
10371     ExportFromCurrentBlock(Cond);
10372   }
10373 
10374   // Create the CaseBlock record that will be used to lower the branch.
10375   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10376                getCurSDLoc(), LeftProb, RightProb);
10377 
10378   if (W.MBB == SwitchMBB)
10379     visitSwitchCase(CB, SwitchMBB);
10380   else
10381     SL->SwitchCases.push_back(CB);
10382 }
10383 
10384 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10385 // from the swith statement.
10386 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10387                                             BranchProbability PeeledCaseProb) {
10388   if (PeeledCaseProb == BranchProbability::getOne())
10389     return BranchProbability::getZero();
10390   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10391 
10392   uint32_t Numerator = CaseProb.getNumerator();
10393   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10394   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10395 }
10396 
10397 // Try to peel the top probability case if it exceeds the threshold.
10398 // Return current MachineBasicBlock for the switch statement if the peeling
10399 // does not occur.
10400 // If the peeling is performed, return the newly created MachineBasicBlock
10401 // for the peeled switch statement. Also update Clusters to remove the peeled
10402 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10403 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10404     const SwitchInst &SI, CaseClusterVector &Clusters,
10405     BranchProbability &PeeledCaseProb) {
10406   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10407   // Don't perform if there is only one cluster or optimizing for size.
10408   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10409       TM.getOptLevel() == CodeGenOpt::None ||
10410       SwitchMBB->getParent()->getFunction().hasMinSize())
10411     return SwitchMBB;
10412 
10413   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10414   unsigned PeeledCaseIndex = 0;
10415   bool SwitchPeeled = false;
10416   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10417     CaseCluster &CC = Clusters[Index];
10418     if (CC.Prob < TopCaseProb)
10419       continue;
10420     TopCaseProb = CC.Prob;
10421     PeeledCaseIndex = Index;
10422     SwitchPeeled = true;
10423   }
10424   if (!SwitchPeeled)
10425     return SwitchMBB;
10426 
10427   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10428                     << TopCaseProb << "\n");
10429 
10430   // Record the MBB for the peeled switch statement.
10431   MachineFunction::iterator BBI(SwitchMBB);
10432   ++BBI;
10433   MachineBasicBlock *PeeledSwitchMBB =
10434       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10435   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10436 
10437   ExportFromCurrentBlock(SI.getCondition());
10438   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10439   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10440                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10441   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10442 
10443   Clusters.erase(PeeledCaseIt);
10444   for (CaseCluster &CC : Clusters) {
10445     LLVM_DEBUG(
10446         dbgs() << "Scale the probablity for one cluster, before scaling: "
10447                << CC.Prob << "\n");
10448     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10449     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10450   }
10451   PeeledCaseProb = TopCaseProb;
10452   return PeeledSwitchMBB;
10453 }
10454 
10455 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10456   // Extract cases from the switch.
10457   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10458   CaseClusterVector Clusters;
10459   Clusters.reserve(SI.getNumCases());
10460   for (auto I : SI.cases()) {
10461     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10462     const ConstantInt *CaseVal = I.getCaseValue();
10463     BranchProbability Prob =
10464         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10465             : BranchProbability(1, SI.getNumCases() + 1);
10466     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10467   }
10468 
10469   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10470 
10471   // Cluster adjacent cases with the same destination. We do this at all
10472   // optimization levels because it's cheap to do and will make codegen faster
10473   // if there are many clusters.
10474   sortAndRangeify(Clusters);
10475 
10476   // The branch probablity of the peeled case.
10477   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10478   MachineBasicBlock *PeeledSwitchMBB =
10479       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10480 
10481   // If there is only the default destination, jump there directly.
10482   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10483   if (Clusters.empty()) {
10484     assert(PeeledSwitchMBB == SwitchMBB);
10485     SwitchMBB->addSuccessor(DefaultMBB);
10486     if (DefaultMBB != NextBlock(SwitchMBB)) {
10487       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10488                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10489     }
10490     return;
10491   }
10492 
10493   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10494   SL->findBitTestClusters(Clusters, &SI);
10495 
10496   LLVM_DEBUG({
10497     dbgs() << "Case clusters: ";
10498     for (const CaseCluster &C : Clusters) {
10499       if (C.Kind == CC_JumpTable)
10500         dbgs() << "JT:";
10501       if (C.Kind == CC_BitTests)
10502         dbgs() << "BT:";
10503 
10504       C.Low->getValue().print(dbgs(), true);
10505       if (C.Low != C.High) {
10506         dbgs() << '-';
10507         C.High->getValue().print(dbgs(), true);
10508       }
10509       dbgs() << ' ';
10510     }
10511     dbgs() << '\n';
10512   });
10513 
10514   assert(!Clusters.empty());
10515   SwitchWorkList WorkList;
10516   CaseClusterIt First = Clusters.begin();
10517   CaseClusterIt Last = Clusters.end() - 1;
10518   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10519   // Scale the branchprobability for DefaultMBB if the peel occurs and
10520   // DefaultMBB is not replaced.
10521   if (PeeledCaseProb != BranchProbability::getZero() &&
10522       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10523     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10524   WorkList.push_back(
10525       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10526 
10527   while (!WorkList.empty()) {
10528     SwitchWorkListItem W = WorkList.back();
10529     WorkList.pop_back();
10530     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10531 
10532     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10533         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10534       // For optimized builds, lower large range as a balanced binary tree.
10535       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10536       continue;
10537     }
10538 
10539     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10540   }
10541 }
10542 
10543 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10544   SDNodeFlags Flags;
10545 
10546   SDValue Op = getValue(I.getOperand(0));
10547   if (I.getOperand(0)->getType()->isAggregateType()) {
10548     EVT VT = Op.getValueType();
10549     SmallVector<SDValue, 1> Values;
10550     for (unsigned i = 0; i < Op.getNumOperands(); ++i) {
10551       SDValue Arg(Op.getNode(), i);
10552       SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), VT, Arg, Flags);
10553       Values.push_back(UnNodeValue);
10554     }
10555     SDValue MergedValue = DAG.getMergeValues(Values, getCurSDLoc());
10556     setValue(&I, MergedValue);
10557   } else {
10558     SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), Op.getValueType(),
10559                                       Op, Flags);
10560     setValue(&I, UnNodeValue);
10561   }
10562 }
10563