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