xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 8a88755610d0f7ae630b5e6124cc0579cb1c32c8)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallingConv.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DebugInfoMetadata.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GetElementPtrTypeIterator.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/IntrinsicsAArch64.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/Metadata.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/Operator.h"
94 #include "llvm/IR/PatternMatch.h"
95 #include "llvm/IR/Statepoint.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/MC/MCContext.h"
100 #include "llvm/MC/MCSymbol.h"
101 #include "llvm/Support/AtomicOrdering.h"
102 #include "llvm/Support/BranchProbability.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CodeGen.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/MachineValueType.h"
110 #include "llvm/Support/MathExtras.h"
111 #include "llvm/Support/raw_ostream.h"
112 #include "llvm/Target/TargetIntrinsicInfo.h"
113 #include "llvm/Target/TargetMachine.h"
114 #include "llvm/Target/TargetOptions.h"
115 #include "llvm/Transforms/Utils/Local.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cstddef>
119 #include <cstdint>
120 #include <cstring>
121 #include <iterator>
122 #include <limits>
123 #include <numeric>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 using namespace llvm;
129 using namespace PatternMatch;
130 using namespace SwitchCG;
131 
132 #define DEBUG_TYPE "isel"
133 
134 /// LimitFloatPrecision - Generate low-precision inline sequences for
135 /// some float libcalls (6, 8 or 12 bits).
136 static unsigned LimitFloatPrecision;
137 
138 static cl::opt<unsigned, true>
139     LimitFPPrecision("limit-float-precision",
140                      cl::desc("Generate low-precision inline sequences "
141                               "for some float libcalls"),
142                      cl::location(LimitFloatPrecision), cl::Hidden,
143                      cl::init(0));
144 
145 static cl::opt<unsigned> SwitchPeelThreshold(
146     "switch-peel-threshold", cl::Hidden, cl::init(66),
147     cl::desc("Set the case probability threshold for peeling the case from a "
148              "switch statement. A value greater than 100 will void this "
149              "optimization"));
150 
151 // Limit the width of DAG chains. This is important in general to prevent
152 // DAG-based analysis from blowing up. For example, alias analysis and
153 // load clustering may not complete in reasonable time. It is difficult to
154 // recognize and avoid this situation within each individual analysis, and
155 // future analyses are likely to have the same behavior. Limiting DAG width is
156 // the safe approach and will be especially important with global DAGs.
157 //
158 // MaxParallelChains default is arbitrarily high to avoid affecting
159 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
160 // sequence over this should have been converted to llvm.memcpy by the
161 // frontend. It is easy to induce this behavior with .ll code such as:
162 // %buffer = alloca [4096 x i8]
163 // %data = load [4096 x i8]* %argPtr
164 // store [4096 x i8] %data, [4096 x i8]* %buffer
165 static const unsigned MaxParallelChains = 64;
166 
167 // Return the calling convention if the Value passed requires ABI mangling as it
168 // is a parameter to a function or a return value from a function which is not
169 // an intrinsic.
170 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
171   if (auto *R = dyn_cast<ReturnInst>(V))
172     return R->getParent()->getParent()->getCallingConv();
173 
174   if (auto *CI = dyn_cast<CallInst>(V)) {
175     const bool IsInlineAsm = CI->isInlineAsm();
176     const bool IsIndirectFunctionCall =
177         !IsInlineAsm && !CI->getCalledFunction();
178 
179     // It is possible that the call instruction is an inline asm statement or an
180     // indirect function call in which case the return value of
181     // getCalledFunction() would be nullptr.
182     const bool IsInstrinsicCall =
183         !IsInlineAsm && !IsIndirectFunctionCall &&
184         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
185 
186     if (!IsInlineAsm && !IsInstrinsicCall)
187       return CI->getCallingConv();
188   }
189 
190   return None;
191 }
192 
193 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
194                                       const SDValue *Parts, unsigned NumParts,
195                                       MVT PartVT, EVT ValueVT, const Value *V,
196                                       Optional<CallingConv::ID> CC);
197 
198 /// getCopyFromParts - Create a value that contains the specified legal parts
199 /// combined into the value they represent.  If the parts combine to a type
200 /// larger than ValueVT then AssertOp can be used to specify whether the extra
201 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
202 /// (ISD::AssertSext).
203 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
204                                 const SDValue *Parts, unsigned NumParts,
205                                 MVT PartVT, EVT ValueVT, const Value *V,
206                                 Optional<CallingConv::ID> CC = None,
207                                 Optional<ISD::NodeType> AssertOp = None) {
208   if (ValueVT.isVector())
209     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
210                                   CC);
211 
212   assert(NumParts > 0 && "No parts to assemble!");
213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
214   SDValue Val = Parts[0];
215 
216   if (NumParts > 1) {
217     // Assemble the value from multiple parts.
218     if (ValueVT.isInteger()) {
219       unsigned PartBits = PartVT.getSizeInBits();
220       unsigned ValueBits = ValueVT.getSizeInBits();
221 
222       // Assemble the power of 2 part.
223       unsigned RoundParts =
224           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
225       unsigned RoundBits = PartBits * RoundParts;
226       EVT RoundVT = RoundBits == ValueBits ?
227         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
228       SDValue Lo, Hi;
229 
230       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
231 
232       if (RoundParts > 2) {
233         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
234                               PartVT, HalfVT, V);
235         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
236                               RoundParts / 2, PartVT, HalfVT, V);
237       } else {
238         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
239         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
240       }
241 
242       if (DAG.getDataLayout().isBigEndian())
243         std::swap(Lo, Hi);
244 
245       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
246 
247       if (RoundParts < NumParts) {
248         // Assemble the trailing non-power-of-2 part.
249         unsigned OddParts = NumParts - RoundParts;
250         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
251         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
252                               OddVT, V, CC);
253 
254         // Combine the round and odd parts.
255         Lo = Val;
256         if (DAG.getDataLayout().isBigEndian())
257           std::swap(Lo, Hi);
258         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
259         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
260         Hi =
261             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
262                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
263                                         TLI.getPointerTy(DAG.getDataLayout())));
264         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
265         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
266       }
267     } else if (PartVT.isFloatingPoint()) {
268       // FP split into multiple FP parts (for ppcf128)
269       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
270              "Unexpected split");
271       SDValue Lo, Hi;
272       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
273       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
274       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
275         std::swap(Lo, Hi);
276       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
277     } else {
278       // FP split into integer parts (soft fp)
279       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
280              !PartVT.isVector() && "Unexpected split");
281       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
282       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
283     }
284   }
285 
286   // There is now one part, held in Val.  Correct it to match ValueVT.
287   // PartEVT is the type of the register class that holds the value.
288   // ValueVT is the type of the inline asm operation.
289   EVT PartEVT = Val.getValueType();
290 
291   if (PartEVT == ValueVT)
292     return Val;
293 
294   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
295       ValueVT.bitsLT(PartEVT)) {
296     // For an FP value in an integer part, we need to truncate to the right
297     // width first.
298     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
299     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
300   }
301 
302   // Handle types that have the same size.
303   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
304     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
305 
306   // Handle types with different sizes.
307   if (PartEVT.isInteger() && ValueVT.isInteger()) {
308     if (ValueVT.bitsLT(PartEVT)) {
309       // For a truncate, see if we have any information to
310       // indicate whether the truncated bits will always be
311       // zero or sign-extension.
312       if (AssertOp.hasValue())
313         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
314                           DAG.getValueType(ValueVT));
315       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316     }
317     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
318   }
319 
320   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
321     // FP_ROUND's are always exact here.
322     if (ValueVT.bitsLT(Val.getValueType()))
323       return DAG.getNode(
324           ISD::FP_ROUND, DL, ValueVT, Val,
325           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
326 
327     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
328   }
329 
330   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
331   // then truncating.
332   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
333       ValueVT.bitsLT(PartEVT)) {
334     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
335     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
336   }
337 
338   report_fatal_error("Unknown mismatch in getCopyFromParts!");
339 }
340 
341 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
342                                               const Twine &ErrMsg) {
343   const Instruction *I = dyn_cast_or_null<Instruction>(V);
344   if (!V)
345     return Ctx.emitError(ErrMsg);
346 
347   const char *AsmError = ", possible invalid constraint for vector type";
348   if (const CallInst *CI = dyn_cast<CallInst>(I))
349     if (CI->isInlineAsm())
350       return Ctx.emitError(I, ErrMsg + AsmError);
351 
352   return Ctx.emitError(I, ErrMsg);
353 }
354 
355 /// getCopyFromPartsVector - Create a value that contains the specified legal
356 /// parts combined into the value they represent.  If the parts combine to a
357 /// type larger than ValueVT then AssertOp can be used to specify whether the
358 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
359 /// ValueVT (ISD::AssertSext).
360 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
361                                       const SDValue *Parts, unsigned NumParts,
362                                       MVT PartVT, EVT ValueVT, const Value *V,
363                                       Optional<CallingConv::ID> CallConv) {
364   assert(ValueVT.isVector() && "Not a vector value");
365   assert(NumParts > 0 && "No parts to assemble!");
366   const bool IsABIRegCopy = CallConv.hasValue();
367 
368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
369   SDValue Val = Parts[0];
370 
371   // Handle a multi-element vector.
372   if (NumParts > 1) {
373     EVT IntermediateVT;
374     MVT RegisterVT;
375     unsigned NumIntermediates;
376     unsigned NumRegs;
377 
378     if (IsABIRegCopy) {
379       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
380           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
381           NumIntermediates, RegisterVT);
382     } else {
383       NumRegs =
384           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
385                                      NumIntermediates, RegisterVT);
386     }
387 
388     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
389     NumParts = NumRegs; // Silence a compiler warning.
390     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
391     assert(RegisterVT.getSizeInBits() ==
392            Parts[0].getSimpleValueType().getSizeInBits() &&
393            "Part type sizes don't match!");
394 
395     // Assemble the parts into intermediate operands.
396     SmallVector<SDValue, 8> Ops(NumIntermediates);
397     if (NumIntermediates == NumParts) {
398       // If the register was not expanded, truncate or copy the value,
399       // as appropriate.
400       for (unsigned i = 0; i != NumParts; ++i)
401         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
402                                   PartVT, IntermediateVT, V);
403     } else if (NumParts > 0) {
404       // If the intermediate type was expanded, build the intermediate
405       // operands from the parts.
406       assert(NumParts % NumIntermediates == 0 &&
407              "Must expand into a divisible number of parts!");
408       unsigned Factor = NumParts / NumIntermediates;
409       for (unsigned i = 0; i != NumIntermediates; ++i)
410         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
411                                   PartVT, IntermediateVT, V);
412     }
413 
414     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
415     // intermediate operands.
416     EVT BuiltVectorTy =
417         IntermediateVT.isVector()
418             ? EVT::getVectorVT(
419                   *DAG.getContext(), IntermediateVT.getScalarType(),
420                   IntermediateVT.getVectorElementCount() * NumParts)
421             : EVT::getVectorVT(*DAG.getContext(),
422                                IntermediateVT.getScalarType(),
423                                NumIntermediates);
424     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
425                                                 : ISD::BUILD_VECTOR,
426                       DL, BuiltVectorTy, Ops);
427   }
428 
429   // There is now one part, held in Val.  Correct it to match ValueVT.
430   EVT PartEVT = Val.getValueType();
431 
432   if (PartEVT == ValueVT)
433     return Val;
434 
435   if (PartEVT.isVector()) {
436     // If the element type of the source/dest vectors are the same, but the
437     // parts vector has more elements than the value vector, then we have a
438     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
439     // elements we want.
440     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
441       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
442              "Cannot narrow, it would be a lossy transformation");
443       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
444                          DAG.getVectorIdxConstant(0, DL));
445     }
446 
447     // Vector/Vector bitcast.
448     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
449       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
450 
451     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
452       "Cannot handle this kind of promotion");
453     // Promoted vector extract
454     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
455 
456   }
457 
458   // Trivial bitcast if the types are the same size and the destination
459   // vector type is legal.
460   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
461       TLI.isTypeLegal(ValueVT))
462     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
463 
464   if (ValueVT.getVectorNumElements() != 1) {
465      // Certain ABIs require that vectors are passed as integers. For vectors
466      // are the same size, this is an obvious bitcast.
467      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
468        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
469      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
470        // Bitcast Val back the original type and extract the corresponding
471        // vector we want.
472        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
473        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
474                                            ValueVT.getVectorElementType(), Elts);
475        Val = DAG.getBitcast(WiderVecType, Val);
476        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477                           DAG.getVectorIdxConstant(0, DL));
478      }
479 
480      diagnosePossiblyInvalidConstraint(
481          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482      return DAG.getUNDEF(ValueVT);
483   }
484 
485   // Handle cases such as i8 -> <1 x i1>
486   EVT ValueSVT = ValueVT.getVectorElementType();
487   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
488     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
489       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
490     else
491       Val = ValueVT.isFloatingPoint()
492                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
493                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
494   }
495 
496   return DAG.getBuildVector(ValueVT, DL, Val);
497 }
498 
499 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
500                                  SDValue Val, SDValue *Parts, unsigned NumParts,
501                                  MVT PartVT, const Value *V,
502                                  Optional<CallingConv::ID> CallConv);
503 
504 /// getCopyToParts - Create a series of nodes that contain the specified value
505 /// split into legal parts.  If the parts contain more bits than Val, then, for
506 /// integers, ExtendKind can be used to specify how to generate the extra bits.
507 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
508                            SDValue *Parts, unsigned NumParts, MVT PartVT,
509                            const Value *V,
510                            Optional<CallingConv::ID> CallConv = None,
511                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
512   EVT ValueVT = Val.getValueType();
513 
514   // Handle the vector case separately.
515   if (ValueVT.isVector())
516     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
517                                 CallConv);
518 
519   unsigned PartBits = PartVT.getSizeInBits();
520   unsigned OrigNumParts = NumParts;
521   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
522          "Copying to an illegal type!");
523 
524   if (NumParts == 0)
525     return;
526 
527   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528   EVT PartEVT = PartVT;
529   if (PartEVT == ValueVT) {
530     assert(NumParts == 1 && "No-op copy with multiple parts!");
531     Parts[0] = Val;
532     return;
533   }
534 
535   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
536     // If the parts cover more bits than the value has, promote the value.
537     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
538       assert(NumParts == 1 && "Do not know what to promote to!");
539       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
540     } else {
541       if (ValueVT.isFloatingPoint()) {
542         // FP values need to be bitcast, then extended if they are being put
543         // into a larger container.
544         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
545         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
546       }
547       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
548              ValueVT.isInteger() &&
549              "Unknown mismatch!");
550       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
551       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
552       if (PartVT == MVT::x86mmx)
553         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555   } else if (PartBits == ValueVT.getSizeInBits()) {
556     // Different types of the same size.
557     assert(NumParts == 1 && PartEVT != ValueVT);
558     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
560     // If the parts cover less bits than value has, truncate the value.
561     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
562            ValueVT.isInteger() &&
563            "Unknown mismatch!");
564     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
565     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
566     if (PartVT == MVT::x86mmx)
567       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
568   }
569 
570   // The value may have changed - recompute ValueVT.
571   ValueVT = Val.getValueType();
572   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
573          "Failed to tile the value with PartVT!");
574 
575   if (NumParts == 1) {
576     if (PartEVT != ValueVT) {
577       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
578                                         "scalar-to-vector conversion failed");
579       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
580     }
581 
582     Parts[0] = Val;
583     return;
584   }
585 
586   // Expand the value into multiple parts.
587   if (NumParts & (NumParts - 1)) {
588     // The number of parts is not a power of 2.  Split off and copy the tail.
589     assert(PartVT.isInteger() && ValueVT.isInteger() &&
590            "Do not know what to expand to!");
591     unsigned RoundParts = 1 << Log2_32(NumParts);
592     unsigned RoundBits = RoundParts * PartBits;
593     unsigned OddParts = NumParts - RoundParts;
594     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
595       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
596 
597     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
598                    CallConv);
599 
600     if (DAG.getDataLayout().isBigEndian())
601       // The odd parts were reversed by getCopyToParts - unreverse them.
602       std::reverse(Parts + RoundParts, Parts + NumParts);
603 
604     NumParts = RoundParts;
605     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
606     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
607   }
608 
609   // The number of parts is a power of 2.  Repeatedly bisect the value using
610   // EXTRACT_ELEMENT.
611   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
612                          EVT::getIntegerVT(*DAG.getContext(),
613                                            ValueVT.getSizeInBits()),
614                          Val);
615 
616   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
617     for (unsigned i = 0; i < NumParts; i += StepSize) {
618       unsigned ThisBits = StepSize * PartBits / 2;
619       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
620       SDValue &Part0 = Parts[i];
621       SDValue &Part1 = Parts[i+StepSize/2];
622 
623       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
625       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
627 
628       if (ThisBits == PartBits && ThisVT != PartVT) {
629         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
630         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
631       }
632     }
633   }
634 
635   if (DAG.getDataLayout().isBigEndian())
636     std::reverse(Parts, Parts + OrigNumParts);
637 }
638 
639 static SDValue widenVectorToPartType(SelectionDAG &DAG,
640                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
641   if (!PartVT.isVector())
642     return SDValue();
643 
644   EVT ValueVT = Val.getValueType();
645   unsigned PartNumElts = PartVT.getVectorNumElements();
646   unsigned ValueNumElts = ValueVT.getVectorNumElements();
647   if (PartNumElts > ValueNumElts &&
648       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
649     EVT ElementVT = PartVT.getVectorElementType();
650     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
651     // undef elements.
652     SmallVector<SDValue, 16> Ops;
653     DAG.ExtractVectorElements(Val, Ops);
654     SDValue EltUndef = DAG.getUNDEF(ElementVT);
655     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
656       Ops.push_back(EltUndef);
657 
658     // FIXME: Use CONCAT for 2x -> 4x.
659     return DAG.getBuildVector(PartVT, DL, Ops);
660   }
661 
662   return SDValue();
663 }
664 
665 /// getCopyToPartsVector - Create a series of nodes that contain the specified
666 /// value split into legal parts.
667 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
668                                  SDValue Val, SDValue *Parts, unsigned NumParts,
669                                  MVT PartVT, const Value *V,
670                                  Optional<CallingConv::ID> CallConv) {
671   EVT ValueVT = Val.getValueType();
672   assert(ValueVT.isVector() && "Not a vector");
673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
674   const bool IsABIRegCopy = CallConv.hasValue();
675 
676   if (NumParts == 1) {
677     EVT PartEVT = PartVT;
678     if (PartEVT == ValueVT) {
679       // Nothing to do.
680     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
681       // Bitconvert vector->vector case.
682       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
683     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
684       Val = Widened;
685     } else if (PartVT.isVector() &&
686                PartEVT.getVectorElementType().bitsGE(
687                  ValueVT.getVectorElementType()) &&
688                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
689 
690       // Promoted vector extract
691       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
692     } else {
693       if (ValueVT.getVectorNumElements() == 1) {
694         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
695                           DAG.getVectorIdxConstant(0, DL));
696       } else {
697         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
698                "lossy conversion of vector to scalar type");
699         EVT IntermediateType =
700             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
701         Val = DAG.getBitcast(IntermediateType, Val);
702         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
703       }
704     }
705 
706     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
707     Parts[0] = Val;
708     return;
709   }
710 
711   // Handle a multi-element vector.
712   EVT IntermediateVT;
713   MVT RegisterVT;
714   unsigned NumIntermediates;
715   unsigned NumRegs;
716   if (IsABIRegCopy) {
717     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
718         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
719         NumIntermediates, RegisterVT);
720   } else {
721     NumRegs =
722         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
723                                    NumIntermediates, RegisterVT);
724   }
725 
726   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
727   NumParts = NumRegs; // Silence a compiler warning.
728   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
729 
730   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
731     IntermediateVT.getVectorNumElements() : 1;
732 
733   // Convert the vector to the appropriate type if necessary.
734   auto DestEltCnt = ElementCount(NumIntermediates * IntermediateNumElts,
735                                  ValueVT.isScalableVector());
736   EVT BuiltVectorTy = EVT::getVectorVT(
737       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt);
738   if (ValueVT != BuiltVectorTy) {
739     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
740       Val = Widened;
741 
742     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743   }
744 
745   // Split the vector into intermediate operands.
746   SmallVector<SDValue, 8> Ops(NumIntermediates);
747   for (unsigned i = 0; i != NumIntermediates; ++i) {
748     if (IntermediateVT.isVector()) {
749       Ops[i] =
750           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
751                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
752     } else {
753       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
754                            DAG.getVectorIdxConstant(i, DL));
755     }
756   }
757 
758   // Split the intermediate operands into legal parts.
759   if (NumParts == NumIntermediates) {
760     // If the register was not expanded, promote or copy the value,
761     // as appropriate.
762     for (unsigned i = 0; i != NumParts; ++i)
763       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
764   } else if (NumParts > 0) {
765     // If the intermediate type was expanded, split each the value into
766     // legal parts.
767     assert(NumIntermediates != 0 && "division by zero");
768     assert(NumParts % NumIntermediates == 0 &&
769            "Must expand into a divisible number of parts!");
770     unsigned Factor = NumParts / NumIntermediates;
771     for (unsigned i = 0; i != NumIntermediates; ++i)
772       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
773                      CallConv);
774   }
775 }
776 
777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
778                            EVT valuevt, Optional<CallingConv::ID> CC)
779     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
780       RegCount(1, regs.size()), CallConv(CC) {}
781 
782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
783                            const DataLayout &DL, unsigned Reg, Type *Ty,
784                            Optional<CallingConv::ID> CC) {
785   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
786 
787   CallConv = CC;
788 
789   for (EVT ValueVT : ValueVTs) {
790     unsigned NumRegs =
791         isABIMangled()
792             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
793             : TLI.getNumRegisters(Context, ValueVT);
794     MVT RegisterVT =
795         isABIMangled()
796             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
797             : TLI.getRegisterType(Context, ValueVT);
798     for (unsigned i = 0; i != NumRegs; ++i)
799       Regs.push_back(Reg + i);
800     RegVTs.push_back(RegisterVT);
801     RegCount.push_back(NumRegs);
802     Reg += NumRegs;
803   }
804 }
805 
806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
807                                       FunctionLoweringInfo &FuncInfo,
808                                       const SDLoc &dl, SDValue &Chain,
809                                       SDValue *Flag, const Value *V) const {
810   // A Value with type {} or [0 x %t] needs no registers.
811   if (ValueVTs.empty())
812     return SDValue();
813 
814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
815 
816   // Assemble the legal parts into the final values.
817   SmallVector<SDValue, 4> Values(ValueVTs.size());
818   SmallVector<SDValue, 8> Parts;
819   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
820     // Copy the legal parts from the registers.
821     EVT ValueVT = ValueVTs[Value];
822     unsigned NumRegs = RegCount[Value];
823     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
824                                           *DAG.getContext(),
825                                           CallConv.getValue(), RegVTs[Value])
826                                     : RegVTs[Value];
827 
828     Parts.resize(NumRegs);
829     for (unsigned i = 0; i != NumRegs; ++i) {
830       SDValue P;
831       if (!Flag) {
832         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
833       } else {
834         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
835         *Flag = P.getValue(2);
836       }
837 
838       Chain = P.getValue(1);
839       Parts[i] = P;
840 
841       // If the source register was virtual and if we know something about it,
842       // add an assert node.
843       if (!Register::isVirtualRegister(Regs[Part + i]) ||
844           !RegisterVT.isInteger())
845         continue;
846 
847       const FunctionLoweringInfo::LiveOutInfo *LOI =
848         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
849       if (!LOI)
850         continue;
851 
852       unsigned RegSize = RegisterVT.getScalarSizeInBits();
853       unsigned NumSignBits = LOI->NumSignBits;
854       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
855 
856       if (NumZeroBits == RegSize) {
857         // The current value is a zero.
858         // Explicitly express that as it would be easier for
859         // optimizations to kick in.
860         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
861         continue;
862       }
863 
864       // FIXME: We capture more information than the dag can represent.  For
865       // now, just use the tightest assertzext/assertsext possible.
866       bool isSExt;
867       EVT FromVT(MVT::Other);
868       if (NumZeroBits) {
869         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
870         isSExt = false;
871       } else if (NumSignBits > 1) {
872         FromVT =
873             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
874         isSExt = true;
875       } else {
876         continue;
877       }
878       // Add an assertion node.
879       assert(FromVT != MVT::Other);
880       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
881                              RegisterVT, P, DAG.getValueType(FromVT));
882     }
883 
884     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
885                                      RegisterVT, ValueVT, V, CallConv);
886     Part += NumRegs;
887     Parts.clear();
888   }
889 
890   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
891 }
892 
893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
894                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
895                                  const Value *V,
896                                  ISD::NodeType PreferredExtendType) const {
897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
898   ISD::NodeType ExtendKind = PreferredExtendType;
899 
900   // Get the list of the values's legal parts.
901   unsigned NumRegs = Regs.size();
902   SmallVector<SDValue, 8> Parts(NumRegs);
903   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
904     unsigned NumParts = RegCount[Value];
905 
906     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
907                                           *DAG.getContext(),
908                                           CallConv.getValue(), RegVTs[Value])
909                                     : RegVTs[Value];
910 
911     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
912       ExtendKind = ISD::ZERO_EXTEND;
913 
914     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
915                    NumParts, RegisterVT, V, CallConv, ExtendKind);
916     Part += NumParts;
917   }
918 
919   // Copy the parts into the registers.
920   SmallVector<SDValue, 8> Chains(NumRegs);
921   for (unsigned i = 0; i != NumRegs; ++i) {
922     SDValue Part;
923     if (!Flag) {
924       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
925     } else {
926       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
927       *Flag = Part.getValue(1);
928     }
929 
930     Chains[i] = Part.getValue(0);
931   }
932 
933   if (NumRegs == 1 || Flag)
934     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
935     // flagged to it. That is the CopyToReg nodes and the user are considered
936     // a single scheduling unit. If we create a TokenFactor and return it as
937     // chain, then the TokenFactor is both a predecessor (operand) of the
938     // user as well as a successor (the TF operands are flagged to the user).
939     // c1, f1 = CopyToReg
940     // c2, f2 = CopyToReg
941     // c3     = TokenFactor c1, c2
942     // ...
943     //        = op c3, ..., f2
944     Chain = Chains[NumRegs-1];
945   else
946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
947 }
948 
949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
950                                         unsigned MatchingIdx, const SDLoc &dl,
951                                         SelectionDAG &DAG,
952                                         std::vector<SDValue> &Ops) const {
953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
954 
955   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
956   if (HasMatching)
957     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
958   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
959     // Put the register class of the virtual registers in the flag word.  That
960     // way, later passes can recompute register class constraints for inline
961     // assembly as well as normal instructions.
962     // Don't do this for tied operands that can use the regclass information
963     // from the def.
964     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
965     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
966     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
967   }
968 
969   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
970   Ops.push_back(Res);
971 
972   if (Code == InlineAsm::Kind_Clobber) {
973     // Clobbers should always have a 1:1 mapping with registers, and may
974     // reference registers that have illegal (e.g. vector) types. Hence, we
975     // shouldn't try to apply any sort of splitting logic to them.
976     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
977            "No 1:1 mapping from clobbers to regs?");
978     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
979     (void)SP;
980     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
981       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
982       assert(
983           (Regs[I] != SP ||
984            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
985           "If we clobbered the stack pointer, MFI should know about it.");
986     }
987     return;
988   }
989 
990   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
991     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
992     MVT RegisterVT = RegVTs[Value];
993     for (unsigned i = 0; i != NumRegs; ++i) {
994       assert(Reg < Regs.size() && "Mismatch in # registers expected");
995       unsigned TheReg = Regs[Reg++];
996       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
997     }
998   }
999 }
1000 
1001 SmallVector<std::pair<unsigned, unsigned>, 4>
1002 RegsForValue::getRegsAndSizes() const {
1003   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1004   unsigned I = 0;
1005   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1006     unsigned RegCount = std::get<0>(CountAndVT);
1007     MVT RegisterVT = std::get<1>(CountAndVT);
1008     unsigned RegisterSize = RegisterVT.getSizeInBits();
1009     for (unsigned E = I + RegCount; I != E; ++I)
1010       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1011   }
1012   return OutVec;
1013 }
1014 
1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1016                                const TargetLibraryInfo *li) {
1017   AA = aa;
1018   GFI = gfi;
1019   LibInfo = li;
1020   DL = &DAG.getDataLayout();
1021   Context = DAG.getContext();
1022   LPadToCallSiteMap.clear();
1023   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1024 }
1025 
1026 void SelectionDAGBuilder::clear() {
1027   NodeMap.clear();
1028   UnusedArgNodeMap.clear();
1029   PendingLoads.clear();
1030   PendingExports.clear();
1031   PendingConstrainedFP.clear();
1032   PendingConstrainedFPStrict.clear();
1033   CurInst = nullptr;
1034   HasTailCall = false;
1035   SDNodeOrder = LowestSDNodeOrder;
1036   StatepointLowering.clear();
1037 }
1038 
1039 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1040   DanglingDebugInfoMap.clear();
1041 }
1042 
1043 // Update DAG root to include dependencies on Pending chains.
1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1045   SDValue Root = DAG.getRoot();
1046 
1047   if (Pending.empty())
1048     return Root;
1049 
1050   // Add current root to PendingChains, unless we already indirectly
1051   // depend on it.
1052   if (Root.getOpcode() != ISD::EntryToken) {
1053     unsigned i = 0, e = Pending.size();
1054     for (; i != e; ++i) {
1055       assert(Pending[i].getNode()->getNumOperands() > 1);
1056       if (Pending[i].getNode()->getOperand(0) == Root)
1057         break;  // Don't add the root if we already indirectly depend on it.
1058     }
1059 
1060     if (i == e)
1061       Pending.push_back(Root);
1062   }
1063 
1064   if (Pending.size() == 1)
1065     Root = Pending[0];
1066   else
1067     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1068 
1069   DAG.setRoot(Root);
1070   Pending.clear();
1071   return Root;
1072 }
1073 
1074 SDValue SelectionDAGBuilder::getMemoryRoot() {
1075   return updateRoot(PendingLoads);
1076 }
1077 
1078 SDValue SelectionDAGBuilder::getRoot() {
1079   // Chain up all pending constrained intrinsics together with all
1080   // pending loads, by simply appending them to PendingLoads and
1081   // then calling getMemoryRoot().
1082   PendingLoads.reserve(PendingLoads.size() +
1083                        PendingConstrainedFP.size() +
1084                        PendingConstrainedFPStrict.size());
1085   PendingLoads.append(PendingConstrainedFP.begin(),
1086                       PendingConstrainedFP.end());
1087   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1088                       PendingConstrainedFPStrict.end());
1089   PendingConstrainedFP.clear();
1090   PendingConstrainedFPStrict.clear();
1091   return getMemoryRoot();
1092 }
1093 
1094 SDValue SelectionDAGBuilder::getControlRoot() {
1095   // We need to emit pending fpexcept.strict constrained intrinsics,
1096   // so append them to the PendingExports list.
1097   PendingExports.append(PendingConstrainedFPStrict.begin(),
1098                         PendingConstrainedFPStrict.end());
1099   PendingConstrainedFPStrict.clear();
1100   return updateRoot(PendingExports);
1101 }
1102 
1103 void SelectionDAGBuilder::visit(const Instruction &I) {
1104   // Set up outgoing PHI node register values before emitting the terminator.
1105   if (I.isTerminator()) {
1106     HandlePHINodesInSuccessorBlocks(I.getParent());
1107   }
1108 
1109   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1110   if (!isa<DbgInfoIntrinsic>(I))
1111     ++SDNodeOrder;
1112 
1113   CurInst = &I;
1114 
1115   visit(I.getOpcode(), I);
1116 
1117   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1118     // ConstrainedFPIntrinsics handle their own FMF.
1119     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1120       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1121       // maps to this instruction.
1122       // TODO: We could handle all flags (nsw, etc) here.
1123       // TODO: If an IR instruction maps to >1 node, only the final node will have
1124       //       flags set.
1125       if (SDNode *Node = getNodeForIRValue(&I)) {
1126         SDNodeFlags IncomingFlags;
1127         IncomingFlags.copyFMF(*FPMO);
1128         if (!Node->getFlags().isDefined())
1129           Node->setFlags(IncomingFlags);
1130         else
1131           Node->intersectFlagsWith(IncomingFlags);
1132       }
1133     }
1134   }
1135 
1136   if (!I.isTerminator() && !HasTailCall &&
1137       !isStatepoint(&I)) // statepoints handle their exports internally
1138     CopyToExportRegsIfNeeded(&I);
1139 
1140   CurInst = nullptr;
1141 }
1142 
1143 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1144   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1145 }
1146 
1147 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1148   // Note: this doesn't use InstVisitor, because it has to work with
1149   // ConstantExpr's in addition to instructions.
1150   switch (Opcode) {
1151   default: llvm_unreachable("Unknown instruction type encountered!");
1152     // Build the switch statement using the Instruction.def file.
1153 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1154     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1155 #include "llvm/IR/Instruction.def"
1156   }
1157 }
1158 
1159 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1160                                                 const DIExpression *Expr) {
1161   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1162     const DbgValueInst *DI = DDI.getDI();
1163     DIVariable *DanglingVariable = DI->getVariable();
1164     DIExpression *DanglingExpr = DI->getExpression();
1165     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1166       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1167       return true;
1168     }
1169     return false;
1170   };
1171 
1172   for (auto &DDIMI : DanglingDebugInfoMap) {
1173     DanglingDebugInfoVector &DDIV = DDIMI.second;
1174 
1175     // If debug info is to be dropped, run it through final checks to see
1176     // whether it can be salvaged.
1177     for (auto &DDI : DDIV)
1178       if (isMatchingDbgValue(DDI))
1179         salvageUnresolvedDbgValue(DDI);
1180 
1181     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1182   }
1183 }
1184 
1185 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1186 // generate the debug data structures now that we've seen its definition.
1187 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1188                                                    SDValue Val) {
1189   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1190   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1191     return;
1192 
1193   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1194   for (auto &DDI : DDIV) {
1195     const DbgValueInst *DI = DDI.getDI();
1196     assert(DI && "Ill-formed DanglingDebugInfo");
1197     DebugLoc dl = DDI.getdl();
1198     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1199     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1200     DILocalVariable *Variable = DI->getVariable();
1201     DIExpression *Expr = DI->getExpression();
1202     assert(Variable->isValidLocationForIntrinsic(dl) &&
1203            "Expected inlined-at fields to agree");
1204     SDDbgValue *SDV;
1205     if (Val.getNode()) {
1206       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1207       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1208       // we couldn't resolve it directly when examining the DbgValue intrinsic
1209       // in the first place we should not be more successful here). Unless we
1210       // have some test case that prove this to be correct we should avoid
1211       // calling EmitFuncArgumentDbgValue here.
1212       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1213         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1214                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1215         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1216         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1217         // inserted after the definition of Val when emitting the instructions
1218         // after ISel. An alternative could be to teach
1219         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1220         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1221                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1222                    << ValSDNodeOrder << "\n");
1223         SDV = getDbgValue(Val, Variable, Expr, dl,
1224                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1225         DAG.AddDbgValue(SDV, Val.getNode(), false);
1226       } else
1227         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1228                           << "in EmitFuncArgumentDbgValue\n");
1229     } else {
1230       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1231       auto Undef =
1232           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1233       auto SDV =
1234           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1235       DAG.AddDbgValue(SDV, nullptr, false);
1236     }
1237   }
1238   DDIV.clear();
1239 }
1240 
1241 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1242   Value *V = DDI.getDI()->getValue();
1243   DILocalVariable *Var = DDI.getDI()->getVariable();
1244   DIExpression *Expr = DDI.getDI()->getExpression();
1245   DebugLoc DL = DDI.getdl();
1246   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1247   unsigned SDOrder = DDI.getSDNodeOrder();
1248 
1249   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1250   // that DW_OP_stack_value is desired.
1251   assert(isa<DbgValueInst>(DDI.getDI()));
1252   bool StackValue = true;
1253 
1254   // Can this Value can be encoded without any further work?
1255   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1256     return;
1257 
1258   // Attempt to salvage back through as many instructions as possible. Bail if
1259   // a non-instruction is seen, such as a constant expression or global
1260   // variable. FIXME: Further work could recover those too.
1261   while (isa<Instruction>(V)) {
1262     Instruction &VAsInst = *cast<Instruction>(V);
1263     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1264 
1265     // If we cannot salvage any further, and haven't yet found a suitable debug
1266     // expression, bail out.
1267     if (!NewExpr)
1268       break;
1269 
1270     // New value and expr now represent this debuginfo.
1271     V = VAsInst.getOperand(0);
1272     Expr = NewExpr;
1273 
1274     // Some kind of simplification occurred: check whether the operand of the
1275     // salvaged debug expression can be encoded in this DAG.
1276     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1277       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1278                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1279       return;
1280     }
1281   }
1282 
1283   // This was the final opportunity to salvage this debug information, and it
1284   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1285   // any earlier variable location.
1286   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1287   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1288   DAG.AddDbgValue(SDV, nullptr, false);
1289 
1290   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1291                     << "\n");
1292   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1293                     << "\n");
1294 }
1295 
1296 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1297                                            DIExpression *Expr, DebugLoc dl,
1298                                            DebugLoc InstDL, unsigned Order) {
1299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1300   SDDbgValue *SDV;
1301   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1302       isa<ConstantPointerNull>(V)) {
1303     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1304     DAG.AddDbgValue(SDV, nullptr, false);
1305     return true;
1306   }
1307 
1308   // If the Value is a frame index, we can create a FrameIndex debug value
1309   // without relying on the DAG at all.
1310   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1311     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1312     if (SI != FuncInfo.StaticAllocaMap.end()) {
1313       auto SDV =
1314           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1315                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1316       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1317       // is still available even if the SDNode gets optimized out.
1318       DAG.AddDbgValue(SDV, nullptr, false);
1319       return true;
1320     }
1321   }
1322 
1323   // Do not use getValue() in here; we don't want to generate code at
1324   // this point if it hasn't been done yet.
1325   SDValue N = NodeMap[V];
1326   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1327     N = UnusedArgNodeMap[V];
1328   if (N.getNode()) {
1329     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1330       return true;
1331     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1332     DAG.AddDbgValue(SDV, N.getNode(), false);
1333     return true;
1334   }
1335 
1336   // Special rules apply for the first dbg.values of parameter variables in a
1337   // function. Identify them by the fact they reference Argument Values, that
1338   // they're parameters, and they are parameters of the current function. We
1339   // need to let them dangle until they get an SDNode.
1340   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1341                        !InstDL.getInlinedAt();
1342   if (!IsParamOfFunc) {
1343     // The value is not used in this block yet (or it would have an SDNode).
1344     // We still want the value to appear for the user if possible -- if it has
1345     // an associated VReg, we can refer to that instead.
1346     auto VMI = FuncInfo.ValueMap.find(V);
1347     if (VMI != FuncInfo.ValueMap.end()) {
1348       unsigned Reg = VMI->second;
1349       // If this is a PHI node, it may be split up into several MI PHI nodes
1350       // (in FunctionLoweringInfo::set).
1351       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1352                        V->getType(), None);
1353       if (RFV.occupiesMultipleRegs()) {
1354         unsigned Offset = 0;
1355         unsigned BitsToDescribe = 0;
1356         if (auto VarSize = Var->getSizeInBits())
1357           BitsToDescribe = *VarSize;
1358         if (auto Fragment = Expr->getFragmentInfo())
1359           BitsToDescribe = Fragment->SizeInBits;
1360         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1361           unsigned RegisterSize = RegAndSize.second;
1362           // Bail out if all bits are described already.
1363           if (Offset >= BitsToDescribe)
1364             break;
1365           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1366               ? BitsToDescribe - Offset
1367               : RegisterSize;
1368           auto FragmentExpr = DIExpression::createFragmentExpression(
1369               Expr, Offset, FragmentSize);
1370           if (!FragmentExpr)
1371               continue;
1372           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1373                                     false, dl, SDNodeOrder);
1374           DAG.AddDbgValue(SDV, nullptr, false);
1375           Offset += RegisterSize;
1376         }
1377       } else {
1378         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1379         DAG.AddDbgValue(SDV, nullptr, false);
1380       }
1381       return true;
1382     }
1383   }
1384 
1385   return false;
1386 }
1387 
1388 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1389   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1390   for (auto &Pair : DanglingDebugInfoMap)
1391     for (auto &DDI : Pair.second)
1392       salvageUnresolvedDbgValue(DDI);
1393   clearDanglingDebugInfo();
1394 }
1395 
1396 /// getCopyFromRegs - If there was virtual register allocated for the value V
1397 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1398 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1399   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1400   SDValue Result;
1401 
1402   if (It != FuncInfo.ValueMap.end()) {
1403     Register InReg = It->second;
1404 
1405     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1406                      DAG.getDataLayout(), InReg, Ty,
1407                      None); // This is not an ABI copy.
1408     SDValue Chain = DAG.getEntryNode();
1409     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1410                                  V);
1411     resolveDanglingDebugInfo(V, Result);
1412   }
1413 
1414   return Result;
1415 }
1416 
1417 /// getValue - Return an SDValue for the given Value.
1418 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1419   // If we already have an SDValue for this value, use it. It's important
1420   // to do this first, so that we don't create a CopyFromReg if we already
1421   // have a regular SDValue.
1422   SDValue &N = NodeMap[V];
1423   if (N.getNode()) return N;
1424 
1425   // If there's a virtual register allocated and initialized for this
1426   // value, use it.
1427   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1428     return copyFromReg;
1429 
1430   // Otherwise create a new SDValue and remember it.
1431   SDValue Val = getValueImpl(V);
1432   NodeMap[V] = Val;
1433   resolveDanglingDebugInfo(V, Val);
1434   return Val;
1435 }
1436 
1437 /// getNonRegisterValue - Return an SDValue for the given Value, but
1438 /// don't look in FuncInfo.ValueMap for a virtual register.
1439 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1440   // If we already have an SDValue for this value, use it.
1441   SDValue &N = NodeMap[V];
1442   if (N.getNode()) {
1443     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1444       // Remove the debug location from the node as the node is about to be used
1445       // in a location which may differ from the original debug location.  This
1446       // is relevant to Constant and ConstantFP nodes because they can appear
1447       // as constant expressions inside PHI nodes.
1448       N->setDebugLoc(DebugLoc());
1449     }
1450     return N;
1451   }
1452 
1453   // Otherwise create a new SDValue and remember it.
1454   SDValue Val = getValueImpl(V);
1455   NodeMap[V] = Val;
1456   resolveDanglingDebugInfo(V, Val);
1457   return Val;
1458 }
1459 
1460 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1461 /// Create an SDValue for the given value.
1462 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1464 
1465   if (const Constant *C = dyn_cast<Constant>(V)) {
1466     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1467 
1468     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1469       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1470 
1471     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1472       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1473 
1474     if (isa<ConstantPointerNull>(C)) {
1475       unsigned AS = V->getType()->getPointerAddressSpace();
1476       return DAG.getConstant(0, getCurSDLoc(),
1477                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1478     }
1479 
1480     if (match(C, m_VScale(DAG.getDataLayout())))
1481       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1482 
1483     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1484       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1485 
1486     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1487       return DAG.getUNDEF(VT);
1488 
1489     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1490       visit(CE->getOpcode(), *CE);
1491       SDValue N1 = NodeMap[V];
1492       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1493       return N1;
1494     }
1495 
1496     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1497       SmallVector<SDValue, 4> Constants;
1498       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1499            OI != OE; ++OI) {
1500         SDNode *Val = getValue(*OI).getNode();
1501         // If the operand is an empty aggregate, there are no values.
1502         if (!Val) continue;
1503         // Add each leaf value from the operand to the Constants list
1504         // to form a flattened list of all the values.
1505         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1506           Constants.push_back(SDValue(Val, i));
1507       }
1508 
1509       return DAG.getMergeValues(Constants, getCurSDLoc());
1510     }
1511 
1512     if (const ConstantDataSequential *CDS =
1513           dyn_cast<ConstantDataSequential>(C)) {
1514       SmallVector<SDValue, 4> Ops;
1515       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1516         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1517         // Add each leaf value from the operand to the Constants list
1518         // to form a flattened list of all the values.
1519         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1520           Ops.push_back(SDValue(Val, i));
1521       }
1522 
1523       if (isa<ArrayType>(CDS->getType()))
1524         return DAG.getMergeValues(Ops, getCurSDLoc());
1525       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1526     }
1527 
1528     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1529       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1530              "Unknown struct or array constant!");
1531 
1532       SmallVector<EVT, 4> ValueVTs;
1533       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1534       unsigned NumElts = ValueVTs.size();
1535       if (NumElts == 0)
1536         return SDValue(); // empty struct
1537       SmallVector<SDValue, 4> Constants(NumElts);
1538       for (unsigned i = 0; i != NumElts; ++i) {
1539         EVT EltVT = ValueVTs[i];
1540         if (isa<UndefValue>(C))
1541           Constants[i] = DAG.getUNDEF(EltVT);
1542         else if (EltVT.isFloatingPoint())
1543           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1544         else
1545           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1546       }
1547 
1548       return DAG.getMergeValues(Constants, getCurSDLoc());
1549     }
1550 
1551     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1552       return DAG.getBlockAddress(BA, VT);
1553 
1554     VectorType *VecTy = cast<VectorType>(V->getType());
1555 
1556     // Now that we know the number and type of the elements, get that number of
1557     // elements into the Ops array based on what kind of constant it is.
1558     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1559       SmallVector<SDValue, 16> Ops;
1560       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1561       for (unsigned i = 0; i != NumElements; ++i)
1562         Ops.push_back(getValue(CV->getOperand(i)));
1563 
1564       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1565     } else if (isa<ConstantAggregateZero>(C)) {
1566       EVT EltVT =
1567           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1568 
1569       SDValue Op;
1570       if (EltVT.isFloatingPoint())
1571         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1572       else
1573         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1574 
1575       if (isa<ScalableVectorType>(VecTy))
1576         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1577       else {
1578         SmallVector<SDValue, 16> Ops;
1579         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1580         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1581       }
1582     }
1583     llvm_unreachable("Unknown vector constant");
1584   }
1585 
1586   // If this is a static alloca, generate it as the frameindex instead of
1587   // computation.
1588   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1589     DenseMap<const AllocaInst*, int>::iterator SI =
1590       FuncInfo.StaticAllocaMap.find(AI);
1591     if (SI != FuncInfo.StaticAllocaMap.end())
1592       return DAG.getFrameIndex(SI->second,
1593                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1594   }
1595 
1596   // If this is an instruction which fast-isel has deferred, select it now.
1597   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1598     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1599 
1600     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1601                      Inst->getType(), getABIRegCopyCC(V));
1602     SDValue Chain = DAG.getEntryNode();
1603     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1604   }
1605 
1606   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1607     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1608   }
1609   llvm_unreachable("Can't get register for value!");
1610 }
1611 
1612 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1613   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1614   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1615   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1616   bool IsSEH = isAsynchronousEHPersonality(Pers);
1617   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1618   if (!IsSEH)
1619     CatchPadMBB->setIsEHScopeEntry();
1620   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1621   if (IsMSVCCXX || IsCoreCLR)
1622     CatchPadMBB->setIsEHFuncletEntry();
1623 }
1624 
1625 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1626   // Update machine-CFG edge.
1627   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1628   FuncInfo.MBB->addSuccessor(TargetMBB);
1629 
1630   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1631   bool IsSEH = isAsynchronousEHPersonality(Pers);
1632   if (IsSEH) {
1633     // If this is not a fall-through branch or optimizations are switched off,
1634     // emit the branch.
1635     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1636         TM.getOptLevel() == CodeGenOpt::None)
1637       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1638                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1639     return;
1640   }
1641 
1642   // Figure out the funclet membership for the catchret's successor.
1643   // This will be used by the FuncletLayout pass to determine how to order the
1644   // BB's.
1645   // A 'catchret' returns to the outer scope's color.
1646   Value *ParentPad = I.getCatchSwitchParentPad();
1647   const BasicBlock *SuccessorColor;
1648   if (isa<ConstantTokenNone>(ParentPad))
1649     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1650   else
1651     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1652   assert(SuccessorColor && "No parent funclet for catchret!");
1653   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1654   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1655 
1656   // Create the terminator node.
1657   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1658                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1659                             DAG.getBasicBlock(SuccessorColorMBB));
1660   DAG.setRoot(Ret);
1661 }
1662 
1663 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1664   // Don't emit any special code for the cleanuppad instruction. It just marks
1665   // the start of an EH scope/funclet.
1666   FuncInfo.MBB->setIsEHScopeEntry();
1667   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1668   if (Pers != EHPersonality::Wasm_CXX) {
1669     FuncInfo.MBB->setIsEHFuncletEntry();
1670     FuncInfo.MBB->setIsCleanupFuncletEntry();
1671   }
1672 }
1673 
1674 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1675 // the control flow always stops at the single catch pad, as it does for a
1676 // cleanup pad. In case the exception caught is not of the types the catch pad
1677 // catches, it will be rethrown by a rethrow.
1678 static void findWasmUnwindDestinations(
1679     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1680     BranchProbability Prob,
1681     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1682         &UnwindDests) {
1683   while (EHPadBB) {
1684     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1685     if (isa<CleanupPadInst>(Pad)) {
1686       // Stop on cleanup pads.
1687       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1688       UnwindDests.back().first->setIsEHScopeEntry();
1689       break;
1690     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1691       // Add the catchpad handlers to the possible destinations. We don't
1692       // continue to the unwind destination of the catchswitch for wasm.
1693       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1694         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1695         UnwindDests.back().first->setIsEHScopeEntry();
1696       }
1697       break;
1698     } else {
1699       continue;
1700     }
1701   }
1702 }
1703 
1704 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1705 /// many places it could ultimately go. In the IR, we have a single unwind
1706 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1707 /// This function skips over imaginary basic blocks that hold catchswitch
1708 /// instructions, and finds all the "real" machine
1709 /// basic block destinations. As those destinations may not be successors of
1710 /// EHPadBB, here we also calculate the edge probability to those destinations.
1711 /// The passed-in Prob is the edge probability to EHPadBB.
1712 static void findUnwindDestinations(
1713     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1714     BranchProbability Prob,
1715     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1716         &UnwindDests) {
1717   EHPersonality Personality =
1718     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1719   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1720   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1721   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1722   bool IsSEH = isAsynchronousEHPersonality(Personality);
1723 
1724   if (IsWasmCXX) {
1725     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1726     assert(UnwindDests.size() <= 1 &&
1727            "There should be at most one unwind destination for wasm");
1728     return;
1729   }
1730 
1731   while (EHPadBB) {
1732     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1733     BasicBlock *NewEHPadBB = nullptr;
1734     if (isa<LandingPadInst>(Pad)) {
1735       // Stop on landingpads. They are not funclets.
1736       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1737       break;
1738     } else if (isa<CleanupPadInst>(Pad)) {
1739       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1740       // personalities.
1741       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1742       UnwindDests.back().first->setIsEHScopeEntry();
1743       UnwindDests.back().first->setIsEHFuncletEntry();
1744       break;
1745     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1746       // Add the catchpad handlers to the possible destinations.
1747       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1748         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1749         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1750         if (IsMSVCCXX || IsCoreCLR)
1751           UnwindDests.back().first->setIsEHFuncletEntry();
1752         if (!IsSEH)
1753           UnwindDests.back().first->setIsEHScopeEntry();
1754       }
1755       NewEHPadBB = CatchSwitch->getUnwindDest();
1756     } else {
1757       continue;
1758     }
1759 
1760     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1761     if (BPI && NewEHPadBB)
1762       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1763     EHPadBB = NewEHPadBB;
1764   }
1765 }
1766 
1767 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1768   // Update successor info.
1769   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1770   auto UnwindDest = I.getUnwindDest();
1771   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1772   BranchProbability UnwindDestProb =
1773       (BPI && UnwindDest)
1774           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1775           : BranchProbability::getZero();
1776   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1777   for (auto &UnwindDest : UnwindDests) {
1778     UnwindDest.first->setIsEHPad();
1779     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1780   }
1781   FuncInfo.MBB->normalizeSuccProbs();
1782 
1783   // Create the terminator node.
1784   SDValue Ret =
1785       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1786   DAG.setRoot(Ret);
1787 }
1788 
1789 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1790   report_fatal_error("visitCatchSwitch not yet implemented!");
1791 }
1792 
1793 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1795   auto &DL = DAG.getDataLayout();
1796   SDValue Chain = getControlRoot();
1797   SmallVector<ISD::OutputArg, 8> Outs;
1798   SmallVector<SDValue, 8> OutVals;
1799 
1800   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1801   // lower
1802   //
1803   //   %val = call <ty> @llvm.experimental.deoptimize()
1804   //   ret <ty> %val
1805   //
1806   // differently.
1807   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1808     LowerDeoptimizingReturn();
1809     return;
1810   }
1811 
1812   if (!FuncInfo.CanLowerReturn) {
1813     unsigned DemoteReg = FuncInfo.DemoteRegister;
1814     const Function *F = I.getParent()->getParent();
1815 
1816     // Emit a store of the return value through the virtual register.
1817     // Leave Outs empty so that LowerReturn won't try to load return
1818     // registers the usual way.
1819     SmallVector<EVT, 1> PtrValueVTs;
1820     ComputeValueVTs(TLI, DL,
1821                     F->getReturnType()->getPointerTo(
1822                         DAG.getDataLayout().getAllocaAddrSpace()),
1823                     PtrValueVTs);
1824 
1825     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1826                                         DemoteReg, PtrValueVTs[0]);
1827     SDValue RetOp = getValue(I.getOperand(0));
1828 
1829     SmallVector<EVT, 4> ValueVTs, MemVTs;
1830     SmallVector<uint64_t, 4> Offsets;
1831     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1832                     &Offsets);
1833     unsigned NumValues = ValueVTs.size();
1834 
1835     SmallVector<SDValue, 4> Chains(NumValues);
1836     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
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(
1846           Chain, getCurSDLoc(), Val,
1847           // FIXME: better loc info would be nice.
1848           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1849           commonAlignment(BaseAlign, Offsets[i]));
1850     }
1851 
1852     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1853                         MVT::Other, Chains);
1854   } else if (I.getNumOperands() != 0) {
1855     SmallVector<EVT, 4> ValueVTs;
1856     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1857     unsigned NumValues = ValueVTs.size();
1858     if (NumValues) {
1859       SDValue RetOp = getValue(I.getOperand(0));
1860 
1861       const Function *F = I.getParent()->getParent();
1862 
1863       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1864           I.getOperand(0)->getType(), F->getCallingConv(),
1865           /*IsVarArg*/ false);
1866 
1867       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1868       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1869                                           Attribute::SExt))
1870         ExtendKind = ISD::SIGN_EXTEND;
1871       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1872                                                Attribute::ZExt))
1873         ExtendKind = ISD::ZERO_EXTEND;
1874 
1875       LLVMContext &Context = F->getContext();
1876       bool RetInReg = F->getAttributes().hasAttribute(
1877           AttributeList::ReturnIndex, Attribute::InReg);
1878 
1879       for (unsigned j = 0; j != NumValues; ++j) {
1880         EVT VT = ValueVTs[j];
1881 
1882         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1883           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1884 
1885         CallingConv::ID CC = F->getCallingConv();
1886 
1887         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1888         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1889         SmallVector<SDValue, 4> Parts(NumParts);
1890         getCopyToParts(DAG, getCurSDLoc(),
1891                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1892                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1893 
1894         // 'inreg' on function refers to return value
1895         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1896         if (RetInReg)
1897           Flags.setInReg();
1898 
1899         if (I.getOperand(0)->getType()->isPointerTy()) {
1900           Flags.setPointer();
1901           Flags.setPointerAddrSpace(
1902               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1903         }
1904 
1905         if (NeedsRegBlock) {
1906           Flags.setInConsecutiveRegs();
1907           if (j == NumValues - 1)
1908             Flags.setInConsecutiveRegsLast();
1909         }
1910 
1911         // Propagate extension type if any
1912         if (ExtendKind == ISD::SIGN_EXTEND)
1913           Flags.setSExt();
1914         else if (ExtendKind == ISD::ZERO_EXTEND)
1915           Flags.setZExt();
1916 
1917         for (unsigned i = 0; i < NumParts; ++i) {
1918           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1919                                         VT, /*isfixed=*/true, 0, 0));
1920           OutVals.push_back(Parts[i]);
1921         }
1922       }
1923     }
1924   }
1925 
1926   // Push in swifterror virtual register as the last element of Outs. This makes
1927   // sure swifterror virtual register will be returned in the swifterror
1928   // physical register.
1929   const Function *F = I.getParent()->getParent();
1930   if (TLI.supportSwiftError() &&
1931       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1932     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1933     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1934     Flags.setSwiftError();
1935     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1936                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1937                                   true /*isfixed*/, 1 /*origidx*/,
1938                                   0 /*partOffs*/));
1939     // Create SDNode for the swifterror virtual register.
1940     OutVals.push_back(
1941         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1942                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1943                         EVT(TLI.getPointerTy(DL))));
1944   }
1945 
1946   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1947   CallingConv::ID CallConv =
1948     DAG.getMachineFunction().getFunction().getCallingConv();
1949   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1950       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1951 
1952   // Verify that the target's LowerReturn behaved as expected.
1953   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1954          "LowerReturn didn't return a valid chain!");
1955 
1956   // Update the DAG with the new chain value resulting from return lowering.
1957   DAG.setRoot(Chain);
1958 }
1959 
1960 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1961 /// created for it, emit nodes to copy the value into the virtual
1962 /// registers.
1963 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1964   // Skip empty types
1965   if (V->getType()->isEmptyTy())
1966     return;
1967 
1968   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1969   if (VMI != FuncInfo.ValueMap.end()) {
1970     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1971     CopyValueToVirtualRegister(V, VMI->second);
1972   }
1973 }
1974 
1975 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1976 /// the current basic block, add it to ValueMap now so that we'll get a
1977 /// CopyTo/FromReg.
1978 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1979   // No need to export constants.
1980   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1981 
1982   // Already exported?
1983   if (FuncInfo.isExportedInst(V)) return;
1984 
1985   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1986   CopyValueToVirtualRegister(V, Reg);
1987 }
1988 
1989 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1990                                                      const BasicBlock *FromBB) {
1991   // The operands of the setcc have to be in this block.  We don't know
1992   // how to export them from some other block.
1993   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1994     // Can export from current BB.
1995     if (VI->getParent() == FromBB)
1996       return true;
1997 
1998     // Is already exported, noop.
1999     return FuncInfo.isExportedInst(V);
2000   }
2001 
2002   // If this is an argument, we can export it if the BB is the entry block or
2003   // if it is already exported.
2004   if (isa<Argument>(V)) {
2005     if (FromBB == &FromBB->getParent()->getEntryBlock())
2006       return true;
2007 
2008     // Otherwise, can only export this if it is already exported.
2009     return FuncInfo.isExportedInst(V);
2010   }
2011 
2012   // Otherwise, constants can always be exported.
2013   return true;
2014 }
2015 
2016 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2017 BranchProbability
2018 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2019                                         const MachineBasicBlock *Dst) const {
2020   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2021   const BasicBlock *SrcBB = Src->getBasicBlock();
2022   const BasicBlock *DstBB = Dst->getBasicBlock();
2023   if (!BPI) {
2024     // If BPI is not available, set the default probability as 1 / N, where N is
2025     // the number of successors.
2026     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2027     return BranchProbability(1, SuccSize);
2028   }
2029   return BPI->getEdgeProbability(SrcBB, DstBB);
2030 }
2031 
2032 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2033                                                MachineBasicBlock *Dst,
2034                                                BranchProbability Prob) {
2035   if (!FuncInfo.BPI)
2036     Src->addSuccessorWithoutProb(Dst);
2037   else {
2038     if (Prob.isUnknown())
2039       Prob = getEdgeProbability(Src, Dst);
2040     Src->addSuccessor(Dst, Prob);
2041   }
2042 }
2043 
2044 static bool InBlock(const Value *V, const BasicBlock *BB) {
2045   if (const Instruction *I = dyn_cast<Instruction>(V))
2046     return I->getParent() == BB;
2047   return true;
2048 }
2049 
2050 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2051 /// This function emits a branch and is used at the leaves of an OR or an
2052 /// AND operator tree.
2053 void
2054 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2055                                                   MachineBasicBlock *TBB,
2056                                                   MachineBasicBlock *FBB,
2057                                                   MachineBasicBlock *CurBB,
2058                                                   MachineBasicBlock *SwitchBB,
2059                                                   BranchProbability TProb,
2060                                                   BranchProbability FProb,
2061                                                   bool InvertCond) {
2062   const BasicBlock *BB = CurBB->getBasicBlock();
2063 
2064   // If the leaf of the tree is a comparison, merge the condition into
2065   // the caseblock.
2066   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2067     // The operands of the cmp have to be in this block.  We don't know
2068     // how to export them from some other block.  If this is the first block
2069     // of the sequence, no exporting is needed.
2070     if (CurBB == SwitchBB ||
2071         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2072          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2073       ISD::CondCode Condition;
2074       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2075         ICmpInst::Predicate Pred =
2076             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2077         Condition = getICmpCondCode(Pred);
2078       } else {
2079         const FCmpInst *FC = cast<FCmpInst>(Cond);
2080         FCmpInst::Predicate Pred =
2081             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2082         Condition = getFCmpCondCode(Pred);
2083         if (TM.Options.NoNaNsFPMath)
2084           Condition = getFCmpCodeWithoutNaN(Condition);
2085       }
2086 
2087       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2088                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2089       SL->SwitchCases.push_back(CB);
2090       return;
2091     }
2092   }
2093 
2094   // Create a CaseBlock record representing this branch.
2095   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2096   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2097                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2098   SL->SwitchCases.push_back(CB);
2099 }
2100 
2101 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2102                                                MachineBasicBlock *TBB,
2103                                                MachineBasicBlock *FBB,
2104                                                MachineBasicBlock *CurBB,
2105                                                MachineBasicBlock *SwitchBB,
2106                                                Instruction::BinaryOps Opc,
2107                                                BranchProbability TProb,
2108                                                BranchProbability FProb,
2109                                                bool InvertCond) {
2110   // Skip over not part of the tree and remember to invert op and operands at
2111   // next level.
2112   Value *NotCond;
2113   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2114       InBlock(NotCond, CurBB->getBasicBlock())) {
2115     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2116                          !InvertCond);
2117     return;
2118   }
2119 
2120   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2121   // Compute the effective opcode for Cond, taking into account whether it needs
2122   // to be inverted, e.g.
2123   //   and (not (or A, B)), C
2124   // gets lowered as
2125   //   and (and (not A, not B), C)
2126   unsigned BOpc = 0;
2127   if (BOp) {
2128     BOpc = BOp->getOpcode();
2129     if (InvertCond) {
2130       if (BOpc == Instruction::And)
2131         BOpc = Instruction::Or;
2132       else if (BOpc == Instruction::Or)
2133         BOpc = Instruction::And;
2134     }
2135   }
2136 
2137   // If this node is not part of the or/and tree, emit it as a branch.
2138   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2139       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2140       BOp->getParent() != CurBB->getBasicBlock() ||
2141       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2142       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2143     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2144                                  TProb, FProb, InvertCond);
2145     return;
2146   }
2147 
2148   //  Create TmpBB after CurBB.
2149   MachineFunction::iterator BBI(CurBB);
2150   MachineFunction &MF = DAG.getMachineFunction();
2151   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2152   CurBB->getParent()->insert(++BBI, TmpBB);
2153 
2154   if (Opc == Instruction::Or) {
2155     // Codegen X | Y as:
2156     // BB1:
2157     //   jmp_if_X TBB
2158     //   jmp TmpBB
2159     // TmpBB:
2160     //   jmp_if_Y TBB
2161     //   jmp FBB
2162     //
2163 
2164     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2165     // The requirement is that
2166     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2167     //     = TrueProb for original BB.
2168     // Assuming the original probabilities are A and B, one choice is to set
2169     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2170     // A/(1+B) and 2B/(1+B). This choice assumes that
2171     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2172     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2173     // TmpBB, but the math is more complicated.
2174 
2175     auto NewTrueProb = TProb / 2;
2176     auto NewFalseProb = TProb / 2 + FProb;
2177     // Emit the LHS condition.
2178     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2179                          NewTrueProb, NewFalseProb, InvertCond);
2180 
2181     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2182     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2183     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2184     // Emit the RHS condition into TmpBB.
2185     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2186                          Probs[0], Probs[1], InvertCond);
2187   } else {
2188     assert(Opc == Instruction::And && "Unknown merge op!");
2189     // Codegen X & Y as:
2190     // BB1:
2191     //   jmp_if_X TmpBB
2192     //   jmp FBB
2193     // TmpBB:
2194     //   jmp_if_Y TBB
2195     //   jmp FBB
2196     //
2197     //  This requires creation of TmpBB after CurBB.
2198 
2199     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2200     // The requirement is that
2201     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2202     //     = FalseProb for original BB.
2203     // Assuming the original probabilities are A and B, one choice is to set
2204     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2205     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2206     // TrueProb for BB1 * FalseProb for TmpBB.
2207 
2208     auto NewTrueProb = TProb + FProb / 2;
2209     auto NewFalseProb = FProb / 2;
2210     // Emit the LHS condition.
2211     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2212                          NewTrueProb, NewFalseProb, InvertCond);
2213 
2214     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2215     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2216     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2217     // Emit the RHS condition into TmpBB.
2218     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2219                          Probs[0], Probs[1], InvertCond);
2220   }
2221 }
2222 
2223 /// If the set of cases should be emitted as a series of branches, return true.
2224 /// If we should emit this as a bunch of and/or'd together conditions, return
2225 /// false.
2226 bool
2227 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2228   if (Cases.size() != 2) return true;
2229 
2230   // If this is two comparisons of the same values or'd or and'd together, they
2231   // will get folded into a single comparison, so don't emit two blocks.
2232   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2233        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2234       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2235        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2236     return false;
2237   }
2238 
2239   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2240   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2241   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2242       Cases[0].CC == Cases[1].CC &&
2243       isa<Constant>(Cases[0].CmpRHS) &&
2244       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2245     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2246       return false;
2247     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2248       return false;
2249   }
2250 
2251   return true;
2252 }
2253 
2254 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2255   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2256 
2257   // Update machine-CFG edges.
2258   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2259 
2260   if (I.isUnconditional()) {
2261     // Update machine-CFG edges.
2262     BrMBB->addSuccessor(Succ0MBB);
2263 
2264     // If this is not a fall-through branch or optimizations are switched off,
2265     // emit the branch.
2266     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2267       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2268                               MVT::Other, getControlRoot(),
2269                               DAG.getBasicBlock(Succ0MBB)));
2270 
2271     return;
2272   }
2273 
2274   // If this condition is one of the special cases we handle, do special stuff
2275   // now.
2276   const Value *CondVal = I.getCondition();
2277   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2278 
2279   // If this is a series of conditions that are or'd or and'd together, emit
2280   // this as a sequence of branches instead of setcc's with and/or operations.
2281   // As long as jumps are not expensive, this should improve performance.
2282   // For example, instead of something like:
2283   //     cmp A, B
2284   //     C = seteq
2285   //     cmp D, E
2286   //     F = setle
2287   //     or C, F
2288   //     jnz foo
2289   // Emit:
2290   //     cmp A, B
2291   //     je foo
2292   //     cmp D, E
2293   //     jle foo
2294   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2295     Instruction::BinaryOps Opcode = BOp->getOpcode();
2296     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2297         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2298         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2299       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2300                            Opcode,
2301                            getEdgeProbability(BrMBB, Succ0MBB),
2302                            getEdgeProbability(BrMBB, Succ1MBB),
2303                            /*InvertCond=*/false);
2304       // If the compares in later blocks need to use values not currently
2305       // exported from this block, export them now.  This block should always
2306       // be the first entry.
2307       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2308 
2309       // Allow some cases to be rejected.
2310       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2311         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2312           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2313           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2314         }
2315 
2316         // Emit the branch for this block.
2317         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2318         SL->SwitchCases.erase(SL->SwitchCases.begin());
2319         return;
2320       }
2321 
2322       // Okay, we decided not to do this, remove any inserted MBB's and clear
2323       // SwitchCases.
2324       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2325         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2326 
2327       SL->SwitchCases.clear();
2328     }
2329   }
2330 
2331   // Create a CaseBlock record representing this branch.
2332   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2333                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2334 
2335   // Use visitSwitchCase to actually insert the fast branch sequence for this
2336   // cond branch.
2337   visitSwitchCase(CB, BrMBB);
2338 }
2339 
2340 /// visitSwitchCase - Emits the necessary code to represent a single node in
2341 /// the binary search tree resulting from lowering a switch instruction.
2342 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2343                                           MachineBasicBlock *SwitchBB) {
2344   SDValue Cond;
2345   SDValue CondLHS = getValue(CB.CmpLHS);
2346   SDLoc dl = CB.DL;
2347 
2348   if (CB.CC == ISD::SETTRUE) {
2349     // Branch or fall through to TrueBB.
2350     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2351     SwitchBB->normalizeSuccProbs();
2352     if (CB.TrueBB != NextBlock(SwitchBB)) {
2353       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2354                               DAG.getBasicBlock(CB.TrueBB)));
2355     }
2356     return;
2357   }
2358 
2359   auto &TLI = DAG.getTargetLoweringInfo();
2360   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2361 
2362   // Build the setcc now.
2363   if (!CB.CmpMHS) {
2364     // Fold "(X == true)" to X and "(X == false)" to !X to
2365     // handle common cases produced by branch lowering.
2366     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2367         CB.CC == ISD::SETEQ)
2368       Cond = CondLHS;
2369     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2370              CB.CC == ISD::SETEQ) {
2371       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2372       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2373     } else {
2374       SDValue CondRHS = getValue(CB.CmpRHS);
2375 
2376       // If a pointer's DAG type is larger than its memory type then the DAG
2377       // values are zero-extended. This breaks signed comparisons so truncate
2378       // back to the underlying type before doing the compare.
2379       if (CondLHS.getValueType() != MemVT) {
2380         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2381         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2382       }
2383       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2384     }
2385   } else {
2386     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2387 
2388     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2389     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2390 
2391     SDValue CmpOp = getValue(CB.CmpMHS);
2392     EVT VT = CmpOp.getValueType();
2393 
2394     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2395       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2396                           ISD::SETLE);
2397     } else {
2398       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2399                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2400       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2401                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2402     }
2403   }
2404 
2405   // Update successor info
2406   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2407   // TrueBB and FalseBB are always different unless the incoming IR is
2408   // degenerate. This only happens when running llc on weird IR.
2409   if (CB.TrueBB != CB.FalseBB)
2410     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2411   SwitchBB->normalizeSuccProbs();
2412 
2413   // If the lhs block is the next block, invert the condition so that we can
2414   // fall through to the lhs instead of the rhs block.
2415   if (CB.TrueBB == NextBlock(SwitchBB)) {
2416     std::swap(CB.TrueBB, CB.FalseBB);
2417     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2418     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2419   }
2420 
2421   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2422                                MVT::Other, getControlRoot(), Cond,
2423                                DAG.getBasicBlock(CB.TrueBB));
2424 
2425   // Insert the false branch. Do this even if it's a fall through branch,
2426   // this makes it easier to do DAG optimizations which require inverting
2427   // the branch condition.
2428   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2429                        DAG.getBasicBlock(CB.FalseBB));
2430 
2431   DAG.setRoot(BrCond);
2432 }
2433 
2434 /// visitJumpTable - Emit JumpTable node in the current MBB
2435 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2436   // Emit the code for the jump table
2437   assert(JT.Reg != -1U && "Should lower JT Header first!");
2438   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2439   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2440                                      JT.Reg, PTy);
2441   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2442   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2443                                     MVT::Other, Index.getValue(1),
2444                                     Table, Index);
2445   DAG.setRoot(BrJumpTable);
2446 }
2447 
2448 /// visitJumpTableHeader - This function emits necessary code to produce index
2449 /// in the JumpTable from switch case.
2450 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2451                                                JumpTableHeader &JTH,
2452                                                MachineBasicBlock *SwitchBB) {
2453   SDLoc dl = getCurSDLoc();
2454 
2455   // Subtract the lowest switch case value from the value being switched on.
2456   SDValue SwitchOp = getValue(JTH.SValue);
2457   EVT VT = SwitchOp.getValueType();
2458   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2459                             DAG.getConstant(JTH.First, dl, VT));
2460 
2461   // The SDNode we just created, which holds the value being switched on minus
2462   // the smallest case value, needs to be copied to a virtual register so it
2463   // can be used as an index into the jump table in a subsequent basic block.
2464   // This value may be smaller or larger than the target's pointer type, and
2465   // therefore require extension or truncating.
2466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2467   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2468 
2469   unsigned JumpTableReg =
2470       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2471   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2472                                     JumpTableReg, SwitchOp);
2473   JT.Reg = JumpTableReg;
2474 
2475   if (!JTH.OmitRangeCheck) {
2476     // Emit the range check for the jump table, and branch to the default block
2477     // for the switch statement if the value being switched on exceeds the
2478     // largest case in the switch.
2479     SDValue CMP = DAG.getSetCC(
2480         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2481                                    Sub.getValueType()),
2482         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2483 
2484     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2485                                  MVT::Other, CopyTo, CMP,
2486                                  DAG.getBasicBlock(JT.Default));
2487 
2488     // Avoid emitting unnecessary branches to the next block.
2489     if (JT.MBB != NextBlock(SwitchBB))
2490       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2491                            DAG.getBasicBlock(JT.MBB));
2492 
2493     DAG.setRoot(BrCond);
2494   } else {
2495     // Avoid emitting unnecessary branches to the next block.
2496     if (JT.MBB != NextBlock(SwitchBB))
2497       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2498                               DAG.getBasicBlock(JT.MBB)));
2499     else
2500       DAG.setRoot(CopyTo);
2501   }
2502 }
2503 
2504 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2505 /// variable if there exists one.
2506 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2507                                  SDValue &Chain) {
2508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2509   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2510   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2511   MachineFunction &MF = DAG.getMachineFunction();
2512   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2513   MachineSDNode *Node =
2514       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2515   if (Global) {
2516     MachinePointerInfo MPInfo(Global);
2517     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2518                  MachineMemOperand::MODereferenceable;
2519     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2520         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2521     DAG.setNodeMemRefs(Node, {MemRef});
2522   }
2523   if (PtrTy != PtrMemTy)
2524     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2525   return SDValue(Node, 0);
2526 }
2527 
2528 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2529 /// tail spliced into a stack protector check success bb.
2530 ///
2531 /// For a high level explanation of how this fits into the stack protector
2532 /// generation see the comment on the declaration of class
2533 /// StackProtectorDescriptor.
2534 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2535                                                   MachineBasicBlock *ParentBB) {
2536 
2537   // First create the loads to the guard/stack slot for the comparison.
2538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2539   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2540   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2541 
2542   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2543   int FI = MFI.getStackProtectorIndex();
2544 
2545   SDValue Guard;
2546   SDLoc dl = getCurSDLoc();
2547   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2548   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2549   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2550 
2551   // Generate code to load the content of the guard slot.
2552   SDValue GuardVal = DAG.getLoad(
2553       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2554       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2555       MachineMemOperand::MOVolatile);
2556 
2557   if (TLI.useStackGuardXorFP())
2558     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2559 
2560   // Retrieve guard check function, nullptr if instrumentation is inlined.
2561   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2562     // The target provides a guard check function to validate the guard value.
2563     // Generate a call to that function with the content of the guard slot as
2564     // argument.
2565     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2566     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2567 
2568     TargetLowering::ArgListTy Args;
2569     TargetLowering::ArgListEntry Entry;
2570     Entry.Node = GuardVal;
2571     Entry.Ty = FnTy->getParamType(0);
2572     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2573       Entry.IsInReg = true;
2574     Args.push_back(Entry);
2575 
2576     TargetLowering::CallLoweringInfo CLI(DAG);
2577     CLI.setDebugLoc(getCurSDLoc())
2578         .setChain(DAG.getEntryNode())
2579         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2580                    getValue(GuardCheckFn), std::move(Args));
2581 
2582     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2583     DAG.setRoot(Result.second);
2584     return;
2585   }
2586 
2587   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2588   // Otherwise, emit a volatile load to retrieve the stack guard value.
2589   SDValue Chain = DAG.getEntryNode();
2590   if (TLI.useLoadStackGuardNode()) {
2591     Guard = getLoadStackGuard(DAG, dl, Chain);
2592   } else {
2593     const Value *IRGuard = TLI.getSDagStackGuard(M);
2594     SDValue GuardPtr = getValue(IRGuard);
2595 
2596     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2597                         MachinePointerInfo(IRGuard, 0), Align,
2598                         MachineMemOperand::MOVolatile);
2599   }
2600 
2601   // Perform the comparison via a getsetcc.
2602   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2603                                                         *DAG.getContext(),
2604                                                         Guard.getValueType()),
2605                              Guard, GuardVal, ISD::SETNE);
2606 
2607   // If the guard/stackslot do not equal, branch to failure MBB.
2608   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2609                                MVT::Other, GuardVal.getOperand(0),
2610                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2611   // Otherwise branch to success MBB.
2612   SDValue Br = DAG.getNode(ISD::BR, dl,
2613                            MVT::Other, BrCond,
2614                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2615 
2616   DAG.setRoot(Br);
2617 }
2618 
2619 /// Codegen the failure basic block for a stack protector check.
2620 ///
2621 /// A failure stack protector machine basic block consists simply of a call to
2622 /// __stack_chk_fail().
2623 ///
2624 /// For a high level explanation of how this fits into the stack protector
2625 /// generation see the comment on the declaration of class
2626 /// StackProtectorDescriptor.
2627 void
2628 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2630   TargetLowering::MakeLibCallOptions CallOptions;
2631   CallOptions.setDiscardResult(true);
2632   SDValue Chain =
2633       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2634                       None, CallOptions, getCurSDLoc()).second;
2635   // On PS4, the "return address" must still be within the calling function,
2636   // even if it's at the very end, so emit an explicit TRAP here.
2637   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2638   if (TM.getTargetTriple().isPS4CPU())
2639     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2640 
2641   DAG.setRoot(Chain);
2642 }
2643 
2644 /// visitBitTestHeader - This function emits necessary code to produce value
2645 /// suitable for "bit tests"
2646 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2647                                              MachineBasicBlock *SwitchBB) {
2648   SDLoc dl = getCurSDLoc();
2649 
2650   // Subtract the minimum value.
2651   SDValue SwitchOp = getValue(B.SValue);
2652   EVT VT = SwitchOp.getValueType();
2653   SDValue RangeSub =
2654       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2655 
2656   // Determine the type of the test operands.
2657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2658   bool UsePtrType = false;
2659   if (!TLI.isTypeLegal(VT)) {
2660     UsePtrType = true;
2661   } else {
2662     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2663       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2664         // Switch table case range are encoded into series of masks.
2665         // Just use pointer type, it's guaranteed to fit.
2666         UsePtrType = true;
2667         break;
2668       }
2669   }
2670   SDValue Sub = RangeSub;
2671   if (UsePtrType) {
2672     VT = TLI.getPointerTy(DAG.getDataLayout());
2673     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2674   }
2675 
2676   B.RegVT = VT.getSimpleVT();
2677   B.Reg = FuncInfo.CreateReg(B.RegVT);
2678   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2679 
2680   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2681 
2682   if (!B.OmitRangeCheck)
2683     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2684   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2685   SwitchBB->normalizeSuccProbs();
2686 
2687   SDValue Root = CopyTo;
2688   if (!B.OmitRangeCheck) {
2689     // Conditional branch to the default block.
2690     SDValue RangeCmp = DAG.getSetCC(dl,
2691         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2692                                RangeSub.getValueType()),
2693         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2694         ISD::SETUGT);
2695 
2696     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2697                        DAG.getBasicBlock(B.Default));
2698   }
2699 
2700   // Avoid emitting unnecessary branches to the next block.
2701   if (MBB != NextBlock(SwitchBB))
2702     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2703 
2704   DAG.setRoot(Root);
2705 }
2706 
2707 /// visitBitTestCase - this function produces one "bit test"
2708 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2709                                            MachineBasicBlock* NextMBB,
2710                                            BranchProbability BranchProbToNext,
2711                                            unsigned Reg,
2712                                            BitTestCase &B,
2713                                            MachineBasicBlock *SwitchBB) {
2714   SDLoc dl = getCurSDLoc();
2715   MVT VT = BB.RegVT;
2716   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2717   SDValue Cmp;
2718   unsigned PopCount = countPopulation(B.Mask);
2719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2720   if (PopCount == 1) {
2721     // Testing for a single bit; just compare the shift count with what it
2722     // would need to be to shift a 1 bit in that position.
2723     Cmp = DAG.getSetCC(
2724         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2725         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2726         ISD::SETEQ);
2727   } else if (PopCount == BB.Range) {
2728     // There is only one zero bit in the range, test for it directly.
2729     Cmp = DAG.getSetCC(
2730         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2731         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2732         ISD::SETNE);
2733   } else {
2734     // Make desired shift
2735     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2736                                     DAG.getConstant(1, dl, VT), ShiftOp);
2737 
2738     // Emit bit tests and jumps
2739     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2740                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2741     Cmp = DAG.getSetCC(
2742         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2743         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2744   }
2745 
2746   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2747   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2748   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2749   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2750   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2751   // one as they are relative probabilities (and thus work more like weights),
2752   // and hence we need to normalize them to let the sum of them become one.
2753   SwitchBB->normalizeSuccProbs();
2754 
2755   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2756                               MVT::Other, getControlRoot(),
2757                               Cmp, DAG.getBasicBlock(B.TargetBB));
2758 
2759   // Avoid emitting unnecessary branches to the next block.
2760   if (NextMBB != NextBlock(SwitchBB))
2761     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2762                         DAG.getBasicBlock(NextMBB));
2763 
2764   DAG.setRoot(BrAnd);
2765 }
2766 
2767 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2768   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2769 
2770   // Retrieve successors. Look through artificial IR level blocks like
2771   // catchswitch for successors.
2772   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2773   const BasicBlock *EHPadBB = I.getSuccessor(1);
2774 
2775   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2776   // have to do anything here to lower funclet bundles.
2777   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2778                                         LLVMContext::OB_funclet,
2779                                         LLVMContext::OB_cfguardtarget}) &&
2780          "Cannot lower invokes with arbitrary operand bundles yet!");
2781 
2782   const Value *Callee(I.getCalledOperand());
2783   const Function *Fn = dyn_cast<Function>(Callee);
2784   if (isa<InlineAsm>(Callee))
2785     visitInlineAsm(I);
2786   else if (Fn && Fn->isIntrinsic()) {
2787     switch (Fn->getIntrinsicID()) {
2788     default:
2789       llvm_unreachable("Cannot invoke this intrinsic");
2790     case Intrinsic::donothing:
2791       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2792       break;
2793     case Intrinsic::experimental_patchpoint_void:
2794     case Intrinsic::experimental_patchpoint_i64:
2795       visitPatchpoint(I, EHPadBB);
2796       break;
2797     case Intrinsic::experimental_gc_statepoint:
2798       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2799       break;
2800     case Intrinsic::wasm_rethrow_in_catch: {
2801       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2802       // special because it can be invoked, so we manually lower it to a DAG
2803       // node here.
2804       SmallVector<SDValue, 8> Ops;
2805       Ops.push_back(getRoot()); // inchain
2806       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2807       Ops.push_back(
2808           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2809                                 TLI.getPointerTy(DAG.getDataLayout())));
2810       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2811       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2812       break;
2813     }
2814     }
2815   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2816     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2817     // Eventually we will support lowering the @llvm.experimental.deoptimize
2818     // intrinsic, and right now there are no plans to support other intrinsics
2819     // with deopt state.
2820     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2821   } else {
2822     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2823   }
2824 
2825   // If the value of the invoke is used outside of its defining block, make it
2826   // available as a virtual register.
2827   // We already took care of the exported value for the statepoint instruction
2828   // during call to the LowerStatepoint.
2829   if (!isStatepoint(I)) {
2830     CopyToExportRegsIfNeeded(&I);
2831   }
2832 
2833   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2834   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2835   BranchProbability EHPadBBProb =
2836       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2837           : BranchProbability::getZero();
2838   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2839 
2840   // Update successor info.
2841   addSuccessorWithProb(InvokeMBB, Return);
2842   for (auto &UnwindDest : UnwindDests) {
2843     UnwindDest.first->setIsEHPad();
2844     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2845   }
2846   InvokeMBB->normalizeSuccProbs();
2847 
2848   // Drop into normal successor.
2849   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2850                           DAG.getBasicBlock(Return)));
2851 }
2852 
2853 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2854   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2855 
2856   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2857   // have to do anything here to lower funclet bundles.
2858   assert(!I.hasOperandBundlesOtherThan(
2859              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2860          "Cannot lower callbrs with arbitrary operand bundles yet!");
2861 
2862   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2863   visitInlineAsm(I);
2864   CopyToExportRegsIfNeeded(&I);
2865 
2866   // Retrieve successors.
2867   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2868   Return->setInlineAsmBrDefaultTarget();
2869 
2870   // Update successor info.
2871   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2872   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2873     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2874     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2875     CallBrMBB->addInlineAsmBrIndirectTarget(Target);
2876   }
2877   CallBrMBB->normalizeSuccProbs();
2878 
2879   // Drop into default successor.
2880   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2881                           MVT::Other, getControlRoot(),
2882                           DAG.getBasicBlock(Return)));
2883 }
2884 
2885 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2886   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2887 }
2888 
2889 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2890   assert(FuncInfo.MBB->isEHPad() &&
2891          "Call to landingpad not in landing pad!");
2892 
2893   // If there aren't registers to copy the values into (e.g., during SjLj
2894   // exceptions), then don't bother to create these DAG nodes.
2895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2896   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2897   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2898       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2899     return;
2900 
2901   // If landingpad's return type is token type, we don't create DAG nodes
2902   // for its exception pointer and selector value. The extraction of exception
2903   // pointer or selector value from token type landingpads is not currently
2904   // supported.
2905   if (LP.getType()->isTokenTy())
2906     return;
2907 
2908   SmallVector<EVT, 2> ValueVTs;
2909   SDLoc dl = getCurSDLoc();
2910   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2911   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2912 
2913   // Get the two live-in registers as SDValues. The physregs have already been
2914   // copied into virtual registers.
2915   SDValue Ops[2];
2916   if (FuncInfo.ExceptionPointerVirtReg) {
2917     Ops[0] = DAG.getZExtOrTrunc(
2918         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2919                            FuncInfo.ExceptionPointerVirtReg,
2920                            TLI.getPointerTy(DAG.getDataLayout())),
2921         dl, ValueVTs[0]);
2922   } else {
2923     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2924   }
2925   Ops[1] = DAG.getZExtOrTrunc(
2926       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2927                          FuncInfo.ExceptionSelectorVirtReg,
2928                          TLI.getPointerTy(DAG.getDataLayout())),
2929       dl, ValueVTs[1]);
2930 
2931   // Merge into one.
2932   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2933                             DAG.getVTList(ValueVTs), Ops);
2934   setValue(&LP, Res);
2935 }
2936 
2937 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2938                                            MachineBasicBlock *Last) {
2939   // Update JTCases.
2940   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2941     if (SL->JTCases[i].first.HeaderBB == First)
2942       SL->JTCases[i].first.HeaderBB = Last;
2943 
2944   // Update BitTestCases.
2945   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2946     if (SL->BitTestCases[i].Parent == First)
2947       SL->BitTestCases[i].Parent = Last;
2948 
2949   // SelectionDAGISel::FinishBasicBlock will add PHI operands for the
2950   // successors of the fallthrough block. Here, we add PHI operands for the
2951   // successors of the INLINEASM_BR block itself.
2952   if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR)
2953     for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate)
2954       if (First->isSuccessor(pair.first->getParent()))
2955         MachineInstrBuilder(*First->getParent(), pair.first)
2956             .addReg(pair.second)
2957             .addMBB(First);
2958 }
2959 
2960 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2961   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2962 
2963   // Update machine-CFG edges with unique successors.
2964   SmallSet<BasicBlock*, 32> Done;
2965   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2966     BasicBlock *BB = I.getSuccessor(i);
2967     bool Inserted = Done.insert(BB).second;
2968     if (!Inserted)
2969         continue;
2970 
2971     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2972     addSuccessorWithProb(IndirectBrMBB, Succ);
2973   }
2974   IndirectBrMBB->normalizeSuccProbs();
2975 
2976   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2977                           MVT::Other, getControlRoot(),
2978                           getValue(I.getAddress())));
2979 }
2980 
2981 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2982   if (!DAG.getTarget().Options.TrapUnreachable)
2983     return;
2984 
2985   // We may be able to ignore unreachable behind a noreturn call.
2986   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2987     const BasicBlock &BB = *I.getParent();
2988     if (&I != &BB.front()) {
2989       BasicBlock::const_iterator PredI =
2990         std::prev(BasicBlock::const_iterator(&I));
2991       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2992         if (Call->doesNotReturn())
2993           return;
2994       }
2995     }
2996   }
2997 
2998   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2999 }
3000 
3001 void SelectionDAGBuilder::visitFSub(const User &I) {
3002   // -0.0 - X --> fneg
3003   Type *Ty = I.getType();
3004   if (isa<Constant>(I.getOperand(0)) &&
3005       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3006     SDValue Op2 = getValue(I.getOperand(1));
3007     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3008                              Op2.getValueType(), Op2));
3009     return;
3010   }
3011 
3012   visitBinary(I, ISD::FSUB);
3013 }
3014 
3015 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3016   SDNodeFlags Flags;
3017 
3018   SDValue Op = getValue(I.getOperand(0));
3019   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3020                                     Op, Flags);
3021   setValue(&I, UnNodeValue);
3022 }
3023 
3024 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3025   SDNodeFlags Flags;
3026   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3027     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3028     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3029   }
3030   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3031     Flags.setExact(ExactOp->isExact());
3032   }
3033 
3034   SDValue Op1 = getValue(I.getOperand(0));
3035   SDValue Op2 = getValue(I.getOperand(1));
3036   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3037                                      Op1, Op2, Flags);
3038   setValue(&I, BinNodeValue);
3039 }
3040 
3041 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3042   SDValue Op1 = getValue(I.getOperand(0));
3043   SDValue Op2 = getValue(I.getOperand(1));
3044 
3045   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3046       Op1.getValueType(), DAG.getDataLayout());
3047 
3048   // Coerce the shift amount to the right type if we can.
3049   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3050     unsigned ShiftSize = ShiftTy.getSizeInBits();
3051     unsigned Op2Size = Op2.getValueSizeInBits();
3052     SDLoc DL = getCurSDLoc();
3053 
3054     // If the operand is smaller than the shift count type, promote it.
3055     if (ShiftSize > Op2Size)
3056       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3057 
3058     // If the operand is larger than the shift count type but the shift
3059     // count type has enough bits to represent any shift value, truncate
3060     // it now. This is a common case and it exposes the truncate to
3061     // optimization early.
3062     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3063       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3064     // Otherwise we'll need to temporarily settle for some other convenient
3065     // type.  Type legalization will make adjustments once the shiftee is split.
3066     else
3067       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3068   }
3069 
3070   bool nuw = false;
3071   bool nsw = false;
3072   bool exact = false;
3073 
3074   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3075 
3076     if (const OverflowingBinaryOperator *OFBinOp =
3077             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3078       nuw = OFBinOp->hasNoUnsignedWrap();
3079       nsw = OFBinOp->hasNoSignedWrap();
3080     }
3081     if (const PossiblyExactOperator *ExactOp =
3082             dyn_cast<const PossiblyExactOperator>(&I))
3083       exact = ExactOp->isExact();
3084   }
3085   SDNodeFlags Flags;
3086   Flags.setExact(exact);
3087   Flags.setNoSignedWrap(nsw);
3088   Flags.setNoUnsignedWrap(nuw);
3089   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3090                             Flags);
3091   setValue(&I, Res);
3092 }
3093 
3094 void SelectionDAGBuilder::visitSDiv(const User &I) {
3095   SDValue Op1 = getValue(I.getOperand(0));
3096   SDValue Op2 = getValue(I.getOperand(1));
3097 
3098   SDNodeFlags Flags;
3099   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3100                  cast<PossiblyExactOperator>(&I)->isExact());
3101   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3102                            Op2, Flags));
3103 }
3104 
3105 void SelectionDAGBuilder::visitICmp(const User &I) {
3106   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3107   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3108     predicate = IC->getPredicate();
3109   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3110     predicate = ICmpInst::Predicate(IC->getPredicate());
3111   SDValue Op1 = getValue(I.getOperand(0));
3112   SDValue Op2 = getValue(I.getOperand(1));
3113   ISD::CondCode Opcode = getICmpCondCode(predicate);
3114 
3115   auto &TLI = DAG.getTargetLoweringInfo();
3116   EVT MemVT =
3117       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3118 
3119   // If a pointer's DAG type is larger than its memory type then the DAG values
3120   // are zero-extended. This breaks signed comparisons so truncate back to the
3121   // underlying type before doing the compare.
3122   if (Op1.getValueType() != MemVT) {
3123     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3124     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3125   }
3126 
3127   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3128                                                         I.getType());
3129   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3130 }
3131 
3132 void SelectionDAGBuilder::visitFCmp(const User &I) {
3133   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3134   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3135     predicate = FC->getPredicate();
3136   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3137     predicate = FCmpInst::Predicate(FC->getPredicate());
3138   SDValue Op1 = getValue(I.getOperand(0));
3139   SDValue Op2 = getValue(I.getOperand(1));
3140 
3141   ISD::CondCode Condition = getFCmpCondCode(predicate);
3142   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3143   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3144     Condition = getFCmpCodeWithoutNaN(Condition);
3145 
3146   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3147                                                         I.getType());
3148   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3149 }
3150 
3151 // Check if the condition of the select has one use or two users that are both
3152 // selects with the same condition.
3153 static bool hasOnlySelectUsers(const Value *Cond) {
3154   return llvm::all_of(Cond->users(), [](const Value *V) {
3155     return isa<SelectInst>(V);
3156   });
3157 }
3158 
3159 void SelectionDAGBuilder::visitSelect(const User &I) {
3160   SmallVector<EVT, 4> ValueVTs;
3161   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3162                   ValueVTs);
3163   unsigned NumValues = ValueVTs.size();
3164   if (NumValues == 0) return;
3165 
3166   SmallVector<SDValue, 4> Values(NumValues);
3167   SDValue Cond     = getValue(I.getOperand(0));
3168   SDValue LHSVal   = getValue(I.getOperand(1));
3169   SDValue RHSVal   = getValue(I.getOperand(2));
3170   SmallVector<SDValue, 1> BaseOps(1, Cond);
3171   ISD::NodeType OpCode =
3172       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3173 
3174   bool IsUnaryAbs = false;
3175 
3176   // Min/max matching is only viable if all output VTs are the same.
3177   if (is_splat(ValueVTs)) {
3178     EVT VT = ValueVTs[0];
3179     LLVMContext &Ctx = *DAG.getContext();
3180     auto &TLI = DAG.getTargetLoweringInfo();
3181 
3182     // We care about the legality of the operation after it has been type
3183     // legalized.
3184     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3185       VT = TLI.getTypeToTransformTo(Ctx, VT);
3186 
3187     // If the vselect is legal, assume we want to leave this as a vector setcc +
3188     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3189     // min/max is legal on the scalar type.
3190     bool UseScalarMinMax = VT.isVector() &&
3191       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3192 
3193     Value *LHS, *RHS;
3194     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3195     ISD::NodeType Opc = ISD::DELETED_NODE;
3196     switch (SPR.Flavor) {
3197     case SPF_UMAX:    Opc = ISD::UMAX; break;
3198     case SPF_UMIN:    Opc = ISD::UMIN; break;
3199     case SPF_SMAX:    Opc = ISD::SMAX; break;
3200     case SPF_SMIN:    Opc = ISD::SMIN; break;
3201     case SPF_FMINNUM:
3202       switch (SPR.NaNBehavior) {
3203       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3204       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3205       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3206       case SPNB_RETURNS_ANY: {
3207         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3208           Opc = ISD::FMINNUM;
3209         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3210           Opc = ISD::FMINIMUM;
3211         else if (UseScalarMinMax)
3212           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3213             ISD::FMINNUM : ISD::FMINIMUM;
3214         break;
3215       }
3216       }
3217       break;
3218     case SPF_FMAXNUM:
3219       switch (SPR.NaNBehavior) {
3220       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3221       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3222       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3223       case SPNB_RETURNS_ANY:
3224 
3225         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3226           Opc = ISD::FMAXNUM;
3227         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3228           Opc = ISD::FMAXIMUM;
3229         else if (UseScalarMinMax)
3230           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3231             ISD::FMAXNUM : ISD::FMAXIMUM;
3232         break;
3233       }
3234       break;
3235     case SPF_ABS:
3236       IsUnaryAbs = true;
3237       Opc = ISD::ABS;
3238       break;
3239     case SPF_NABS:
3240       // TODO: we need to produce sub(0, abs(X)).
3241     default: break;
3242     }
3243 
3244     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3245         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3246          (UseScalarMinMax &&
3247           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3248         // If the underlying comparison instruction is used by any other
3249         // instruction, the consumed instructions won't be destroyed, so it is
3250         // not profitable to convert to a min/max.
3251         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3252       OpCode = Opc;
3253       LHSVal = getValue(LHS);
3254       RHSVal = getValue(RHS);
3255       BaseOps.clear();
3256     }
3257 
3258     if (IsUnaryAbs) {
3259       OpCode = Opc;
3260       LHSVal = getValue(LHS);
3261       BaseOps.clear();
3262     }
3263   }
3264 
3265   if (IsUnaryAbs) {
3266     for (unsigned i = 0; i != NumValues; ++i) {
3267       Values[i] =
3268           DAG.getNode(OpCode, getCurSDLoc(),
3269                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3270                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3271     }
3272   } else {
3273     for (unsigned i = 0; i != NumValues; ++i) {
3274       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3275       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3276       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3277       Values[i] = DAG.getNode(
3278           OpCode, getCurSDLoc(),
3279           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3280     }
3281   }
3282 
3283   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3284                            DAG.getVTList(ValueVTs), Values));
3285 }
3286 
3287 void SelectionDAGBuilder::visitTrunc(const User &I) {
3288   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3289   SDValue N = getValue(I.getOperand(0));
3290   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3291                                                         I.getType());
3292   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3293 }
3294 
3295 void SelectionDAGBuilder::visitZExt(const User &I) {
3296   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3297   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3298   SDValue N = getValue(I.getOperand(0));
3299   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3300                                                         I.getType());
3301   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3302 }
3303 
3304 void SelectionDAGBuilder::visitSExt(const User &I) {
3305   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3306   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3307   SDValue N = getValue(I.getOperand(0));
3308   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3309                                                         I.getType());
3310   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3311 }
3312 
3313 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3314   // FPTrunc is never a no-op cast, no need to check
3315   SDValue N = getValue(I.getOperand(0));
3316   SDLoc dl = getCurSDLoc();
3317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3318   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3319   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3320                            DAG.getTargetConstant(
3321                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3322 }
3323 
3324 void SelectionDAGBuilder::visitFPExt(const User &I) {
3325   // FPExt is never a no-op cast, no need to check
3326   SDValue N = getValue(I.getOperand(0));
3327   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3328                                                         I.getType());
3329   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3330 }
3331 
3332 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3333   // FPToUI is never a no-op cast, no need to check
3334   SDValue N = getValue(I.getOperand(0));
3335   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3336                                                         I.getType());
3337   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3338 }
3339 
3340 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3341   // FPToSI is never a no-op cast, no need to check
3342   SDValue N = getValue(I.getOperand(0));
3343   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3344                                                         I.getType());
3345   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3346 }
3347 
3348 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3349   // UIToFP is never a no-op cast, no need to check
3350   SDValue N = getValue(I.getOperand(0));
3351   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3352                                                         I.getType());
3353   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3354 }
3355 
3356 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3357   // SIToFP is never a no-op cast, no need to check
3358   SDValue N = getValue(I.getOperand(0));
3359   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3360                                                         I.getType());
3361   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3362 }
3363 
3364 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3365   // What to do depends on the size of the integer and the size of the pointer.
3366   // We can either truncate, zero extend, or no-op, accordingly.
3367   SDValue N = getValue(I.getOperand(0));
3368   auto &TLI = DAG.getTargetLoweringInfo();
3369   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3370                                                         I.getType());
3371   EVT PtrMemVT =
3372       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3373   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3374   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3375   setValue(&I, N);
3376 }
3377 
3378 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3379   // What to do depends on the size of the integer and the size of the pointer.
3380   // We can either truncate, zero extend, or no-op, accordingly.
3381   SDValue N = getValue(I.getOperand(0));
3382   auto &TLI = DAG.getTargetLoweringInfo();
3383   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3384   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3385   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3386   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3387   setValue(&I, N);
3388 }
3389 
3390 void SelectionDAGBuilder::visitBitCast(const User &I) {
3391   SDValue N = getValue(I.getOperand(0));
3392   SDLoc dl = getCurSDLoc();
3393   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3394                                                         I.getType());
3395 
3396   // BitCast assures us that source and destination are the same size so this is
3397   // either a BITCAST or a no-op.
3398   if (DestVT != N.getValueType())
3399     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3400                              DestVT, N)); // convert types.
3401   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3402   // might fold any kind of constant expression to an integer constant and that
3403   // is not what we are looking for. Only recognize a bitcast of a genuine
3404   // constant integer as an opaque constant.
3405   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3406     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3407                                  /*isOpaque*/true));
3408   else
3409     setValue(&I, N);            // noop cast.
3410 }
3411 
3412 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3414   const Value *SV = I.getOperand(0);
3415   SDValue N = getValue(SV);
3416   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3417 
3418   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3419   unsigned DestAS = I.getType()->getPointerAddressSpace();
3420 
3421   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3422     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3423 
3424   setValue(&I, N);
3425 }
3426 
3427 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3429   SDValue InVec = getValue(I.getOperand(0));
3430   SDValue InVal = getValue(I.getOperand(1));
3431   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3432                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3433   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3434                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3435                            InVec, InVal, InIdx));
3436 }
3437 
3438 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3440   SDValue InVec = getValue(I.getOperand(0));
3441   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3442                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3443   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3444                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3445                            InVec, InIdx));
3446 }
3447 
3448 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3449   SDValue Src1 = getValue(I.getOperand(0));
3450   SDValue Src2 = getValue(I.getOperand(1));
3451   ArrayRef<int> Mask;
3452   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3453     Mask = SVI->getShuffleMask();
3454   else
3455     Mask = cast<ConstantExpr>(I).getShuffleMask();
3456   SDLoc DL = getCurSDLoc();
3457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3458   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3459   EVT SrcVT = Src1.getValueType();
3460   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3461 
3462   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3463       VT.isScalableVector()) {
3464     // Canonical splat form of first element of first input vector.
3465     SDValue FirstElt =
3466         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3467                     DAG.getVectorIdxConstant(0, DL));
3468     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3469     return;
3470   }
3471 
3472   // For now, we only handle splats for scalable vectors.
3473   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3474   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3475   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3476 
3477   unsigned MaskNumElts = Mask.size();
3478 
3479   if (SrcNumElts == MaskNumElts) {
3480     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3481     return;
3482   }
3483 
3484   // Normalize the shuffle vector since mask and vector length don't match.
3485   if (SrcNumElts < MaskNumElts) {
3486     // Mask is longer than the source vectors. We can use concatenate vector to
3487     // make the mask and vectors lengths match.
3488 
3489     if (MaskNumElts % SrcNumElts == 0) {
3490       // Mask length is a multiple of the source vector length.
3491       // Check if the shuffle is some kind of concatenation of the input
3492       // vectors.
3493       unsigned NumConcat = MaskNumElts / SrcNumElts;
3494       bool IsConcat = true;
3495       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3496       for (unsigned i = 0; i != MaskNumElts; ++i) {
3497         int Idx = Mask[i];
3498         if (Idx < 0)
3499           continue;
3500         // Ensure the indices in each SrcVT sized piece are sequential and that
3501         // the same source is used for the whole piece.
3502         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3503             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3504              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3505           IsConcat = false;
3506           break;
3507         }
3508         // Remember which source this index came from.
3509         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3510       }
3511 
3512       // The shuffle is concatenating multiple vectors together. Just emit
3513       // a CONCAT_VECTORS operation.
3514       if (IsConcat) {
3515         SmallVector<SDValue, 8> ConcatOps;
3516         for (auto Src : ConcatSrcs) {
3517           if (Src < 0)
3518             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3519           else if (Src == 0)
3520             ConcatOps.push_back(Src1);
3521           else
3522             ConcatOps.push_back(Src2);
3523         }
3524         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3525         return;
3526       }
3527     }
3528 
3529     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3530     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3531     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3532                                     PaddedMaskNumElts);
3533 
3534     // Pad both vectors with undefs to make them the same length as the mask.
3535     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3536 
3537     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3538     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3539     MOps1[0] = Src1;
3540     MOps2[0] = Src2;
3541 
3542     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3543     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3544 
3545     // Readjust mask for new input vector length.
3546     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3547     for (unsigned i = 0; i != MaskNumElts; ++i) {
3548       int Idx = Mask[i];
3549       if (Idx >= (int)SrcNumElts)
3550         Idx -= SrcNumElts - PaddedMaskNumElts;
3551       MappedOps[i] = Idx;
3552     }
3553 
3554     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3555 
3556     // If the concatenated vector was padded, extract a subvector with the
3557     // correct number of elements.
3558     if (MaskNumElts != PaddedMaskNumElts)
3559       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3560                            DAG.getVectorIdxConstant(0, DL));
3561 
3562     setValue(&I, Result);
3563     return;
3564   }
3565 
3566   if (SrcNumElts > MaskNumElts) {
3567     // Analyze the access pattern of the vector to see if we can extract
3568     // two subvectors and do the shuffle.
3569     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3570     bool CanExtract = true;
3571     for (int Idx : Mask) {
3572       unsigned Input = 0;
3573       if (Idx < 0)
3574         continue;
3575 
3576       if (Idx >= (int)SrcNumElts) {
3577         Input = 1;
3578         Idx -= SrcNumElts;
3579       }
3580 
3581       // If all the indices come from the same MaskNumElts sized portion of
3582       // the sources we can use extract. Also make sure the extract wouldn't
3583       // extract past the end of the source.
3584       int NewStartIdx = alignDown(Idx, MaskNumElts);
3585       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3586           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3587         CanExtract = false;
3588       // Make sure we always update StartIdx as we use it to track if all
3589       // elements are undef.
3590       StartIdx[Input] = NewStartIdx;
3591     }
3592 
3593     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3594       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3595       return;
3596     }
3597     if (CanExtract) {
3598       // Extract appropriate subvector and generate a vector shuffle
3599       for (unsigned Input = 0; Input < 2; ++Input) {
3600         SDValue &Src = Input == 0 ? Src1 : Src2;
3601         if (StartIdx[Input] < 0)
3602           Src = DAG.getUNDEF(VT);
3603         else {
3604           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3605                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3606         }
3607       }
3608 
3609       // Calculate new mask.
3610       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3611       for (int &Idx : MappedOps) {
3612         if (Idx >= (int)SrcNumElts)
3613           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3614         else if (Idx >= 0)
3615           Idx -= StartIdx[0];
3616       }
3617 
3618       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3619       return;
3620     }
3621   }
3622 
3623   // We can't use either concat vectors or extract subvectors so fall back to
3624   // replacing the shuffle with extract and build vector.
3625   // to insert and build vector.
3626   EVT EltVT = VT.getVectorElementType();
3627   SmallVector<SDValue,8> Ops;
3628   for (int Idx : Mask) {
3629     SDValue Res;
3630 
3631     if (Idx < 0) {
3632       Res = DAG.getUNDEF(EltVT);
3633     } else {
3634       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3635       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3636 
3637       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3638                         DAG.getVectorIdxConstant(Idx, DL));
3639     }
3640 
3641     Ops.push_back(Res);
3642   }
3643 
3644   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3645 }
3646 
3647 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3648   ArrayRef<unsigned> Indices;
3649   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3650     Indices = IV->getIndices();
3651   else
3652     Indices = cast<ConstantExpr>(&I)->getIndices();
3653 
3654   const Value *Op0 = I.getOperand(0);
3655   const Value *Op1 = I.getOperand(1);
3656   Type *AggTy = I.getType();
3657   Type *ValTy = Op1->getType();
3658   bool IntoUndef = isa<UndefValue>(Op0);
3659   bool FromUndef = isa<UndefValue>(Op1);
3660 
3661   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3662 
3663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3664   SmallVector<EVT, 4> AggValueVTs;
3665   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3666   SmallVector<EVT, 4> ValValueVTs;
3667   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3668 
3669   unsigned NumAggValues = AggValueVTs.size();
3670   unsigned NumValValues = ValValueVTs.size();
3671   SmallVector<SDValue, 4> Values(NumAggValues);
3672 
3673   // Ignore an insertvalue that produces an empty object
3674   if (!NumAggValues) {
3675     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3676     return;
3677   }
3678 
3679   SDValue Agg = getValue(Op0);
3680   unsigned i = 0;
3681   // Copy the beginning value(s) from the original aggregate.
3682   for (; i != LinearIndex; ++i)
3683     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3684                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3685   // Copy values from the inserted value(s).
3686   if (NumValValues) {
3687     SDValue Val = getValue(Op1);
3688     for (; i != LinearIndex + NumValValues; ++i)
3689       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3690                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3691   }
3692   // Copy remaining value(s) from the original aggregate.
3693   for (; i != NumAggValues; ++i)
3694     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3695                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3696 
3697   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3698                            DAG.getVTList(AggValueVTs), Values));
3699 }
3700 
3701 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3702   ArrayRef<unsigned> Indices;
3703   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3704     Indices = EV->getIndices();
3705   else
3706     Indices = cast<ConstantExpr>(&I)->getIndices();
3707 
3708   const Value *Op0 = I.getOperand(0);
3709   Type *AggTy = Op0->getType();
3710   Type *ValTy = I.getType();
3711   bool OutOfUndef = isa<UndefValue>(Op0);
3712 
3713   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3714 
3715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3716   SmallVector<EVT, 4> ValValueVTs;
3717   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3718 
3719   unsigned NumValValues = ValValueVTs.size();
3720 
3721   // Ignore a extractvalue that produces an empty object
3722   if (!NumValValues) {
3723     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3724     return;
3725   }
3726 
3727   SmallVector<SDValue, 4> Values(NumValValues);
3728 
3729   SDValue Agg = getValue(Op0);
3730   // Copy out the selected value(s).
3731   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3732     Values[i - LinearIndex] =
3733       OutOfUndef ?
3734         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3735         SDValue(Agg.getNode(), Agg.getResNo() + i);
3736 
3737   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3738                            DAG.getVTList(ValValueVTs), Values));
3739 }
3740 
3741 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3742   Value *Op0 = I.getOperand(0);
3743   // Note that the pointer operand may be a vector of pointers. Take the scalar
3744   // element which holds a pointer.
3745   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3746   SDValue N = getValue(Op0);
3747   SDLoc dl = getCurSDLoc();
3748   auto &TLI = DAG.getTargetLoweringInfo();
3749   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3750   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3751 
3752   // Normalize Vector GEP - all scalar operands should be converted to the
3753   // splat vector.
3754   bool IsVectorGEP = I.getType()->isVectorTy();
3755   ElementCount VectorElementCount =
3756       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3757                   : ElementCount(0, false);
3758 
3759   if (IsVectorGEP && !N.getValueType().isVector()) {
3760     LLVMContext &Context = *DAG.getContext();
3761     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3762     if (VectorElementCount.Scalable)
3763       N = DAG.getSplatVector(VT, dl, N);
3764     else
3765       N = DAG.getSplatBuildVector(VT, dl, N);
3766   }
3767 
3768   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3769        GTI != E; ++GTI) {
3770     const Value *Idx = GTI.getOperand();
3771     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3772       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3773       if (Field) {
3774         // N = N + Offset
3775         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3776 
3777         // In an inbounds GEP with an offset that is nonnegative even when
3778         // interpreted as signed, assume there is no unsigned overflow.
3779         SDNodeFlags Flags;
3780         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3781           Flags.setNoUnsignedWrap(true);
3782 
3783         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3784                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3785       }
3786     } else {
3787       // IdxSize is the width of the arithmetic according to IR semantics.
3788       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3789       // (and fix up the result later).
3790       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3791       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3792       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3793       // We intentionally mask away the high bits here; ElementSize may not
3794       // fit in IdxTy.
3795       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3796       bool ElementScalable = ElementSize.isScalable();
3797 
3798       // If this is a scalar constant or a splat vector of constants,
3799       // handle it quickly.
3800       const auto *C = dyn_cast<Constant>(Idx);
3801       if (C && isa<VectorType>(C->getType()))
3802         C = C->getSplatValue();
3803 
3804       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3805       if (CI && CI->isZero())
3806         continue;
3807       if (CI && !ElementScalable) {
3808         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3809         LLVMContext &Context = *DAG.getContext();
3810         SDValue OffsVal;
3811         if (IsVectorGEP)
3812           OffsVal = DAG.getConstant(
3813               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3814         else
3815           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3816 
3817         // In an inbounds GEP with an offset that is nonnegative even when
3818         // interpreted as signed, assume there is no unsigned overflow.
3819         SDNodeFlags Flags;
3820         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3821           Flags.setNoUnsignedWrap(true);
3822 
3823         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3824 
3825         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3826         continue;
3827       }
3828 
3829       // N = N + Idx * ElementMul;
3830       SDValue IdxN = getValue(Idx);
3831 
3832       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3833         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3834                                   VectorElementCount);
3835         if (VectorElementCount.Scalable)
3836           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3837         else
3838           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3839       }
3840 
3841       // If the index is smaller or larger than intptr_t, truncate or extend
3842       // it.
3843       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3844 
3845       if (ElementScalable) {
3846         EVT VScaleTy = N.getValueType().getScalarType();
3847         SDValue VScale = DAG.getNode(
3848             ISD::VSCALE, dl, VScaleTy,
3849             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3850         if (IsVectorGEP)
3851           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3852         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3853       } else {
3854         // If this is a multiply by a power of two, turn it into a shl
3855         // immediately.  This is a very common case.
3856         if (ElementMul != 1) {
3857           if (ElementMul.isPowerOf2()) {
3858             unsigned Amt = ElementMul.logBase2();
3859             IdxN = DAG.getNode(ISD::SHL, dl,
3860                                N.getValueType(), IdxN,
3861                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3862           } else {
3863             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3864                                             IdxN.getValueType());
3865             IdxN = DAG.getNode(ISD::MUL, dl,
3866                                N.getValueType(), IdxN, Scale);
3867           }
3868         }
3869       }
3870 
3871       N = DAG.getNode(ISD::ADD, dl,
3872                       N.getValueType(), N, IdxN);
3873     }
3874   }
3875 
3876   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3877     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3878 
3879   setValue(&I, N);
3880 }
3881 
3882 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3883   // If this is a fixed sized alloca in the entry block of the function,
3884   // allocate it statically on the stack.
3885   if (FuncInfo.StaticAllocaMap.count(&I))
3886     return;   // getValue will auto-populate this.
3887 
3888   SDLoc dl = getCurSDLoc();
3889   Type *Ty = I.getAllocatedType();
3890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3891   auto &DL = DAG.getDataLayout();
3892   uint64_t TySize = DL.getTypeAllocSize(Ty);
3893   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3894 
3895   SDValue AllocSize = getValue(I.getArraySize());
3896 
3897   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3898   if (AllocSize.getValueType() != IntPtr)
3899     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3900 
3901   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3902                           AllocSize,
3903                           DAG.getConstant(TySize, dl, IntPtr));
3904 
3905   // Handle alignment.  If the requested alignment is less than or equal to
3906   // the stack alignment, ignore it.  If the size is greater than or equal to
3907   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3908   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3909   if (Alignment <= StackAlign)
3910     Alignment = None;
3911 
3912   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3913   // Round the size of the allocation up to the stack alignment size
3914   // by add SA-1 to the size. This doesn't overflow because we're computing
3915   // an address inside an alloca.
3916   SDNodeFlags Flags;
3917   Flags.setNoUnsignedWrap(true);
3918   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3919                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3920 
3921   // Mask out the low bits for alignment purposes.
3922   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3923                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3924 
3925   SDValue Ops[] = {
3926       getRoot(), AllocSize,
3927       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3928   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3929   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3930   setValue(&I, DSA);
3931   DAG.setRoot(DSA.getValue(1));
3932 
3933   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3934 }
3935 
3936 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3937   if (I.isAtomic())
3938     return visitAtomicLoad(I);
3939 
3940   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3941   const Value *SV = I.getOperand(0);
3942   if (TLI.supportSwiftError()) {
3943     // Swifterror values can come from either a function parameter with
3944     // swifterror attribute or an alloca with swifterror attribute.
3945     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3946       if (Arg->hasSwiftErrorAttr())
3947         return visitLoadFromSwiftError(I);
3948     }
3949 
3950     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3951       if (Alloca->isSwiftError())
3952         return visitLoadFromSwiftError(I);
3953     }
3954   }
3955 
3956   SDValue Ptr = getValue(SV);
3957 
3958   Type *Ty = I.getType();
3959   Align Alignment = I.getAlign();
3960 
3961   AAMDNodes AAInfo;
3962   I.getAAMetadata(AAInfo);
3963   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3964 
3965   SmallVector<EVT, 4> ValueVTs, MemVTs;
3966   SmallVector<uint64_t, 4> Offsets;
3967   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3968   unsigned NumValues = ValueVTs.size();
3969   if (NumValues == 0)
3970     return;
3971 
3972   bool isVolatile = I.isVolatile();
3973 
3974   SDValue Root;
3975   bool ConstantMemory = false;
3976   if (isVolatile)
3977     // Serialize volatile loads with other side effects.
3978     Root = getRoot();
3979   else if (NumValues > MaxParallelChains)
3980     Root = getMemoryRoot();
3981   else if (AA &&
3982            AA->pointsToConstantMemory(MemoryLocation(
3983                SV,
3984                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3985                AAInfo))) {
3986     // Do not serialize (non-volatile) loads of constant memory with anything.
3987     Root = DAG.getEntryNode();
3988     ConstantMemory = true;
3989   } else {
3990     // Do not serialize non-volatile loads against each other.
3991     Root = DAG.getRoot();
3992   }
3993 
3994   SDLoc dl = getCurSDLoc();
3995 
3996   if (isVolatile)
3997     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3998 
3999   // An aggregate load cannot wrap around the address space, so offsets to its
4000   // parts don't wrap either.
4001   SDNodeFlags Flags;
4002   Flags.setNoUnsignedWrap(true);
4003 
4004   SmallVector<SDValue, 4> Values(NumValues);
4005   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4006   EVT PtrVT = Ptr.getValueType();
4007 
4008   MachineMemOperand::Flags MMOFlags
4009     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4010 
4011   unsigned ChainI = 0;
4012   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4013     // Serializing loads here may result in excessive register pressure, and
4014     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4015     // could recover a bit by hoisting nodes upward in the chain by recognizing
4016     // they are side-effect free or do not alias. The optimizer should really
4017     // avoid this case by converting large object/array copies to llvm.memcpy
4018     // (MaxParallelChains should always remain as failsafe).
4019     if (ChainI == MaxParallelChains) {
4020       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4021       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4022                                   makeArrayRef(Chains.data(), ChainI));
4023       Root = Chain;
4024       ChainI = 0;
4025     }
4026     SDValue A = DAG.getNode(ISD::ADD, dl,
4027                             PtrVT, Ptr,
4028                             DAG.getConstant(Offsets[i], dl, PtrVT),
4029                             Flags);
4030 
4031     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4032                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4033                             MMOFlags, AAInfo, Ranges);
4034     Chains[ChainI] = L.getValue(1);
4035 
4036     if (MemVTs[i] != ValueVTs[i])
4037       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4038 
4039     Values[i] = L;
4040   }
4041 
4042   if (!ConstantMemory) {
4043     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4044                                 makeArrayRef(Chains.data(), ChainI));
4045     if (isVolatile)
4046       DAG.setRoot(Chain);
4047     else
4048       PendingLoads.push_back(Chain);
4049   }
4050 
4051   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4052                            DAG.getVTList(ValueVTs), Values));
4053 }
4054 
4055 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4056   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4057          "call visitStoreToSwiftError when backend supports swifterror");
4058 
4059   SmallVector<EVT, 4> ValueVTs;
4060   SmallVector<uint64_t, 4> Offsets;
4061   const Value *SrcV = I.getOperand(0);
4062   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4063                   SrcV->getType(), ValueVTs, &Offsets);
4064   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4065          "expect a single EVT for swifterror");
4066 
4067   SDValue Src = getValue(SrcV);
4068   // Create a virtual register, then update the virtual register.
4069   Register VReg =
4070       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4071   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4072   // Chain can be getRoot or getControlRoot.
4073   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4074                                       SDValue(Src.getNode(), Src.getResNo()));
4075   DAG.setRoot(CopyNode);
4076 }
4077 
4078 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4079   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4080          "call visitLoadFromSwiftError when backend supports swifterror");
4081 
4082   assert(!I.isVolatile() &&
4083          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4084          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4085          "Support volatile, non temporal, invariant for load_from_swift_error");
4086 
4087   const Value *SV = I.getOperand(0);
4088   Type *Ty = I.getType();
4089   AAMDNodes AAInfo;
4090   I.getAAMetadata(AAInfo);
4091   assert(
4092       (!AA ||
4093        !AA->pointsToConstantMemory(MemoryLocation(
4094            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4095            AAInfo))) &&
4096       "load_from_swift_error should not be constant memory");
4097 
4098   SmallVector<EVT, 4> ValueVTs;
4099   SmallVector<uint64_t, 4> Offsets;
4100   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4101                   ValueVTs, &Offsets);
4102   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4103          "expect a single EVT for swifterror");
4104 
4105   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4106   SDValue L = DAG.getCopyFromReg(
4107       getRoot(), getCurSDLoc(),
4108       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4109 
4110   setValue(&I, L);
4111 }
4112 
4113 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4114   if (I.isAtomic())
4115     return visitAtomicStore(I);
4116 
4117   const Value *SrcV = I.getOperand(0);
4118   const Value *PtrV = I.getOperand(1);
4119 
4120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4121   if (TLI.supportSwiftError()) {
4122     // Swifterror values can come from either a function parameter with
4123     // swifterror attribute or an alloca with swifterror attribute.
4124     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4125       if (Arg->hasSwiftErrorAttr())
4126         return visitStoreToSwiftError(I);
4127     }
4128 
4129     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4130       if (Alloca->isSwiftError())
4131         return visitStoreToSwiftError(I);
4132     }
4133   }
4134 
4135   SmallVector<EVT, 4> ValueVTs, MemVTs;
4136   SmallVector<uint64_t, 4> Offsets;
4137   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4138                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4139   unsigned NumValues = ValueVTs.size();
4140   if (NumValues == 0)
4141     return;
4142 
4143   // Get the lowered operands. Note that we do this after
4144   // checking if NumResults is zero, because with zero results
4145   // the operands won't have values in the map.
4146   SDValue Src = getValue(SrcV);
4147   SDValue Ptr = getValue(PtrV);
4148 
4149   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4150   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4151   SDLoc dl = getCurSDLoc();
4152   Align Alignment = I.getAlign();
4153   AAMDNodes AAInfo;
4154   I.getAAMetadata(AAInfo);
4155 
4156   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4157 
4158   // An aggregate load cannot wrap around the address space, so offsets to its
4159   // parts don't wrap either.
4160   SDNodeFlags Flags;
4161   Flags.setNoUnsignedWrap(true);
4162 
4163   unsigned ChainI = 0;
4164   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4165     // See visitLoad comments.
4166     if (ChainI == MaxParallelChains) {
4167       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4168                                   makeArrayRef(Chains.data(), ChainI));
4169       Root = Chain;
4170       ChainI = 0;
4171     }
4172     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4173     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4174     if (MemVTs[i] != ValueVTs[i])
4175       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4176     SDValue St =
4177         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4178                      Alignment, MMOFlags, AAInfo);
4179     Chains[ChainI] = St;
4180   }
4181 
4182   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4183                                   makeArrayRef(Chains.data(), ChainI));
4184   DAG.setRoot(StoreNode);
4185 }
4186 
4187 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4188                                            bool IsCompressing) {
4189   SDLoc sdl = getCurSDLoc();
4190 
4191   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4192                                MaybeAlign &Alignment) {
4193     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4194     Src0 = I.getArgOperand(0);
4195     Ptr = I.getArgOperand(1);
4196     Alignment =
4197         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4198     Mask = I.getArgOperand(3);
4199   };
4200   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4201                                     MaybeAlign &Alignment) {
4202     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4203     Src0 = I.getArgOperand(0);
4204     Ptr = I.getArgOperand(1);
4205     Mask = I.getArgOperand(2);
4206     Alignment = None;
4207   };
4208 
4209   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4210   MaybeAlign Alignment;
4211   if (IsCompressing)
4212     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4213   else
4214     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4215 
4216   SDValue Ptr = getValue(PtrOperand);
4217   SDValue Src0 = getValue(Src0Operand);
4218   SDValue Mask = getValue(MaskOperand);
4219   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4220 
4221   EVT VT = Src0.getValueType();
4222   if (!Alignment)
4223     Alignment = DAG.getEVTAlign(VT);
4224 
4225   AAMDNodes AAInfo;
4226   I.getAAMetadata(AAInfo);
4227 
4228   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4229       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4230       // TODO: Make MachineMemOperands aware of scalable
4231       // vectors.
4232       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4233   SDValue StoreNode =
4234       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4235                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4236   DAG.setRoot(StoreNode);
4237   setValue(&I, StoreNode);
4238 }
4239 
4240 // Get a uniform base for the Gather/Scatter intrinsic.
4241 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4242 // We try to represent it as a base pointer + vector of indices.
4243 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4244 // The first operand of the GEP may be a single pointer or a vector of pointers
4245 // Example:
4246 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4247 //  or
4248 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4249 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4250 //
4251 // When the first GEP operand is a single pointer - it is the uniform base we
4252 // are looking for. If first operand of the GEP is a splat vector - we
4253 // extract the splat value and use it as a uniform base.
4254 // In all other cases the function returns 'false'.
4255 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4256                            ISD::MemIndexType &IndexType, SDValue &Scale,
4257                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4258   SelectionDAG& DAG = SDB->DAG;
4259   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4260   const DataLayout &DL = DAG.getDataLayout();
4261 
4262   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4263 
4264   // Handle splat constant pointer.
4265   if (auto *C = dyn_cast<Constant>(Ptr)) {
4266     C = C->getSplatValue();
4267     if (!C)
4268       return false;
4269 
4270     Base = SDB->getValue(C);
4271 
4272     unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements();
4273     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4274     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4275     IndexType = ISD::SIGNED_SCALED;
4276     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4277     return true;
4278   }
4279 
4280   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4281   if (!GEP || GEP->getParent() != CurBB)
4282     return false;
4283 
4284   if (GEP->getNumOperands() != 2)
4285     return false;
4286 
4287   const Value *BasePtr = GEP->getPointerOperand();
4288   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4289 
4290   // Make sure the base is scalar and the index is a vector.
4291   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4292     return false;
4293 
4294   Base = SDB->getValue(BasePtr);
4295   Index = SDB->getValue(IndexVal);
4296   IndexType = ISD::SIGNED_SCALED;
4297   Scale = DAG.getTargetConstant(
4298               DL.getTypeAllocSize(GEP->getResultElementType()),
4299               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4300   return true;
4301 }
4302 
4303 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4304   SDLoc sdl = getCurSDLoc();
4305 
4306   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4307   const Value *Ptr = I.getArgOperand(1);
4308   SDValue Src0 = getValue(I.getArgOperand(0));
4309   SDValue Mask = getValue(I.getArgOperand(3));
4310   EVT VT = Src0.getValueType();
4311   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4312   if (!Alignment)
4313     Alignment = DAG.getEVTAlign(VT);
4314   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4315 
4316   AAMDNodes AAInfo;
4317   I.getAAMetadata(AAInfo);
4318 
4319   SDValue Base;
4320   SDValue Index;
4321   ISD::MemIndexType IndexType;
4322   SDValue Scale;
4323   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4324                                     I.getParent());
4325 
4326   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4327   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4328       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4329       // TODO: Make MachineMemOperands aware of scalable
4330       // vectors.
4331       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4332   if (!UniformBase) {
4333     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4334     Index = getValue(Ptr);
4335     IndexType = ISD::SIGNED_SCALED;
4336     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4337   }
4338   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4339   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4340                                          Ops, MMO, IndexType);
4341   DAG.setRoot(Scatter);
4342   setValue(&I, Scatter);
4343 }
4344 
4345 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4346   SDLoc sdl = getCurSDLoc();
4347 
4348   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4349                               MaybeAlign &Alignment) {
4350     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4351     Ptr = I.getArgOperand(0);
4352     Alignment =
4353         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4354     Mask = I.getArgOperand(2);
4355     Src0 = I.getArgOperand(3);
4356   };
4357   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4358                                  MaybeAlign &Alignment) {
4359     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4360     Ptr = I.getArgOperand(0);
4361     Alignment = None;
4362     Mask = I.getArgOperand(1);
4363     Src0 = I.getArgOperand(2);
4364   };
4365 
4366   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4367   MaybeAlign Alignment;
4368   if (IsExpanding)
4369     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4370   else
4371     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4372 
4373   SDValue Ptr = getValue(PtrOperand);
4374   SDValue Src0 = getValue(Src0Operand);
4375   SDValue Mask = getValue(MaskOperand);
4376   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4377 
4378   EVT VT = Src0.getValueType();
4379   if (!Alignment)
4380     Alignment = DAG.getEVTAlign(VT);
4381 
4382   AAMDNodes AAInfo;
4383   I.getAAMetadata(AAInfo);
4384   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4385 
4386   // Do not serialize masked loads of constant memory with anything.
4387   MemoryLocation ML;
4388   if (VT.isScalableVector())
4389     ML = MemoryLocation(PtrOperand);
4390   else
4391     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4392                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4393                            AAInfo);
4394   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4395 
4396   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4397 
4398   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4399       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4400       // TODO: Make MachineMemOperands aware of scalable
4401       // vectors.
4402       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4403 
4404   SDValue Load =
4405       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4406                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4407   if (AddToChain)
4408     PendingLoads.push_back(Load.getValue(1));
4409   setValue(&I, Load);
4410 }
4411 
4412 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4413   SDLoc sdl = getCurSDLoc();
4414 
4415   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4416   const Value *Ptr = I.getArgOperand(0);
4417   SDValue Src0 = getValue(I.getArgOperand(3));
4418   SDValue Mask = getValue(I.getArgOperand(2));
4419 
4420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4421   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4422   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4423   if (!Alignment)
4424     Alignment = DAG.getEVTAlign(VT);
4425 
4426   AAMDNodes AAInfo;
4427   I.getAAMetadata(AAInfo);
4428   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4429 
4430   SDValue Root = DAG.getRoot();
4431   SDValue Base;
4432   SDValue Index;
4433   ISD::MemIndexType IndexType;
4434   SDValue Scale;
4435   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4436                                     I.getParent());
4437   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4438   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4439       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4440       // TODO: Make MachineMemOperands aware of scalable
4441       // vectors.
4442       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4443 
4444   if (!UniformBase) {
4445     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4446     Index = getValue(Ptr);
4447     IndexType = ISD::SIGNED_SCALED;
4448     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4449   }
4450   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4451   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4452                                        Ops, MMO, IndexType);
4453 
4454   PendingLoads.push_back(Gather.getValue(1));
4455   setValue(&I, Gather);
4456 }
4457 
4458 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4459   SDLoc dl = getCurSDLoc();
4460   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4461   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4462   SyncScope::ID SSID = I.getSyncScopeID();
4463 
4464   SDValue InChain = getRoot();
4465 
4466   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4467   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4468 
4469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4470   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4471 
4472   MachineFunction &MF = DAG.getMachineFunction();
4473   MachineMemOperand *MMO = MF.getMachineMemOperand(
4474       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4475       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4476       FailureOrdering);
4477 
4478   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4479                                    dl, MemVT, VTs, InChain,
4480                                    getValue(I.getPointerOperand()),
4481                                    getValue(I.getCompareOperand()),
4482                                    getValue(I.getNewValOperand()), MMO);
4483 
4484   SDValue OutChain = L.getValue(2);
4485 
4486   setValue(&I, L);
4487   DAG.setRoot(OutChain);
4488 }
4489 
4490 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4491   SDLoc dl = getCurSDLoc();
4492   ISD::NodeType NT;
4493   switch (I.getOperation()) {
4494   default: llvm_unreachable("Unknown atomicrmw operation");
4495   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4496   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4497   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4498   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4499   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4500   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4501   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4502   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4503   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4504   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4505   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4506   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4507   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4508   }
4509   AtomicOrdering Ordering = I.getOrdering();
4510   SyncScope::ID SSID = I.getSyncScopeID();
4511 
4512   SDValue InChain = getRoot();
4513 
4514   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4516   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4517 
4518   MachineFunction &MF = DAG.getMachineFunction();
4519   MachineMemOperand *MMO = MF.getMachineMemOperand(
4520       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4521       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4522 
4523   SDValue L =
4524     DAG.getAtomic(NT, dl, MemVT, InChain,
4525                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4526                   MMO);
4527 
4528   SDValue OutChain = L.getValue(1);
4529 
4530   setValue(&I, L);
4531   DAG.setRoot(OutChain);
4532 }
4533 
4534 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4535   SDLoc dl = getCurSDLoc();
4536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4537   SDValue Ops[3];
4538   Ops[0] = getRoot();
4539   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4540                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4541   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4542                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4543   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4544 }
4545 
4546 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4547   SDLoc dl = getCurSDLoc();
4548   AtomicOrdering Order = I.getOrdering();
4549   SyncScope::ID SSID = I.getSyncScopeID();
4550 
4551   SDValue InChain = getRoot();
4552 
4553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4554   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4555   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4556 
4557   if (!TLI.supportsUnalignedAtomics() &&
4558       I.getAlignment() < MemVT.getSizeInBits() / 8)
4559     report_fatal_error("Cannot generate unaligned atomic load");
4560 
4561   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4562 
4563   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4564       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4565       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4566 
4567   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4568 
4569   SDValue Ptr = getValue(I.getPointerOperand());
4570 
4571   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4572     // TODO: Once this is better exercised by tests, it should be merged with
4573     // the normal path for loads to prevent future divergence.
4574     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4575     if (MemVT != VT)
4576       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4577 
4578     setValue(&I, L);
4579     SDValue OutChain = L.getValue(1);
4580     if (!I.isUnordered())
4581       DAG.setRoot(OutChain);
4582     else
4583       PendingLoads.push_back(OutChain);
4584     return;
4585   }
4586 
4587   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4588                             Ptr, MMO);
4589 
4590   SDValue OutChain = L.getValue(1);
4591   if (MemVT != VT)
4592     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4593 
4594   setValue(&I, L);
4595   DAG.setRoot(OutChain);
4596 }
4597 
4598 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4599   SDLoc dl = getCurSDLoc();
4600 
4601   AtomicOrdering Ordering = I.getOrdering();
4602   SyncScope::ID SSID = I.getSyncScopeID();
4603 
4604   SDValue InChain = getRoot();
4605 
4606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4607   EVT MemVT =
4608       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4609 
4610   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4611     report_fatal_error("Cannot generate unaligned atomic store");
4612 
4613   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4614 
4615   MachineFunction &MF = DAG.getMachineFunction();
4616   MachineMemOperand *MMO = MF.getMachineMemOperand(
4617       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4618       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4619 
4620   SDValue Val = getValue(I.getValueOperand());
4621   if (Val.getValueType() != MemVT)
4622     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4623   SDValue Ptr = getValue(I.getPointerOperand());
4624 
4625   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4626     // TODO: Once this is better exercised by tests, it should be merged with
4627     // the normal path for stores to prevent future divergence.
4628     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4629     DAG.setRoot(S);
4630     return;
4631   }
4632   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4633                                    Ptr, Val, MMO);
4634 
4635 
4636   DAG.setRoot(OutChain);
4637 }
4638 
4639 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4640 /// node.
4641 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4642                                                unsigned Intrinsic) {
4643   // Ignore the callsite's attributes. A specific call site may be marked with
4644   // readnone, but the lowering code will expect the chain based on the
4645   // definition.
4646   const Function *F = I.getCalledFunction();
4647   bool HasChain = !F->doesNotAccessMemory();
4648   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4649 
4650   // Build the operand list.
4651   SmallVector<SDValue, 8> Ops;
4652   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4653     if (OnlyLoad) {
4654       // We don't need to serialize loads against other loads.
4655       Ops.push_back(DAG.getRoot());
4656     } else {
4657       Ops.push_back(getRoot());
4658     }
4659   }
4660 
4661   // Info is set by getTgtMemInstrinsic
4662   TargetLowering::IntrinsicInfo Info;
4663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4664   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4665                                                DAG.getMachineFunction(),
4666                                                Intrinsic);
4667 
4668   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4669   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4670       Info.opc == ISD::INTRINSIC_W_CHAIN)
4671     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4672                                         TLI.getPointerTy(DAG.getDataLayout())));
4673 
4674   // Add all operands of the call to the operand list.
4675   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4676     const Value *Arg = I.getArgOperand(i);
4677     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4678       Ops.push_back(getValue(Arg));
4679       continue;
4680     }
4681 
4682     // Use TargetConstant instead of a regular constant for immarg.
4683     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4684     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4685       assert(CI->getBitWidth() <= 64 &&
4686              "large intrinsic immediates not handled");
4687       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4688     } else {
4689       Ops.push_back(
4690           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4691     }
4692   }
4693 
4694   SmallVector<EVT, 4> ValueVTs;
4695   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4696 
4697   if (HasChain)
4698     ValueVTs.push_back(MVT::Other);
4699 
4700   SDVTList VTs = DAG.getVTList(ValueVTs);
4701 
4702   // Create the node.
4703   SDValue Result;
4704   if (IsTgtIntrinsic) {
4705     // This is target intrinsic that touches memory
4706     AAMDNodes AAInfo;
4707     I.getAAMetadata(AAInfo);
4708     Result =
4709         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4710                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4711                                 Info.align, Info.flags, Info.size, AAInfo);
4712   } else if (!HasChain) {
4713     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4714   } else if (!I.getType()->isVoidTy()) {
4715     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4716   } else {
4717     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4718   }
4719 
4720   if (HasChain) {
4721     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4722     if (OnlyLoad)
4723       PendingLoads.push_back(Chain);
4724     else
4725       DAG.setRoot(Chain);
4726   }
4727 
4728   if (!I.getType()->isVoidTy()) {
4729     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4730       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4731       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4732     } else
4733       Result = lowerRangeToAssertZExt(DAG, I, Result);
4734 
4735     setValue(&I, Result);
4736   }
4737 }
4738 
4739 /// GetSignificand - Get the significand and build it into a floating-point
4740 /// number with exponent of 1:
4741 ///
4742 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4743 ///
4744 /// where Op is the hexadecimal representation of floating point value.
4745 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4746   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4747                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4748   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4749                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4750   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4751 }
4752 
4753 /// GetExponent - Get the exponent:
4754 ///
4755 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4756 ///
4757 /// where Op is the hexadecimal representation of floating point value.
4758 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4759                            const TargetLowering &TLI, const SDLoc &dl) {
4760   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4761                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4762   SDValue t1 = DAG.getNode(
4763       ISD::SRL, dl, MVT::i32, t0,
4764       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4765   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4766                            DAG.getConstant(127, dl, MVT::i32));
4767   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4768 }
4769 
4770 /// getF32Constant - Get 32-bit floating point constant.
4771 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4772                               const SDLoc &dl) {
4773   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4774                            MVT::f32);
4775 }
4776 
4777 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4778                                        SelectionDAG &DAG) {
4779   // TODO: What fast-math-flags should be set on the floating-point nodes?
4780 
4781   //   IntegerPartOfX = ((int32_t)(t0);
4782   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4783 
4784   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4785   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4786   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4787 
4788   //   IntegerPartOfX <<= 23;
4789   IntegerPartOfX = DAG.getNode(
4790       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4791       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4792                                   DAG.getDataLayout())));
4793 
4794   SDValue TwoToFractionalPartOfX;
4795   if (LimitFloatPrecision <= 6) {
4796     // For floating-point precision of 6:
4797     //
4798     //   TwoToFractionalPartOfX =
4799     //     0.997535578f +
4800     //       (0.735607626f + 0.252464424f * x) * x;
4801     //
4802     // error 0.0144103317, which is 6 bits
4803     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4804                              getF32Constant(DAG, 0x3e814304, dl));
4805     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4806                              getF32Constant(DAG, 0x3f3c50c8, dl));
4807     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4808     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4809                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4810   } else if (LimitFloatPrecision <= 12) {
4811     // For floating-point precision of 12:
4812     //
4813     //   TwoToFractionalPartOfX =
4814     //     0.999892986f +
4815     //       (0.696457318f +
4816     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4817     //
4818     // error 0.000107046256, which is 13 to 14 bits
4819     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4820                              getF32Constant(DAG, 0x3da235e3, dl));
4821     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4822                              getF32Constant(DAG, 0x3e65b8f3, dl));
4823     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4824     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4825                              getF32Constant(DAG, 0x3f324b07, dl));
4826     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4827     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4828                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4829   } else { // LimitFloatPrecision <= 18
4830     // For floating-point precision of 18:
4831     //
4832     //   TwoToFractionalPartOfX =
4833     //     0.999999982f +
4834     //       (0.693148872f +
4835     //         (0.240227044f +
4836     //           (0.554906021e-1f +
4837     //             (0.961591928e-2f +
4838     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4839     // error 2.47208000*10^(-7), which is better than 18 bits
4840     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4841                              getF32Constant(DAG, 0x3924b03e, dl));
4842     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4843                              getF32Constant(DAG, 0x3ab24b87, dl));
4844     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4845     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4846                              getF32Constant(DAG, 0x3c1d8c17, dl));
4847     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4848     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4849                              getF32Constant(DAG, 0x3d634a1d, dl));
4850     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4851     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4852                              getF32Constant(DAG, 0x3e75fe14, dl));
4853     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4854     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4855                               getF32Constant(DAG, 0x3f317234, dl));
4856     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4857     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4858                                          getF32Constant(DAG, 0x3f800000, dl));
4859   }
4860 
4861   // Add the exponent into the result in integer domain.
4862   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4863   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4864                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4865 }
4866 
4867 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4868 /// limited-precision mode.
4869 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4870                          const TargetLowering &TLI) {
4871   if (Op.getValueType() == MVT::f32 &&
4872       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4873 
4874     // Put the exponent in the right bit position for later addition to the
4875     // final result:
4876     //
4877     // t0 = Op * log2(e)
4878 
4879     // TODO: What fast-math-flags should be set here?
4880     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4881                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4882     return getLimitedPrecisionExp2(t0, dl, DAG);
4883   }
4884 
4885   // No special expansion.
4886   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4887 }
4888 
4889 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4890 /// limited-precision mode.
4891 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4892                          const TargetLowering &TLI) {
4893   // TODO: What fast-math-flags should be set on the floating-point nodes?
4894 
4895   if (Op.getValueType() == MVT::f32 &&
4896       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4897     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4898 
4899     // Scale the exponent by log(2).
4900     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4901     SDValue LogOfExponent =
4902         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4903                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4904 
4905     // Get the significand and build it into a floating-point number with
4906     // exponent of 1.
4907     SDValue X = GetSignificand(DAG, Op1, dl);
4908 
4909     SDValue LogOfMantissa;
4910     if (LimitFloatPrecision <= 6) {
4911       // For floating-point precision of 6:
4912       //
4913       //   LogofMantissa =
4914       //     -1.1609546f +
4915       //       (1.4034025f - 0.23903021f * x) * x;
4916       //
4917       // error 0.0034276066, which is better than 8 bits
4918       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4919                                getF32Constant(DAG, 0xbe74c456, dl));
4920       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4921                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4922       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4923       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4924                                   getF32Constant(DAG, 0x3f949a29, dl));
4925     } else if (LimitFloatPrecision <= 12) {
4926       // For floating-point precision of 12:
4927       //
4928       //   LogOfMantissa =
4929       //     -1.7417939f +
4930       //       (2.8212026f +
4931       //         (-1.4699568f +
4932       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4933       //
4934       // error 0.000061011436, which is 14 bits
4935       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4936                                getF32Constant(DAG, 0xbd67b6d6, dl));
4937       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4938                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4939       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4940       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4941                                getF32Constant(DAG, 0x3fbc278b, dl));
4942       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4943       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4944                                getF32Constant(DAG, 0x40348e95, dl));
4945       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4946       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4947                                   getF32Constant(DAG, 0x3fdef31a, dl));
4948     } else { // LimitFloatPrecision <= 18
4949       // For floating-point precision of 18:
4950       //
4951       //   LogOfMantissa =
4952       //     -2.1072184f +
4953       //       (4.2372794f +
4954       //         (-3.7029485f +
4955       //           (2.2781945f +
4956       //             (-0.87823314f +
4957       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4958       //
4959       // error 0.0000023660568, which is better than 18 bits
4960       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4961                                getF32Constant(DAG, 0xbc91e5ac, dl));
4962       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4963                                getF32Constant(DAG, 0x3e4350aa, dl));
4964       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4965       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4966                                getF32Constant(DAG, 0x3f60d3e3, dl));
4967       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4968       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4969                                getF32Constant(DAG, 0x4011cdf0, dl));
4970       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4971       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4972                                getF32Constant(DAG, 0x406cfd1c, dl));
4973       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4974       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4975                                getF32Constant(DAG, 0x408797cb, dl));
4976       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4977       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4978                                   getF32Constant(DAG, 0x4006dcab, dl));
4979     }
4980 
4981     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4982   }
4983 
4984   // No special expansion.
4985   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4986 }
4987 
4988 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4989 /// limited-precision mode.
4990 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4991                           const TargetLowering &TLI) {
4992   // TODO: What fast-math-flags should be set on the floating-point nodes?
4993 
4994   if (Op.getValueType() == MVT::f32 &&
4995       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4996     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4997 
4998     // Get the exponent.
4999     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5000 
5001     // Get the significand and build it into a floating-point number with
5002     // exponent of 1.
5003     SDValue X = GetSignificand(DAG, Op1, dl);
5004 
5005     // Different possible minimax approximations of significand in
5006     // floating-point for various degrees of accuracy over [1,2].
5007     SDValue Log2ofMantissa;
5008     if (LimitFloatPrecision <= 6) {
5009       // For floating-point precision of 6:
5010       //
5011       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5012       //
5013       // error 0.0049451742, which is more than 7 bits
5014       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5015                                getF32Constant(DAG, 0xbeb08fe0, dl));
5016       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5017                                getF32Constant(DAG, 0x40019463, dl));
5018       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5019       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5020                                    getF32Constant(DAG, 0x3fd6633d, dl));
5021     } else if (LimitFloatPrecision <= 12) {
5022       // For floating-point precision of 12:
5023       //
5024       //   Log2ofMantissa =
5025       //     -2.51285454f +
5026       //       (4.07009056f +
5027       //         (-2.12067489f +
5028       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5029       //
5030       // error 0.0000876136000, which is better than 13 bits
5031       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5032                                getF32Constant(DAG, 0xbda7262e, dl));
5033       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5034                                getF32Constant(DAG, 0x3f25280b, dl));
5035       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5036       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5037                                getF32Constant(DAG, 0x4007b923, dl));
5038       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5039       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5040                                getF32Constant(DAG, 0x40823e2f, dl));
5041       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5042       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5043                                    getF32Constant(DAG, 0x4020d29c, dl));
5044     } else { // LimitFloatPrecision <= 18
5045       // For floating-point precision of 18:
5046       //
5047       //   Log2ofMantissa =
5048       //     -3.0400495f +
5049       //       (6.1129976f +
5050       //         (-5.3420409f +
5051       //           (3.2865683f +
5052       //             (-1.2669343f +
5053       //               (0.27515199f -
5054       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5055       //
5056       // error 0.0000018516, which is better than 18 bits
5057       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5058                                getF32Constant(DAG, 0xbcd2769e, dl));
5059       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5060                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5061       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5062       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5063                                getF32Constant(DAG, 0x3fa22ae7, dl));
5064       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5065       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5066                                getF32Constant(DAG, 0x40525723, dl));
5067       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5068       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5069                                getF32Constant(DAG, 0x40aaf200, dl));
5070       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5071       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5072                                getF32Constant(DAG, 0x40c39dad, dl));
5073       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5074       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5075                                    getF32Constant(DAG, 0x4042902c, dl));
5076     }
5077 
5078     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5079   }
5080 
5081   // No special expansion.
5082   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5083 }
5084 
5085 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5086 /// limited-precision mode.
5087 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5088                            const TargetLowering &TLI) {
5089   // TODO: What fast-math-flags should be set on the floating-point nodes?
5090 
5091   if (Op.getValueType() == MVT::f32 &&
5092       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5093     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5094 
5095     // Scale the exponent by log10(2) [0.30102999f].
5096     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5097     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5098                                         getF32Constant(DAG, 0x3e9a209a, dl));
5099 
5100     // Get the significand and build it into a floating-point number with
5101     // exponent of 1.
5102     SDValue X = GetSignificand(DAG, Op1, dl);
5103 
5104     SDValue Log10ofMantissa;
5105     if (LimitFloatPrecision <= 6) {
5106       // For floating-point precision of 6:
5107       //
5108       //   Log10ofMantissa =
5109       //     -0.50419619f +
5110       //       (0.60948995f - 0.10380950f * x) * x;
5111       //
5112       // error 0.0014886165, which is 6 bits
5113       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5114                                getF32Constant(DAG, 0xbdd49a13, dl));
5115       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5116                                getF32Constant(DAG, 0x3f1c0789, dl));
5117       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5118       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5119                                     getF32Constant(DAG, 0x3f011300, dl));
5120     } else if (LimitFloatPrecision <= 12) {
5121       // For floating-point precision of 12:
5122       //
5123       //   Log10ofMantissa =
5124       //     -0.64831180f +
5125       //       (0.91751397f +
5126       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5127       //
5128       // error 0.00019228036, which is better than 12 bits
5129       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5130                                getF32Constant(DAG, 0x3d431f31, dl));
5131       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5132                                getF32Constant(DAG, 0x3ea21fb2, dl));
5133       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5134       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5135                                getF32Constant(DAG, 0x3f6ae232, dl));
5136       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5137       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5138                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5139     } else { // LimitFloatPrecision <= 18
5140       // For floating-point precision of 18:
5141       //
5142       //   Log10ofMantissa =
5143       //     -0.84299375f +
5144       //       (1.5327582f +
5145       //         (-1.0688956f +
5146       //           (0.49102474f +
5147       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5148       //
5149       // error 0.0000037995730, which is better than 18 bits
5150       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5151                                getF32Constant(DAG, 0x3c5d51ce, dl));
5152       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5153                                getF32Constant(DAG, 0x3e00685a, dl));
5154       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5155       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5156                                getF32Constant(DAG, 0x3efb6798, dl));
5157       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5158       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5159                                getF32Constant(DAG, 0x3f88d192, dl));
5160       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5161       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5162                                getF32Constant(DAG, 0x3fc4316c, dl));
5163       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5164       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5165                                     getF32Constant(DAG, 0x3f57ce70, dl));
5166     }
5167 
5168     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5169   }
5170 
5171   // No special expansion.
5172   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5173 }
5174 
5175 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5176 /// limited-precision mode.
5177 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5178                           const TargetLowering &TLI) {
5179   if (Op.getValueType() == MVT::f32 &&
5180       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5181     return getLimitedPrecisionExp2(Op, dl, DAG);
5182 
5183   // No special expansion.
5184   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5185 }
5186 
5187 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5188 /// limited-precision mode with x == 10.0f.
5189 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5190                          SelectionDAG &DAG, const TargetLowering &TLI) {
5191   bool IsExp10 = false;
5192   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5193       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5194     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5195       APFloat Ten(10.0f);
5196       IsExp10 = LHSC->isExactlyValue(Ten);
5197     }
5198   }
5199 
5200   // TODO: What fast-math-flags should be set on the FMUL node?
5201   if (IsExp10) {
5202     // Put the exponent in the right bit position for later addition to the
5203     // final result:
5204     //
5205     //   #define LOG2OF10 3.3219281f
5206     //   t0 = Op * LOG2OF10;
5207     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5208                              getF32Constant(DAG, 0x40549a78, dl));
5209     return getLimitedPrecisionExp2(t0, dl, DAG);
5210   }
5211 
5212   // No special expansion.
5213   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5214 }
5215 
5216 /// ExpandPowI - Expand a llvm.powi intrinsic.
5217 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5218                           SelectionDAG &DAG) {
5219   // If RHS is a constant, we can expand this out to a multiplication tree,
5220   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5221   // optimizing for size, we only want to do this if the expansion would produce
5222   // a small number of multiplies, otherwise we do the full expansion.
5223   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5224     // Get the exponent as a positive value.
5225     unsigned Val = RHSC->getSExtValue();
5226     if ((int)Val < 0) Val = -Val;
5227 
5228     // powi(x, 0) -> 1.0
5229     if (Val == 0)
5230       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5231 
5232     bool OptForSize = DAG.shouldOptForSize();
5233     if (!OptForSize ||
5234         // If optimizing for size, don't insert too many multiplies.
5235         // This inserts up to 5 multiplies.
5236         countPopulation(Val) + Log2_32(Val) < 7) {
5237       // We use the simple binary decomposition method to generate the multiply
5238       // sequence.  There are more optimal ways to do this (for example,
5239       // powi(x,15) generates one more multiply than it should), but this has
5240       // the benefit of being both really simple and much better than a libcall.
5241       SDValue Res;  // Logically starts equal to 1.0
5242       SDValue CurSquare = LHS;
5243       // TODO: Intrinsics should have fast-math-flags that propagate to these
5244       // nodes.
5245       while (Val) {
5246         if (Val & 1) {
5247           if (Res.getNode())
5248             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5249           else
5250             Res = CurSquare;  // 1.0*CurSquare.
5251         }
5252 
5253         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5254                                 CurSquare, CurSquare);
5255         Val >>= 1;
5256       }
5257 
5258       // If the original was negative, invert the result, producing 1/(x*x*x).
5259       if (RHSC->getSExtValue() < 0)
5260         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5261                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5262       return Res;
5263     }
5264   }
5265 
5266   // Otherwise, expand to a libcall.
5267   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5268 }
5269 
5270 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5271                             SDValue LHS, SDValue RHS, SDValue Scale,
5272                             SelectionDAG &DAG, const TargetLowering &TLI) {
5273   EVT VT = LHS.getValueType();
5274   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5275   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5276   LLVMContext &Ctx = *DAG.getContext();
5277 
5278   // If the type is legal but the operation isn't, this node might survive all
5279   // the way to operation legalization. If we end up there and we do not have
5280   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5281   // node.
5282 
5283   // Coax the legalizer into expanding the node during type legalization instead
5284   // by bumping the size by one bit. This will force it to Promote, enabling the
5285   // early expansion and avoiding the need to expand later.
5286 
5287   // We don't have to do this if Scale is 0; that can always be expanded, unless
5288   // it's a saturating signed operation. Those can experience true integer
5289   // division overflow, a case which we must avoid.
5290 
5291   // FIXME: We wouldn't have to do this (or any of the early
5292   // expansion/promotion) if it was possible to expand a libcall of an
5293   // illegal type during operation legalization. But it's not, so things
5294   // get a bit hacky.
5295   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5296   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5297       (TLI.isTypeLegal(VT) ||
5298        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5299     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5300         Opcode, VT, ScaleInt);
5301     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5302       EVT PromVT;
5303       if (VT.isScalarInteger())
5304         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5305       else if (VT.isVector()) {
5306         PromVT = VT.getVectorElementType();
5307         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5308         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5309       } else
5310         llvm_unreachable("Wrong VT for DIVFIX?");
5311       if (Signed) {
5312         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5313         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5314       } else {
5315         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5316         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5317       }
5318       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5319       // For saturating operations, we need to shift up the LHS to get the
5320       // proper saturation width, and then shift down again afterwards.
5321       if (Saturating)
5322         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5323                           DAG.getConstant(1, DL, ShiftTy));
5324       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5325       if (Saturating)
5326         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5327                           DAG.getConstant(1, DL, ShiftTy));
5328       return DAG.getZExtOrTrunc(Res, DL, VT);
5329     }
5330   }
5331 
5332   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5333 }
5334 
5335 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5336 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5337 static void
5338 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5339                      const SDValue &N) {
5340   switch (N.getOpcode()) {
5341   case ISD::CopyFromReg: {
5342     SDValue Op = N.getOperand(1);
5343     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5344                       Op.getValueType().getSizeInBits());
5345     return;
5346   }
5347   case ISD::BITCAST:
5348   case ISD::AssertZext:
5349   case ISD::AssertSext:
5350   case ISD::TRUNCATE:
5351     getUnderlyingArgRegs(Regs, N.getOperand(0));
5352     return;
5353   case ISD::BUILD_PAIR:
5354   case ISD::BUILD_VECTOR:
5355   case ISD::CONCAT_VECTORS:
5356     for (SDValue Op : N->op_values())
5357       getUnderlyingArgRegs(Regs, Op);
5358     return;
5359   default:
5360     return;
5361   }
5362 }
5363 
5364 /// If the DbgValueInst is a dbg_value of a function argument, create the
5365 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5366 /// instruction selection, they will be inserted to the entry BB.
5367 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5368     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5369     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5370   const Argument *Arg = dyn_cast<Argument>(V);
5371   if (!Arg)
5372     return false;
5373 
5374   if (!IsDbgDeclare) {
5375     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5376     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5377     // the entry block.
5378     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5379     if (!IsInEntryBlock)
5380       return false;
5381 
5382     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5383     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5384     // variable that also is a param.
5385     //
5386     // Although, if we are at the top of the entry block already, we can still
5387     // emit using ArgDbgValue. This might catch some situations when the
5388     // dbg.value refers to an argument that isn't used in the entry block, so
5389     // any CopyToReg node would be optimized out and the only way to express
5390     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5391     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5392     // we should only emit as ArgDbgValue if the Variable is an argument to the
5393     // current function, and the dbg.value intrinsic is found in the entry
5394     // block.
5395     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5396         !DL->getInlinedAt();
5397     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5398     if (!IsInPrologue && !VariableIsFunctionInputArg)
5399       return false;
5400 
5401     // Here we assume that a function argument on IR level only can be used to
5402     // describe one input parameter on source level. If we for example have
5403     // source code like this
5404     //
5405     //    struct A { long x, y; };
5406     //    void foo(struct A a, long b) {
5407     //      ...
5408     //      b = a.x;
5409     //      ...
5410     //    }
5411     //
5412     // and IR like this
5413     //
5414     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5415     //  entry:
5416     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5417     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5418     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5419     //    ...
5420     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5421     //    ...
5422     //
5423     // then the last dbg.value is describing a parameter "b" using a value that
5424     // is an argument. But since we already has used %a1 to describe a parameter
5425     // we should not handle that last dbg.value here (that would result in an
5426     // incorrect hoisting of the DBG_VALUE to the function entry).
5427     // Notice that we allow one dbg.value per IR level argument, to accommodate
5428     // for the situation with fragments above.
5429     if (VariableIsFunctionInputArg) {
5430       unsigned ArgNo = Arg->getArgNo();
5431       if (ArgNo >= FuncInfo.DescribedArgs.size())
5432         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5433       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5434         return false;
5435       FuncInfo.DescribedArgs.set(ArgNo);
5436     }
5437   }
5438 
5439   MachineFunction &MF = DAG.getMachineFunction();
5440   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5441 
5442   bool IsIndirect = false;
5443   Optional<MachineOperand> Op;
5444   // Some arguments' frame index is recorded during argument lowering.
5445   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5446   if (FI != std::numeric_limits<int>::max())
5447     Op = MachineOperand::CreateFI(FI);
5448 
5449   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5450   if (!Op && N.getNode()) {
5451     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5452     Register Reg;
5453     if (ArgRegsAndSizes.size() == 1)
5454       Reg = ArgRegsAndSizes.front().first;
5455 
5456     if (Reg && Reg.isVirtual()) {
5457       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5458       Register PR = RegInfo.getLiveInPhysReg(Reg);
5459       if (PR)
5460         Reg = PR;
5461     }
5462     if (Reg) {
5463       Op = MachineOperand::CreateReg(Reg, false);
5464       IsIndirect = IsDbgDeclare;
5465     }
5466   }
5467 
5468   if (!Op && N.getNode()) {
5469     // Check if frame index is available.
5470     SDValue LCandidate = peekThroughBitcasts(N);
5471     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5472       if (FrameIndexSDNode *FINode =
5473           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5474         Op = MachineOperand::CreateFI(FINode->getIndex());
5475   }
5476 
5477   if (!Op) {
5478     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5479     auto splitMultiRegDbgValue
5480       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5481       unsigned Offset = 0;
5482       for (auto RegAndSize : SplitRegs) {
5483         // If the expression is already a fragment, the current register
5484         // offset+size might extend beyond the fragment. In this case, only
5485         // the register bits that are inside the fragment are relevant.
5486         int RegFragmentSizeInBits = RegAndSize.second;
5487         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5488           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5489           // The register is entirely outside the expression fragment,
5490           // so is irrelevant for debug info.
5491           if (Offset >= ExprFragmentSizeInBits)
5492             break;
5493           // The register is partially outside the expression fragment, only
5494           // the low bits within the fragment are relevant for debug info.
5495           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5496             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5497           }
5498         }
5499 
5500         auto FragmentExpr = DIExpression::createFragmentExpression(
5501             Expr, Offset, RegFragmentSizeInBits);
5502         Offset += RegAndSize.second;
5503         // If a valid fragment expression cannot be created, the variable's
5504         // correct value cannot be determined and so it is set as Undef.
5505         if (!FragmentExpr) {
5506           SDDbgValue *SDV = DAG.getConstantDbgValue(
5507               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5508           DAG.AddDbgValue(SDV, nullptr, false);
5509           continue;
5510         }
5511         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5512         FuncInfo.ArgDbgValues.push_back(
5513           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5514                   RegAndSize.first, Variable, *FragmentExpr));
5515       }
5516     };
5517 
5518     // Check if ValueMap has reg number.
5519     DenseMap<const Value *, Register>::const_iterator
5520       VMI = FuncInfo.ValueMap.find(V);
5521     if (VMI != FuncInfo.ValueMap.end()) {
5522       const auto &TLI = DAG.getTargetLoweringInfo();
5523       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5524                        V->getType(), getABIRegCopyCC(V));
5525       if (RFV.occupiesMultipleRegs()) {
5526         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5527         return true;
5528       }
5529 
5530       Op = MachineOperand::CreateReg(VMI->second, false);
5531       IsIndirect = IsDbgDeclare;
5532     } else if (ArgRegsAndSizes.size() > 1) {
5533       // This was split due to the calling convention, and no virtual register
5534       // mapping exists for the value.
5535       splitMultiRegDbgValue(ArgRegsAndSizes);
5536       return true;
5537     }
5538   }
5539 
5540   if (!Op)
5541     return false;
5542 
5543   assert(Variable->isValidLocationForIntrinsic(DL) &&
5544          "Expected inlined-at fields to agree");
5545   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5546   FuncInfo.ArgDbgValues.push_back(
5547       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5548               *Op, Variable, Expr));
5549 
5550   return true;
5551 }
5552 
5553 /// Return the appropriate SDDbgValue based on N.
5554 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5555                                              DILocalVariable *Variable,
5556                                              DIExpression *Expr,
5557                                              const DebugLoc &dl,
5558                                              unsigned DbgSDNodeOrder) {
5559   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5560     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5561     // stack slot locations.
5562     //
5563     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5564     // debug values here after optimization:
5565     //
5566     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5567     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5568     //
5569     // Both describe the direct values of their associated variables.
5570     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5571                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5572   }
5573   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5574                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5575 }
5576 
5577 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5578   switch (Intrinsic) {
5579   case Intrinsic::smul_fix:
5580     return ISD::SMULFIX;
5581   case Intrinsic::umul_fix:
5582     return ISD::UMULFIX;
5583   case Intrinsic::smul_fix_sat:
5584     return ISD::SMULFIXSAT;
5585   case Intrinsic::umul_fix_sat:
5586     return ISD::UMULFIXSAT;
5587   case Intrinsic::sdiv_fix:
5588     return ISD::SDIVFIX;
5589   case Intrinsic::udiv_fix:
5590     return ISD::UDIVFIX;
5591   case Intrinsic::sdiv_fix_sat:
5592     return ISD::SDIVFIXSAT;
5593   case Intrinsic::udiv_fix_sat:
5594     return ISD::UDIVFIXSAT;
5595   default:
5596     llvm_unreachable("Unhandled fixed point intrinsic");
5597   }
5598 }
5599 
5600 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5601                                            const char *FunctionName) {
5602   assert(FunctionName && "FunctionName must not be nullptr");
5603   SDValue Callee = DAG.getExternalSymbol(
5604       FunctionName,
5605       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5606   LowerCallTo(I, Callee, I.isTailCall());
5607 }
5608 
5609 /// Given a @llvm.call.preallocated.setup, return the corresponding
5610 /// preallocated call.
5611 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5612   assert(cast<CallBase>(PreallocatedSetup)
5613                  ->getCalledFunction()
5614                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5615          "expected call_preallocated_setup Value");
5616   for (auto *U : PreallocatedSetup->users()) {
5617     auto *UseCall = cast<CallBase>(U);
5618     const Function *Fn = UseCall->getCalledFunction();
5619     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5620       return UseCall;
5621     }
5622   }
5623   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5624 }
5625 
5626 /// Lower the call to the specified intrinsic function.
5627 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5628                                              unsigned Intrinsic) {
5629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5630   SDLoc sdl = getCurSDLoc();
5631   DebugLoc dl = getCurDebugLoc();
5632   SDValue Res;
5633 
5634   switch (Intrinsic) {
5635   default:
5636     // By default, turn this into a target intrinsic node.
5637     visitTargetIntrinsic(I, Intrinsic);
5638     return;
5639   case Intrinsic::vscale: {
5640     match(&I, m_VScale(DAG.getDataLayout()));
5641     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5642     setValue(&I,
5643              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5644     return;
5645   }
5646   case Intrinsic::vastart:  visitVAStart(I); return;
5647   case Intrinsic::vaend:    visitVAEnd(I); return;
5648   case Intrinsic::vacopy:   visitVACopy(I); return;
5649   case Intrinsic::returnaddress:
5650     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5651                              TLI.getPointerTy(DAG.getDataLayout()),
5652                              getValue(I.getArgOperand(0))));
5653     return;
5654   case Intrinsic::addressofreturnaddress:
5655     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5656                              TLI.getPointerTy(DAG.getDataLayout())));
5657     return;
5658   case Intrinsic::sponentry:
5659     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5660                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5661     return;
5662   case Intrinsic::frameaddress:
5663     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5664                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5665                              getValue(I.getArgOperand(0))));
5666     return;
5667   case Intrinsic::read_register: {
5668     Value *Reg = I.getArgOperand(0);
5669     SDValue Chain = getRoot();
5670     SDValue RegName =
5671         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5672     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5673     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5674       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5675     setValue(&I, Res);
5676     DAG.setRoot(Res.getValue(1));
5677     return;
5678   }
5679   case Intrinsic::write_register: {
5680     Value *Reg = I.getArgOperand(0);
5681     Value *RegValue = I.getArgOperand(1);
5682     SDValue Chain = getRoot();
5683     SDValue RegName =
5684         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5685     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5686                             RegName, getValue(RegValue)));
5687     return;
5688   }
5689   case Intrinsic::memcpy: {
5690     const auto &MCI = cast<MemCpyInst>(I);
5691     SDValue Op1 = getValue(I.getArgOperand(0));
5692     SDValue Op2 = getValue(I.getArgOperand(1));
5693     SDValue Op3 = getValue(I.getArgOperand(2));
5694     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5695     Align DstAlign = MCI.getDestAlign().valueOrOne();
5696     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5697     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5698     bool isVol = MCI.isVolatile();
5699     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5700     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5701     // node.
5702     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5703     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5704                                /* AlwaysInline */ false, isTC,
5705                                MachinePointerInfo(I.getArgOperand(0)),
5706                                MachinePointerInfo(I.getArgOperand(1)));
5707     updateDAGForMaybeTailCall(MC);
5708     return;
5709   }
5710   case Intrinsic::memcpy_inline: {
5711     const auto &MCI = cast<MemCpyInlineInst>(I);
5712     SDValue Dst = getValue(I.getArgOperand(0));
5713     SDValue Src = getValue(I.getArgOperand(1));
5714     SDValue Size = getValue(I.getArgOperand(2));
5715     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5716     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5717     Align DstAlign = MCI.getDestAlign().valueOrOne();
5718     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5719     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5720     bool isVol = MCI.isVolatile();
5721     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5722     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5723     // node.
5724     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5725                                /* AlwaysInline */ true, isTC,
5726                                MachinePointerInfo(I.getArgOperand(0)),
5727                                MachinePointerInfo(I.getArgOperand(1)));
5728     updateDAGForMaybeTailCall(MC);
5729     return;
5730   }
5731   case Intrinsic::memset: {
5732     const auto &MSI = cast<MemSetInst>(I);
5733     SDValue Op1 = getValue(I.getArgOperand(0));
5734     SDValue Op2 = getValue(I.getArgOperand(1));
5735     SDValue Op3 = getValue(I.getArgOperand(2));
5736     // @llvm.memset defines 0 and 1 to both mean no alignment.
5737     Align Alignment = MSI.getDestAlign().valueOrOne();
5738     bool isVol = MSI.isVolatile();
5739     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5740     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5741     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5742                                MachinePointerInfo(I.getArgOperand(0)));
5743     updateDAGForMaybeTailCall(MS);
5744     return;
5745   }
5746   case Intrinsic::memmove: {
5747     const auto &MMI = cast<MemMoveInst>(I);
5748     SDValue Op1 = getValue(I.getArgOperand(0));
5749     SDValue Op2 = getValue(I.getArgOperand(1));
5750     SDValue Op3 = getValue(I.getArgOperand(2));
5751     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5752     Align DstAlign = MMI.getDestAlign().valueOrOne();
5753     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5754     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5755     bool isVol = MMI.isVolatile();
5756     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5757     // FIXME: Support passing different dest/src alignments to the memmove DAG
5758     // node.
5759     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5760     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5761                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5762                                 MachinePointerInfo(I.getArgOperand(1)));
5763     updateDAGForMaybeTailCall(MM);
5764     return;
5765   }
5766   case Intrinsic::memcpy_element_unordered_atomic: {
5767     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5768     SDValue Dst = getValue(MI.getRawDest());
5769     SDValue Src = getValue(MI.getRawSource());
5770     SDValue Length = getValue(MI.getLength());
5771 
5772     unsigned DstAlign = MI.getDestAlignment();
5773     unsigned SrcAlign = MI.getSourceAlignment();
5774     Type *LengthTy = MI.getLength()->getType();
5775     unsigned ElemSz = MI.getElementSizeInBytes();
5776     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5777     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5778                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5779                                      MachinePointerInfo(MI.getRawDest()),
5780                                      MachinePointerInfo(MI.getRawSource()));
5781     updateDAGForMaybeTailCall(MC);
5782     return;
5783   }
5784   case Intrinsic::memmove_element_unordered_atomic: {
5785     auto &MI = cast<AtomicMemMoveInst>(I);
5786     SDValue Dst = getValue(MI.getRawDest());
5787     SDValue Src = getValue(MI.getRawSource());
5788     SDValue Length = getValue(MI.getLength());
5789 
5790     unsigned DstAlign = MI.getDestAlignment();
5791     unsigned SrcAlign = MI.getSourceAlignment();
5792     Type *LengthTy = MI.getLength()->getType();
5793     unsigned ElemSz = MI.getElementSizeInBytes();
5794     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5795     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5796                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5797                                       MachinePointerInfo(MI.getRawDest()),
5798                                       MachinePointerInfo(MI.getRawSource()));
5799     updateDAGForMaybeTailCall(MC);
5800     return;
5801   }
5802   case Intrinsic::memset_element_unordered_atomic: {
5803     auto &MI = cast<AtomicMemSetInst>(I);
5804     SDValue Dst = getValue(MI.getRawDest());
5805     SDValue Val = getValue(MI.getValue());
5806     SDValue Length = getValue(MI.getLength());
5807 
5808     unsigned DstAlign = MI.getDestAlignment();
5809     Type *LengthTy = MI.getLength()->getType();
5810     unsigned ElemSz = MI.getElementSizeInBytes();
5811     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5812     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5813                                      LengthTy, ElemSz, isTC,
5814                                      MachinePointerInfo(MI.getRawDest()));
5815     updateDAGForMaybeTailCall(MC);
5816     return;
5817   }
5818   case Intrinsic::call_preallocated_setup: {
5819     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5820     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5821     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5822                               getRoot(), SrcValue);
5823     setValue(&I, Res);
5824     DAG.setRoot(Res);
5825     return;
5826   }
5827   case Intrinsic::call_preallocated_arg: {
5828     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5829     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5830     SDValue Ops[3];
5831     Ops[0] = getRoot();
5832     Ops[1] = SrcValue;
5833     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5834                                    MVT::i32); // arg index
5835     SDValue Res = DAG.getNode(
5836         ISD::PREALLOCATED_ARG, sdl,
5837         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5838     setValue(&I, Res);
5839     DAG.setRoot(Res.getValue(1));
5840     return;
5841   }
5842   case Intrinsic::dbg_addr:
5843   case Intrinsic::dbg_declare: {
5844     const auto &DI = cast<DbgVariableIntrinsic>(I);
5845     DILocalVariable *Variable = DI.getVariable();
5846     DIExpression *Expression = DI.getExpression();
5847     dropDanglingDebugInfo(Variable, Expression);
5848     assert(Variable && "Missing variable");
5849     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5850                       << "\n");
5851     // Check if address has undef value.
5852     const Value *Address = DI.getVariableLocation();
5853     if (!Address || isa<UndefValue>(Address) ||
5854         (Address->use_empty() && !isa<Argument>(Address))) {
5855       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5856                         << " (bad/undef/unused-arg address)\n");
5857       return;
5858     }
5859 
5860     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5861 
5862     // Check if this variable can be described by a frame index, typically
5863     // either as a static alloca or a byval parameter.
5864     int FI = std::numeric_limits<int>::max();
5865     if (const auto *AI =
5866             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5867       if (AI->isStaticAlloca()) {
5868         auto I = FuncInfo.StaticAllocaMap.find(AI);
5869         if (I != FuncInfo.StaticAllocaMap.end())
5870           FI = I->second;
5871       }
5872     } else if (const auto *Arg = dyn_cast<Argument>(
5873                    Address->stripInBoundsConstantOffsets())) {
5874       FI = FuncInfo.getArgumentFrameIndex(Arg);
5875     }
5876 
5877     // llvm.dbg.addr is control dependent and always generates indirect
5878     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5879     // the MachineFunction variable table.
5880     if (FI != std::numeric_limits<int>::max()) {
5881       if (Intrinsic == Intrinsic::dbg_addr) {
5882         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5883             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5884         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5885       } else {
5886         LLVM_DEBUG(dbgs() << "Skipping " << DI
5887                           << " (variable info stashed in MF side table)\n");
5888       }
5889       return;
5890     }
5891 
5892     SDValue &N = NodeMap[Address];
5893     if (!N.getNode() && isa<Argument>(Address))
5894       // Check unused arguments map.
5895       N = UnusedArgNodeMap[Address];
5896     SDDbgValue *SDV;
5897     if (N.getNode()) {
5898       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5899         Address = BCI->getOperand(0);
5900       // Parameters are handled specially.
5901       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5902       if (isParameter && FINode) {
5903         // Byval parameter. We have a frame index at this point.
5904         SDV =
5905             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5906                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5907       } else if (isa<Argument>(Address)) {
5908         // Address is an argument, so try to emit its dbg value using
5909         // virtual register info from the FuncInfo.ValueMap.
5910         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5911         return;
5912       } else {
5913         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5914                               true, dl, SDNodeOrder);
5915       }
5916       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5917     } else {
5918       // If Address is an argument then try to emit its dbg value using
5919       // virtual register info from the FuncInfo.ValueMap.
5920       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5921                                     N)) {
5922         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5923                           << " (could not emit func-arg dbg_value)\n");
5924       }
5925     }
5926     return;
5927   }
5928   case Intrinsic::dbg_label: {
5929     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5930     DILabel *Label = DI.getLabel();
5931     assert(Label && "Missing label");
5932 
5933     SDDbgLabel *SDV;
5934     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5935     DAG.AddDbgLabel(SDV);
5936     return;
5937   }
5938   case Intrinsic::dbg_value: {
5939     const DbgValueInst &DI = cast<DbgValueInst>(I);
5940     assert(DI.getVariable() && "Missing variable");
5941 
5942     DILocalVariable *Variable = DI.getVariable();
5943     DIExpression *Expression = DI.getExpression();
5944     dropDanglingDebugInfo(Variable, Expression);
5945     const Value *V = DI.getValue();
5946     if (!V)
5947       return;
5948 
5949     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5950         SDNodeOrder))
5951       return;
5952 
5953     // TODO: Dangling debug info will eventually either be resolved or produce
5954     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5955     // between the original dbg.value location and its resolved DBG_VALUE, which
5956     // we should ideally fill with an extra Undef DBG_VALUE.
5957 
5958     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5959     return;
5960   }
5961 
5962   case Intrinsic::eh_typeid_for: {
5963     // Find the type id for the given typeinfo.
5964     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5965     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5966     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5967     setValue(&I, Res);
5968     return;
5969   }
5970 
5971   case Intrinsic::eh_return_i32:
5972   case Intrinsic::eh_return_i64:
5973     DAG.getMachineFunction().setCallsEHReturn(true);
5974     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5975                             MVT::Other,
5976                             getControlRoot(),
5977                             getValue(I.getArgOperand(0)),
5978                             getValue(I.getArgOperand(1))));
5979     return;
5980   case Intrinsic::eh_unwind_init:
5981     DAG.getMachineFunction().setCallsUnwindInit(true);
5982     return;
5983   case Intrinsic::eh_dwarf_cfa:
5984     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5985                              TLI.getPointerTy(DAG.getDataLayout()),
5986                              getValue(I.getArgOperand(0))));
5987     return;
5988   case Intrinsic::eh_sjlj_callsite: {
5989     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5990     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5991     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5992     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5993 
5994     MMI.setCurrentCallSite(CI->getZExtValue());
5995     return;
5996   }
5997   case Intrinsic::eh_sjlj_functioncontext: {
5998     // Get and store the index of the function context.
5999     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6000     AllocaInst *FnCtx =
6001       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6002     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6003     MFI.setFunctionContextIndex(FI);
6004     return;
6005   }
6006   case Intrinsic::eh_sjlj_setjmp: {
6007     SDValue Ops[2];
6008     Ops[0] = getRoot();
6009     Ops[1] = getValue(I.getArgOperand(0));
6010     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6011                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6012     setValue(&I, Op.getValue(0));
6013     DAG.setRoot(Op.getValue(1));
6014     return;
6015   }
6016   case Intrinsic::eh_sjlj_longjmp:
6017     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6018                             getRoot(), getValue(I.getArgOperand(0))));
6019     return;
6020   case Intrinsic::eh_sjlj_setup_dispatch:
6021     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6022                             getRoot()));
6023     return;
6024   case Intrinsic::masked_gather:
6025     visitMaskedGather(I);
6026     return;
6027   case Intrinsic::masked_load:
6028     visitMaskedLoad(I);
6029     return;
6030   case Intrinsic::masked_scatter:
6031     visitMaskedScatter(I);
6032     return;
6033   case Intrinsic::masked_store:
6034     visitMaskedStore(I);
6035     return;
6036   case Intrinsic::masked_expandload:
6037     visitMaskedLoad(I, true /* IsExpanding */);
6038     return;
6039   case Intrinsic::masked_compressstore:
6040     visitMaskedStore(I, true /* IsCompressing */);
6041     return;
6042   case Intrinsic::powi:
6043     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6044                             getValue(I.getArgOperand(1)), DAG));
6045     return;
6046   case Intrinsic::log:
6047     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6048     return;
6049   case Intrinsic::log2:
6050     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6051     return;
6052   case Intrinsic::log10:
6053     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6054     return;
6055   case Intrinsic::exp:
6056     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6057     return;
6058   case Intrinsic::exp2:
6059     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6060     return;
6061   case Intrinsic::pow:
6062     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6063                            getValue(I.getArgOperand(1)), DAG, TLI));
6064     return;
6065   case Intrinsic::sqrt:
6066   case Intrinsic::fabs:
6067   case Intrinsic::sin:
6068   case Intrinsic::cos:
6069   case Intrinsic::floor:
6070   case Intrinsic::ceil:
6071   case Intrinsic::trunc:
6072   case Intrinsic::rint:
6073   case Intrinsic::nearbyint:
6074   case Intrinsic::round:
6075   case Intrinsic::canonicalize: {
6076     unsigned Opcode;
6077     switch (Intrinsic) {
6078     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6079     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6080     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6081     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6082     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6083     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6084     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6085     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6086     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6087     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6088     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6089     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6090     }
6091 
6092     setValue(&I, DAG.getNode(Opcode, sdl,
6093                              getValue(I.getArgOperand(0)).getValueType(),
6094                              getValue(I.getArgOperand(0))));
6095     return;
6096   }
6097   case Intrinsic::lround:
6098   case Intrinsic::llround:
6099   case Intrinsic::lrint:
6100   case Intrinsic::llrint: {
6101     unsigned Opcode;
6102     switch (Intrinsic) {
6103     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6104     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6105     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6106     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6107     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6108     }
6109 
6110     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6111     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6112                              getValue(I.getArgOperand(0))));
6113     return;
6114   }
6115   case Intrinsic::minnum:
6116     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6117                              getValue(I.getArgOperand(0)).getValueType(),
6118                              getValue(I.getArgOperand(0)),
6119                              getValue(I.getArgOperand(1))));
6120     return;
6121   case Intrinsic::maxnum:
6122     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6123                              getValue(I.getArgOperand(0)).getValueType(),
6124                              getValue(I.getArgOperand(0)),
6125                              getValue(I.getArgOperand(1))));
6126     return;
6127   case Intrinsic::minimum:
6128     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6129                              getValue(I.getArgOperand(0)).getValueType(),
6130                              getValue(I.getArgOperand(0)),
6131                              getValue(I.getArgOperand(1))));
6132     return;
6133   case Intrinsic::maximum:
6134     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0)),
6137                              getValue(I.getArgOperand(1))));
6138     return;
6139   case Intrinsic::copysign:
6140     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6141                              getValue(I.getArgOperand(0)).getValueType(),
6142                              getValue(I.getArgOperand(0)),
6143                              getValue(I.getArgOperand(1))));
6144     return;
6145   case Intrinsic::fma:
6146     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6147                              getValue(I.getArgOperand(0)).getValueType(),
6148                              getValue(I.getArgOperand(0)),
6149                              getValue(I.getArgOperand(1)),
6150                              getValue(I.getArgOperand(2))));
6151     return;
6152 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6153   case Intrinsic::INTRINSIC:
6154 #include "llvm/IR/ConstrainedOps.def"
6155     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6156     return;
6157   case Intrinsic::fmuladd: {
6158     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6159     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6160         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6161       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6162                                getValue(I.getArgOperand(0)).getValueType(),
6163                                getValue(I.getArgOperand(0)),
6164                                getValue(I.getArgOperand(1)),
6165                                getValue(I.getArgOperand(2))));
6166     } else {
6167       // TODO: Intrinsic calls should have fast-math-flags.
6168       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6169                                 getValue(I.getArgOperand(0)).getValueType(),
6170                                 getValue(I.getArgOperand(0)),
6171                                 getValue(I.getArgOperand(1)));
6172       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6173                                 getValue(I.getArgOperand(0)).getValueType(),
6174                                 Mul,
6175                                 getValue(I.getArgOperand(2)));
6176       setValue(&I, Add);
6177     }
6178     return;
6179   }
6180   case Intrinsic::convert_to_fp16:
6181     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6182                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6183                                          getValue(I.getArgOperand(0)),
6184                                          DAG.getTargetConstant(0, sdl,
6185                                                                MVT::i32))));
6186     return;
6187   case Intrinsic::convert_from_fp16:
6188     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6189                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6190                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6191                                          getValue(I.getArgOperand(0)))));
6192     return;
6193   case Intrinsic::pcmarker: {
6194     SDValue Tmp = getValue(I.getArgOperand(0));
6195     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6196     return;
6197   }
6198   case Intrinsic::readcyclecounter: {
6199     SDValue Op = getRoot();
6200     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6201                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6202     setValue(&I, Res);
6203     DAG.setRoot(Res.getValue(1));
6204     return;
6205   }
6206   case Intrinsic::bitreverse:
6207     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6208                              getValue(I.getArgOperand(0)).getValueType(),
6209                              getValue(I.getArgOperand(0))));
6210     return;
6211   case Intrinsic::bswap:
6212     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6213                              getValue(I.getArgOperand(0)).getValueType(),
6214                              getValue(I.getArgOperand(0))));
6215     return;
6216   case Intrinsic::cttz: {
6217     SDValue Arg = getValue(I.getArgOperand(0));
6218     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6219     EVT Ty = Arg.getValueType();
6220     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6221                              sdl, Ty, Arg));
6222     return;
6223   }
6224   case Intrinsic::ctlz: {
6225     SDValue Arg = getValue(I.getArgOperand(0));
6226     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6227     EVT Ty = Arg.getValueType();
6228     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6229                              sdl, Ty, Arg));
6230     return;
6231   }
6232   case Intrinsic::ctpop: {
6233     SDValue Arg = getValue(I.getArgOperand(0));
6234     EVT Ty = Arg.getValueType();
6235     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6236     return;
6237   }
6238   case Intrinsic::fshl:
6239   case Intrinsic::fshr: {
6240     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6241     SDValue X = getValue(I.getArgOperand(0));
6242     SDValue Y = getValue(I.getArgOperand(1));
6243     SDValue Z = getValue(I.getArgOperand(2));
6244     EVT VT = X.getValueType();
6245     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6246     SDValue Zero = DAG.getConstant(0, sdl, VT);
6247     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6248 
6249     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6250     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6251       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6252       return;
6253     }
6254 
6255     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6256     // avoid the select that is necessary in the general case to filter out
6257     // the 0-shift possibility that leads to UB.
6258     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6259       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6260       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6261         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6262         return;
6263       }
6264 
6265       // Some targets only rotate one way. Try the opposite direction.
6266       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6267       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6268         // Negate the shift amount because it is safe to ignore the high bits.
6269         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6270         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6271         return;
6272       }
6273 
6274       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6275       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6276       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6277       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6278       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6279       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6280       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6281       return;
6282     }
6283 
6284     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6285     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6286     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6287     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6288     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6289     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6290 
6291     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6292     // and that is undefined. We must compare and select to avoid UB.
6293     EVT CCVT = MVT::i1;
6294     if (VT.isVector())
6295       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6296 
6297     // For fshl, 0-shift returns the 1st arg (X).
6298     // For fshr, 0-shift returns the 2nd arg (Y).
6299     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6300     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6301     return;
6302   }
6303   case Intrinsic::sadd_sat: {
6304     SDValue Op1 = getValue(I.getArgOperand(0));
6305     SDValue Op2 = getValue(I.getArgOperand(1));
6306     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6307     return;
6308   }
6309   case Intrinsic::uadd_sat: {
6310     SDValue Op1 = getValue(I.getArgOperand(0));
6311     SDValue Op2 = getValue(I.getArgOperand(1));
6312     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6313     return;
6314   }
6315   case Intrinsic::ssub_sat: {
6316     SDValue Op1 = getValue(I.getArgOperand(0));
6317     SDValue Op2 = getValue(I.getArgOperand(1));
6318     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6319     return;
6320   }
6321   case Intrinsic::usub_sat: {
6322     SDValue Op1 = getValue(I.getArgOperand(0));
6323     SDValue Op2 = getValue(I.getArgOperand(1));
6324     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6325     return;
6326   }
6327   case Intrinsic::smul_fix:
6328   case Intrinsic::umul_fix:
6329   case Intrinsic::smul_fix_sat:
6330   case Intrinsic::umul_fix_sat: {
6331     SDValue Op1 = getValue(I.getArgOperand(0));
6332     SDValue Op2 = getValue(I.getArgOperand(1));
6333     SDValue Op3 = getValue(I.getArgOperand(2));
6334     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6335                              Op1.getValueType(), Op1, Op2, Op3));
6336     return;
6337   }
6338   case Intrinsic::sdiv_fix:
6339   case Intrinsic::udiv_fix:
6340   case Intrinsic::sdiv_fix_sat:
6341   case Intrinsic::udiv_fix_sat: {
6342     SDValue Op1 = getValue(I.getArgOperand(0));
6343     SDValue Op2 = getValue(I.getArgOperand(1));
6344     SDValue Op3 = getValue(I.getArgOperand(2));
6345     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6346                               Op1, Op2, Op3, DAG, TLI));
6347     return;
6348   }
6349   case Intrinsic::stacksave: {
6350     SDValue Op = getRoot();
6351     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6352     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6353     setValue(&I, Res);
6354     DAG.setRoot(Res.getValue(1));
6355     return;
6356   }
6357   case Intrinsic::stackrestore:
6358     Res = getValue(I.getArgOperand(0));
6359     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6360     return;
6361   case Intrinsic::get_dynamic_area_offset: {
6362     SDValue Op = getRoot();
6363     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6364     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6365     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6366     // target.
6367     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6368       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6369                          " intrinsic!");
6370     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6371                       Op);
6372     DAG.setRoot(Op);
6373     setValue(&I, Res);
6374     return;
6375   }
6376   case Intrinsic::stackguard: {
6377     MachineFunction &MF = DAG.getMachineFunction();
6378     const Module &M = *MF.getFunction().getParent();
6379     SDValue Chain = getRoot();
6380     if (TLI.useLoadStackGuardNode()) {
6381       Res = getLoadStackGuard(DAG, sdl, Chain);
6382     } else {
6383       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6384       const Value *Global = TLI.getSDagStackGuard(M);
6385       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6386       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6387                         MachinePointerInfo(Global, 0), Align,
6388                         MachineMemOperand::MOVolatile);
6389     }
6390     if (TLI.useStackGuardXorFP())
6391       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6392     DAG.setRoot(Chain);
6393     setValue(&I, Res);
6394     return;
6395   }
6396   case Intrinsic::stackprotector: {
6397     // Emit code into the DAG to store the stack guard onto the stack.
6398     MachineFunction &MF = DAG.getMachineFunction();
6399     MachineFrameInfo &MFI = MF.getFrameInfo();
6400     SDValue Src, Chain = getRoot();
6401 
6402     if (TLI.useLoadStackGuardNode())
6403       Src = getLoadStackGuard(DAG, sdl, Chain);
6404     else
6405       Src = getValue(I.getArgOperand(0));   // The guard's value.
6406 
6407     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6408 
6409     int FI = FuncInfo.StaticAllocaMap[Slot];
6410     MFI.setStackProtectorIndex(FI);
6411     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6412 
6413     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6414 
6415     // Store the stack protector onto the stack.
6416     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6417                                                  DAG.getMachineFunction(), FI),
6418                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6419     setValue(&I, Res);
6420     DAG.setRoot(Res);
6421     return;
6422   }
6423   case Intrinsic::objectsize:
6424     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6425 
6426   case Intrinsic::is_constant:
6427     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6428 
6429   case Intrinsic::annotation:
6430   case Intrinsic::ptr_annotation:
6431   case Intrinsic::launder_invariant_group:
6432   case Intrinsic::strip_invariant_group:
6433     // Drop the intrinsic, but forward the value
6434     setValue(&I, getValue(I.getOperand(0)));
6435     return;
6436   case Intrinsic::assume:
6437   case Intrinsic::var_annotation:
6438   case Intrinsic::sideeffect:
6439     // Discard annotate attributes, assumptions, and artificial side-effects.
6440     return;
6441 
6442   case Intrinsic::codeview_annotation: {
6443     // Emit a label associated with this metadata.
6444     MachineFunction &MF = DAG.getMachineFunction();
6445     MCSymbol *Label =
6446         MF.getMMI().getContext().createTempSymbol("annotation", true);
6447     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6448     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6449     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6450     DAG.setRoot(Res);
6451     return;
6452   }
6453 
6454   case Intrinsic::init_trampoline: {
6455     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6456 
6457     SDValue Ops[6];
6458     Ops[0] = getRoot();
6459     Ops[1] = getValue(I.getArgOperand(0));
6460     Ops[2] = getValue(I.getArgOperand(1));
6461     Ops[3] = getValue(I.getArgOperand(2));
6462     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6463     Ops[5] = DAG.getSrcValue(F);
6464 
6465     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6466 
6467     DAG.setRoot(Res);
6468     return;
6469   }
6470   case Intrinsic::adjust_trampoline:
6471     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6472                              TLI.getPointerTy(DAG.getDataLayout()),
6473                              getValue(I.getArgOperand(0))));
6474     return;
6475   case Intrinsic::gcroot: {
6476     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6477            "only valid in functions with gc specified, enforced by Verifier");
6478     assert(GFI && "implied by previous");
6479     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6480     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6481 
6482     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6483     GFI->addStackRoot(FI->getIndex(), TypeMap);
6484     return;
6485   }
6486   case Intrinsic::gcread:
6487   case Intrinsic::gcwrite:
6488     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6489   case Intrinsic::flt_rounds:
6490     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6491     setValue(&I, Res);
6492     DAG.setRoot(Res.getValue(1));
6493     return;
6494 
6495   case Intrinsic::expect:
6496     // Just replace __builtin_expect(exp, c) with EXP.
6497     setValue(&I, getValue(I.getArgOperand(0)));
6498     return;
6499 
6500   case Intrinsic::debugtrap:
6501   case Intrinsic::trap: {
6502     StringRef TrapFuncName =
6503         I.getAttributes()
6504             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6505             .getValueAsString();
6506     if (TrapFuncName.empty()) {
6507       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6508         ISD::TRAP : ISD::DEBUGTRAP;
6509       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6510       return;
6511     }
6512     TargetLowering::ArgListTy Args;
6513 
6514     TargetLowering::CallLoweringInfo CLI(DAG);
6515     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6516         CallingConv::C, I.getType(),
6517         DAG.getExternalSymbol(TrapFuncName.data(),
6518                               TLI.getPointerTy(DAG.getDataLayout())),
6519         std::move(Args));
6520 
6521     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6522     DAG.setRoot(Result.second);
6523     return;
6524   }
6525 
6526   case Intrinsic::uadd_with_overflow:
6527   case Intrinsic::sadd_with_overflow:
6528   case Intrinsic::usub_with_overflow:
6529   case Intrinsic::ssub_with_overflow:
6530   case Intrinsic::umul_with_overflow:
6531   case Intrinsic::smul_with_overflow: {
6532     ISD::NodeType Op;
6533     switch (Intrinsic) {
6534     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6535     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6536     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6537     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6538     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6539     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6540     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6541     }
6542     SDValue Op1 = getValue(I.getArgOperand(0));
6543     SDValue Op2 = getValue(I.getArgOperand(1));
6544 
6545     EVT ResultVT = Op1.getValueType();
6546     EVT OverflowVT = MVT::i1;
6547     if (ResultVT.isVector())
6548       OverflowVT = EVT::getVectorVT(
6549           *Context, OverflowVT, ResultVT.getVectorNumElements());
6550 
6551     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6552     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6553     return;
6554   }
6555   case Intrinsic::prefetch: {
6556     SDValue Ops[5];
6557     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6558     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6559     Ops[0] = DAG.getRoot();
6560     Ops[1] = getValue(I.getArgOperand(0));
6561     Ops[2] = getValue(I.getArgOperand(1));
6562     Ops[3] = getValue(I.getArgOperand(2));
6563     Ops[4] = getValue(I.getArgOperand(3));
6564     SDValue Result = DAG.getMemIntrinsicNode(
6565         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6566         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6567         /* align */ None, Flags);
6568 
6569     // Chain the prefetch in parallell with any pending loads, to stay out of
6570     // the way of later optimizations.
6571     PendingLoads.push_back(Result);
6572     Result = getRoot();
6573     DAG.setRoot(Result);
6574     return;
6575   }
6576   case Intrinsic::lifetime_start:
6577   case Intrinsic::lifetime_end: {
6578     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6579     // Stack coloring is not enabled in O0, discard region information.
6580     if (TM.getOptLevel() == CodeGenOpt::None)
6581       return;
6582 
6583     const int64_t ObjectSize =
6584         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6585     Value *const ObjectPtr = I.getArgOperand(1);
6586     SmallVector<const Value *, 4> Allocas;
6587     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6588 
6589     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6590            E = Allocas.end(); Object != E; ++Object) {
6591       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6592 
6593       // Could not find an Alloca.
6594       if (!LifetimeObject)
6595         continue;
6596 
6597       // First check that the Alloca is static, otherwise it won't have a
6598       // valid frame index.
6599       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6600       if (SI == FuncInfo.StaticAllocaMap.end())
6601         return;
6602 
6603       const int FrameIndex = SI->second;
6604       int64_t Offset;
6605       if (GetPointerBaseWithConstantOffset(
6606               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6607         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6608       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6609                                 Offset);
6610       DAG.setRoot(Res);
6611     }
6612     return;
6613   }
6614   case Intrinsic::invariant_start:
6615     // Discard region information.
6616     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6617     return;
6618   case Intrinsic::invariant_end:
6619     // Discard region information.
6620     return;
6621   case Intrinsic::clear_cache:
6622     /// FunctionName may be null.
6623     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6624       lowerCallToExternalSymbol(I, FunctionName);
6625     return;
6626   case Intrinsic::donothing:
6627     // ignore
6628     return;
6629   case Intrinsic::experimental_stackmap:
6630     visitStackmap(I);
6631     return;
6632   case Intrinsic::experimental_patchpoint_void:
6633   case Intrinsic::experimental_patchpoint_i64:
6634     visitPatchpoint(I);
6635     return;
6636   case Intrinsic::experimental_gc_statepoint:
6637     LowerStatepoint(ImmutableStatepoint(&I));
6638     return;
6639   case Intrinsic::experimental_gc_result:
6640     visitGCResult(cast<GCResultInst>(I));
6641     return;
6642   case Intrinsic::experimental_gc_relocate:
6643     visitGCRelocate(cast<GCRelocateInst>(I));
6644     return;
6645   case Intrinsic::instrprof_increment:
6646     llvm_unreachable("instrprof failed to lower an increment");
6647   case Intrinsic::instrprof_value_profile:
6648     llvm_unreachable("instrprof failed to lower a value profiling call");
6649   case Intrinsic::localescape: {
6650     MachineFunction &MF = DAG.getMachineFunction();
6651     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6652 
6653     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6654     // is the same on all targets.
6655     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6656       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6657       if (isa<ConstantPointerNull>(Arg))
6658         continue; // Skip null pointers. They represent a hole in index space.
6659       AllocaInst *Slot = cast<AllocaInst>(Arg);
6660       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6661              "can only escape static allocas");
6662       int FI = FuncInfo.StaticAllocaMap[Slot];
6663       MCSymbol *FrameAllocSym =
6664           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6665               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6666       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6667               TII->get(TargetOpcode::LOCAL_ESCAPE))
6668           .addSym(FrameAllocSym)
6669           .addFrameIndex(FI);
6670     }
6671 
6672     return;
6673   }
6674 
6675   case Intrinsic::localrecover: {
6676     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6677     MachineFunction &MF = DAG.getMachineFunction();
6678 
6679     // Get the symbol that defines the frame offset.
6680     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6681     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6682     unsigned IdxVal =
6683         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6684     MCSymbol *FrameAllocSym =
6685         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6686             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6687 
6688     Value *FP = I.getArgOperand(1);
6689     SDValue FPVal = getValue(FP);
6690     EVT PtrVT = FPVal.getValueType();
6691 
6692     // Create a MCSymbol for the label to avoid any target lowering
6693     // that would make this PC relative.
6694     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6695     SDValue OffsetVal =
6696         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6697 
6698     // Add the offset to the FP.
6699     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6700     setValue(&I, Add);
6701 
6702     return;
6703   }
6704 
6705   case Intrinsic::eh_exceptionpointer:
6706   case Intrinsic::eh_exceptioncode: {
6707     // Get the exception pointer vreg, copy from it, and resize it to fit.
6708     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6709     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6710     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6711     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6712     SDValue N =
6713         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6714     if (Intrinsic == Intrinsic::eh_exceptioncode)
6715       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6716     setValue(&I, N);
6717     return;
6718   }
6719   case Intrinsic::xray_customevent: {
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     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6732     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6733     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6734     SDValue Chain = getRoot();
6735     Ops.push_back(LogEntryVal);
6736     Ops.push_back(StrSizeVal);
6737     Ops.push_back(Chain);
6738 
6739     // We need to enforce the calling convention for the callsite, so that
6740     // argument ordering is enforced correctly, and that register allocation can
6741     // see that some registers may be assumed clobbered and have to preserve
6742     // them across calls to the intrinsic.
6743     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6744                                            DL, NodeTys, Ops);
6745     SDValue patchableNode = SDValue(MN, 0);
6746     DAG.setRoot(patchableNode);
6747     setValue(&I, patchableNode);
6748     return;
6749   }
6750   case Intrinsic::xray_typedevent: {
6751     // Here we want to make sure that the intrinsic behaves as if it has a
6752     // specific calling convention, and only for x86_64.
6753     // FIXME: Support other platforms later.
6754     const auto &Triple = DAG.getTarget().getTargetTriple();
6755     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6756       return;
6757 
6758     SDLoc DL = getCurSDLoc();
6759     SmallVector<SDValue, 8> Ops;
6760 
6761     // We want to say that we always want the arguments in registers.
6762     // It's unclear to me how manipulating the selection DAG here forces callers
6763     // to provide arguments in registers instead of on the stack.
6764     SDValue LogTypeId = getValue(I.getArgOperand(0));
6765     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6766     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6767     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6768     SDValue Chain = getRoot();
6769     Ops.push_back(LogTypeId);
6770     Ops.push_back(LogEntryVal);
6771     Ops.push_back(StrSizeVal);
6772     Ops.push_back(Chain);
6773 
6774     // We need to enforce the calling convention for the callsite, so that
6775     // argument ordering is enforced correctly, and that register allocation can
6776     // see that some registers may be assumed clobbered and have to preserve
6777     // them across calls to the intrinsic.
6778     MachineSDNode *MN = DAG.getMachineNode(
6779         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6780     SDValue patchableNode = SDValue(MN, 0);
6781     DAG.setRoot(patchableNode);
6782     setValue(&I, patchableNode);
6783     return;
6784   }
6785   case Intrinsic::experimental_deoptimize:
6786     LowerDeoptimizeCall(&I);
6787     return;
6788 
6789   case Intrinsic::experimental_vector_reduce_v2_fadd:
6790   case Intrinsic::experimental_vector_reduce_v2_fmul:
6791   case Intrinsic::experimental_vector_reduce_add:
6792   case Intrinsic::experimental_vector_reduce_mul:
6793   case Intrinsic::experimental_vector_reduce_and:
6794   case Intrinsic::experimental_vector_reduce_or:
6795   case Intrinsic::experimental_vector_reduce_xor:
6796   case Intrinsic::experimental_vector_reduce_smax:
6797   case Intrinsic::experimental_vector_reduce_smin:
6798   case Intrinsic::experimental_vector_reduce_umax:
6799   case Intrinsic::experimental_vector_reduce_umin:
6800   case Intrinsic::experimental_vector_reduce_fmax:
6801   case Intrinsic::experimental_vector_reduce_fmin:
6802     visitVectorReduce(I, Intrinsic);
6803     return;
6804 
6805   case Intrinsic::icall_branch_funnel: {
6806     SmallVector<SDValue, 16> Ops;
6807     Ops.push_back(getValue(I.getArgOperand(0)));
6808 
6809     int64_t Offset;
6810     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6811         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6812     if (!Base)
6813       report_fatal_error(
6814           "llvm.icall.branch.funnel operand must be a GlobalValue");
6815     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6816 
6817     struct BranchFunnelTarget {
6818       int64_t Offset;
6819       SDValue Target;
6820     };
6821     SmallVector<BranchFunnelTarget, 8> Targets;
6822 
6823     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6824       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6825           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6826       if (ElemBase != Base)
6827         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6828                            "to the same GlobalValue");
6829 
6830       SDValue Val = getValue(I.getArgOperand(Op + 1));
6831       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6832       if (!GA)
6833         report_fatal_error(
6834             "llvm.icall.branch.funnel operand must be a GlobalValue");
6835       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6836                                      GA->getGlobal(), getCurSDLoc(),
6837                                      Val.getValueType(), GA->getOffset())});
6838     }
6839     llvm::sort(Targets,
6840                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6841                  return T1.Offset < T2.Offset;
6842                });
6843 
6844     for (auto &T : Targets) {
6845       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6846       Ops.push_back(T.Target);
6847     }
6848 
6849     Ops.push_back(DAG.getRoot()); // Chain
6850     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6851                                  getCurSDLoc(), MVT::Other, Ops),
6852               0);
6853     DAG.setRoot(N);
6854     setValue(&I, N);
6855     HasTailCall = true;
6856     return;
6857   }
6858 
6859   case Intrinsic::wasm_landingpad_index:
6860     // Information this intrinsic contained has been transferred to
6861     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6862     // delete it now.
6863     return;
6864 
6865   case Intrinsic::aarch64_settag:
6866   case Intrinsic::aarch64_settag_zero: {
6867     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6868     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6869     SDValue Val = TSI.EmitTargetCodeForSetTag(
6870         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6871         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6872         ZeroMemory);
6873     DAG.setRoot(Val);
6874     setValue(&I, Val);
6875     return;
6876   }
6877   case Intrinsic::ptrmask: {
6878     SDValue Ptr = getValue(I.getOperand(0));
6879     SDValue Const = getValue(I.getOperand(1));
6880 
6881     EVT PtrVT = Ptr.getValueType();
6882     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6883                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6884     return;
6885   }
6886   }
6887 }
6888 
6889 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6890     const ConstrainedFPIntrinsic &FPI) {
6891   SDLoc sdl = getCurSDLoc();
6892 
6893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6894   SmallVector<EVT, 4> ValueVTs;
6895   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6896   ValueVTs.push_back(MVT::Other); // Out chain
6897 
6898   // We do not need to serialize constrained FP intrinsics against
6899   // each other or against (nonvolatile) loads, so they can be
6900   // chained like loads.
6901   SDValue Chain = DAG.getRoot();
6902   SmallVector<SDValue, 4> Opers;
6903   Opers.push_back(Chain);
6904   if (FPI.isUnaryOp()) {
6905     Opers.push_back(getValue(FPI.getArgOperand(0)));
6906   } else if (FPI.isTernaryOp()) {
6907     Opers.push_back(getValue(FPI.getArgOperand(0)));
6908     Opers.push_back(getValue(FPI.getArgOperand(1)));
6909     Opers.push_back(getValue(FPI.getArgOperand(2)));
6910   } else {
6911     Opers.push_back(getValue(FPI.getArgOperand(0)));
6912     Opers.push_back(getValue(FPI.getArgOperand(1)));
6913   }
6914 
6915   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6916     assert(Result.getNode()->getNumValues() == 2);
6917 
6918     // Push node to the appropriate list so that future instructions can be
6919     // chained up correctly.
6920     SDValue OutChain = Result.getValue(1);
6921     switch (EB) {
6922     case fp::ExceptionBehavior::ebIgnore:
6923       // The only reason why ebIgnore nodes still need to be chained is that
6924       // they might depend on the current rounding mode, and therefore must
6925       // not be moved across instruction that may change that mode.
6926       LLVM_FALLTHROUGH;
6927     case fp::ExceptionBehavior::ebMayTrap:
6928       // These must not be moved across calls or instructions that may change
6929       // floating-point exception masks.
6930       PendingConstrainedFP.push_back(OutChain);
6931       break;
6932     case fp::ExceptionBehavior::ebStrict:
6933       // These must not be moved across calls or instructions that may change
6934       // floating-point exception masks or read floating-point exception flags.
6935       // In addition, they cannot be optimized out even if unused.
6936       PendingConstrainedFPStrict.push_back(OutChain);
6937       break;
6938     }
6939   };
6940 
6941   SDVTList VTs = DAG.getVTList(ValueVTs);
6942   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6943 
6944   SDNodeFlags Flags;
6945   if (EB == fp::ExceptionBehavior::ebIgnore)
6946     Flags.setNoFPExcept(true);
6947 
6948   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6949     Flags.copyFMF(*FPOp);
6950 
6951   unsigned Opcode;
6952   switch (FPI.getIntrinsicID()) {
6953   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6954 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6955   case Intrinsic::INTRINSIC:                                                   \
6956     Opcode = ISD::STRICT_##DAGN;                                               \
6957     break;
6958 #include "llvm/IR/ConstrainedOps.def"
6959   case Intrinsic::experimental_constrained_fmuladd: {
6960     Opcode = ISD::STRICT_FMA;
6961     // Break fmuladd into fmul and fadd.
6962     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6963         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6964                                         ValueVTs[0])) {
6965       Opers.pop_back();
6966       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6967       pushOutChain(Mul, EB);
6968       Opcode = ISD::STRICT_FADD;
6969       Opers.clear();
6970       Opers.push_back(Mul.getValue(1));
6971       Opers.push_back(Mul.getValue(0));
6972       Opers.push_back(getValue(FPI.getArgOperand(2)));
6973     }
6974     break;
6975   }
6976   }
6977 
6978   // A few strict DAG nodes carry additional operands that are not
6979   // set up by the default code above.
6980   switch (Opcode) {
6981   default: break;
6982   case ISD::STRICT_FP_ROUND:
6983     Opers.push_back(
6984         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6985     break;
6986   case ISD::STRICT_FSETCC:
6987   case ISD::STRICT_FSETCCS: {
6988     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6989     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6990     break;
6991   }
6992   }
6993 
6994   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
6995   pushOutChain(Result, EB);
6996 
6997   SDValue FPResult = Result.getValue(0);
6998   setValue(&FPI, FPResult);
6999 }
7000 
7001 std::pair<SDValue, SDValue>
7002 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7003                                     const BasicBlock *EHPadBB) {
7004   MachineFunction &MF = DAG.getMachineFunction();
7005   MachineModuleInfo &MMI = MF.getMMI();
7006   MCSymbol *BeginLabel = nullptr;
7007 
7008   if (EHPadBB) {
7009     // Insert a label before the invoke call to mark the try range.  This can be
7010     // used to detect deletion of the invoke via the MachineModuleInfo.
7011     BeginLabel = MMI.getContext().createTempSymbol();
7012 
7013     // For SjLj, keep track of which landing pads go with which invokes
7014     // so as to maintain the ordering of pads in the LSDA.
7015     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7016     if (CallSiteIndex) {
7017       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7018       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7019 
7020       // Now that the call site is handled, stop tracking it.
7021       MMI.setCurrentCallSite(0);
7022     }
7023 
7024     // Both PendingLoads and PendingExports must be flushed here;
7025     // this call might not return.
7026     (void)getRoot();
7027     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7028 
7029     CLI.setChain(getRoot());
7030   }
7031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7032   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7033 
7034   assert((CLI.IsTailCall || Result.second.getNode()) &&
7035          "Non-null chain expected with non-tail call!");
7036   assert((Result.second.getNode() || !Result.first.getNode()) &&
7037          "Null value expected with tail call!");
7038 
7039   if (!Result.second.getNode()) {
7040     // As a special case, a null chain means that a tail call has been emitted
7041     // and the DAG root is already updated.
7042     HasTailCall = true;
7043 
7044     // Since there's no actual continuation from this block, nothing can be
7045     // relying on us setting vregs for them.
7046     PendingExports.clear();
7047   } else {
7048     DAG.setRoot(Result.second);
7049   }
7050 
7051   if (EHPadBB) {
7052     // Insert a label at the end of the invoke call to mark the try range.  This
7053     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7054     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7055     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7056 
7057     // Inform MachineModuleInfo of range.
7058     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7059     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7060     // actually use outlined funclets and their LSDA info style.
7061     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7062       assert(CLI.CB);
7063       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7064       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7065     } else if (!isScopedEHPersonality(Pers)) {
7066       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7067     }
7068   }
7069 
7070   return Result;
7071 }
7072 
7073 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7074                                       bool isTailCall,
7075                                       const BasicBlock *EHPadBB) {
7076   auto &DL = DAG.getDataLayout();
7077   FunctionType *FTy = CB.getFunctionType();
7078   Type *RetTy = CB.getType();
7079 
7080   TargetLowering::ArgListTy Args;
7081   Args.reserve(CB.arg_size());
7082 
7083   const Value *SwiftErrorVal = nullptr;
7084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7085 
7086   if (isTailCall) {
7087     // Avoid emitting tail calls in functions with the disable-tail-calls
7088     // attribute.
7089     auto *Caller = CB.getParent()->getParent();
7090     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7091         "true")
7092       isTailCall = false;
7093 
7094     // We can't tail call inside a function with a swifterror argument. Lowering
7095     // does not support this yet. It would have to move into the swifterror
7096     // register before the call.
7097     if (TLI.supportSwiftError() &&
7098         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7099       isTailCall = false;
7100   }
7101 
7102   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7103     TargetLowering::ArgListEntry Entry;
7104     const Value *V = *I;
7105 
7106     // Skip empty types
7107     if (V->getType()->isEmptyTy())
7108       continue;
7109 
7110     SDValue ArgNode = getValue(V);
7111     Entry.Node = ArgNode; Entry.Ty = V->getType();
7112 
7113     Entry.setAttributes(&CB, I - CB.arg_begin());
7114 
7115     // Use swifterror virtual register as input to the call.
7116     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7117       SwiftErrorVal = V;
7118       // We find the virtual register for the actual swifterror argument.
7119       // Instead of using the Value, we use the virtual register instead.
7120       Entry.Node =
7121           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7122                           EVT(TLI.getPointerTy(DL)));
7123     }
7124 
7125     Args.push_back(Entry);
7126 
7127     // If we have an explicit sret argument that is an Instruction, (i.e., it
7128     // might point to function-local memory), we can't meaningfully tail-call.
7129     if (Entry.IsSRet && isa<Instruction>(V))
7130       isTailCall = false;
7131   }
7132 
7133   // If call site has a cfguardtarget operand bundle, create and add an
7134   // additional ArgListEntry.
7135   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7136     TargetLowering::ArgListEntry Entry;
7137     Value *V = Bundle->Inputs[0];
7138     SDValue ArgNode = getValue(V);
7139     Entry.Node = ArgNode;
7140     Entry.Ty = V->getType();
7141     Entry.IsCFGuardTarget = true;
7142     Args.push_back(Entry);
7143   }
7144 
7145   // Check if target-independent constraints permit a tail call here.
7146   // Target-dependent constraints are checked within TLI->LowerCallTo.
7147   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7148     isTailCall = false;
7149 
7150   // Disable tail calls if there is an swifterror argument. Targets have not
7151   // been updated to support tail calls.
7152   if (TLI.supportSwiftError() && SwiftErrorVal)
7153     isTailCall = false;
7154 
7155   TargetLowering::CallLoweringInfo CLI(DAG);
7156   CLI.setDebugLoc(getCurSDLoc())
7157       .setChain(getRoot())
7158       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7159       .setTailCall(isTailCall)
7160       .setConvergent(CB.isConvergent())
7161       .setIsPreallocated(
7162           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7163   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7164 
7165   if (Result.first.getNode()) {
7166     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7167     setValue(&CB, Result.first);
7168   }
7169 
7170   // The last element of CLI.InVals has the SDValue for swifterror return.
7171   // Here we copy it to a virtual register and update SwiftErrorMap for
7172   // book-keeping.
7173   if (SwiftErrorVal && TLI.supportSwiftError()) {
7174     // Get the last element of InVals.
7175     SDValue Src = CLI.InVals.back();
7176     Register VReg =
7177         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7178     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7179     DAG.setRoot(CopyNode);
7180   }
7181 }
7182 
7183 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7184                              SelectionDAGBuilder &Builder) {
7185   // Check to see if this load can be trivially constant folded, e.g. if the
7186   // input is from a string literal.
7187   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7188     // Cast pointer to the type we really want to load.
7189     Type *LoadTy =
7190         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7191     if (LoadVT.isVector())
7192       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7193 
7194     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7195                                          PointerType::getUnqual(LoadTy));
7196 
7197     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7198             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7199       return Builder.getValue(LoadCst);
7200   }
7201 
7202   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7203   // still constant memory, the input chain can be the entry node.
7204   SDValue Root;
7205   bool ConstantMemory = false;
7206 
7207   // Do not serialize (non-volatile) loads of constant memory with anything.
7208   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7209     Root = Builder.DAG.getEntryNode();
7210     ConstantMemory = true;
7211   } else {
7212     // Do not serialize non-volatile loads against each other.
7213     Root = Builder.DAG.getRoot();
7214   }
7215 
7216   SDValue Ptr = Builder.getValue(PtrVal);
7217   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7218                                         Ptr, MachinePointerInfo(PtrVal),
7219                                         /* Alignment = */ 1);
7220 
7221   if (!ConstantMemory)
7222     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7223   return LoadVal;
7224 }
7225 
7226 /// Record the value for an instruction that produces an integer result,
7227 /// converting the type where necessary.
7228 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7229                                                   SDValue Value,
7230                                                   bool IsSigned) {
7231   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7232                                                     I.getType(), true);
7233   if (IsSigned)
7234     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7235   else
7236     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7237   setValue(&I, Value);
7238 }
7239 
7240 /// See if we can lower a memcmp call into an optimized form. If so, return
7241 /// true and lower it. Otherwise return false, and it will be lowered like a
7242 /// normal call.
7243 /// The caller already checked that \p I calls the appropriate LibFunc with a
7244 /// correct prototype.
7245 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7246   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7247   const Value *Size = I.getArgOperand(2);
7248   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7249   if (CSize && CSize->getZExtValue() == 0) {
7250     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7251                                                           I.getType(), true);
7252     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7253     return true;
7254   }
7255 
7256   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7257   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7258       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7259       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7260   if (Res.first.getNode()) {
7261     processIntegerCallValue(I, Res.first, true);
7262     PendingLoads.push_back(Res.second);
7263     return true;
7264   }
7265 
7266   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7267   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7268   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7269     return false;
7270 
7271   // If the target has a fast compare for the given size, it will return a
7272   // preferred load type for that size. Require that the load VT is legal and
7273   // that the target supports unaligned loads of that type. Otherwise, return
7274   // INVALID.
7275   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7276     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7277     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7278     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7279       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7280       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7281       // TODO: Check alignment of src and dest ptrs.
7282       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7283       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7284       if (!TLI.isTypeLegal(LVT) ||
7285           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7286           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7287         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7288     }
7289 
7290     return LVT;
7291   };
7292 
7293   // This turns into unaligned loads. We only do this if the target natively
7294   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7295   // we'll only produce a small number of byte loads.
7296   MVT LoadVT;
7297   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7298   switch (NumBitsToCompare) {
7299   default:
7300     return false;
7301   case 16:
7302     LoadVT = MVT::i16;
7303     break;
7304   case 32:
7305     LoadVT = MVT::i32;
7306     break;
7307   case 64:
7308   case 128:
7309   case 256:
7310     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7311     break;
7312   }
7313 
7314   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7315     return false;
7316 
7317   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7318   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7319 
7320   // Bitcast to a wide integer type if the loads are vectors.
7321   if (LoadVT.isVector()) {
7322     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7323     LoadL = DAG.getBitcast(CmpVT, LoadL);
7324     LoadR = DAG.getBitcast(CmpVT, LoadR);
7325   }
7326 
7327   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7328   processIntegerCallValue(I, Cmp, false);
7329   return true;
7330 }
7331 
7332 /// See if we can lower a memchr call into an optimized form. If so, return
7333 /// true and lower it. Otherwise return false, and it will be lowered like a
7334 /// normal call.
7335 /// The caller already checked that \p I calls the appropriate LibFunc with a
7336 /// correct prototype.
7337 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7338   const Value *Src = I.getArgOperand(0);
7339   const Value *Char = I.getArgOperand(1);
7340   const Value *Length = I.getArgOperand(2);
7341 
7342   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7343   std::pair<SDValue, SDValue> Res =
7344     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7345                                 getValue(Src), getValue(Char), getValue(Length),
7346                                 MachinePointerInfo(Src));
7347   if (Res.first.getNode()) {
7348     setValue(&I, Res.first);
7349     PendingLoads.push_back(Res.second);
7350     return true;
7351   }
7352 
7353   return false;
7354 }
7355 
7356 /// See if we can lower a mempcpy call into an optimized form. If so, return
7357 /// true and lower it. Otherwise return false, and it will be lowered like a
7358 /// normal call.
7359 /// The caller already checked that \p I calls the appropriate LibFunc with a
7360 /// correct prototype.
7361 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7362   SDValue Dst = getValue(I.getArgOperand(0));
7363   SDValue Src = getValue(I.getArgOperand(1));
7364   SDValue Size = getValue(I.getArgOperand(2));
7365 
7366   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7367   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7368   // DAG::getMemcpy needs Alignment to be defined.
7369   Align Alignment = std::min(DstAlign, SrcAlign);
7370 
7371   bool isVol = false;
7372   SDLoc sdl = getCurSDLoc();
7373 
7374   // In the mempcpy context we need to pass in a false value for isTailCall
7375   // because the return pointer needs to be adjusted by the size of
7376   // the copied memory.
7377   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7378   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7379                              /*isTailCall=*/false,
7380                              MachinePointerInfo(I.getArgOperand(0)),
7381                              MachinePointerInfo(I.getArgOperand(1)));
7382   assert(MC.getNode() != nullptr &&
7383          "** memcpy should not be lowered as TailCall in mempcpy context **");
7384   DAG.setRoot(MC);
7385 
7386   // Check if Size needs to be truncated or extended.
7387   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7388 
7389   // Adjust return pointer to point just past the last dst byte.
7390   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7391                                     Dst, Size);
7392   setValue(&I, DstPlusSize);
7393   return true;
7394 }
7395 
7396 /// See if we can lower a strcpy call into an optimized form.  If so, return
7397 /// true and lower it, otherwise return false and it will be lowered like a
7398 /// normal call.
7399 /// The caller already checked that \p I calls the appropriate LibFunc with a
7400 /// correct prototype.
7401 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7402   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7403 
7404   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7405   std::pair<SDValue, SDValue> Res =
7406     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7407                                 getValue(Arg0), getValue(Arg1),
7408                                 MachinePointerInfo(Arg0),
7409                                 MachinePointerInfo(Arg1), isStpcpy);
7410   if (Res.first.getNode()) {
7411     setValue(&I, Res.first);
7412     DAG.setRoot(Res.second);
7413     return true;
7414   }
7415 
7416   return false;
7417 }
7418 
7419 /// See if we can lower a strcmp call into an optimized form.  If so, return
7420 /// true and lower it, otherwise return false and it will be lowered like a
7421 /// normal call.
7422 /// The caller already checked that \p I calls the appropriate LibFunc with a
7423 /// correct prototype.
7424 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7425   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7426 
7427   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7428   std::pair<SDValue, SDValue> Res =
7429     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7430                                 getValue(Arg0), getValue(Arg1),
7431                                 MachinePointerInfo(Arg0),
7432                                 MachinePointerInfo(Arg1));
7433   if (Res.first.getNode()) {
7434     processIntegerCallValue(I, Res.first, true);
7435     PendingLoads.push_back(Res.second);
7436     return true;
7437   }
7438 
7439   return false;
7440 }
7441 
7442 /// See if we can lower a strlen call into an optimized form.  If so, return
7443 /// true and lower it, otherwise return false and it will be lowered like a
7444 /// normal call.
7445 /// The caller already checked that \p I calls the appropriate LibFunc with a
7446 /// correct prototype.
7447 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7448   const Value *Arg0 = I.getArgOperand(0);
7449 
7450   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7451   std::pair<SDValue, SDValue> Res =
7452     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7453                                 getValue(Arg0), MachinePointerInfo(Arg0));
7454   if (Res.first.getNode()) {
7455     processIntegerCallValue(I, Res.first, false);
7456     PendingLoads.push_back(Res.second);
7457     return true;
7458   }
7459 
7460   return false;
7461 }
7462 
7463 /// See if we can lower a strnlen call into an optimized form.  If so, return
7464 /// true and lower it, otherwise return false and it will be lowered like a
7465 /// normal call.
7466 /// The caller already checked that \p I calls the appropriate LibFunc with a
7467 /// correct prototype.
7468 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7469   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7470 
7471   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7472   std::pair<SDValue, SDValue> Res =
7473     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7474                                  getValue(Arg0), getValue(Arg1),
7475                                  MachinePointerInfo(Arg0));
7476   if (Res.first.getNode()) {
7477     processIntegerCallValue(I, Res.first, false);
7478     PendingLoads.push_back(Res.second);
7479     return true;
7480   }
7481 
7482   return false;
7483 }
7484 
7485 /// See if we can lower a unary floating-point operation into an SDNode with
7486 /// the specified Opcode.  If so, return true and lower it, otherwise return
7487 /// false and it will be lowered like a normal call.
7488 /// The caller already checked that \p I calls the appropriate LibFunc with a
7489 /// correct prototype.
7490 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7491                                               unsigned Opcode) {
7492   // We already checked this call's prototype; verify it doesn't modify errno.
7493   if (!I.onlyReadsMemory())
7494     return false;
7495 
7496   SDValue Tmp = getValue(I.getArgOperand(0));
7497   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7498   return true;
7499 }
7500 
7501 /// See if we can lower a binary floating-point operation into an SDNode with
7502 /// the specified Opcode. If so, return true and lower it. Otherwise return
7503 /// false, and it will be lowered like a normal call.
7504 /// The caller already checked that \p I calls the appropriate LibFunc with a
7505 /// correct prototype.
7506 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7507                                                unsigned Opcode) {
7508   // We already checked this call's prototype; verify it doesn't modify errno.
7509   if (!I.onlyReadsMemory())
7510     return false;
7511 
7512   SDValue Tmp0 = getValue(I.getArgOperand(0));
7513   SDValue Tmp1 = getValue(I.getArgOperand(1));
7514   EVT VT = Tmp0.getValueType();
7515   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7516   return true;
7517 }
7518 
7519 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7520   // Handle inline assembly differently.
7521   if (I.isInlineAsm()) {
7522     visitInlineAsm(I);
7523     return;
7524   }
7525 
7526   if (Function *F = I.getCalledFunction()) {
7527     if (F->isDeclaration()) {
7528       // Is this an LLVM intrinsic or a target-specific intrinsic?
7529       unsigned IID = F->getIntrinsicID();
7530       if (!IID)
7531         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7532           IID = II->getIntrinsicID(F);
7533 
7534       if (IID) {
7535         visitIntrinsicCall(I, IID);
7536         return;
7537       }
7538     }
7539 
7540     // Check for well-known libc/libm calls.  If the function is internal, it
7541     // can't be a library call.  Don't do the check if marked as nobuiltin for
7542     // some reason or the call site requires strict floating point semantics.
7543     LibFunc Func;
7544     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7545         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7546         LibInfo->hasOptimizedCodeGen(Func)) {
7547       switch (Func) {
7548       default: break;
7549       case LibFunc_copysign:
7550       case LibFunc_copysignf:
7551       case LibFunc_copysignl:
7552         // We already checked this call's prototype; verify it doesn't modify
7553         // errno.
7554         if (I.onlyReadsMemory()) {
7555           SDValue LHS = getValue(I.getArgOperand(0));
7556           SDValue RHS = getValue(I.getArgOperand(1));
7557           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7558                                    LHS.getValueType(), LHS, RHS));
7559           return;
7560         }
7561         break;
7562       case LibFunc_fabs:
7563       case LibFunc_fabsf:
7564       case LibFunc_fabsl:
7565         if (visitUnaryFloatCall(I, ISD::FABS))
7566           return;
7567         break;
7568       case LibFunc_fmin:
7569       case LibFunc_fminf:
7570       case LibFunc_fminl:
7571         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7572           return;
7573         break;
7574       case LibFunc_fmax:
7575       case LibFunc_fmaxf:
7576       case LibFunc_fmaxl:
7577         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7578           return;
7579         break;
7580       case LibFunc_sin:
7581       case LibFunc_sinf:
7582       case LibFunc_sinl:
7583         if (visitUnaryFloatCall(I, ISD::FSIN))
7584           return;
7585         break;
7586       case LibFunc_cos:
7587       case LibFunc_cosf:
7588       case LibFunc_cosl:
7589         if (visitUnaryFloatCall(I, ISD::FCOS))
7590           return;
7591         break;
7592       case LibFunc_sqrt:
7593       case LibFunc_sqrtf:
7594       case LibFunc_sqrtl:
7595       case LibFunc_sqrt_finite:
7596       case LibFunc_sqrtf_finite:
7597       case LibFunc_sqrtl_finite:
7598         if (visitUnaryFloatCall(I, ISD::FSQRT))
7599           return;
7600         break;
7601       case LibFunc_floor:
7602       case LibFunc_floorf:
7603       case LibFunc_floorl:
7604         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7605           return;
7606         break;
7607       case LibFunc_nearbyint:
7608       case LibFunc_nearbyintf:
7609       case LibFunc_nearbyintl:
7610         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7611           return;
7612         break;
7613       case LibFunc_ceil:
7614       case LibFunc_ceilf:
7615       case LibFunc_ceill:
7616         if (visitUnaryFloatCall(I, ISD::FCEIL))
7617           return;
7618         break;
7619       case LibFunc_rint:
7620       case LibFunc_rintf:
7621       case LibFunc_rintl:
7622         if (visitUnaryFloatCall(I, ISD::FRINT))
7623           return;
7624         break;
7625       case LibFunc_round:
7626       case LibFunc_roundf:
7627       case LibFunc_roundl:
7628         if (visitUnaryFloatCall(I, ISD::FROUND))
7629           return;
7630         break;
7631       case LibFunc_trunc:
7632       case LibFunc_truncf:
7633       case LibFunc_truncl:
7634         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7635           return;
7636         break;
7637       case LibFunc_log2:
7638       case LibFunc_log2f:
7639       case LibFunc_log2l:
7640         if (visitUnaryFloatCall(I, ISD::FLOG2))
7641           return;
7642         break;
7643       case LibFunc_exp2:
7644       case LibFunc_exp2f:
7645       case LibFunc_exp2l:
7646         if (visitUnaryFloatCall(I, ISD::FEXP2))
7647           return;
7648         break;
7649       case LibFunc_memcmp:
7650         if (visitMemCmpCall(I))
7651           return;
7652         break;
7653       case LibFunc_mempcpy:
7654         if (visitMemPCpyCall(I))
7655           return;
7656         break;
7657       case LibFunc_memchr:
7658         if (visitMemChrCall(I))
7659           return;
7660         break;
7661       case LibFunc_strcpy:
7662         if (visitStrCpyCall(I, false))
7663           return;
7664         break;
7665       case LibFunc_stpcpy:
7666         if (visitStrCpyCall(I, true))
7667           return;
7668         break;
7669       case LibFunc_strcmp:
7670         if (visitStrCmpCall(I))
7671           return;
7672         break;
7673       case LibFunc_strlen:
7674         if (visitStrLenCall(I))
7675           return;
7676         break;
7677       case LibFunc_strnlen:
7678         if (visitStrNLenCall(I))
7679           return;
7680         break;
7681       }
7682     }
7683   }
7684 
7685   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7686   // have to do anything here to lower funclet bundles.
7687   // CFGuardTarget bundles are lowered in LowerCallTo.
7688   assert(!I.hasOperandBundlesOtherThan(
7689              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7690               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7691          "Cannot lower calls with arbitrary operand bundles!");
7692 
7693   SDValue Callee = getValue(I.getCalledOperand());
7694 
7695   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7696     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7697   else
7698     // Check if we can potentially perform a tail call. More detailed checking
7699     // is be done within LowerCallTo, after more information about the call is
7700     // known.
7701     LowerCallTo(I, Callee, I.isTailCall());
7702 }
7703 
7704 namespace {
7705 
7706 /// AsmOperandInfo - This contains information for each constraint that we are
7707 /// lowering.
7708 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7709 public:
7710   /// CallOperand - If this is the result output operand or a clobber
7711   /// this is null, otherwise it is the incoming operand to the CallInst.
7712   /// This gets modified as the asm is processed.
7713   SDValue CallOperand;
7714 
7715   /// AssignedRegs - If this is a register or register class operand, this
7716   /// contains the set of register corresponding to the operand.
7717   RegsForValue AssignedRegs;
7718 
7719   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7720     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7721   }
7722 
7723   /// Whether or not this operand accesses memory
7724   bool hasMemory(const TargetLowering &TLI) const {
7725     // Indirect operand accesses access memory.
7726     if (isIndirect)
7727       return true;
7728 
7729     for (const auto &Code : Codes)
7730       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7731         return true;
7732 
7733     return false;
7734   }
7735 
7736   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7737   /// corresponds to.  If there is no Value* for this operand, it returns
7738   /// MVT::Other.
7739   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7740                            const DataLayout &DL) const {
7741     if (!CallOperandVal) return MVT::Other;
7742 
7743     if (isa<BasicBlock>(CallOperandVal))
7744       return TLI.getProgramPointerTy(DL);
7745 
7746     llvm::Type *OpTy = CallOperandVal->getType();
7747 
7748     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7749     // If this is an indirect operand, the operand is a pointer to the
7750     // accessed type.
7751     if (isIndirect) {
7752       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7753       if (!PtrTy)
7754         report_fatal_error("Indirect operand for inline asm not a pointer!");
7755       OpTy = PtrTy->getElementType();
7756     }
7757 
7758     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7759     if (StructType *STy = dyn_cast<StructType>(OpTy))
7760       if (STy->getNumElements() == 1)
7761         OpTy = STy->getElementType(0);
7762 
7763     // If OpTy is not a single value, it may be a struct/union that we
7764     // can tile with integers.
7765     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7766       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7767       switch (BitSize) {
7768       default: break;
7769       case 1:
7770       case 8:
7771       case 16:
7772       case 32:
7773       case 64:
7774       case 128:
7775         OpTy = IntegerType::get(Context, BitSize);
7776         break;
7777       }
7778     }
7779 
7780     return TLI.getValueType(DL, OpTy, true);
7781   }
7782 };
7783 
7784 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7785 
7786 } // end anonymous namespace
7787 
7788 /// Make sure that the output operand \p OpInfo and its corresponding input
7789 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7790 /// out).
7791 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7792                                SDISelAsmOperandInfo &MatchingOpInfo,
7793                                SelectionDAG &DAG) {
7794   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7795     return;
7796 
7797   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7798   const auto &TLI = DAG.getTargetLoweringInfo();
7799 
7800   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7801       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7802                                        OpInfo.ConstraintVT);
7803   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7804       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7805                                        MatchingOpInfo.ConstraintVT);
7806   if ((OpInfo.ConstraintVT.isInteger() !=
7807        MatchingOpInfo.ConstraintVT.isInteger()) ||
7808       (MatchRC.second != InputRC.second)) {
7809     // FIXME: error out in a more elegant fashion
7810     report_fatal_error("Unsupported asm: input constraint"
7811                        " with a matching output constraint of"
7812                        " incompatible type!");
7813   }
7814   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7815 }
7816 
7817 /// Get a direct memory input to behave well as an indirect operand.
7818 /// This may introduce stores, hence the need for a \p Chain.
7819 /// \return The (possibly updated) chain.
7820 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7821                                         SDISelAsmOperandInfo &OpInfo,
7822                                         SelectionDAG &DAG) {
7823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7824 
7825   // If we don't have an indirect input, put it in the constpool if we can,
7826   // otherwise spill it to a stack slot.
7827   // TODO: This isn't quite right. We need to handle these according to
7828   // the addressing mode that the constraint wants. Also, this may take
7829   // an additional register for the computation and we don't want that
7830   // either.
7831 
7832   // If the operand is a float, integer, or vector constant, spill to a
7833   // constant pool entry to get its address.
7834   const Value *OpVal = OpInfo.CallOperandVal;
7835   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7836       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7837     OpInfo.CallOperand = DAG.getConstantPool(
7838         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7839     return Chain;
7840   }
7841 
7842   // Otherwise, create a stack slot and emit a store to it before the asm.
7843   Type *Ty = OpVal->getType();
7844   auto &DL = DAG.getDataLayout();
7845   uint64_t TySize = DL.getTypeAllocSize(Ty);
7846   unsigned Align = DL.getPrefTypeAlignment(Ty);
7847   MachineFunction &MF = DAG.getMachineFunction();
7848   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7849   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7850   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7851                             MachinePointerInfo::getFixedStack(MF, SSFI),
7852                             TLI.getMemValueType(DL, Ty));
7853   OpInfo.CallOperand = StackSlot;
7854 
7855   return Chain;
7856 }
7857 
7858 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7859 /// specified operand.  We prefer to assign virtual registers, to allow the
7860 /// register allocator to handle the assignment process.  However, if the asm
7861 /// uses features that we can't model on machineinstrs, we have SDISel do the
7862 /// allocation.  This produces generally horrible, but correct, code.
7863 ///
7864 ///   OpInfo describes the operand
7865 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7866 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7867                                  SDISelAsmOperandInfo &OpInfo,
7868                                  SDISelAsmOperandInfo &RefOpInfo) {
7869   LLVMContext &Context = *DAG.getContext();
7870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7871 
7872   MachineFunction &MF = DAG.getMachineFunction();
7873   SmallVector<unsigned, 4> Regs;
7874   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7875 
7876   // No work to do for memory operations.
7877   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7878     return;
7879 
7880   // If this is a constraint for a single physreg, or a constraint for a
7881   // register class, find it.
7882   unsigned AssignedReg;
7883   const TargetRegisterClass *RC;
7884   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7885       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7886   // RC is unset only on failure. Return immediately.
7887   if (!RC)
7888     return;
7889 
7890   // Get the actual register value type.  This is important, because the user
7891   // may have asked for (e.g.) the AX register in i32 type.  We need to
7892   // remember that AX is actually i16 to get the right extension.
7893   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7894 
7895   if (OpInfo.ConstraintVT != MVT::Other) {
7896     // If this is an FP operand in an integer register (or visa versa), or more
7897     // generally if the operand value disagrees with the register class we plan
7898     // to stick it in, fix the operand type.
7899     //
7900     // If this is an input value, the bitcast to the new type is done now.
7901     // Bitcast for output value is done at the end of visitInlineAsm().
7902     if ((OpInfo.Type == InlineAsm::isOutput ||
7903          OpInfo.Type == InlineAsm::isInput) &&
7904         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7905       // Try to convert to the first EVT that the reg class contains.  If the
7906       // types are identical size, use a bitcast to convert (e.g. two differing
7907       // vector types).  Note: output bitcast is done at the end of
7908       // visitInlineAsm().
7909       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7910         // Exclude indirect inputs while they are unsupported because the code
7911         // to perform the load is missing and thus OpInfo.CallOperand still
7912         // refers to the input address rather than the pointed-to value.
7913         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7914           OpInfo.CallOperand =
7915               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7916         OpInfo.ConstraintVT = RegVT;
7917         // If the operand is an FP value and we want it in integer registers,
7918         // use the corresponding integer type. This turns an f64 value into
7919         // i64, which can be passed with two i32 values on a 32-bit machine.
7920       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7921         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7922         if (OpInfo.Type == InlineAsm::isInput)
7923           OpInfo.CallOperand =
7924               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7925         OpInfo.ConstraintVT = VT;
7926       }
7927     }
7928   }
7929 
7930   // No need to allocate a matching input constraint since the constraint it's
7931   // matching to has already been allocated.
7932   if (OpInfo.isMatchingInputConstraint())
7933     return;
7934 
7935   EVT ValueVT = OpInfo.ConstraintVT;
7936   if (OpInfo.ConstraintVT == MVT::Other)
7937     ValueVT = RegVT;
7938 
7939   // Initialize NumRegs.
7940   unsigned NumRegs = 1;
7941   if (OpInfo.ConstraintVT != MVT::Other)
7942     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7943 
7944   // If this is a constraint for a specific physical register, like {r17},
7945   // assign it now.
7946 
7947   // If this associated to a specific register, initialize iterator to correct
7948   // place. If virtual, make sure we have enough registers
7949 
7950   // Initialize iterator if necessary
7951   TargetRegisterClass::iterator I = RC->begin();
7952   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7953 
7954   // Do not check for single registers.
7955   if (AssignedReg) {
7956       for (; *I != AssignedReg; ++I)
7957         assert(I != RC->end() && "AssignedReg should be member of RC");
7958   }
7959 
7960   for (; NumRegs; --NumRegs, ++I) {
7961     assert(I != RC->end() && "Ran out of registers to allocate!");
7962     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7963     Regs.push_back(R);
7964   }
7965 
7966   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7967 }
7968 
7969 static unsigned
7970 findMatchingInlineAsmOperand(unsigned OperandNo,
7971                              const std::vector<SDValue> &AsmNodeOperands) {
7972   // Scan until we find the definition we already emitted of this operand.
7973   unsigned CurOp = InlineAsm::Op_FirstOperand;
7974   for (; OperandNo; --OperandNo) {
7975     // Advance to the next operand.
7976     unsigned OpFlag =
7977         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7978     assert((InlineAsm::isRegDefKind(OpFlag) ||
7979             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7980             InlineAsm::isMemKind(OpFlag)) &&
7981            "Skipped past definitions?");
7982     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7983   }
7984   return CurOp;
7985 }
7986 
7987 namespace {
7988 
7989 class ExtraFlags {
7990   unsigned Flags = 0;
7991 
7992 public:
7993   explicit ExtraFlags(const CallBase &Call) {
7994     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
7995     if (IA->hasSideEffects())
7996       Flags |= InlineAsm::Extra_HasSideEffects;
7997     if (IA->isAlignStack())
7998       Flags |= InlineAsm::Extra_IsAlignStack;
7999     if (Call.isConvergent())
8000       Flags |= InlineAsm::Extra_IsConvergent;
8001     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8002   }
8003 
8004   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8005     // Ideally, we would only check against memory constraints.  However, the
8006     // meaning of an Other constraint can be target-specific and we can't easily
8007     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8008     // for Other constraints as well.
8009     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8010         OpInfo.ConstraintType == TargetLowering::C_Other) {
8011       if (OpInfo.Type == InlineAsm::isInput)
8012         Flags |= InlineAsm::Extra_MayLoad;
8013       else if (OpInfo.Type == InlineAsm::isOutput)
8014         Flags |= InlineAsm::Extra_MayStore;
8015       else if (OpInfo.Type == InlineAsm::isClobber)
8016         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8017     }
8018   }
8019 
8020   unsigned get() const { return Flags; }
8021 };
8022 
8023 } // end anonymous namespace
8024 
8025 /// visitInlineAsm - Handle a call to an InlineAsm object.
8026 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8027   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8028 
8029   /// ConstraintOperands - Information about all of the constraints.
8030   SDISelAsmOperandInfoVector ConstraintOperands;
8031 
8032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8033   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8034       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8035 
8036   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8037   // AsmDialect, MayLoad, MayStore).
8038   bool HasSideEffect = IA->hasSideEffects();
8039   ExtraFlags ExtraInfo(Call);
8040 
8041   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8042   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8043   unsigned NumMatchingOps = 0;
8044   for (auto &T : TargetConstraints) {
8045     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8046     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8047 
8048     // Compute the value type for each operand.
8049     if (OpInfo.Type == InlineAsm::isInput ||
8050         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8051       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8052 
8053       // Process the call argument. BasicBlocks are labels, currently appearing
8054       // only in asm's.
8055       if (isa<CallBrInst>(Call) &&
8056           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8057                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8058                         NumMatchingOps) &&
8059           (NumMatchingOps == 0 ||
8060            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8061                         NumMatchingOps))) {
8062         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8063         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8064         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8065       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8066         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8067       } else {
8068         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8069       }
8070 
8071       OpInfo.ConstraintVT =
8072           OpInfo
8073               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8074               .getSimpleVT();
8075     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8076       // The return value of the call is this value.  As such, there is no
8077       // corresponding argument.
8078       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8079       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8080         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8081             DAG.getDataLayout(), STy->getElementType(ResNo));
8082       } else {
8083         assert(ResNo == 0 && "Asm only has one result!");
8084         OpInfo.ConstraintVT =
8085             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8086       }
8087       ++ResNo;
8088     } else {
8089       OpInfo.ConstraintVT = MVT::Other;
8090     }
8091 
8092     if (OpInfo.hasMatchingInput())
8093       ++NumMatchingOps;
8094 
8095     if (!HasSideEffect)
8096       HasSideEffect = OpInfo.hasMemory(TLI);
8097 
8098     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8099     // FIXME: Could we compute this on OpInfo rather than T?
8100 
8101     // Compute the constraint code and ConstraintType to use.
8102     TLI.ComputeConstraintToUse(T, SDValue());
8103 
8104     if (T.ConstraintType == TargetLowering::C_Immediate &&
8105         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8106       // We've delayed emitting a diagnostic like the "n" constraint because
8107       // inlining could cause an integer showing up.
8108       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8109                                           "' expects an integer constant "
8110                                           "expression");
8111 
8112     ExtraInfo.update(T);
8113   }
8114 
8115 
8116   // We won't need to flush pending loads if this asm doesn't touch
8117   // memory and is nonvolatile.
8118   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8119 
8120   bool IsCallBr = isa<CallBrInst>(Call);
8121   if (IsCallBr) {
8122     // If this is a callbr we need to flush pending exports since inlineasm_br
8123     // is a terminator. We need to do this before nodes are glued to
8124     // the inlineasm_br node.
8125     Chain = getControlRoot();
8126   }
8127 
8128   // Second pass over the constraints: compute which constraint option to use.
8129   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8130     // If this is an output operand with a matching input operand, look up the
8131     // matching input. If their types mismatch, e.g. one is an integer, the
8132     // other is floating point, or their sizes are different, flag it as an
8133     // error.
8134     if (OpInfo.hasMatchingInput()) {
8135       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8136       patchMatchingInput(OpInfo, Input, DAG);
8137     }
8138 
8139     // Compute the constraint code and ConstraintType to use.
8140     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8141 
8142     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8143         OpInfo.Type == InlineAsm::isClobber)
8144       continue;
8145 
8146     // If this is a memory input, and if the operand is not indirect, do what we
8147     // need to provide an address for the memory input.
8148     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8149         !OpInfo.isIndirect) {
8150       assert((OpInfo.isMultipleAlternative ||
8151               (OpInfo.Type == InlineAsm::isInput)) &&
8152              "Can only indirectify direct input operands!");
8153 
8154       // Memory operands really want the address of the value.
8155       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8156 
8157       // There is no longer a Value* corresponding to this operand.
8158       OpInfo.CallOperandVal = nullptr;
8159 
8160       // It is now an indirect operand.
8161       OpInfo.isIndirect = true;
8162     }
8163 
8164   }
8165 
8166   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8167   std::vector<SDValue> AsmNodeOperands;
8168   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8169   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8170       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8171 
8172   // If we have a !srcloc metadata node associated with it, we want to attach
8173   // this to the ultimately generated inline asm machineinstr.  To do this, we
8174   // pass in the third operand as this (potentially null) inline asm MDNode.
8175   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8176   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8177 
8178   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8179   // bits as operand 3.
8180   AsmNodeOperands.push_back(DAG.getTargetConstant(
8181       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8182 
8183   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8184   // this, assign virtual and physical registers for inputs and otput.
8185   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8186     // Assign Registers.
8187     SDISelAsmOperandInfo &RefOpInfo =
8188         OpInfo.isMatchingInputConstraint()
8189             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8190             : OpInfo;
8191     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8192 
8193     auto DetectWriteToReservedRegister = [&]() {
8194       const MachineFunction &MF = DAG.getMachineFunction();
8195       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8196       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8197         if (Register::isPhysicalRegister(Reg) &&
8198             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8199           const char *RegName = TRI.getName(Reg);
8200           emitInlineAsmError(Call, "write to reserved register '" +
8201                                        Twine(RegName) + "'");
8202           return true;
8203         }
8204       }
8205       return false;
8206     };
8207 
8208     switch (OpInfo.Type) {
8209     case InlineAsm::isOutput:
8210       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8211         unsigned ConstraintID =
8212             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8213         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8214                "Failed to convert memory constraint code to constraint id.");
8215 
8216         // Add information to the INLINEASM node to know about this output.
8217         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8218         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8219         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8220                                                         MVT::i32));
8221         AsmNodeOperands.push_back(OpInfo.CallOperand);
8222       } else {
8223         // Otherwise, this outputs to a register (directly for C_Register /
8224         // C_RegisterClass, and a target-defined fashion for
8225         // C_Immediate/C_Other). Find a register that we can use.
8226         if (OpInfo.AssignedRegs.Regs.empty()) {
8227           emitInlineAsmError(
8228               Call, "couldn't allocate output register for constraint '" +
8229                         Twine(OpInfo.ConstraintCode) + "'");
8230           return;
8231         }
8232 
8233         if (DetectWriteToReservedRegister())
8234           return;
8235 
8236         // Add information to the INLINEASM node to know that this register is
8237         // set.
8238         OpInfo.AssignedRegs.AddInlineAsmOperands(
8239             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8240                                   : InlineAsm::Kind_RegDef,
8241             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8242       }
8243       break;
8244 
8245     case InlineAsm::isInput: {
8246       SDValue InOperandVal = OpInfo.CallOperand;
8247 
8248       if (OpInfo.isMatchingInputConstraint()) {
8249         // If this is required to match an output register we have already set,
8250         // just use its register.
8251         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8252                                                   AsmNodeOperands);
8253         unsigned OpFlag =
8254           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8255         if (InlineAsm::isRegDefKind(OpFlag) ||
8256             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8257           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8258           if (OpInfo.isIndirect) {
8259             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8260             emitInlineAsmError(Call, "inline asm not supported yet: "
8261                                      "don't know how to handle tied "
8262                                      "indirect register inputs");
8263             return;
8264           }
8265 
8266           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8267           SmallVector<unsigned, 4> Regs;
8268 
8269           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8270             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8271             MachineRegisterInfo &RegInfo =
8272                 DAG.getMachineFunction().getRegInfo();
8273             for (unsigned i = 0; i != NumRegs; ++i)
8274               Regs.push_back(RegInfo.createVirtualRegister(RC));
8275           } else {
8276             emitInlineAsmError(Call,
8277                                "inline asm error: This value type register "
8278                                "class is not natively supported!");
8279             return;
8280           }
8281 
8282           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8283 
8284           SDLoc dl = getCurSDLoc();
8285           // Use the produced MatchedRegs object to
8286           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8287           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8288                                            true, OpInfo.getMatchedOperand(), dl,
8289                                            DAG, AsmNodeOperands);
8290           break;
8291         }
8292 
8293         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8294         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8295                "Unexpected number of operands");
8296         // Add information to the INLINEASM node to know about this input.
8297         // See InlineAsm.h isUseOperandTiedToDef.
8298         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8299         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8300                                                     OpInfo.getMatchedOperand());
8301         AsmNodeOperands.push_back(DAG.getTargetConstant(
8302             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8303         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8304         break;
8305       }
8306 
8307       // Treat indirect 'X' constraint as memory.
8308       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8309           OpInfo.isIndirect)
8310         OpInfo.ConstraintType = TargetLowering::C_Memory;
8311 
8312       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8313           OpInfo.ConstraintType == TargetLowering::C_Other) {
8314         std::vector<SDValue> Ops;
8315         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8316                                           Ops, DAG);
8317         if (Ops.empty()) {
8318           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8319             if (isa<ConstantSDNode>(InOperandVal)) {
8320               emitInlineAsmError(Call, "value out of range for constraint '" +
8321                                            Twine(OpInfo.ConstraintCode) + "'");
8322               return;
8323             }
8324 
8325           emitInlineAsmError(Call,
8326                              "invalid operand for inline asm constraint '" +
8327                                  Twine(OpInfo.ConstraintCode) + "'");
8328           return;
8329         }
8330 
8331         // Add information to the INLINEASM node to know about this input.
8332         unsigned ResOpType =
8333           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8334         AsmNodeOperands.push_back(DAG.getTargetConstant(
8335             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8336         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8337         break;
8338       }
8339 
8340       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8341         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8342         assert(InOperandVal.getValueType() ==
8343                    TLI.getPointerTy(DAG.getDataLayout()) &&
8344                "Memory operands expect pointer values");
8345 
8346         unsigned ConstraintID =
8347             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8348         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8349                "Failed to convert memory constraint code to constraint id.");
8350 
8351         // Add information to the INLINEASM node to know about this input.
8352         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8353         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8354         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8355                                                         getCurSDLoc(),
8356                                                         MVT::i32));
8357         AsmNodeOperands.push_back(InOperandVal);
8358         break;
8359       }
8360 
8361       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8362               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8363              "Unknown constraint type!");
8364 
8365       // TODO: Support this.
8366       if (OpInfo.isIndirect) {
8367         emitInlineAsmError(
8368             Call, "Don't know how to handle indirect register inputs yet "
8369                   "for constraint '" +
8370                       Twine(OpInfo.ConstraintCode) + "'");
8371         return;
8372       }
8373 
8374       // Copy the input into the appropriate registers.
8375       if (OpInfo.AssignedRegs.Regs.empty()) {
8376         emitInlineAsmError(Call,
8377                            "couldn't allocate input reg for constraint '" +
8378                                Twine(OpInfo.ConstraintCode) + "'");
8379         return;
8380       }
8381 
8382       if (DetectWriteToReservedRegister())
8383         return;
8384 
8385       SDLoc dl = getCurSDLoc();
8386 
8387       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8388                                         &Call);
8389 
8390       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8391                                                dl, DAG, AsmNodeOperands);
8392       break;
8393     }
8394     case InlineAsm::isClobber:
8395       // Add the clobbered value to the operand list, so that the register
8396       // allocator is aware that the physreg got clobbered.
8397       if (!OpInfo.AssignedRegs.Regs.empty())
8398         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8399                                                  false, 0, getCurSDLoc(), DAG,
8400                                                  AsmNodeOperands);
8401       break;
8402     }
8403   }
8404 
8405   // Finish up input operands.  Set the input chain and add the flag last.
8406   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8407   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8408 
8409   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8410   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8411                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8412   Flag = Chain.getValue(1);
8413 
8414   // Do additional work to generate outputs.
8415 
8416   SmallVector<EVT, 1> ResultVTs;
8417   SmallVector<SDValue, 1> ResultValues;
8418   SmallVector<SDValue, 8> OutChains;
8419 
8420   llvm::Type *CallResultType = Call.getType();
8421   ArrayRef<Type *> ResultTypes;
8422   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8423     ResultTypes = StructResult->elements();
8424   else if (!CallResultType->isVoidTy())
8425     ResultTypes = makeArrayRef(CallResultType);
8426 
8427   auto CurResultType = ResultTypes.begin();
8428   auto handleRegAssign = [&](SDValue V) {
8429     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8430     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8431     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8432     ++CurResultType;
8433     // If the type of the inline asm call site return value is different but has
8434     // same size as the type of the asm output bitcast it.  One example of this
8435     // is for vectors with different width / number of elements.  This can
8436     // happen for register classes that can contain multiple different value
8437     // types.  The preg or vreg allocated may not have the same VT as was
8438     // expected.
8439     //
8440     // This can also happen for a return value that disagrees with the register
8441     // class it is put in, eg. a double in a general-purpose register on a
8442     // 32-bit machine.
8443     if (ResultVT != V.getValueType() &&
8444         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8445       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8446     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8447              V.getValueType().isInteger()) {
8448       // If a result value was tied to an input value, the computed result
8449       // may have a wider width than the expected result.  Extract the
8450       // relevant portion.
8451       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8452     }
8453     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8454     ResultVTs.push_back(ResultVT);
8455     ResultValues.push_back(V);
8456   };
8457 
8458   // Deal with output operands.
8459   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8460     if (OpInfo.Type == InlineAsm::isOutput) {
8461       SDValue Val;
8462       // Skip trivial output operands.
8463       if (OpInfo.AssignedRegs.Regs.empty())
8464         continue;
8465 
8466       switch (OpInfo.ConstraintType) {
8467       case TargetLowering::C_Register:
8468       case TargetLowering::C_RegisterClass:
8469         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8470                                                   Chain, &Flag, &Call);
8471         break;
8472       case TargetLowering::C_Immediate:
8473       case TargetLowering::C_Other:
8474         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8475                                               OpInfo, DAG);
8476         break;
8477       case TargetLowering::C_Memory:
8478         break; // Already handled.
8479       case TargetLowering::C_Unknown:
8480         assert(false && "Unexpected unknown constraint");
8481       }
8482 
8483       // Indirect output manifest as stores. Record output chains.
8484       if (OpInfo.isIndirect) {
8485         const Value *Ptr = OpInfo.CallOperandVal;
8486         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8487         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8488                                      MachinePointerInfo(Ptr));
8489         OutChains.push_back(Store);
8490       } else {
8491         // generate CopyFromRegs to associated registers.
8492         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8493         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8494           for (const SDValue &V : Val->op_values())
8495             handleRegAssign(V);
8496         } else
8497           handleRegAssign(Val);
8498       }
8499     }
8500   }
8501 
8502   // Set results.
8503   if (!ResultValues.empty()) {
8504     assert(CurResultType == ResultTypes.end() &&
8505            "Mismatch in number of ResultTypes");
8506     assert(ResultValues.size() == ResultTypes.size() &&
8507            "Mismatch in number of output operands in asm result");
8508 
8509     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8510                             DAG.getVTList(ResultVTs), ResultValues);
8511     setValue(&Call, V);
8512   }
8513 
8514   // Collect store chains.
8515   if (!OutChains.empty())
8516     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8517 
8518   // Only Update Root if inline assembly has a memory effect.
8519   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8520     DAG.setRoot(Chain);
8521 }
8522 
8523 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8524                                              const Twine &Message) {
8525   LLVMContext &Ctx = *DAG.getContext();
8526   Ctx.emitError(&Call, Message);
8527 
8528   // Make sure we leave the DAG in a valid state
8529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8530   SmallVector<EVT, 1> ValueVTs;
8531   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8532 
8533   if (ValueVTs.empty())
8534     return;
8535 
8536   SmallVector<SDValue, 1> Ops;
8537   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8538     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8539 
8540   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8541 }
8542 
8543 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8544   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8545                           MVT::Other, getRoot(),
8546                           getValue(I.getArgOperand(0)),
8547                           DAG.getSrcValue(I.getArgOperand(0))));
8548 }
8549 
8550 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8552   const DataLayout &DL = DAG.getDataLayout();
8553   SDValue V = DAG.getVAArg(
8554       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8555       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8556       DL.getABITypeAlignment(I.getType()));
8557   DAG.setRoot(V.getValue(1));
8558 
8559   if (I.getType()->isPointerTy())
8560     V = DAG.getPtrExtOrTrunc(
8561         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8562   setValue(&I, V);
8563 }
8564 
8565 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8566   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8567                           MVT::Other, getRoot(),
8568                           getValue(I.getArgOperand(0)),
8569                           DAG.getSrcValue(I.getArgOperand(0))));
8570 }
8571 
8572 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8573   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8574                           MVT::Other, getRoot(),
8575                           getValue(I.getArgOperand(0)),
8576                           getValue(I.getArgOperand(1)),
8577                           DAG.getSrcValue(I.getArgOperand(0)),
8578                           DAG.getSrcValue(I.getArgOperand(1))));
8579 }
8580 
8581 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8582                                                     const Instruction &I,
8583                                                     SDValue Op) {
8584   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8585   if (!Range)
8586     return Op;
8587 
8588   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8589   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8590     return Op;
8591 
8592   APInt Lo = CR.getUnsignedMin();
8593   if (!Lo.isMinValue())
8594     return Op;
8595 
8596   APInt Hi = CR.getUnsignedMax();
8597   unsigned Bits = std::max(Hi.getActiveBits(),
8598                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8599 
8600   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8601 
8602   SDLoc SL = getCurSDLoc();
8603 
8604   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8605                              DAG.getValueType(SmallVT));
8606   unsigned NumVals = Op.getNode()->getNumValues();
8607   if (NumVals == 1)
8608     return ZExt;
8609 
8610   SmallVector<SDValue, 4> Ops;
8611 
8612   Ops.push_back(ZExt);
8613   for (unsigned I = 1; I != NumVals; ++I)
8614     Ops.push_back(Op.getValue(I));
8615 
8616   return DAG.getMergeValues(Ops, SL);
8617 }
8618 
8619 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8620 /// the call being lowered.
8621 ///
8622 /// This is a helper for lowering intrinsics that follow a target calling
8623 /// convention or require stack pointer adjustment. Only a subset of the
8624 /// intrinsic's operands need to participate in the calling convention.
8625 void SelectionDAGBuilder::populateCallLoweringInfo(
8626     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8627     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8628     bool IsPatchPoint) {
8629   TargetLowering::ArgListTy Args;
8630   Args.reserve(NumArgs);
8631 
8632   // Populate the argument list.
8633   // Attributes for args start at offset 1, after the return attribute.
8634   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8635        ArgI != ArgE; ++ArgI) {
8636     const Value *V = Call->getOperand(ArgI);
8637 
8638     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8639 
8640     TargetLowering::ArgListEntry Entry;
8641     Entry.Node = getValue(V);
8642     Entry.Ty = V->getType();
8643     Entry.setAttributes(Call, ArgI);
8644     Args.push_back(Entry);
8645   }
8646 
8647   CLI.setDebugLoc(getCurSDLoc())
8648       .setChain(getRoot())
8649       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8650       .setDiscardResult(Call->use_empty())
8651       .setIsPatchPoint(IsPatchPoint)
8652       .setIsPreallocated(
8653           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8654 }
8655 
8656 /// Add a stack map intrinsic call's live variable operands to a stackmap
8657 /// or patchpoint target node's operand list.
8658 ///
8659 /// Constants are converted to TargetConstants purely as an optimization to
8660 /// avoid constant materialization and register allocation.
8661 ///
8662 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8663 /// generate addess computation nodes, and so FinalizeISel can convert the
8664 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8665 /// address materialization and register allocation, but may also be required
8666 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8667 /// alloca in the entry block, then the runtime may assume that the alloca's
8668 /// StackMap location can be read immediately after compilation and that the
8669 /// location is valid at any point during execution (this is similar to the
8670 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8671 /// only available in a register, then the runtime would need to trap when
8672 /// execution reaches the StackMap in order to read the alloca's location.
8673 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8674                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8675                                 SelectionDAGBuilder &Builder) {
8676   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8677     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8679       Ops.push_back(
8680         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8681       Ops.push_back(
8682         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8683     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8684       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8685       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8686           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8687     } else
8688       Ops.push_back(OpVal);
8689   }
8690 }
8691 
8692 /// Lower llvm.experimental.stackmap directly to its target opcode.
8693 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8694   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8695   //                                  [live variables...])
8696 
8697   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8698 
8699   SDValue Chain, InFlag, Callee, NullPtr;
8700   SmallVector<SDValue, 32> Ops;
8701 
8702   SDLoc DL = getCurSDLoc();
8703   Callee = getValue(CI.getCalledOperand());
8704   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8705 
8706   // The stackmap intrinsic only records the live variables (the arguments
8707   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8708   // intrinsic, this won't be lowered to a function call. This means we don't
8709   // have to worry about calling conventions and target specific lowering code.
8710   // Instead we perform the call lowering right here.
8711   //
8712   // chain, flag = CALLSEQ_START(chain, 0, 0)
8713   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8714   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8715   //
8716   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8717   InFlag = Chain.getValue(1);
8718 
8719   // Add the <id> and <numBytes> constants.
8720   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8721   Ops.push_back(DAG.getTargetConstant(
8722                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8723   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8724   Ops.push_back(DAG.getTargetConstant(
8725                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8726                   MVT::i32));
8727 
8728   // Push live variables for the stack map.
8729   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8730 
8731   // We are not pushing any register mask info here on the operands list,
8732   // because the stackmap doesn't clobber anything.
8733 
8734   // Push the chain and the glue flag.
8735   Ops.push_back(Chain);
8736   Ops.push_back(InFlag);
8737 
8738   // Create the STACKMAP node.
8739   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8740   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8741   Chain = SDValue(SM, 0);
8742   InFlag = Chain.getValue(1);
8743 
8744   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8745 
8746   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8747 
8748   // Set the root to the target-lowered call chain.
8749   DAG.setRoot(Chain);
8750 
8751   // Inform the Frame Information that we have a stackmap in this function.
8752   FuncInfo.MF->getFrameInfo().setHasStackMap();
8753 }
8754 
8755 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8756 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8757                                           const BasicBlock *EHPadBB) {
8758   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8759   //                                                 i32 <numBytes>,
8760   //                                                 i8* <target>,
8761   //                                                 i32 <numArgs>,
8762   //                                                 [Args...],
8763   //                                                 [live variables...])
8764 
8765   CallingConv::ID CC = CB.getCallingConv();
8766   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8767   bool HasDef = !CB.getType()->isVoidTy();
8768   SDLoc dl = getCurSDLoc();
8769   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8770 
8771   // Handle immediate and symbolic callees.
8772   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8773     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8774                                    /*isTarget=*/true);
8775   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8776     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8777                                          SDLoc(SymbolicCallee),
8778                                          SymbolicCallee->getValueType(0));
8779 
8780   // Get the real number of arguments participating in the call <numArgs>
8781   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8782   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8783 
8784   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8785   // Intrinsics include all meta-operands up to but not including CC.
8786   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8787   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8788          "Not enough arguments provided to the patchpoint intrinsic");
8789 
8790   // For AnyRegCC the arguments are lowered later on manually.
8791   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8792   Type *ReturnTy =
8793       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8794 
8795   TargetLowering::CallLoweringInfo CLI(DAG);
8796   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8797                            ReturnTy, true);
8798   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8799 
8800   SDNode *CallEnd = Result.second.getNode();
8801   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8802     CallEnd = CallEnd->getOperand(0).getNode();
8803 
8804   /// Get a call instruction from the call sequence chain.
8805   /// Tail calls are not allowed.
8806   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8807          "Expected a callseq node.");
8808   SDNode *Call = CallEnd->getOperand(0).getNode();
8809   bool HasGlue = Call->getGluedNode();
8810 
8811   // Replace the target specific call node with the patchable intrinsic.
8812   SmallVector<SDValue, 8> Ops;
8813 
8814   // Add the <id> and <numBytes> constants.
8815   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8816   Ops.push_back(DAG.getTargetConstant(
8817                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8818   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8819   Ops.push_back(DAG.getTargetConstant(
8820                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8821                   MVT::i32));
8822 
8823   // Add the callee.
8824   Ops.push_back(Callee);
8825 
8826   // Adjust <numArgs> to account for any arguments that have been passed on the
8827   // stack instead.
8828   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8829   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8830   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8831   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8832 
8833   // Add the calling convention
8834   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8835 
8836   // Add the arguments we omitted previously. The register allocator should
8837   // place these in any free register.
8838   if (IsAnyRegCC)
8839     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8840       Ops.push_back(getValue(CB.getArgOperand(i)));
8841 
8842   // Push the arguments from the call instruction up to the register mask.
8843   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8844   Ops.append(Call->op_begin() + 2, e);
8845 
8846   // Push live variables for the stack map.
8847   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8848 
8849   // Push the register mask info.
8850   if (HasGlue)
8851     Ops.push_back(*(Call->op_end()-2));
8852   else
8853     Ops.push_back(*(Call->op_end()-1));
8854 
8855   // Push the chain (this is originally the first operand of the call, but
8856   // becomes now the last or second to last operand).
8857   Ops.push_back(*(Call->op_begin()));
8858 
8859   // Push the glue flag (last operand).
8860   if (HasGlue)
8861     Ops.push_back(*(Call->op_end()-1));
8862 
8863   SDVTList NodeTys;
8864   if (IsAnyRegCC && HasDef) {
8865     // Create the return types based on the intrinsic definition
8866     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8867     SmallVector<EVT, 3> ValueVTs;
8868     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8869     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8870 
8871     // There is always a chain and a glue type at the end
8872     ValueVTs.push_back(MVT::Other);
8873     ValueVTs.push_back(MVT::Glue);
8874     NodeTys = DAG.getVTList(ValueVTs);
8875   } else
8876     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8877 
8878   // Replace the target specific call node with a PATCHPOINT node.
8879   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8880                                          dl, NodeTys, Ops);
8881 
8882   // Update the NodeMap.
8883   if (HasDef) {
8884     if (IsAnyRegCC)
8885       setValue(&CB, SDValue(MN, 0));
8886     else
8887       setValue(&CB, Result.first);
8888   }
8889 
8890   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8891   // call sequence. Furthermore the location of the chain and glue can change
8892   // when the AnyReg calling convention is used and the intrinsic returns a
8893   // value.
8894   if (IsAnyRegCC && HasDef) {
8895     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8896     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8897     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8898   } else
8899     DAG.ReplaceAllUsesWith(Call, MN);
8900   DAG.DeleteNode(Call);
8901 
8902   // Inform the Frame Information that we have a patchpoint in this function.
8903   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8904 }
8905 
8906 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8907                                             unsigned Intrinsic) {
8908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8909   SDValue Op1 = getValue(I.getArgOperand(0));
8910   SDValue Op2;
8911   if (I.getNumArgOperands() > 1)
8912     Op2 = getValue(I.getArgOperand(1));
8913   SDLoc dl = getCurSDLoc();
8914   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8915   SDValue Res;
8916   FastMathFlags FMF;
8917   if (isa<FPMathOperator>(I))
8918     FMF = I.getFastMathFlags();
8919 
8920   switch (Intrinsic) {
8921   case Intrinsic::experimental_vector_reduce_v2_fadd:
8922     if (FMF.allowReassoc())
8923       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8924                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8925     else
8926       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8927     break;
8928   case Intrinsic::experimental_vector_reduce_v2_fmul:
8929     if (FMF.allowReassoc())
8930       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8931                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8932     else
8933       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8934     break;
8935   case Intrinsic::experimental_vector_reduce_add:
8936     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8937     break;
8938   case Intrinsic::experimental_vector_reduce_mul:
8939     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8940     break;
8941   case Intrinsic::experimental_vector_reduce_and:
8942     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8943     break;
8944   case Intrinsic::experimental_vector_reduce_or:
8945     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8946     break;
8947   case Intrinsic::experimental_vector_reduce_xor:
8948     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8949     break;
8950   case Intrinsic::experimental_vector_reduce_smax:
8951     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8952     break;
8953   case Intrinsic::experimental_vector_reduce_smin:
8954     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8955     break;
8956   case Intrinsic::experimental_vector_reduce_umax:
8957     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8958     break;
8959   case Intrinsic::experimental_vector_reduce_umin:
8960     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8961     break;
8962   case Intrinsic::experimental_vector_reduce_fmax:
8963     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8964     break;
8965   case Intrinsic::experimental_vector_reduce_fmin:
8966     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8967     break;
8968   default:
8969     llvm_unreachable("Unhandled vector reduce intrinsic");
8970   }
8971   setValue(&I, Res);
8972 }
8973 
8974 /// Returns an AttributeList representing the attributes applied to the return
8975 /// value of the given call.
8976 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8977   SmallVector<Attribute::AttrKind, 2> Attrs;
8978   if (CLI.RetSExt)
8979     Attrs.push_back(Attribute::SExt);
8980   if (CLI.RetZExt)
8981     Attrs.push_back(Attribute::ZExt);
8982   if (CLI.IsInReg)
8983     Attrs.push_back(Attribute::InReg);
8984 
8985   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8986                             Attrs);
8987 }
8988 
8989 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8990 /// implementation, which just calls LowerCall.
8991 /// FIXME: When all targets are
8992 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8993 std::pair<SDValue, SDValue>
8994 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8995   // Handle the incoming return values from the call.
8996   CLI.Ins.clear();
8997   Type *OrigRetTy = CLI.RetTy;
8998   SmallVector<EVT, 4> RetTys;
8999   SmallVector<uint64_t, 4> Offsets;
9000   auto &DL = CLI.DAG.getDataLayout();
9001   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9002 
9003   if (CLI.IsPostTypeLegalization) {
9004     // If we are lowering a libcall after legalization, split the return type.
9005     SmallVector<EVT, 4> OldRetTys;
9006     SmallVector<uint64_t, 4> OldOffsets;
9007     RetTys.swap(OldRetTys);
9008     Offsets.swap(OldOffsets);
9009 
9010     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9011       EVT RetVT = OldRetTys[i];
9012       uint64_t Offset = OldOffsets[i];
9013       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9014       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9015       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9016       RetTys.append(NumRegs, RegisterVT);
9017       for (unsigned j = 0; j != NumRegs; ++j)
9018         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9019     }
9020   }
9021 
9022   SmallVector<ISD::OutputArg, 4> Outs;
9023   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9024 
9025   bool CanLowerReturn =
9026       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9027                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9028 
9029   SDValue DemoteStackSlot;
9030   int DemoteStackIdx = -100;
9031   if (!CanLowerReturn) {
9032     // FIXME: equivalent assert?
9033     // assert(!CS.hasInAllocaArgument() &&
9034     //        "sret demotion is incompatible with inalloca");
9035     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9036     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9037     MachineFunction &MF = CLI.DAG.getMachineFunction();
9038     DemoteStackIdx =
9039         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9040     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9041                                               DL.getAllocaAddrSpace());
9042 
9043     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9044     ArgListEntry Entry;
9045     Entry.Node = DemoteStackSlot;
9046     Entry.Ty = StackSlotPtrType;
9047     Entry.IsSExt = false;
9048     Entry.IsZExt = false;
9049     Entry.IsInReg = false;
9050     Entry.IsSRet = true;
9051     Entry.IsNest = false;
9052     Entry.IsByVal = false;
9053     Entry.IsReturned = false;
9054     Entry.IsSwiftSelf = false;
9055     Entry.IsSwiftError = false;
9056     Entry.IsCFGuardTarget = false;
9057     Entry.Alignment = Alignment;
9058     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9059     CLI.NumFixedArgs += 1;
9060     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9061 
9062     // sret demotion isn't compatible with tail-calls, since the sret argument
9063     // points into the callers stack frame.
9064     CLI.IsTailCall = false;
9065   } else {
9066     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9067         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9068     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9069       ISD::ArgFlagsTy Flags;
9070       if (NeedsRegBlock) {
9071         Flags.setInConsecutiveRegs();
9072         if (I == RetTys.size() - 1)
9073           Flags.setInConsecutiveRegsLast();
9074       }
9075       EVT VT = RetTys[I];
9076       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9077                                                      CLI.CallConv, VT);
9078       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9079                                                        CLI.CallConv, VT);
9080       for (unsigned i = 0; i != NumRegs; ++i) {
9081         ISD::InputArg MyFlags;
9082         MyFlags.Flags = Flags;
9083         MyFlags.VT = RegisterVT;
9084         MyFlags.ArgVT = VT;
9085         MyFlags.Used = CLI.IsReturnValueUsed;
9086         if (CLI.RetTy->isPointerTy()) {
9087           MyFlags.Flags.setPointer();
9088           MyFlags.Flags.setPointerAddrSpace(
9089               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9090         }
9091         if (CLI.RetSExt)
9092           MyFlags.Flags.setSExt();
9093         if (CLI.RetZExt)
9094           MyFlags.Flags.setZExt();
9095         if (CLI.IsInReg)
9096           MyFlags.Flags.setInReg();
9097         CLI.Ins.push_back(MyFlags);
9098       }
9099     }
9100   }
9101 
9102   // We push in swifterror return as the last element of CLI.Ins.
9103   ArgListTy &Args = CLI.getArgs();
9104   if (supportSwiftError()) {
9105     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9106       if (Args[i].IsSwiftError) {
9107         ISD::InputArg MyFlags;
9108         MyFlags.VT = getPointerTy(DL);
9109         MyFlags.ArgVT = EVT(getPointerTy(DL));
9110         MyFlags.Flags.setSwiftError();
9111         CLI.Ins.push_back(MyFlags);
9112       }
9113     }
9114   }
9115 
9116   // Handle all of the outgoing arguments.
9117   CLI.Outs.clear();
9118   CLI.OutVals.clear();
9119   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9120     SmallVector<EVT, 4> ValueVTs;
9121     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9122     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9123     Type *FinalType = Args[i].Ty;
9124     if (Args[i].IsByVal)
9125       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9126     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9127         FinalType, CLI.CallConv, CLI.IsVarArg);
9128     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9129          ++Value) {
9130       EVT VT = ValueVTs[Value];
9131       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9132       SDValue Op = SDValue(Args[i].Node.getNode(),
9133                            Args[i].Node.getResNo() + Value);
9134       ISD::ArgFlagsTy Flags;
9135 
9136       // Certain targets (such as MIPS), may have a different ABI alignment
9137       // for a type depending on the context. Give the target a chance to
9138       // specify the alignment it wants.
9139       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9140 
9141       if (Args[i].Ty->isPointerTy()) {
9142         Flags.setPointer();
9143         Flags.setPointerAddrSpace(
9144             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9145       }
9146       if (Args[i].IsZExt)
9147         Flags.setZExt();
9148       if (Args[i].IsSExt)
9149         Flags.setSExt();
9150       if (Args[i].IsInReg) {
9151         // If we are using vectorcall calling convention, a structure that is
9152         // passed InReg - is surely an HVA
9153         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9154             isa<StructType>(FinalType)) {
9155           // The first value of a structure is marked
9156           if (0 == Value)
9157             Flags.setHvaStart();
9158           Flags.setHva();
9159         }
9160         // Set InReg Flag
9161         Flags.setInReg();
9162       }
9163       if (Args[i].IsSRet)
9164         Flags.setSRet();
9165       if (Args[i].IsSwiftSelf)
9166         Flags.setSwiftSelf();
9167       if (Args[i].IsSwiftError)
9168         Flags.setSwiftError();
9169       if (Args[i].IsCFGuardTarget)
9170         Flags.setCFGuardTarget();
9171       if (Args[i].IsByVal)
9172         Flags.setByVal();
9173       if (Args[i].IsPreallocated) {
9174         Flags.setPreallocated();
9175         // Set the byval flag for CCAssignFn callbacks that don't know about
9176         // preallocated.  This way we can know how many bytes we should've
9177         // allocated and how many bytes a callee cleanup function will pop.  If
9178         // we port preallocated to more targets, we'll have to add custom
9179         // preallocated handling in the various CC lowering callbacks.
9180         Flags.setByVal();
9181       }
9182       if (Args[i].IsInAlloca) {
9183         Flags.setInAlloca();
9184         // Set the byval flag for CCAssignFn callbacks that don't know about
9185         // inalloca.  This way we can know how many bytes we should've allocated
9186         // and how many bytes a callee cleanup function will pop.  If we port
9187         // inalloca to more targets, we'll have to add custom inalloca handling
9188         // in the various CC lowering callbacks.
9189         Flags.setByVal();
9190       }
9191       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9192         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9193         Type *ElementTy = Ty->getElementType();
9194 
9195         unsigned FrameSize = DL.getTypeAllocSize(
9196             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9197         Flags.setByValSize(FrameSize);
9198 
9199         // info is not there but there are cases it cannot get right.
9200         Align FrameAlign;
9201         if (auto MA = Args[i].Alignment)
9202           FrameAlign = *MA;
9203         else
9204           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9205         Flags.setByValAlign(FrameAlign);
9206       }
9207       if (Args[i].IsNest)
9208         Flags.setNest();
9209       if (NeedsRegBlock)
9210         Flags.setInConsecutiveRegs();
9211       Flags.setOrigAlign(OriginalAlignment);
9212 
9213       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9214                                                  CLI.CallConv, VT);
9215       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9216                                                         CLI.CallConv, VT);
9217       SmallVector<SDValue, 4> Parts(NumParts);
9218       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9219 
9220       if (Args[i].IsSExt)
9221         ExtendKind = ISD::SIGN_EXTEND;
9222       else if (Args[i].IsZExt)
9223         ExtendKind = ISD::ZERO_EXTEND;
9224 
9225       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9226       // for now.
9227       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9228           CanLowerReturn) {
9229         assert((CLI.RetTy == Args[i].Ty ||
9230                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9231                  CLI.RetTy->getPointerAddressSpace() ==
9232                      Args[i].Ty->getPointerAddressSpace())) &&
9233                RetTys.size() == NumValues && "unexpected use of 'returned'");
9234         // Before passing 'returned' to the target lowering code, ensure that
9235         // either the register MVT and the actual EVT are the same size or that
9236         // the return value and argument are extended in the same way; in these
9237         // cases it's safe to pass the argument register value unchanged as the
9238         // return register value (although it's at the target's option whether
9239         // to do so)
9240         // TODO: allow code generation to take advantage of partially preserved
9241         // registers rather than clobbering the entire register when the
9242         // parameter extension method is not compatible with the return
9243         // extension method
9244         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9245             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9246              CLI.RetZExt == Args[i].IsZExt))
9247           Flags.setReturned();
9248       }
9249 
9250       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9251                      CLI.CallConv, ExtendKind);
9252 
9253       for (unsigned j = 0; j != NumParts; ++j) {
9254         // if it isn't first piece, alignment must be 1
9255         // For scalable vectors the scalable part is currently handled
9256         // by individual targets, so we just use the known minimum size here.
9257         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9258                     i < CLI.NumFixedArgs, i,
9259                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9260         if (NumParts > 1 && j == 0)
9261           MyFlags.Flags.setSplit();
9262         else if (j != 0) {
9263           MyFlags.Flags.setOrigAlign(Align(1));
9264           if (j == NumParts - 1)
9265             MyFlags.Flags.setSplitEnd();
9266         }
9267 
9268         CLI.Outs.push_back(MyFlags);
9269         CLI.OutVals.push_back(Parts[j]);
9270       }
9271 
9272       if (NeedsRegBlock && Value == NumValues - 1)
9273         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9274     }
9275   }
9276 
9277   SmallVector<SDValue, 4> InVals;
9278   CLI.Chain = LowerCall(CLI, InVals);
9279 
9280   // Update CLI.InVals to use outside of this function.
9281   CLI.InVals = InVals;
9282 
9283   // Verify that the target's LowerCall behaved as expected.
9284   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9285          "LowerCall didn't return a valid chain!");
9286   assert((!CLI.IsTailCall || InVals.empty()) &&
9287          "LowerCall emitted a return value for a tail call!");
9288   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9289          "LowerCall didn't emit the correct number of values!");
9290 
9291   // For a tail call, the return value is merely live-out and there aren't
9292   // any nodes in the DAG representing it. Return a special value to
9293   // indicate that a tail call has been emitted and no more Instructions
9294   // should be processed in the current block.
9295   if (CLI.IsTailCall) {
9296     CLI.DAG.setRoot(CLI.Chain);
9297     return std::make_pair(SDValue(), SDValue());
9298   }
9299 
9300 #ifndef NDEBUG
9301   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9302     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9303     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9304            "LowerCall emitted a value with the wrong type!");
9305   }
9306 #endif
9307 
9308   SmallVector<SDValue, 4> ReturnValues;
9309   if (!CanLowerReturn) {
9310     // The instruction result is the result of loading from the
9311     // hidden sret parameter.
9312     SmallVector<EVT, 1> PVTs;
9313     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9314 
9315     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9316     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9317     EVT PtrVT = PVTs[0];
9318 
9319     unsigned NumValues = RetTys.size();
9320     ReturnValues.resize(NumValues);
9321     SmallVector<SDValue, 4> Chains(NumValues);
9322 
9323     // An aggregate return value cannot wrap around the address space, so
9324     // offsets to its parts don't wrap either.
9325     SDNodeFlags Flags;
9326     Flags.setNoUnsignedWrap(true);
9327 
9328     MachineFunction &MF = CLI.DAG.getMachineFunction();
9329     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9330     for (unsigned i = 0; i < NumValues; ++i) {
9331       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9332                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9333                                                         PtrVT), Flags);
9334       SDValue L = CLI.DAG.getLoad(
9335           RetTys[i], CLI.DL, CLI.Chain, Add,
9336           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9337                                             DemoteStackIdx, Offsets[i]),
9338           HiddenSRetAlign);
9339       ReturnValues[i] = L;
9340       Chains[i] = L.getValue(1);
9341     }
9342 
9343     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9344   } else {
9345     // Collect the legal value parts into potentially illegal values
9346     // that correspond to the original function's return values.
9347     Optional<ISD::NodeType> AssertOp;
9348     if (CLI.RetSExt)
9349       AssertOp = ISD::AssertSext;
9350     else if (CLI.RetZExt)
9351       AssertOp = ISD::AssertZext;
9352     unsigned CurReg = 0;
9353     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9354       EVT VT = RetTys[I];
9355       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9356                                                      CLI.CallConv, VT);
9357       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9358                                                        CLI.CallConv, VT);
9359 
9360       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9361                                               NumRegs, RegisterVT, VT, nullptr,
9362                                               CLI.CallConv, AssertOp));
9363       CurReg += NumRegs;
9364     }
9365 
9366     // For a function returning void, there is no return value. We can't create
9367     // such a node, so we just return a null return value in that case. In
9368     // that case, nothing will actually look at the value.
9369     if (ReturnValues.empty())
9370       return std::make_pair(SDValue(), CLI.Chain);
9371   }
9372 
9373   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9374                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9375   return std::make_pair(Res, CLI.Chain);
9376 }
9377 
9378 void TargetLowering::LowerOperationWrapper(SDNode *N,
9379                                            SmallVectorImpl<SDValue> &Results,
9380                                            SelectionDAG &DAG) const {
9381   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9382     Results.push_back(Res);
9383 }
9384 
9385 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9386   llvm_unreachable("LowerOperation not implemented for this target!");
9387 }
9388 
9389 void
9390 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9391   SDValue Op = getNonRegisterValue(V);
9392   assert((Op.getOpcode() != ISD::CopyFromReg ||
9393           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9394          "Copy from a reg to the same reg!");
9395   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9396 
9397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398   // If this is an InlineAsm we have to match the registers required, not the
9399   // notional registers required by the type.
9400 
9401   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9402                    None); // This is not an ABI copy.
9403   SDValue Chain = DAG.getEntryNode();
9404 
9405   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9406                               FuncInfo.PreferredExtendType.end())
9407                                  ? ISD::ANY_EXTEND
9408                                  : FuncInfo.PreferredExtendType[V];
9409   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9410   PendingExports.push_back(Chain);
9411 }
9412 
9413 #include "llvm/CodeGen/SelectionDAGISel.h"
9414 
9415 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9416 /// entry block, return true.  This includes arguments used by switches, since
9417 /// the switch may expand into multiple basic blocks.
9418 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9419   // With FastISel active, we may be splitting blocks, so force creation
9420   // of virtual registers for all non-dead arguments.
9421   if (FastISel)
9422     return A->use_empty();
9423 
9424   const BasicBlock &Entry = A->getParent()->front();
9425   for (const User *U : A->users())
9426     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9427       return false;  // Use not in entry block.
9428 
9429   return true;
9430 }
9431 
9432 using ArgCopyElisionMapTy =
9433     DenseMap<const Argument *,
9434              std::pair<const AllocaInst *, const StoreInst *>>;
9435 
9436 /// Scan the entry block of the function in FuncInfo for arguments that look
9437 /// like copies into a local alloca. Record any copied arguments in
9438 /// ArgCopyElisionCandidates.
9439 static void
9440 findArgumentCopyElisionCandidates(const DataLayout &DL,
9441                                   FunctionLoweringInfo *FuncInfo,
9442                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9443   // Record the state of every static alloca used in the entry block. Argument
9444   // allocas are all used in the entry block, so we need approximately as many
9445   // entries as we have arguments.
9446   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9447   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9448   unsigned NumArgs = FuncInfo->Fn->arg_size();
9449   StaticAllocas.reserve(NumArgs * 2);
9450 
9451   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9452     if (!V)
9453       return nullptr;
9454     V = V->stripPointerCasts();
9455     const auto *AI = dyn_cast<AllocaInst>(V);
9456     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9457       return nullptr;
9458     auto Iter = StaticAllocas.insert({AI, Unknown});
9459     return &Iter.first->second;
9460   };
9461 
9462   // Look for stores of arguments to static allocas. Look through bitcasts and
9463   // GEPs to handle type coercions, as long as the alloca is fully initialized
9464   // by the store. Any non-store use of an alloca escapes it and any subsequent
9465   // unanalyzed store might write it.
9466   // FIXME: Handle structs initialized with multiple stores.
9467   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9468     // Look for stores, and handle non-store uses conservatively.
9469     const auto *SI = dyn_cast<StoreInst>(&I);
9470     if (!SI) {
9471       // We will look through cast uses, so ignore them completely.
9472       if (I.isCast())
9473         continue;
9474       // Ignore debug info intrinsics, they don't escape or store to allocas.
9475       if (isa<DbgInfoIntrinsic>(I))
9476         continue;
9477       // This is an unknown instruction. Assume it escapes or writes to all
9478       // static alloca operands.
9479       for (const Use &U : I.operands()) {
9480         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9481           *Info = StaticAllocaInfo::Clobbered;
9482       }
9483       continue;
9484     }
9485 
9486     // If the stored value is a static alloca, mark it as escaped.
9487     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9488       *Info = StaticAllocaInfo::Clobbered;
9489 
9490     // Check if the destination is a static alloca.
9491     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9492     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9493     if (!Info)
9494       continue;
9495     const AllocaInst *AI = cast<AllocaInst>(Dst);
9496 
9497     // Skip allocas that have been initialized or clobbered.
9498     if (*Info != StaticAllocaInfo::Unknown)
9499       continue;
9500 
9501     // Check if the stored value is an argument, and that this store fully
9502     // initializes the alloca. Don't elide copies from the same argument twice.
9503     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9504     const auto *Arg = dyn_cast<Argument>(Val);
9505     if (!Arg || Arg->hasPassPointeeByValueAttr() ||
9506         Arg->getType()->isEmptyTy() ||
9507         DL.getTypeStoreSize(Arg->getType()) !=
9508             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9509         ArgCopyElisionCandidates.count(Arg)) {
9510       *Info = StaticAllocaInfo::Clobbered;
9511       continue;
9512     }
9513 
9514     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9515                       << '\n');
9516 
9517     // Mark this alloca and store for argument copy elision.
9518     *Info = StaticAllocaInfo::Elidable;
9519     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9520 
9521     // Stop scanning if we've seen all arguments. This will happen early in -O0
9522     // builds, which is useful, because -O0 builds have large entry blocks and
9523     // many allocas.
9524     if (ArgCopyElisionCandidates.size() == NumArgs)
9525       break;
9526   }
9527 }
9528 
9529 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9530 /// ArgVal is a load from a suitable fixed stack object.
9531 static void tryToElideArgumentCopy(
9532     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9533     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9534     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9535     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9536     SDValue ArgVal, bool &ArgHasUses) {
9537   // Check if this is a load from a fixed stack object.
9538   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9539   if (!LNode)
9540     return;
9541   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9542   if (!FINode)
9543     return;
9544 
9545   // Check that the fixed stack object is the right size and alignment.
9546   // Look at the alignment that the user wrote on the alloca instead of looking
9547   // at the stack object.
9548   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9549   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9550   const AllocaInst *AI = ArgCopyIter->second.first;
9551   int FixedIndex = FINode->getIndex();
9552   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9553   int OldIndex = AllocaIndex;
9554   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9555   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9556     LLVM_DEBUG(
9557         dbgs() << "  argument copy elision failed due to bad fixed stack "
9558                   "object size\n");
9559     return;
9560   }
9561   Align RequiredAlignment = AI->getAlign();
9562   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9563     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9564                          "greater than stack argument alignment ("
9565                       << DebugStr(RequiredAlignment) << " vs "
9566                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9567     return;
9568   }
9569 
9570   // Perform the elision. Delete the old stack object and replace its only use
9571   // in the variable info map. Mark the stack object as mutable.
9572   LLVM_DEBUG({
9573     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9574            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9575            << '\n';
9576   });
9577   MFI.RemoveStackObject(OldIndex);
9578   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9579   AllocaIndex = FixedIndex;
9580   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9581   Chains.push_back(ArgVal.getValue(1));
9582 
9583   // Avoid emitting code for the store implementing the copy.
9584   const StoreInst *SI = ArgCopyIter->second.second;
9585   ElidedArgCopyInstrs.insert(SI);
9586 
9587   // Check for uses of the argument again so that we can avoid exporting ArgVal
9588   // if it is't used by anything other than the store.
9589   for (const Value *U : Arg.users()) {
9590     if (U != SI) {
9591       ArgHasUses = true;
9592       break;
9593     }
9594   }
9595 }
9596 
9597 void SelectionDAGISel::LowerArguments(const Function &F) {
9598   SelectionDAG &DAG = SDB->DAG;
9599   SDLoc dl = SDB->getCurSDLoc();
9600   const DataLayout &DL = DAG.getDataLayout();
9601   SmallVector<ISD::InputArg, 16> Ins;
9602 
9603   if (!FuncInfo->CanLowerReturn) {
9604     // Put in an sret pointer parameter before all the other parameters.
9605     SmallVector<EVT, 1> ValueVTs;
9606     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9607                     F.getReturnType()->getPointerTo(
9608                         DAG.getDataLayout().getAllocaAddrSpace()),
9609                     ValueVTs);
9610 
9611     // NOTE: Assuming that a pointer will never break down to more than one VT
9612     // or one register.
9613     ISD::ArgFlagsTy Flags;
9614     Flags.setSRet();
9615     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9616     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9617                          ISD::InputArg::NoArgIndex, 0);
9618     Ins.push_back(RetArg);
9619   }
9620 
9621   // Look for stores of arguments to static allocas. Mark such arguments with a
9622   // flag to ask the target to give us the memory location of that argument if
9623   // available.
9624   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9625   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9626                                     ArgCopyElisionCandidates);
9627 
9628   // Set up the incoming argument description vector.
9629   for (const Argument &Arg : F.args()) {
9630     unsigned ArgNo = Arg.getArgNo();
9631     SmallVector<EVT, 4> ValueVTs;
9632     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9633     bool isArgValueUsed = !Arg.use_empty();
9634     unsigned PartBase = 0;
9635     Type *FinalType = Arg.getType();
9636     if (Arg.hasAttribute(Attribute::ByVal))
9637       FinalType = Arg.getParamByValType();
9638     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9639         FinalType, F.getCallingConv(), F.isVarArg());
9640     for (unsigned Value = 0, NumValues = ValueVTs.size();
9641          Value != NumValues; ++Value) {
9642       EVT VT = ValueVTs[Value];
9643       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9644       ISD::ArgFlagsTy Flags;
9645 
9646       // Certain targets (such as MIPS), may have a different ABI alignment
9647       // for a type depending on the context. Give the target a chance to
9648       // specify the alignment it wants.
9649       const Align OriginalAlignment(
9650           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9651 
9652       if (Arg.getType()->isPointerTy()) {
9653         Flags.setPointer();
9654         Flags.setPointerAddrSpace(
9655             cast<PointerType>(Arg.getType())->getAddressSpace());
9656       }
9657       if (Arg.hasAttribute(Attribute::ZExt))
9658         Flags.setZExt();
9659       if (Arg.hasAttribute(Attribute::SExt))
9660         Flags.setSExt();
9661       if (Arg.hasAttribute(Attribute::InReg)) {
9662         // If we are using vectorcall calling convention, a structure that is
9663         // passed InReg - is surely an HVA
9664         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9665             isa<StructType>(Arg.getType())) {
9666           // The first value of a structure is marked
9667           if (0 == Value)
9668             Flags.setHvaStart();
9669           Flags.setHva();
9670         }
9671         // Set InReg Flag
9672         Flags.setInReg();
9673       }
9674       if (Arg.hasAttribute(Attribute::StructRet))
9675         Flags.setSRet();
9676       if (Arg.hasAttribute(Attribute::SwiftSelf))
9677         Flags.setSwiftSelf();
9678       if (Arg.hasAttribute(Attribute::SwiftError))
9679         Flags.setSwiftError();
9680       if (Arg.hasAttribute(Attribute::ByVal))
9681         Flags.setByVal();
9682       if (Arg.hasAttribute(Attribute::InAlloca)) {
9683         Flags.setInAlloca();
9684         // Set the byval flag for CCAssignFn callbacks that don't know about
9685         // inalloca.  This way we can know how many bytes we should've allocated
9686         // and how many bytes a callee cleanup function will pop.  If we port
9687         // inalloca to more targets, we'll have to add custom inalloca handling
9688         // in the various CC lowering callbacks.
9689         Flags.setByVal();
9690       }
9691       if (Arg.hasAttribute(Attribute::Preallocated)) {
9692         Flags.setPreallocated();
9693         // Set the byval flag for CCAssignFn callbacks that don't know about
9694         // preallocated.  This way we can know how many bytes we should've
9695         // allocated and how many bytes a callee cleanup function will pop.  If
9696         // we port preallocated to more targets, we'll have to add custom
9697         // preallocated handling in the various CC lowering callbacks.
9698         Flags.setByVal();
9699       }
9700       if (F.getCallingConv() == CallingConv::X86_INTR) {
9701         // IA Interrupt passes frame (1st parameter) by value in the stack.
9702         if (ArgNo == 0)
9703           Flags.setByVal();
9704       }
9705       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
9706         Type *ElementTy = Arg.getParamByValType();
9707 
9708         // For ByVal, size and alignment should be passed from FE.  BE will
9709         // guess if this info is not there but there are cases it cannot get
9710         // right.
9711         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9712         Flags.setByValSize(FrameSize);
9713 
9714         unsigned FrameAlign;
9715         if (Arg.getParamAlignment())
9716           FrameAlign = Arg.getParamAlignment();
9717         else
9718           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9719         Flags.setByValAlign(Align(FrameAlign));
9720       }
9721       if (Arg.hasAttribute(Attribute::Nest))
9722         Flags.setNest();
9723       if (NeedsRegBlock)
9724         Flags.setInConsecutiveRegs();
9725       Flags.setOrigAlign(OriginalAlignment);
9726       if (ArgCopyElisionCandidates.count(&Arg))
9727         Flags.setCopyElisionCandidate();
9728       if (Arg.hasAttribute(Attribute::Returned))
9729         Flags.setReturned();
9730 
9731       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9732           *CurDAG->getContext(), F.getCallingConv(), VT);
9733       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9734           *CurDAG->getContext(), F.getCallingConv(), VT);
9735       for (unsigned i = 0; i != NumRegs; ++i) {
9736         // For scalable vectors, use the minimum size; individual targets
9737         // are responsible for handling scalable vector arguments and
9738         // return values.
9739         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9740                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9741         if (NumRegs > 1 && i == 0)
9742           MyFlags.Flags.setSplit();
9743         // if it isn't first piece, alignment must be 1
9744         else if (i > 0) {
9745           MyFlags.Flags.setOrigAlign(Align(1));
9746           if (i == NumRegs - 1)
9747             MyFlags.Flags.setSplitEnd();
9748         }
9749         Ins.push_back(MyFlags);
9750       }
9751       if (NeedsRegBlock && Value == NumValues - 1)
9752         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9753       PartBase += VT.getStoreSize().getKnownMinSize();
9754     }
9755   }
9756 
9757   // Call the target to set up the argument values.
9758   SmallVector<SDValue, 8> InVals;
9759   SDValue NewRoot = TLI->LowerFormalArguments(
9760       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9761 
9762   // Verify that the target's LowerFormalArguments behaved as expected.
9763   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9764          "LowerFormalArguments didn't return a valid chain!");
9765   assert(InVals.size() == Ins.size() &&
9766          "LowerFormalArguments didn't emit the correct number of values!");
9767   LLVM_DEBUG({
9768     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9769       assert(InVals[i].getNode() &&
9770              "LowerFormalArguments emitted a null value!");
9771       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9772              "LowerFormalArguments emitted a value with the wrong type!");
9773     }
9774   });
9775 
9776   // Update the DAG with the new chain value resulting from argument lowering.
9777   DAG.setRoot(NewRoot);
9778 
9779   // Set up the argument values.
9780   unsigned i = 0;
9781   if (!FuncInfo->CanLowerReturn) {
9782     // Create a virtual register for the sret pointer, and put in a copy
9783     // from the sret argument into it.
9784     SmallVector<EVT, 1> ValueVTs;
9785     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9786                     F.getReturnType()->getPointerTo(
9787                         DAG.getDataLayout().getAllocaAddrSpace()),
9788                     ValueVTs);
9789     MVT VT = ValueVTs[0].getSimpleVT();
9790     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9791     Optional<ISD::NodeType> AssertOp = None;
9792     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9793                                         nullptr, F.getCallingConv(), AssertOp);
9794 
9795     MachineFunction& MF = SDB->DAG.getMachineFunction();
9796     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9797     Register SRetReg =
9798         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9799     FuncInfo->DemoteRegister = SRetReg;
9800     NewRoot =
9801         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9802     DAG.setRoot(NewRoot);
9803 
9804     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9805     ++i;
9806   }
9807 
9808   SmallVector<SDValue, 4> Chains;
9809   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9810   for (const Argument &Arg : F.args()) {
9811     SmallVector<SDValue, 4> ArgValues;
9812     SmallVector<EVT, 4> ValueVTs;
9813     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9814     unsigned NumValues = ValueVTs.size();
9815     if (NumValues == 0)
9816       continue;
9817 
9818     bool ArgHasUses = !Arg.use_empty();
9819 
9820     // Elide the copying store if the target loaded this argument from a
9821     // suitable fixed stack object.
9822     if (Ins[i].Flags.isCopyElisionCandidate()) {
9823       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9824                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9825                              InVals[i], ArgHasUses);
9826     }
9827 
9828     // If this argument is unused then remember its value. It is used to generate
9829     // debugging information.
9830     bool isSwiftErrorArg =
9831         TLI->supportSwiftError() &&
9832         Arg.hasAttribute(Attribute::SwiftError);
9833     if (!ArgHasUses && !isSwiftErrorArg) {
9834       SDB->setUnusedArgValue(&Arg, InVals[i]);
9835 
9836       // Also remember any frame index for use in FastISel.
9837       if (FrameIndexSDNode *FI =
9838           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9839         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9840     }
9841 
9842     for (unsigned Val = 0; Val != NumValues; ++Val) {
9843       EVT VT = ValueVTs[Val];
9844       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9845                                                       F.getCallingConv(), VT);
9846       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9847           *CurDAG->getContext(), F.getCallingConv(), VT);
9848 
9849       // Even an apparent 'unused' swifterror argument needs to be returned. So
9850       // we do generate a copy for it that can be used on return from the
9851       // function.
9852       if (ArgHasUses || isSwiftErrorArg) {
9853         Optional<ISD::NodeType> AssertOp;
9854         if (Arg.hasAttribute(Attribute::SExt))
9855           AssertOp = ISD::AssertSext;
9856         else if (Arg.hasAttribute(Attribute::ZExt))
9857           AssertOp = ISD::AssertZext;
9858 
9859         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9860                                              PartVT, VT, nullptr,
9861                                              F.getCallingConv(), AssertOp));
9862       }
9863 
9864       i += NumParts;
9865     }
9866 
9867     // We don't need to do anything else for unused arguments.
9868     if (ArgValues.empty())
9869       continue;
9870 
9871     // Note down frame index.
9872     if (FrameIndexSDNode *FI =
9873         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9874       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9875 
9876     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9877                                      SDB->getCurSDLoc());
9878 
9879     SDB->setValue(&Arg, Res);
9880     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9881       // We want to associate the argument with the frame index, among
9882       // involved operands, that correspond to the lowest address. The
9883       // getCopyFromParts function, called earlier, is swapping the order of
9884       // the operands to BUILD_PAIR depending on endianness. The result of
9885       // that swapping is that the least significant bits of the argument will
9886       // be in the first operand of the BUILD_PAIR node, and the most
9887       // significant bits will be in the second operand.
9888       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9889       if (LoadSDNode *LNode =
9890           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9891         if (FrameIndexSDNode *FI =
9892             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9893           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9894     }
9895 
9896     // Analyses past this point are naive and don't expect an assertion.
9897     if (Res.getOpcode() == ISD::AssertZext)
9898       Res = Res.getOperand(0);
9899 
9900     // Update the SwiftErrorVRegDefMap.
9901     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9902       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9903       if (Register::isVirtualRegister(Reg))
9904         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9905                                    Reg);
9906     }
9907 
9908     // If this argument is live outside of the entry block, insert a copy from
9909     // wherever we got it to the vreg that other BB's will reference it as.
9910     if (Res.getOpcode() == ISD::CopyFromReg) {
9911       // If we can, though, try to skip creating an unnecessary vreg.
9912       // FIXME: This isn't very clean... it would be nice to make this more
9913       // general.
9914       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9915       if (Register::isVirtualRegister(Reg)) {
9916         FuncInfo->ValueMap[&Arg] = Reg;
9917         continue;
9918       }
9919     }
9920     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9921       FuncInfo->InitializeRegForValue(&Arg);
9922       SDB->CopyToExportRegsIfNeeded(&Arg);
9923     }
9924   }
9925 
9926   if (!Chains.empty()) {
9927     Chains.push_back(NewRoot);
9928     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9929   }
9930 
9931   DAG.setRoot(NewRoot);
9932 
9933   assert(i == InVals.size() && "Argument register count mismatch!");
9934 
9935   // If any argument copy elisions occurred and we have debug info, update the
9936   // stale frame indices used in the dbg.declare variable info table.
9937   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9938   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9939     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9940       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9941       if (I != ArgCopyElisionFrameIndexMap.end())
9942         VI.Slot = I->second;
9943     }
9944   }
9945 
9946   // Finally, if the target has anything special to do, allow it to do so.
9947   emitFunctionEntryCode();
9948 }
9949 
9950 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9951 /// ensure constants are generated when needed.  Remember the virtual registers
9952 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9953 /// directly add them, because expansion might result in multiple MBB's for one
9954 /// BB.  As such, the start of the BB might correspond to a different MBB than
9955 /// the end.
9956 void
9957 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9958   const Instruction *TI = LLVMBB->getTerminator();
9959 
9960   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9961 
9962   // Check PHI nodes in successors that expect a value to be available from this
9963   // block.
9964   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9965     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9966     if (!isa<PHINode>(SuccBB->begin())) continue;
9967     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9968 
9969     // If this terminator has multiple identical successors (common for
9970     // switches), only handle each succ once.
9971     if (!SuccsHandled.insert(SuccMBB).second)
9972       continue;
9973 
9974     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9975 
9976     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9977     // nodes and Machine PHI nodes, but the incoming operands have not been
9978     // emitted yet.
9979     for (const PHINode &PN : SuccBB->phis()) {
9980       // Ignore dead phi's.
9981       if (PN.use_empty())
9982         continue;
9983 
9984       // Skip empty types
9985       if (PN.getType()->isEmptyTy())
9986         continue;
9987 
9988       unsigned Reg;
9989       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9990 
9991       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9992         unsigned &RegOut = ConstantsOut[C];
9993         if (RegOut == 0) {
9994           RegOut = FuncInfo.CreateRegs(C);
9995           CopyValueToVirtualRegister(C, RegOut);
9996         }
9997         Reg = RegOut;
9998       } else {
9999         DenseMap<const Value *, Register>::iterator I =
10000           FuncInfo.ValueMap.find(PHIOp);
10001         if (I != FuncInfo.ValueMap.end())
10002           Reg = I->second;
10003         else {
10004           assert(isa<AllocaInst>(PHIOp) &&
10005                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10006                  "Didn't codegen value into a register!??");
10007           Reg = FuncInfo.CreateRegs(PHIOp);
10008           CopyValueToVirtualRegister(PHIOp, Reg);
10009         }
10010       }
10011 
10012       // Remember that this register needs to added to the machine PHI node as
10013       // the input for this MBB.
10014       SmallVector<EVT, 4> ValueVTs;
10015       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10016       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10017       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10018         EVT VT = ValueVTs[vti];
10019         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10020         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10021           FuncInfo.PHINodesToUpdate.push_back(
10022               std::make_pair(&*MBBI++, Reg + i));
10023         Reg += NumRegisters;
10024       }
10025     }
10026   }
10027 
10028   ConstantsOut.clear();
10029 }
10030 
10031 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10032 /// is 0.
10033 MachineBasicBlock *
10034 SelectionDAGBuilder::StackProtectorDescriptor::
10035 AddSuccessorMBB(const BasicBlock *BB,
10036                 MachineBasicBlock *ParentMBB,
10037                 bool IsLikely,
10038                 MachineBasicBlock *SuccMBB) {
10039   // If SuccBB has not been created yet, create it.
10040   if (!SuccMBB) {
10041     MachineFunction *MF = ParentMBB->getParent();
10042     MachineFunction::iterator BBI(ParentMBB);
10043     SuccMBB = MF->CreateMachineBasicBlock(BB);
10044     MF->insert(++BBI, SuccMBB);
10045   }
10046   // Add it as a successor of ParentMBB.
10047   ParentMBB->addSuccessor(
10048       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10049   return SuccMBB;
10050 }
10051 
10052 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10053   MachineFunction::iterator I(MBB);
10054   if (++I == FuncInfo.MF->end())
10055     return nullptr;
10056   return &*I;
10057 }
10058 
10059 /// During lowering new call nodes can be created (such as memset, etc.).
10060 /// Those will become new roots of the current DAG, but complications arise
10061 /// when they are tail calls. In such cases, the call lowering will update
10062 /// the root, but the builder still needs to know that a tail call has been
10063 /// lowered in order to avoid generating an additional return.
10064 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10065   // If the node is null, we do have a tail call.
10066   if (MaybeTC.getNode() != nullptr)
10067     DAG.setRoot(MaybeTC);
10068   else
10069     HasTailCall = true;
10070 }
10071 
10072 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10073                                         MachineBasicBlock *SwitchMBB,
10074                                         MachineBasicBlock *DefaultMBB) {
10075   MachineFunction *CurMF = FuncInfo.MF;
10076   MachineBasicBlock *NextMBB = nullptr;
10077   MachineFunction::iterator BBI(W.MBB);
10078   if (++BBI != FuncInfo.MF->end())
10079     NextMBB = &*BBI;
10080 
10081   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10082 
10083   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10084 
10085   if (Size == 2 && W.MBB == SwitchMBB) {
10086     // If any two of the cases has the same destination, and if one value
10087     // is the same as the other, but has one bit unset that the other has set,
10088     // use bit manipulation to do two compares at once.  For example:
10089     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10090     // TODO: This could be extended to merge any 2 cases in switches with 3
10091     // cases.
10092     // TODO: Handle cases where W.CaseBB != SwitchBB.
10093     CaseCluster &Small = *W.FirstCluster;
10094     CaseCluster &Big = *W.LastCluster;
10095 
10096     if (Small.Low == Small.High && Big.Low == Big.High &&
10097         Small.MBB == Big.MBB) {
10098       const APInt &SmallValue = Small.Low->getValue();
10099       const APInt &BigValue = Big.Low->getValue();
10100 
10101       // Check that there is only one bit different.
10102       APInt CommonBit = BigValue ^ SmallValue;
10103       if (CommonBit.isPowerOf2()) {
10104         SDValue CondLHS = getValue(Cond);
10105         EVT VT = CondLHS.getValueType();
10106         SDLoc DL = getCurSDLoc();
10107 
10108         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10109                                  DAG.getConstant(CommonBit, DL, VT));
10110         SDValue Cond = DAG.getSetCC(
10111             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10112             ISD::SETEQ);
10113 
10114         // Update successor info.
10115         // Both Small and Big will jump to Small.BB, so we sum up the
10116         // probabilities.
10117         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10118         if (BPI)
10119           addSuccessorWithProb(
10120               SwitchMBB, DefaultMBB,
10121               // The default destination is the first successor in IR.
10122               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10123         else
10124           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10125 
10126         // Insert the true branch.
10127         SDValue BrCond =
10128             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10129                         DAG.getBasicBlock(Small.MBB));
10130         // Insert the false branch.
10131         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10132                              DAG.getBasicBlock(DefaultMBB));
10133 
10134         DAG.setRoot(BrCond);
10135         return;
10136       }
10137     }
10138   }
10139 
10140   if (TM.getOptLevel() != CodeGenOpt::None) {
10141     // Here, we order cases by probability so the most likely case will be
10142     // checked first. However, two clusters can have the same probability in
10143     // which case their relative ordering is non-deterministic. So we use Low
10144     // as a tie-breaker as clusters are guaranteed to never overlap.
10145     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10146                [](const CaseCluster &a, const CaseCluster &b) {
10147       return a.Prob != b.Prob ?
10148              a.Prob > b.Prob :
10149              a.Low->getValue().slt(b.Low->getValue());
10150     });
10151 
10152     // Rearrange the case blocks so that the last one falls through if possible
10153     // without changing the order of probabilities.
10154     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10155       --I;
10156       if (I->Prob > W.LastCluster->Prob)
10157         break;
10158       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10159         std::swap(*I, *W.LastCluster);
10160         break;
10161       }
10162     }
10163   }
10164 
10165   // Compute total probability.
10166   BranchProbability DefaultProb = W.DefaultProb;
10167   BranchProbability UnhandledProbs = DefaultProb;
10168   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10169     UnhandledProbs += I->Prob;
10170 
10171   MachineBasicBlock *CurMBB = W.MBB;
10172   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10173     bool FallthroughUnreachable = false;
10174     MachineBasicBlock *Fallthrough;
10175     if (I == W.LastCluster) {
10176       // For the last cluster, fall through to the default destination.
10177       Fallthrough = DefaultMBB;
10178       FallthroughUnreachable = isa<UnreachableInst>(
10179           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10180     } else {
10181       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10182       CurMF->insert(BBI, Fallthrough);
10183       // Put Cond in a virtual register to make it available from the new blocks.
10184       ExportFromCurrentBlock(Cond);
10185     }
10186     UnhandledProbs -= I->Prob;
10187 
10188     switch (I->Kind) {
10189       case CC_JumpTable: {
10190         // FIXME: Optimize away range check based on pivot comparisons.
10191         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10192         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10193 
10194         // The jump block hasn't been inserted yet; insert it here.
10195         MachineBasicBlock *JumpMBB = JT->MBB;
10196         CurMF->insert(BBI, JumpMBB);
10197 
10198         auto JumpProb = I->Prob;
10199         auto FallthroughProb = UnhandledProbs;
10200 
10201         // If the default statement is a target of the jump table, we evenly
10202         // distribute the default probability to successors of CurMBB. Also
10203         // update the probability on the edge from JumpMBB to Fallthrough.
10204         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10205                                               SE = JumpMBB->succ_end();
10206              SI != SE; ++SI) {
10207           if (*SI == DefaultMBB) {
10208             JumpProb += DefaultProb / 2;
10209             FallthroughProb -= DefaultProb / 2;
10210             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10211             JumpMBB->normalizeSuccProbs();
10212             break;
10213           }
10214         }
10215 
10216         if (FallthroughUnreachable) {
10217           // Skip the range check if the fallthrough block is unreachable.
10218           JTH->OmitRangeCheck = true;
10219         }
10220 
10221         if (!JTH->OmitRangeCheck)
10222           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10223         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10224         CurMBB->normalizeSuccProbs();
10225 
10226         // The jump table header will be inserted in our current block, do the
10227         // range check, and fall through to our fallthrough block.
10228         JTH->HeaderBB = CurMBB;
10229         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10230 
10231         // If we're in the right place, emit the jump table header right now.
10232         if (CurMBB == SwitchMBB) {
10233           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10234           JTH->Emitted = true;
10235         }
10236         break;
10237       }
10238       case CC_BitTests: {
10239         // FIXME: Optimize away range check based on pivot comparisons.
10240         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10241 
10242         // The bit test blocks haven't been inserted yet; insert them here.
10243         for (BitTestCase &BTC : BTB->Cases)
10244           CurMF->insert(BBI, BTC.ThisBB);
10245 
10246         // Fill in fields of the BitTestBlock.
10247         BTB->Parent = CurMBB;
10248         BTB->Default = Fallthrough;
10249 
10250         BTB->DefaultProb = UnhandledProbs;
10251         // If the cases in bit test don't form a contiguous range, we evenly
10252         // distribute the probability on the edge to Fallthrough to two
10253         // successors of CurMBB.
10254         if (!BTB->ContiguousRange) {
10255           BTB->Prob += DefaultProb / 2;
10256           BTB->DefaultProb -= DefaultProb / 2;
10257         }
10258 
10259         if (FallthroughUnreachable) {
10260           // Skip the range check if the fallthrough block is unreachable.
10261           BTB->OmitRangeCheck = true;
10262         }
10263 
10264         // If we're in the right place, emit the bit test header right now.
10265         if (CurMBB == SwitchMBB) {
10266           visitBitTestHeader(*BTB, SwitchMBB);
10267           BTB->Emitted = true;
10268         }
10269         break;
10270       }
10271       case CC_Range: {
10272         const Value *RHS, *LHS, *MHS;
10273         ISD::CondCode CC;
10274         if (I->Low == I->High) {
10275           // Check Cond == I->Low.
10276           CC = ISD::SETEQ;
10277           LHS = Cond;
10278           RHS=I->Low;
10279           MHS = nullptr;
10280         } else {
10281           // Check I->Low <= Cond <= I->High.
10282           CC = ISD::SETLE;
10283           LHS = I->Low;
10284           MHS = Cond;
10285           RHS = I->High;
10286         }
10287 
10288         // If Fallthrough is unreachable, fold away the comparison.
10289         if (FallthroughUnreachable)
10290           CC = ISD::SETTRUE;
10291 
10292         // The false probability is the sum of all unhandled cases.
10293         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10294                      getCurSDLoc(), I->Prob, UnhandledProbs);
10295 
10296         if (CurMBB == SwitchMBB)
10297           visitSwitchCase(CB, SwitchMBB);
10298         else
10299           SL->SwitchCases.push_back(CB);
10300 
10301         break;
10302       }
10303     }
10304     CurMBB = Fallthrough;
10305   }
10306 }
10307 
10308 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10309                                               CaseClusterIt First,
10310                                               CaseClusterIt Last) {
10311   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10312     if (X.Prob != CC.Prob)
10313       return X.Prob > CC.Prob;
10314 
10315     // Ties are broken by comparing the case value.
10316     return X.Low->getValue().slt(CC.Low->getValue());
10317   });
10318 }
10319 
10320 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10321                                         const SwitchWorkListItem &W,
10322                                         Value *Cond,
10323                                         MachineBasicBlock *SwitchMBB) {
10324   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10325          "Clusters not sorted?");
10326 
10327   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10328 
10329   // Balance the tree based on branch probabilities to create a near-optimal (in
10330   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10331   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10332   CaseClusterIt LastLeft = W.FirstCluster;
10333   CaseClusterIt FirstRight = W.LastCluster;
10334   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10335   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10336 
10337   // Move LastLeft and FirstRight towards each other from opposite directions to
10338   // find a partitioning of the clusters which balances the probability on both
10339   // sides. If LeftProb and RightProb are equal, alternate which side is
10340   // taken to ensure 0-probability nodes are distributed evenly.
10341   unsigned I = 0;
10342   while (LastLeft + 1 < FirstRight) {
10343     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10344       LeftProb += (++LastLeft)->Prob;
10345     else
10346       RightProb += (--FirstRight)->Prob;
10347     I++;
10348   }
10349 
10350   while (true) {
10351     // Our binary search tree differs from a typical BST in that ours can have up
10352     // to three values in each leaf. The pivot selection above doesn't take that
10353     // into account, which means the tree might require more nodes and be less
10354     // efficient. We compensate for this here.
10355 
10356     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10357     unsigned NumRight = W.LastCluster - FirstRight + 1;
10358 
10359     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10360       // If one side has less than 3 clusters, and the other has more than 3,
10361       // consider taking a cluster from the other side.
10362 
10363       if (NumLeft < NumRight) {
10364         // Consider moving the first cluster on the right to the left side.
10365         CaseCluster &CC = *FirstRight;
10366         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10367         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10368         if (LeftSideRank <= RightSideRank) {
10369           // Moving the cluster to the left does not demote it.
10370           ++LastLeft;
10371           ++FirstRight;
10372           continue;
10373         }
10374       } else {
10375         assert(NumRight < NumLeft);
10376         // Consider moving the last element on the left to the right side.
10377         CaseCluster &CC = *LastLeft;
10378         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10379         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10380         if (RightSideRank <= LeftSideRank) {
10381           // Moving the cluster to the right does not demot it.
10382           --LastLeft;
10383           --FirstRight;
10384           continue;
10385         }
10386       }
10387     }
10388     break;
10389   }
10390 
10391   assert(LastLeft + 1 == FirstRight);
10392   assert(LastLeft >= W.FirstCluster);
10393   assert(FirstRight <= W.LastCluster);
10394 
10395   // Use the first element on the right as pivot since we will make less-than
10396   // comparisons against it.
10397   CaseClusterIt PivotCluster = FirstRight;
10398   assert(PivotCluster > W.FirstCluster);
10399   assert(PivotCluster <= W.LastCluster);
10400 
10401   CaseClusterIt FirstLeft = W.FirstCluster;
10402   CaseClusterIt LastRight = W.LastCluster;
10403 
10404   const ConstantInt *Pivot = PivotCluster->Low;
10405 
10406   // New blocks will be inserted immediately after the current one.
10407   MachineFunction::iterator BBI(W.MBB);
10408   ++BBI;
10409 
10410   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10411   // we can branch to its destination directly if it's squeezed exactly in
10412   // between the known lower bound and Pivot - 1.
10413   MachineBasicBlock *LeftMBB;
10414   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10415       FirstLeft->Low == W.GE &&
10416       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10417     LeftMBB = FirstLeft->MBB;
10418   } else {
10419     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10420     FuncInfo.MF->insert(BBI, LeftMBB);
10421     WorkList.push_back(
10422         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10423     // Put Cond in a virtual register to make it available from the new blocks.
10424     ExportFromCurrentBlock(Cond);
10425   }
10426 
10427   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10428   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10429   // directly if RHS.High equals the current upper bound.
10430   MachineBasicBlock *RightMBB;
10431   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10432       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10433     RightMBB = FirstRight->MBB;
10434   } else {
10435     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10436     FuncInfo.MF->insert(BBI, RightMBB);
10437     WorkList.push_back(
10438         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10439     // Put Cond in a virtual register to make it available from the new blocks.
10440     ExportFromCurrentBlock(Cond);
10441   }
10442 
10443   // Create the CaseBlock record that will be used to lower the branch.
10444   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10445                getCurSDLoc(), LeftProb, RightProb);
10446 
10447   if (W.MBB == SwitchMBB)
10448     visitSwitchCase(CB, SwitchMBB);
10449   else
10450     SL->SwitchCases.push_back(CB);
10451 }
10452 
10453 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10454 // from the swith statement.
10455 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10456                                             BranchProbability PeeledCaseProb) {
10457   if (PeeledCaseProb == BranchProbability::getOne())
10458     return BranchProbability::getZero();
10459   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10460 
10461   uint32_t Numerator = CaseProb.getNumerator();
10462   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10463   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10464 }
10465 
10466 // Try to peel the top probability case if it exceeds the threshold.
10467 // Return current MachineBasicBlock for the switch statement if the peeling
10468 // does not occur.
10469 // If the peeling is performed, return the newly created MachineBasicBlock
10470 // for the peeled switch statement. Also update Clusters to remove the peeled
10471 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10472 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10473     const SwitchInst &SI, CaseClusterVector &Clusters,
10474     BranchProbability &PeeledCaseProb) {
10475   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10476   // Don't perform if there is only one cluster or optimizing for size.
10477   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10478       TM.getOptLevel() == CodeGenOpt::None ||
10479       SwitchMBB->getParent()->getFunction().hasMinSize())
10480     return SwitchMBB;
10481 
10482   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10483   unsigned PeeledCaseIndex = 0;
10484   bool SwitchPeeled = false;
10485   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10486     CaseCluster &CC = Clusters[Index];
10487     if (CC.Prob < TopCaseProb)
10488       continue;
10489     TopCaseProb = CC.Prob;
10490     PeeledCaseIndex = Index;
10491     SwitchPeeled = true;
10492   }
10493   if (!SwitchPeeled)
10494     return SwitchMBB;
10495 
10496   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10497                     << TopCaseProb << "\n");
10498 
10499   // Record the MBB for the peeled switch statement.
10500   MachineFunction::iterator BBI(SwitchMBB);
10501   ++BBI;
10502   MachineBasicBlock *PeeledSwitchMBB =
10503       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10504   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10505 
10506   ExportFromCurrentBlock(SI.getCondition());
10507   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10508   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10509                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10510   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10511 
10512   Clusters.erase(PeeledCaseIt);
10513   for (CaseCluster &CC : Clusters) {
10514     LLVM_DEBUG(
10515         dbgs() << "Scale the probablity for one cluster, before scaling: "
10516                << CC.Prob << "\n");
10517     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10518     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10519   }
10520   PeeledCaseProb = TopCaseProb;
10521   return PeeledSwitchMBB;
10522 }
10523 
10524 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10525   // Extract cases from the switch.
10526   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10527   CaseClusterVector Clusters;
10528   Clusters.reserve(SI.getNumCases());
10529   for (auto I : SI.cases()) {
10530     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10531     const ConstantInt *CaseVal = I.getCaseValue();
10532     BranchProbability Prob =
10533         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10534             : BranchProbability(1, SI.getNumCases() + 1);
10535     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10536   }
10537 
10538   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10539 
10540   // Cluster adjacent cases with the same destination. We do this at all
10541   // optimization levels because it's cheap to do and will make codegen faster
10542   // if there are many clusters.
10543   sortAndRangeify(Clusters);
10544 
10545   // The branch probablity of the peeled case.
10546   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10547   MachineBasicBlock *PeeledSwitchMBB =
10548       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10549 
10550   // If there is only the default destination, jump there directly.
10551   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10552   if (Clusters.empty()) {
10553     assert(PeeledSwitchMBB == SwitchMBB);
10554     SwitchMBB->addSuccessor(DefaultMBB);
10555     if (DefaultMBB != NextBlock(SwitchMBB)) {
10556       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10557                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10558     }
10559     return;
10560   }
10561 
10562   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10563   SL->findBitTestClusters(Clusters, &SI);
10564 
10565   LLVM_DEBUG({
10566     dbgs() << "Case clusters: ";
10567     for (const CaseCluster &C : Clusters) {
10568       if (C.Kind == CC_JumpTable)
10569         dbgs() << "JT:";
10570       if (C.Kind == CC_BitTests)
10571         dbgs() << "BT:";
10572 
10573       C.Low->getValue().print(dbgs(), true);
10574       if (C.Low != C.High) {
10575         dbgs() << '-';
10576         C.High->getValue().print(dbgs(), true);
10577       }
10578       dbgs() << ' ';
10579     }
10580     dbgs() << '\n';
10581   });
10582 
10583   assert(!Clusters.empty());
10584   SwitchWorkList WorkList;
10585   CaseClusterIt First = Clusters.begin();
10586   CaseClusterIt Last = Clusters.end() - 1;
10587   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10588   // Scale the branchprobability for DefaultMBB if the peel occurs and
10589   // DefaultMBB is not replaced.
10590   if (PeeledCaseProb != BranchProbability::getZero() &&
10591       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10592     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10593   WorkList.push_back(
10594       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10595 
10596   while (!WorkList.empty()) {
10597     SwitchWorkListItem W = WorkList.back();
10598     WorkList.pop_back();
10599     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10600 
10601     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10602         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10603       // For optimized builds, lower large range as a balanced binary tree.
10604       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10605       continue;
10606     }
10607 
10608     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10609   }
10610 }
10611 
10612 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10613   SmallVector<EVT, 4> ValueVTs;
10614   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10615                   ValueVTs);
10616   unsigned NumValues = ValueVTs.size();
10617   if (NumValues == 0) return;
10618 
10619   SmallVector<SDValue, 4> Values(NumValues);
10620   SDValue Op = getValue(I.getOperand(0));
10621 
10622   for (unsigned i = 0; i != NumValues; ++i)
10623     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10624                             SDValue(Op.getNode(), Op.getResNo() + i));
10625 
10626   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10627                            DAG.getVTList(ValueVTs), Values));
10628 }
10629