xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 0d9f919b73a62191492fa60792264b2f5966b7c6)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(
442           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
443           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
444     }
445 
446     // Vector/Vector bitcast.
447     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
448       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
449 
450     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
451       "Cannot handle this kind of promotion");
452     // Promoted vector extract
453     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
454 
455   }
456 
457   // Trivial bitcast if the types are the same size and the destination
458   // vector type is legal.
459   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
460       TLI.isTypeLegal(ValueVT))
461     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462 
463   if (ValueVT.getVectorNumElements() != 1) {
464      // Certain ABIs require that vectors are passed as integers. For vectors
465      // are the same size, this is an obvious bitcast.
466      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
467        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
468      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
469        // Bitcast Val back the original type and extract the corresponding
470        // vector we want.
471        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
472        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
473                                            ValueVT.getVectorElementType(), Elts);
474        Val = DAG.getBitcast(WiderVecType, Val);
475        return DAG.getNode(
476            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
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     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  Optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
503                            SDValue *Parts, unsigned NumParts, MVT PartVT,
504                            const Value *V,
505                            Optional<CallingConv::ID> CallConv = None,
506                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   EVT ValueVT = Val.getValueType();
508 
509   // Handle the vector case separately.
510   if (ValueVT.isVector())
511     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
512                                 CallConv);
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   unsigned OrigNumParts = NumParts;
516   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
517          "Copying to an illegal type!");
518 
519   if (NumParts == 0)
520     return;
521 
522   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
523   EVT PartEVT = PartVT;
524   if (PartEVT == ValueVT) {
525     assert(NumParts == 1 && "No-op copy with multiple parts!");
526     Parts[0] = Val;
527     return;
528   }
529 
530   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
531     // If the parts cover more bits than the value has, promote the value.
532     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
533       assert(NumParts == 1 && "Do not know what to promote to!");
534       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
535     } else {
536       if (ValueVT.isFloatingPoint()) {
537         // FP values need to be bitcast, then extended if they are being put
538         // into a larger container.
539         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
540         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
541       }
542       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543              ValueVT.isInteger() &&
544              "Unknown mismatch!");
545       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
547       if (PartVT == MVT::x86mmx)
548         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549     }
550   } else if (PartBits == ValueVT.getSizeInBits()) {
551     // Different types of the same size.
552     assert(NumParts == 1 && PartEVT != ValueVT);
553     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555     // If the parts cover less bits than value has, truncate the value.
556     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
557            ValueVT.isInteger() &&
558            "Unknown mismatch!");
559     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
561     if (PartVT == MVT::x86mmx)
562       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   }
564 
565   // The value may have changed - recompute ValueVT.
566   ValueVT = Val.getValueType();
567   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568          "Failed to tile the value with PartVT!");
569 
570   if (NumParts == 1) {
571     if (PartEVT != ValueVT) {
572       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
573                                         "scalar-to-vector conversion failed");
574       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575     }
576 
577     Parts[0] = Val;
578     return;
579   }
580 
581   // Expand the value into multiple parts.
582   if (NumParts & (NumParts - 1)) {
583     // The number of parts is not a power of 2.  Split off and copy the tail.
584     assert(PartVT.isInteger() && ValueVT.isInteger() &&
585            "Do not know what to expand to!");
586     unsigned RoundParts = 1 << Log2_32(NumParts);
587     unsigned RoundBits = RoundParts * PartBits;
588     unsigned OddParts = NumParts - RoundParts;
589     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
590       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
591 
592     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
593                    CallConv);
594 
595     if (DAG.getDataLayout().isBigEndian())
596       // The odd parts were reversed by getCopyToParts - unreverse them.
597       std::reverse(Parts + RoundParts, Parts + NumParts);
598 
599     NumParts = RoundParts;
600     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
601     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
602   }
603 
604   // The number of parts is a power of 2.  Repeatedly bisect the value using
605   // EXTRACT_ELEMENT.
606   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
607                          EVT::getIntegerVT(*DAG.getContext(),
608                                            ValueVT.getSizeInBits()),
609                          Val);
610 
611   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
612     for (unsigned i = 0; i < NumParts; i += StepSize) {
613       unsigned ThisBits = StepSize * PartBits / 2;
614       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
615       SDValue &Part0 = Parts[i];
616       SDValue &Part1 = Parts[i+StepSize/2];
617 
618       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
620       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
621                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
622 
623       if (ThisBits == PartBits && ThisVT != PartVT) {
624         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
625         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626       }
627     }
628   }
629 
630   if (DAG.getDataLayout().isBigEndian())
631     std::reverse(Parts, Parts + OrigNumParts);
632 }
633 
634 static SDValue widenVectorToPartType(SelectionDAG &DAG,
635                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
636   if (!PartVT.isVector())
637     return SDValue();
638 
639   EVT ValueVT = Val.getValueType();
640   unsigned PartNumElts = PartVT.getVectorNumElements();
641   unsigned ValueNumElts = ValueVT.getVectorNumElements();
642   if (PartNumElts > ValueNumElts &&
643       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
644     EVT ElementVT = PartVT.getVectorElementType();
645     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
646     // undef elements.
647     SmallVector<SDValue, 16> Ops;
648     DAG.ExtractVectorElements(Val, Ops);
649     SDValue EltUndef = DAG.getUNDEF(ElementVT);
650     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
651       Ops.push_back(EltUndef);
652 
653     // FIXME: Use CONCAT for 2x -> 4x.
654     return DAG.getBuildVector(PartVT, DL, Ops);
655   }
656 
657   return SDValue();
658 }
659 
660 /// getCopyToPartsVector - Create a series of nodes that contain the specified
661 /// value split into legal parts.
662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
663                                  SDValue Val, SDValue *Parts, unsigned NumParts,
664                                  MVT PartVT, const Value *V,
665                                  Optional<CallingConv::ID> CallConv) {
666   EVT ValueVT = Val.getValueType();
667   assert(ValueVT.isVector() && "Not a vector");
668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
669   const bool IsABIRegCopy = CallConv.hasValue();
670 
671   if (NumParts == 1) {
672     EVT PartEVT = PartVT;
673     if (PartEVT == ValueVT) {
674       // Nothing to do.
675     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
676       // Bitconvert vector->vector case.
677       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
678     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
679       Val = Widened;
680     } else if (PartVT.isVector() &&
681                PartEVT.getVectorElementType().bitsGE(
682                  ValueVT.getVectorElementType()) &&
683                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
684 
685       // Promoted vector extract
686       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorNumElements() == 1) {
689         Val = DAG.getNode(
690             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
691             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
692       } else {
693         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType =
696             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
697         Val = DAG.getBitcast(IntermediateType, Val);
698         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
699       }
700     }
701 
702     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703     Parts[0] = Val;
704     return;
705   }
706 
707   // Handle a multi-element vector.
708   EVT IntermediateVT;
709   MVT RegisterVT;
710   unsigned NumIntermediates;
711   unsigned NumRegs;
712   if (IsABIRegCopy) {
713     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
714         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
715         NumIntermediates, RegisterVT);
716   } else {
717     NumRegs =
718         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
719                                    NumIntermediates, RegisterVT);
720   }
721 
722   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
723   NumParts = NumRegs; // Silence a compiler warning.
724   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
725 
726   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
727     IntermediateVT.getVectorNumElements() : 1;
728 
729   // Convert the vector to the appropriate type if necessary.
730   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
731 
732   EVT BuiltVectorTy = EVT::getVectorVT(
733       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
734   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
735   if (ValueVT != BuiltVectorTy) {
736     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
737       Val = Widened;
738 
739     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
740   }
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
747                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
748     } else {
749       Ops[i] = DAG.getNode(
750           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
751           DAG.getConstant(i, DL, IdxVT));
752     }
753   }
754 
755   // Split the intermediate operands into legal parts.
756   if (NumParts == NumIntermediates) {
757     // If the register was not expanded, promote or copy the value,
758     // as appropriate.
759     for (unsigned i = 0; i != NumParts; ++i)
760       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
761   } else if (NumParts > 0) {
762     // If the intermediate type was expanded, split each the value into
763     // legal parts.
764     assert(NumIntermediates != 0 && "division by zero");
765     assert(NumParts % NumIntermediates == 0 &&
766            "Must expand into a divisible number of parts!");
767     unsigned Factor = NumParts / NumIntermediates;
768     for (unsigned i = 0; i != NumIntermediates; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770                      CallConv);
771   }
772 }
773 
774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
775                            EVT valuevt, Optional<CallingConv::ID> CC)
776     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
777       RegCount(1, regs.size()), CallConv(CC) {}
778 
779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
780                            const DataLayout &DL, unsigned Reg, Type *Ty,
781                            Optional<CallingConv::ID> CC) {
782   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
783 
784   CallConv = CC;
785 
786   for (EVT ValueVT : ValueVTs) {
787     unsigned NumRegs =
788         isABIMangled()
789             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getNumRegisters(Context, ValueVT);
791     MVT RegisterVT =
792         isABIMangled()
793             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getRegisterType(Context, ValueVT);
795     for (unsigned i = 0; i != NumRegs; ++i)
796       Regs.push_back(Reg + i);
797     RegVTs.push_back(RegisterVT);
798     RegCount.push_back(NumRegs);
799     Reg += NumRegs;
800   }
801 }
802 
803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
804                                       FunctionLoweringInfo &FuncInfo,
805                                       const SDLoc &dl, SDValue &Chain,
806                                       SDValue *Flag, const Value *V) const {
807   // A Value with type {} or [0 x %t] needs no registers.
808   if (ValueVTs.empty())
809     return SDValue();
810 
811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
812 
813   // Assemble the legal parts into the final values.
814   SmallVector<SDValue, 4> Values(ValueVTs.size());
815   SmallVector<SDValue, 8> Parts;
816   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
817     // Copy the legal parts from the registers.
818     EVT ValueVT = ValueVTs[Value];
819     unsigned NumRegs = RegCount[Value];
820     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
821                                           *DAG.getContext(),
822                                           CallConv.getValue(), RegVTs[Value])
823                                     : RegVTs[Value];
824 
825     Parts.resize(NumRegs);
826     for (unsigned i = 0; i != NumRegs; ++i) {
827       SDValue P;
828       if (!Flag) {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
830       } else {
831         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
832         *Flag = P.getValue(2);
833       }
834 
835       Chain = P.getValue(1);
836       Parts[i] = P;
837 
838       // If the source register was virtual and if we know something about it,
839       // add an assert node.
840       if (!Register::isVirtualRegister(Regs[Part + i]) ||
841           !RegisterVT.isInteger())
842         continue;
843 
844       const FunctionLoweringInfo::LiveOutInfo *LOI =
845         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
846       if (!LOI)
847         continue;
848 
849       unsigned RegSize = RegisterVT.getScalarSizeInBits();
850       unsigned NumSignBits = LOI->NumSignBits;
851       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
852 
853       if (NumZeroBits == RegSize) {
854         // The current value is a zero.
855         // Explicitly express that as it would be easier for
856         // optimizations to kick in.
857         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
858         continue;
859       }
860 
861       // FIXME: We capture more information than the dag can represent.  For
862       // now, just use the tightest assertzext/assertsext possible.
863       bool isSExt;
864       EVT FromVT(MVT::Other);
865       if (NumZeroBits) {
866         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
867         isSExt = false;
868       } else if (NumSignBits > 1) {
869         FromVT =
870             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871         isSExt = true;
872       } else {
873         continue;
874       }
875       // Add an assertion node.
876       assert(FromVT != MVT::Other);
877       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
878                              RegisterVT, P, DAG.getValueType(FromVT));
879     }
880 
881     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
882                                      RegisterVT, ValueVT, V, CallConv);
883     Part += NumRegs;
884     Parts.clear();
885   }
886 
887   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
888 }
889 
890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
891                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
892                                  const Value *V,
893                                  ISD::NodeType PreferredExtendType) const {
894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
895   ISD::NodeType ExtendKind = PreferredExtendType;
896 
897   // Get the list of the values's legal parts.
898   unsigned NumRegs = Regs.size();
899   SmallVector<SDValue, 8> Parts(NumRegs);
900   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
901     unsigned NumParts = RegCount[Value];
902 
903     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
904                                           *DAG.getContext(),
905                                           CallConv.getValue(), RegVTs[Value])
906                                     : RegVTs[Value];
907 
908     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
909       ExtendKind = ISD::ZERO_EXTEND;
910 
911     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
912                    NumParts, RegisterVT, V, CallConv, ExtendKind);
913     Part += NumParts;
914   }
915 
916   // Copy the parts into the registers.
917   SmallVector<SDValue, 8> Chains(NumRegs);
918   for (unsigned i = 0; i != NumRegs; ++i) {
919     SDValue Part;
920     if (!Flag) {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
922     } else {
923       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
924       *Flag = Part.getValue(1);
925     }
926 
927     Chains[i] = Part.getValue(0);
928   }
929 
930   if (NumRegs == 1 || Flag)
931     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
932     // flagged to it. That is the CopyToReg nodes and the user are considered
933     // a single scheduling unit. If we create a TokenFactor and return it as
934     // chain, then the TokenFactor is both a predecessor (operand) of the
935     // user as well as a successor (the TF operands are flagged to the user).
936     // c1, f1 = CopyToReg
937     // c2, f2 = CopyToReg
938     // c3     = TokenFactor c1, c2
939     // ...
940     //        = op c3, ..., f2
941     Chain = Chains[NumRegs-1];
942   else
943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
944 }
945 
946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
947                                         unsigned MatchingIdx, const SDLoc &dl,
948                                         SelectionDAG &DAG,
949                                         std::vector<SDValue> &Ops) const {
950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
951 
952   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
953   if (HasMatching)
954     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
955   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
956     // Put the register class of the virtual registers in the flag word.  That
957     // way, later passes can recompute register class constraints for inline
958     // assembly as well as normal instructions.
959     // Don't do this for tied operands that can use the regclass information
960     // from the def.
961     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
962     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
963     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
964   }
965 
966   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
967   Ops.push_back(Res);
968 
969   if (Code == InlineAsm::Kind_Clobber) {
970     // Clobbers should always have a 1:1 mapping with registers, and may
971     // reference registers that have illegal (e.g. vector) types. Hence, we
972     // shouldn't try to apply any sort of splitting logic to them.
973     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
974            "No 1:1 mapping from clobbers to regs?");
975     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
976     (void)SP;
977     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
978       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
979       assert(
980           (Regs[I] != SP ||
981            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
982           "If we clobbered the stack pointer, MFI should know about it.");
983     }
984     return;
985   }
986 
987   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
988     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
989     MVT RegisterVT = RegVTs[Value];
990     for (unsigned i = 0; i != NumRegs; ++i) {
991       assert(Reg < Regs.size() && "Mismatch in # registers expected");
992       unsigned TheReg = Regs[Reg++];
993       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994     }
995   }
996 }
997 
998 SmallVector<std::pair<unsigned, unsigned>, 4>
999 RegsForValue::getRegsAndSizes() const {
1000   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1001   unsigned I = 0;
1002   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1003     unsigned RegCount = std::get<0>(CountAndVT);
1004     MVT RegisterVT = std::get<1>(CountAndVT);
1005     unsigned RegisterSize = RegisterVT.getSizeInBits();
1006     for (unsigned E = I + RegCount; I != E; ++I)
1007       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1008   }
1009   return OutVec;
1010 }
1011 
1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1013                                const TargetLibraryInfo *li) {
1014   AA = aa;
1015   GFI = gfi;
1016   LibInfo = li;
1017   DL = &DAG.getDataLayout();
1018   Context = DAG.getContext();
1019   LPadToCallSiteMap.clear();
1020   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1021 }
1022 
1023 void SelectionDAGBuilder::clear() {
1024   NodeMap.clear();
1025   UnusedArgNodeMap.clear();
1026   PendingLoads.clear();
1027   PendingExports.clear();
1028   CurInst = nullptr;
1029   HasTailCall = false;
1030   SDNodeOrder = LowestSDNodeOrder;
1031   StatepointLowering.clear();
1032 }
1033 
1034 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1035   DanglingDebugInfoMap.clear();
1036 }
1037 
1038 SDValue SelectionDAGBuilder::getRoot() {
1039   if (PendingLoads.empty())
1040     return DAG.getRoot();
1041 
1042   if (PendingLoads.size() == 1) {
1043     SDValue Root = PendingLoads[0];
1044     DAG.setRoot(Root);
1045     PendingLoads.clear();
1046     return Root;
1047   }
1048 
1049   // Otherwise, we have to make a token factor node.
1050   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1051   PendingLoads.clear();
1052   DAG.setRoot(Root);
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getControlRoot() {
1057   SDValue Root = DAG.getRoot();
1058 
1059   if (PendingExports.empty())
1060     return Root;
1061 
1062   // Turn all of the CopyToReg chains into one factored node.
1063   if (Root.getOpcode() != ISD::EntryToken) {
1064     unsigned i = 0, e = PendingExports.size();
1065     for (; i != e; ++i) {
1066       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1067       if (PendingExports[i].getNode()->getOperand(0) == Root)
1068         break;  // Don't add the root if we already indirectly depend on it.
1069     }
1070 
1071     if (i == e)
1072       PendingExports.push_back(Root);
1073   }
1074 
1075   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1076                      PendingExports);
1077   PendingExports.clear();
1078   DAG.setRoot(Root);
1079   return Root;
1080 }
1081 
1082 void SelectionDAGBuilder::visit(const Instruction &I) {
1083   // Set up outgoing PHI node register values before emitting the terminator.
1084   if (I.isTerminator()) {
1085     HandlePHINodesInSuccessorBlocks(I.getParent());
1086   }
1087 
1088   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1089   if (!isa<DbgInfoIntrinsic>(I))
1090     ++SDNodeOrder;
1091 
1092   CurInst = &I;
1093 
1094   visit(I.getOpcode(), I);
1095 
1096   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1097     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1098     // maps to this instruction.
1099     // TODO: We could handle all flags (nsw, etc) here.
1100     // TODO: If an IR instruction maps to >1 node, only the final node will have
1101     //       flags set.
1102     if (SDNode *Node = getNodeForIRValue(&I)) {
1103       SDNodeFlags IncomingFlags;
1104       IncomingFlags.copyFMF(*FPMO);
1105       if (!Node->getFlags().isDefined())
1106         Node->setFlags(IncomingFlags);
1107       else
1108         Node->intersectFlagsWith(IncomingFlags);
1109     }
1110   }
1111   // Constrained FP intrinsics with fpexcept.ignore should also get
1112   // the NoFPExcept flag.
1113   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1114     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1115       if (SDNode *Node = getNodeForIRValue(&I)) {
1116         SDNodeFlags Flags = Node->getFlags();
1117         Flags.setNoFPExcept(true);
1118         Node->setFlags(Flags);
1119       }
1120 
1121   if (!I.isTerminator() && !HasTailCall &&
1122       !isStatepoint(&I)) // statepoints handle their exports internally
1123     CopyToExportRegsIfNeeded(&I);
1124 
1125   CurInst = nullptr;
1126 }
1127 
1128 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1129   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1130 }
1131 
1132 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1133   // Note: this doesn't use InstVisitor, because it has to work with
1134   // ConstantExpr's in addition to instructions.
1135   switch (Opcode) {
1136   default: llvm_unreachable("Unknown instruction type encountered!");
1137     // Build the switch statement using the Instruction.def file.
1138 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1139     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1140 #include "llvm/IR/Instruction.def"
1141   }
1142 }
1143 
1144 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1145                                                 const DIExpression *Expr) {
1146   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1147     const DbgValueInst *DI = DDI.getDI();
1148     DIVariable *DanglingVariable = DI->getVariable();
1149     DIExpression *DanglingExpr = DI->getExpression();
1150     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1151       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1152       return true;
1153     }
1154     return false;
1155   };
1156 
1157   for (auto &DDIMI : DanglingDebugInfoMap) {
1158     DanglingDebugInfoVector &DDIV = DDIMI.second;
1159 
1160     // If debug info is to be dropped, run it through final checks to see
1161     // whether it can be salvaged.
1162     for (auto &DDI : DDIV)
1163       if (isMatchingDbgValue(DDI))
1164         salvageUnresolvedDbgValue(DDI);
1165 
1166     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1167   }
1168 }
1169 
1170 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1171 // generate the debug data structures now that we've seen its definition.
1172 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1173                                                    SDValue Val) {
1174   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1175   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1176     return;
1177 
1178   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1179   for (auto &DDI : DDIV) {
1180     const DbgValueInst *DI = DDI.getDI();
1181     assert(DI && "Ill-formed DanglingDebugInfo");
1182     DebugLoc dl = DDI.getdl();
1183     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1184     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1185     DILocalVariable *Variable = DI->getVariable();
1186     DIExpression *Expr = DI->getExpression();
1187     assert(Variable->isValidLocationForIntrinsic(dl) &&
1188            "Expected inlined-at fields to agree");
1189     SDDbgValue *SDV;
1190     if (Val.getNode()) {
1191       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1192       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1193       // we couldn't resolve it directly when examining the DbgValue intrinsic
1194       // in the first place we should not be more successful here). Unless we
1195       // have some test case that prove this to be correct we should avoid
1196       // calling EmitFuncArgumentDbgValue here.
1197       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1198         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1199                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1200         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1201         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1202         // inserted after the definition of Val when emitting the instructions
1203         // after ISel. An alternative could be to teach
1204         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1205         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1206                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1207                    << ValSDNodeOrder << "\n");
1208         SDV = getDbgValue(Val, Variable, Expr, dl,
1209                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1210         DAG.AddDbgValue(SDV, Val.getNode(), false);
1211       } else
1212         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1213                           << "in EmitFuncArgumentDbgValue\n");
1214     } else {
1215       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1216       auto Undef =
1217           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1218       auto SDV =
1219           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1220       DAG.AddDbgValue(SDV, nullptr, false);
1221     }
1222   }
1223   DDIV.clear();
1224 }
1225 
1226 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1227   Value *V = DDI.getDI()->getValue();
1228   DILocalVariable *Var = DDI.getDI()->getVariable();
1229   DIExpression *Expr = DDI.getDI()->getExpression();
1230   DebugLoc DL = DDI.getdl();
1231   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1232   unsigned SDOrder = DDI.getSDNodeOrder();
1233 
1234   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1235   // that DW_OP_stack_value is desired.
1236   assert(isa<DbgValueInst>(DDI.getDI()));
1237   bool StackValue = true;
1238 
1239   // Can this Value can be encoded without any further work?
1240   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1241     return;
1242 
1243   // Attempt to salvage back through as many instructions as possible. Bail if
1244   // a non-instruction is seen, such as a constant expression or global
1245   // variable. FIXME: Further work could recover those too.
1246   while (isa<Instruction>(V)) {
1247     Instruction &VAsInst = *cast<Instruction>(V);
1248     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1249 
1250     // If we cannot salvage any further, and haven't yet found a suitable debug
1251     // expression, bail out.
1252     if (!NewExpr)
1253       break;
1254 
1255     // New value and expr now represent this debuginfo.
1256     V = VAsInst.getOperand(0);
1257     Expr = NewExpr;
1258 
1259     // Some kind of simplification occurred: check whether the operand of the
1260     // salvaged debug expression can be encoded in this DAG.
1261     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1262       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1263                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1264       return;
1265     }
1266   }
1267 
1268   // This was the final opportunity to salvage this debug information, and it
1269   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1270   // any earlier variable location.
1271   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1272   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1273   DAG.AddDbgValue(SDV, nullptr, false);
1274 
1275   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1276                     << "\n");
1277   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1278                     << "\n");
1279 }
1280 
1281 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1282                                            DIExpression *Expr, DebugLoc dl,
1283                                            DebugLoc InstDL, unsigned Order) {
1284   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1285   SDDbgValue *SDV;
1286   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1287       isa<ConstantPointerNull>(V)) {
1288     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1289     DAG.AddDbgValue(SDV, nullptr, false);
1290     return true;
1291   }
1292 
1293   // If the Value is a frame index, we can create a FrameIndex debug value
1294   // without relying on the DAG at all.
1295   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1296     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1297     if (SI != FuncInfo.StaticAllocaMap.end()) {
1298       auto SDV =
1299           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1300                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1301       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1302       // is still available even if the SDNode gets optimized out.
1303       DAG.AddDbgValue(SDV, nullptr, false);
1304       return true;
1305     }
1306   }
1307 
1308   // Do not use getValue() in here; we don't want to generate code at
1309   // this point if it hasn't been done yet.
1310   SDValue N = NodeMap[V];
1311   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1312     N = UnusedArgNodeMap[V];
1313   if (N.getNode()) {
1314     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1315       return true;
1316     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1317     DAG.AddDbgValue(SDV, N.getNode(), false);
1318     return true;
1319   }
1320 
1321   // Special rules apply for the first dbg.values of parameter variables in a
1322   // function. Identify them by the fact they reference Argument Values, that
1323   // they're parameters, and they are parameters of the current function. We
1324   // need to let them dangle until they get an SDNode.
1325   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1326                        !InstDL.getInlinedAt();
1327   if (!IsParamOfFunc) {
1328     // The value is not used in this block yet (or it would have an SDNode).
1329     // We still want the value to appear for the user if possible -- if it has
1330     // an associated VReg, we can refer to that instead.
1331     auto VMI = FuncInfo.ValueMap.find(V);
1332     if (VMI != FuncInfo.ValueMap.end()) {
1333       unsigned Reg = VMI->second;
1334       // If this is a PHI node, it may be split up into several MI PHI nodes
1335       // (in FunctionLoweringInfo::set).
1336       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1337                        V->getType(), None);
1338       if (RFV.occupiesMultipleRegs()) {
1339         unsigned Offset = 0;
1340         unsigned BitsToDescribe = 0;
1341         if (auto VarSize = Var->getSizeInBits())
1342           BitsToDescribe = *VarSize;
1343         if (auto Fragment = Expr->getFragmentInfo())
1344           BitsToDescribe = Fragment->SizeInBits;
1345         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1346           unsigned RegisterSize = RegAndSize.second;
1347           // Bail out if all bits are described already.
1348           if (Offset >= BitsToDescribe)
1349             break;
1350           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1351               ? BitsToDescribe - Offset
1352               : RegisterSize;
1353           auto FragmentExpr = DIExpression::createFragmentExpression(
1354               Expr, Offset, FragmentSize);
1355           if (!FragmentExpr)
1356               continue;
1357           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1358                                     false, dl, SDNodeOrder);
1359           DAG.AddDbgValue(SDV, nullptr, false);
1360           Offset += RegisterSize;
1361         }
1362       } else {
1363         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1364         DAG.AddDbgValue(SDV, nullptr, false);
1365       }
1366       return true;
1367     }
1368   }
1369 
1370   return false;
1371 }
1372 
1373 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1374   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1375   for (auto &Pair : DanglingDebugInfoMap)
1376     for (auto &DDI : Pair.second)
1377       salvageUnresolvedDbgValue(DDI);
1378   clearDanglingDebugInfo();
1379 }
1380 
1381 /// getCopyFromRegs - If there was virtual register allocated for the value V
1382 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1383 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1384   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1385   SDValue Result;
1386 
1387   if (It != FuncInfo.ValueMap.end()) {
1388     unsigned InReg = It->second;
1389 
1390     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1391                      DAG.getDataLayout(), InReg, Ty,
1392                      None); // This is not an ABI copy.
1393     SDValue Chain = DAG.getEntryNode();
1394     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1395                                  V);
1396     resolveDanglingDebugInfo(V, Result);
1397   }
1398 
1399   return Result;
1400 }
1401 
1402 /// getValue - Return an SDValue for the given Value.
1403 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1404   // If we already have an SDValue for this value, use it. It's important
1405   // to do this first, so that we don't create a CopyFromReg if we already
1406   // have a regular SDValue.
1407   SDValue &N = NodeMap[V];
1408   if (N.getNode()) return N;
1409 
1410   // If there's a virtual register allocated and initialized for this
1411   // value, use it.
1412   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1413     return copyFromReg;
1414 
1415   // Otherwise create a new SDValue and remember it.
1416   SDValue Val = getValueImpl(V);
1417   NodeMap[V] = Val;
1418   resolveDanglingDebugInfo(V, Val);
1419   return Val;
1420 }
1421 
1422 // Return true if SDValue exists for the given Value
1423 bool SelectionDAGBuilder::findValue(const Value *V) const {
1424   return (NodeMap.find(V) != NodeMap.end()) ||
1425     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1426 }
1427 
1428 /// getNonRegisterValue - Return an SDValue for the given Value, but
1429 /// don't look in FuncInfo.ValueMap for a virtual register.
1430 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1431   // If we already have an SDValue for this value, use it.
1432   SDValue &N = NodeMap[V];
1433   if (N.getNode()) {
1434     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1435       // Remove the debug location from the node as the node is about to be used
1436       // in a location which may differ from the original debug location.  This
1437       // is relevant to Constant and ConstantFP nodes because they can appear
1438       // as constant expressions inside PHI nodes.
1439       N->setDebugLoc(DebugLoc());
1440     }
1441     return N;
1442   }
1443 
1444   // Otherwise create a new SDValue and remember it.
1445   SDValue Val = getValueImpl(V);
1446   NodeMap[V] = Val;
1447   resolveDanglingDebugInfo(V, Val);
1448   return Val;
1449 }
1450 
1451 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1452 /// Create an SDValue for the given value.
1453 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1455 
1456   if (const Constant *C = dyn_cast<Constant>(V)) {
1457     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1458 
1459     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1460       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1461 
1462     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1463       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1464 
1465     if (isa<ConstantPointerNull>(C)) {
1466       unsigned AS = V->getType()->getPointerAddressSpace();
1467       return DAG.getConstant(0, getCurSDLoc(),
1468                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1469     }
1470 
1471     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1472       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1473 
1474     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1475       return DAG.getUNDEF(VT);
1476 
1477     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1478       visit(CE->getOpcode(), *CE);
1479       SDValue N1 = NodeMap[V];
1480       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1481       return N1;
1482     }
1483 
1484     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1485       SmallVector<SDValue, 4> Constants;
1486       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1487            OI != OE; ++OI) {
1488         SDNode *Val = getValue(*OI).getNode();
1489         // If the operand is an empty aggregate, there are no values.
1490         if (!Val) continue;
1491         // Add each leaf value from the operand to the Constants list
1492         // to form a flattened list of all the values.
1493         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1494           Constants.push_back(SDValue(Val, i));
1495       }
1496 
1497       return DAG.getMergeValues(Constants, getCurSDLoc());
1498     }
1499 
1500     if (const ConstantDataSequential *CDS =
1501           dyn_cast<ConstantDataSequential>(C)) {
1502       SmallVector<SDValue, 4> Ops;
1503       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1504         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1505         // Add each leaf value from the operand to the Constants list
1506         // to form a flattened list of all the values.
1507         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1508           Ops.push_back(SDValue(Val, i));
1509       }
1510 
1511       if (isa<ArrayType>(CDS->getType()))
1512         return DAG.getMergeValues(Ops, getCurSDLoc());
1513       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1514     }
1515 
1516     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1517       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1518              "Unknown struct or array constant!");
1519 
1520       SmallVector<EVT, 4> ValueVTs;
1521       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1522       unsigned NumElts = ValueVTs.size();
1523       if (NumElts == 0)
1524         return SDValue(); // empty struct
1525       SmallVector<SDValue, 4> Constants(NumElts);
1526       for (unsigned i = 0; i != NumElts; ++i) {
1527         EVT EltVT = ValueVTs[i];
1528         if (isa<UndefValue>(C))
1529           Constants[i] = DAG.getUNDEF(EltVT);
1530         else if (EltVT.isFloatingPoint())
1531           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1532         else
1533           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1534       }
1535 
1536       return DAG.getMergeValues(Constants, getCurSDLoc());
1537     }
1538 
1539     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1540       return DAG.getBlockAddress(BA, VT);
1541 
1542     VectorType *VecTy = cast<VectorType>(V->getType());
1543     unsigned NumElements = VecTy->getNumElements();
1544 
1545     // Now that we know the number and type of the elements, get that number of
1546     // elements into the Ops array based on what kind of constant it is.
1547     SmallVector<SDValue, 16> Ops;
1548     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1549       for (unsigned i = 0; i != NumElements; ++i)
1550         Ops.push_back(getValue(CV->getOperand(i)));
1551     } else {
1552       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1553       EVT EltVT =
1554           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1555 
1556       SDValue Op;
1557       if (EltVT.isFloatingPoint())
1558         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1559       else
1560         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1561       Ops.assign(NumElements, Op);
1562     }
1563 
1564     // Create a BUILD_VECTOR node.
1565     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1566   }
1567 
1568   // If this is a static alloca, generate it as the frameindex instead of
1569   // computation.
1570   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1571     DenseMap<const AllocaInst*, int>::iterator SI =
1572       FuncInfo.StaticAllocaMap.find(AI);
1573     if (SI != FuncInfo.StaticAllocaMap.end())
1574       return DAG.getFrameIndex(SI->second,
1575                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1576   }
1577 
1578   // If this is an instruction which fast-isel has deferred, select it now.
1579   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1580     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1581 
1582     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1583                      Inst->getType(), getABIRegCopyCC(V));
1584     SDValue Chain = DAG.getEntryNode();
1585     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1586   }
1587 
1588   llvm_unreachable("Can't get register for value!");
1589 }
1590 
1591 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1592   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1593   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1594   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1595   bool IsSEH = isAsynchronousEHPersonality(Pers);
1596   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1597   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1598   if (!IsSEH)
1599     CatchPadMBB->setIsEHScopeEntry();
1600   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1601   if (IsMSVCCXX || IsCoreCLR)
1602     CatchPadMBB->setIsEHFuncletEntry();
1603   // Wasm does not need catchpads anymore
1604   if (!IsWasmCXX)
1605     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1606                             getControlRoot()));
1607 }
1608 
1609 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1610   // Update machine-CFG edge.
1611   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1612   FuncInfo.MBB->addSuccessor(TargetMBB);
1613 
1614   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1615   bool IsSEH = isAsynchronousEHPersonality(Pers);
1616   if (IsSEH) {
1617     // If this is not a fall-through branch or optimizations are switched off,
1618     // emit the branch.
1619     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1620         TM.getOptLevel() == CodeGenOpt::None)
1621       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1622                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1623     return;
1624   }
1625 
1626   // Figure out the funclet membership for the catchret's successor.
1627   // This will be used by the FuncletLayout pass to determine how to order the
1628   // BB's.
1629   // A 'catchret' returns to the outer scope's color.
1630   Value *ParentPad = I.getCatchSwitchParentPad();
1631   const BasicBlock *SuccessorColor;
1632   if (isa<ConstantTokenNone>(ParentPad))
1633     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1634   else
1635     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1636   assert(SuccessorColor && "No parent funclet for catchret!");
1637   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1638   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1639 
1640   // Create the terminator node.
1641   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1642                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1643                             DAG.getBasicBlock(SuccessorColorMBB));
1644   DAG.setRoot(Ret);
1645 }
1646 
1647 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1648   // Don't emit any special code for the cleanuppad instruction. It just marks
1649   // the start of an EH scope/funclet.
1650   FuncInfo.MBB->setIsEHScopeEntry();
1651   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1652   if (Pers != EHPersonality::Wasm_CXX) {
1653     FuncInfo.MBB->setIsEHFuncletEntry();
1654     FuncInfo.MBB->setIsCleanupFuncletEntry();
1655   }
1656 }
1657 
1658 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1659 // the control flow always stops at the single catch pad, as it does for a
1660 // cleanup pad. In case the exception caught is not of the types the catch pad
1661 // catches, it will be rethrown by a rethrow.
1662 static void findWasmUnwindDestinations(
1663     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1664     BranchProbability Prob,
1665     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1666         &UnwindDests) {
1667   while (EHPadBB) {
1668     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1669     if (isa<CleanupPadInst>(Pad)) {
1670       // Stop on cleanup pads.
1671       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1672       UnwindDests.back().first->setIsEHScopeEntry();
1673       break;
1674     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1675       // Add the catchpad handlers to the possible destinations. We don't
1676       // continue to the unwind destination of the catchswitch for wasm.
1677       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1678         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1679         UnwindDests.back().first->setIsEHScopeEntry();
1680       }
1681       break;
1682     } else {
1683       continue;
1684     }
1685   }
1686 }
1687 
1688 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1689 /// many places it could ultimately go. In the IR, we have a single unwind
1690 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1691 /// This function skips over imaginary basic blocks that hold catchswitch
1692 /// instructions, and finds all the "real" machine
1693 /// basic block destinations. As those destinations may not be successors of
1694 /// EHPadBB, here we also calculate the edge probability to those destinations.
1695 /// The passed-in Prob is the edge probability to EHPadBB.
1696 static void findUnwindDestinations(
1697     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1698     BranchProbability Prob,
1699     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1700         &UnwindDests) {
1701   EHPersonality Personality =
1702     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1703   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1704   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1705   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1706   bool IsSEH = isAsynchronousEHPersonality(Personality);
1707 
1708   if (IsWasmCXX) {
1709     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1710     assert(UnwindDests.size() <= 1 &&
1711            "There should be at most one unwind destination for wasm");
1712     return;
1713   }
1714 
1715   while (EHPadBB) {
1716     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1717     BasicBlock *NewEHPadBB = nullptr;
1718     if (isa<LandingPadInst>(Pad)) {
1719       // Stop on landingpads. They are not funclets.
1720       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1721       break;
1722     } else if (isa<CleanupPadInst>(Pad)) {
1723       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1724       // personalities.
1725       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1726       UnwindDests.back().first->setIsEHScopeEntry();
1727       UnwindDests.back().first->setIsEHFuncletEntry();
1728       break;
1729     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1730       // Add the catchpad handlers to the possible destinations.
1731       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1732         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1733         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1734         if (IsMSVCCXX || IsCoreCLR)
1735           UnwindDests.back().first->setIsEHFuncletEntry();
1736         if (!IsSEH)
1737           UnwindDests.back().first->setIsEHScopeEntry();
1738       }
1739       NewEHPadBB = CatchSwitch->getUnwindDest();
1740     } else {
1741       continue;
1742     }
1743 
1744     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1745     if (BPI && NewEHPadBB)
1746       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1747     EHPadBB = NewEHPadBB;
1748   }
1749 }
1750 
1751 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1752   // Update successor info.
1753   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1754   auto UnwindDest = I.getUnwindDest();
1755   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1756   BranchProbability UnwindDestProb =
1757       (BPI && UnwindDest)
1758           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1759           : BranchProbability::getZero();
1760   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1761   for (auto &UnwindDest : UnwindDests) {
1762     UnwindDest.first->setIsEHPad();
1763     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1764   }
1765   FuncInfo.MBB->normalizeSuccProbs();
1766 
1767   // Create the terminator node.
1768   SDValue Ret =
1769       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1770   DAG.setRoot(Ret);
1771 }
1772 
1773 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1774   report_fatal_error("visitCatchSwitch not yet implemented!");
1775 }
1776 
1777 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1779   auto &DL = DAG.getDataLayout();
1780   SDValue Chain = getControlRoot();
1781   SmallVector<ISD::OutputArg, 8> Outs;
1782   SmallVector<SDValue, 8> OutVals;
1783 
1784   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1785   // lower
1786   //
1787   //   %val = call <ty> @llvm.experimental.deoptimize()
1788   //   ret <ty> %val
1789   //
1790   // differently.
1791   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1792     LowerDeoptimizingReturn();
1793     return;
1794   }
1795 
1796   if (!FuncInfo.CanLowerReturn) {
1797     unsigned DemoteReg = FuncInfo.DemoteRegister;
1798     const Function *F = I.getParent()->getParent();
1799 
1800     // Emit a store of the return value through the virtual register.
1801     // Leave Outs empty so that LowerReturn won't try to load return
1802     // registers the usual way.
1803     SmallVector<EVT, 1> PtrValueVTs;
1804     ComputeValueVTs(TLI, DL,
1805                     F->getReturnType()->getPointerTo(
1806                         DAG.getDataLayout().getAllocaAddrSpace()),
1807                     PtrValueVTs);
1808 
1809     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1810                                         DemoteReg, PtrValueVTs[0]);
1811     SDValue RetOp = getValue(I.getOperand(0));
1812 
1813     SmallVector<EVT, 4> ValueVTs, MemVTs;
1814     SmallVector<uint64_t, 4> Offsets;
1815     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1816                     &Offsets);
1817     unsigned NumValues = ValueVTs.size();
1818 
1819     SmallVector<SDValue, 4> Chains(NumValues);
1820     for (unsigned i = 0; i != NumValues; ++i) {
1821       // An aggregate return value cannot wrap around the address space, so
1822       // offsets to its parts don't wrap either.
1823       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1824 
1825       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1826       if (MemVTs[i] != ValueVTs[i])
1827         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1828       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1829           // FIXME: better loc info would be nice.
1830           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1831     }
1832 
1833     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1834                         MVT::Other, Chains);
1835   } else if (I.getNumOperands() != 0) {
1836     SmallVector<EVT, 4> ValueVTs;
1837     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1838     unsigned NumValues = ValueVTs.size();
1839     if (NumValues) {
1840       SDValue RetOp = getValue(I.getOperand(0));
1841 
1842       const Function *F = I.getParent()->getParent();
1843 
1844       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1845           I.getOperand(0)->getType(), F->getCallingConv(),
1846           /*IsVarArg*/ false);
1847 
1848       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1849       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1850                                           Attribute::SExt))
1851         ExtendKind = ISD::SIGN_EXTEND;
1852       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1853                                                Attribute::ZExt))
1854         ExtendKind = ISD::ZERO_EXTEND;
1855 
1856       LLVMContext &Context = F->getContext();
1857       bool RetInReg = F->getAttributes().hasAttribute(
1858           AttributeList::ReturnIndex, Attribute::InReg);
1859 
1860       for (unsigned j = 0; j != NumValues; ++j) {
1861         EVT VT = ValueVTs[j];
1862 
1863         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1864           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1865 
1866         CallingConv::ID CC = F->getCallingConv();
1867 
1868         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1869         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1870         SmallVector<SDValue, 4> Parts(NumParts);
1871         getCopyToParts(DAG, getCurSDLoc(),
1872                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1873                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1874 
1875         // 'inreg' on function refers to return value
1876         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1877         if (RetInReg)
1878           Flags.setInReg();
1879 
1880         if (I.getOperand(0)->getType()->isPointerTy()) {
1881           Flags.setPointer();
1882           Flags.setPointerAddrSpace(
1883               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1884         }
1885 
1886         if (NeedsRegBlock) {
1887           Flags.setInConsecutiveRegs();
1888           if (j == NumValues - 1)
1889             Flags.setInConsecutiveRegsLast();
1890         }
1891 
1892         // Propagate extension type if any
1893         if (ExtendKind == ISD::SIGN_EXTEND)
1894           Flags.setSExt();
1895         else if (ExtendKind == ISD::ZERO_EXTEND)
1896           Flags.setZExt();
1897 
1898         for (unsigned i = 0; i < NumParts; ++i) {
1899           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1900                                         VT, /*isfixed=*/true, 0, 0));
1901           OutVals.push_back(Parts[i]);
1902         }
1903       }
1904     }
1905   }
1906 
1907   // Push in swifterror virtual register as the last element of Outs. This makes
1908   // sure swifterror virtual register will be returned in the swifterror
1909   // physical register.
1910   const Function *F = I.getParent()->getParent();
1911   if (TLI.supportSwiftError() &&
1912       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1913     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1914     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1915     Flags.setSwiftError();
1916     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1917                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1918                                   true /*isfixed*/, 1 /*origidx*/,
1919                                   0 /*partOffs*/));
1920     // Create SDNode for the swifterror virtual register.
1921     OutVals.push_back(
1922         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1923                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1924                         EVT(TLI.getPointerTy(DL))));
1925   }
1926 
1927   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1928   CallingConv::ID CallConv =
1929     DAG.getMachineFunction().getFunction().getCallingConv();
1930   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1931       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1932 
1933   // Verify that the target's LowerReturn behaved as expected.
1934   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1935          "LowerReturn didn't return a valid chain!");
1936 
1937   // Update the DAG with the new chain value resulting from return lowering.
1938   DAG.setRoot(Chain);
1939 }
1940 
1941 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1942 /// created for it, emit nodes to copy the value into the virtual
1943 /// registers.
1944 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1945   // Skip empty types
1946   if (V->getType()->isEmptyTy())
1947     return;
1948 
1949   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1950   if (VMI != FuncInfo.ValueMap.end()) {
1951     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1952     CopyValueToVirtualRegister(V, VMI->second);
1953   }
1954 }
1955 
1956 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1957 /// the current basic block, add it to ValueMap now so that we'll get a
1958 /// CopyTo/FromReg.
1959 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1960   // No need to export constants.
1961   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1962 
1963   // Already exported?
1964   if (FuncInfo.isExportedInst(V)) return;
1965 
1966   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1967   CopyValueToVirtualRegister(V, Reg);
1968 }
1969 
1970 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1971                                                      const BasicBlock *FromBB) {
1972   // The operands of the setcc have to be in this block.  We don't know
1973   // how to export them from some other block.
1974   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1975     // Can export from current BB.
1976     if (VI->getParent() == FromBB)
1977       return true;
1978 
1979     // Is already exported, noop.
1980     return FuncInfo.isExportedInst(V);
1981   }
1982 
1983   // If this is an argument, we can export it if the BB is the entry block or
1984   // if it is already exported.
1985   if (isa<Argument>(V)) {
1986     if (FromBB == &FromBB->getParent()->getEntryBlock())
1987       return true;
1988 
1989     // Otherwise, can only export this if it is already exported.
1990     return FuncInfo.isExportedInst(V);
1991   }
1992 
1993   // Otherwise, constants can always be exported.
1994   return true;
1995 }
1996 
1997 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1998 BranchProbability
1999 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2000                                         const MachineBasicBlock *Dst) const {
2001   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2002   const BasicBlock *SrcBB = Src->getBasicBlock();
2003   const BasicBlock *DstBB = Dst->getBasicBlock();
2004   if (!BPI) {
2005     // If BPI is not available, set the default probability as 1 / N, where N is
2006     // the number of successors.
2007     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2008     return BranchProbability(1, SuccSize);
2009   }
2010   return BPI->getEdgeProbability(SrcBB, DstBB);
2011 }
2012 
2013 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2014                                                MachineBasicBlock *Dst,
2015                                                BranchProbability Prob) {
2016   if (!FuncInfo.BPI)
2017     Src->addSuccessorWithoutProb(Dst);
2018   else {
2019     if (Prob.isUnknown())
2020       Prob = getEdgeProbability(Src, Dst);
2021     Src->addSuccessor(Dst, Prob);
2022   }
2023 }
2024 
2025 static bool InBlock(const Value *V, const BasicBlock *BB) {
2026   if (const Instruction *I = dyn_cast<Instruction>(V))
2027     return I->getParent() == BB;
2028   return true;
2029 }
2030 
2031 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2032 /// This function emits a branch and is used at the leaves of an OR or an
2033 /// AND operator tree.
2034 void
2035 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2036                                                   MachineBasicBlock *TBB,
2037                                                   MachineBasicBlock *FBB,
2038                                                   MachineBasicBlock *CurBB,
2039                                                   MachineBasicBlock *SwitchBB,
2040                                                   BranchProbability TProb,
2041                                                   BranchProbability FProb,
2042                                                   bool InvertCond) {
2043   const BasicBlock *BB = CurBB->getBasicBlock();
2044 
2045   // If the leaf of the tree is a comparison, merge the condition into
2046   // the caseblock.
2047   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2048     // The operands of the cmp have to be in this block.  We don't know
2049     // how to export them from some other block.  If this is the first block
2050     // of the sequence, no exporting is needed.
2051     if (CurBB == SwitchBB ||
2052         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2053          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2054       ISD::CondCode Condition;
2055       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2056         ICmpInst::Predicate Pred =
2057             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2058         Condition = getICmpCondCode(Pred);
2059       } else {
2060         const FCmpInst *FC = cast<FCmpInst>(Cond);
2061         FCmpInst::Predicate Pred =
2062             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2063         Condition = getFCmpCondCode(Pred);
2064         if (TM.Options.NoNaNsFPMath)
2065           Condition = getFCmpCodeWithoutNaN(Condition);
2066       }
2067 
2068       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2069                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2070       SL->SwitchCases.push_back(CB);
2071       return;
2072     }
2073   }
2074 
2075   // Create a CaseBlock record representing this branch.
2076   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2077   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2078                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2079   SL->SwitchCases.push_back(CB);
2080 }
2081 
2082 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2083                                                MachineBasicBlock *TBB,
2084                                                MachineBasicBlock *FBB,
2085                                                MachineBasicBlock *CurBB,
2086                                                MachineBasicBlock *SwitchBB,
2087                                                Instruction::BinaryOps Opc,
2088                                                BranchProbability TProb,
2089                                                BranchProbability FProb,
2090                                                bool InvertCond) {
2091   // Skip over not part of the tree and remember to invert op and operands at
2092   // next level.
2093   Value *NotCond;
2094   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2095       InBlock(NotCond, CurBB->getBasicBlock())) {
2096     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2097                          !InvertCond);
2098     return;
2099   }
2100 
2101   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2102   // Compute the effective opcode for Cond, taking into account whether it needs
2103   // to be inverted, e.g.
2104   //   and (not (or A, B)), C
2105   // gets lowered as
2106   //   and (and (not A, not B), C)
2107   unsigned BOpc = 0;
2108   if (BOp) {
2109     BOpc = BOp->getOpcode();
2110     if (InvertCond) {
2111       if (BOpc == Instruction::And)
2112         BOpc = Instruction::Or;
2113       else if (BOpc == Instruction::Or)
2114         BOpc = Instruction::And;
2115     }
2116   }
2117 
2118   // If this node is not part of the or/and tree, emit it as a branch.
2119   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2120       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2121       BOp->getParent() != CurBB->getBasicBlock() ||
2122       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2123       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2124     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2125                                  TProb, FProb, InvertCond);
2126     return;
2127   }
2128 
2129   //  Create TmpBB after CurBB.
2130   MachineFunction::iterator BBI(CurBB);
2131   MachineFunction &MF = DAG.getMachineFunction();
2132   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2133   CurBB->getParent()->insert(++BBI, TmpBB);
2134 
2135   if (Opc == Instruction::Or) {
2136     // Codegen X | Y as:
2137     // BB1:
2138     //   jmp_if_X TBB
2139     //   jmp TmpBB
2140     // TmpBB:
2141     //   jmp_if_Y TBB
2142     //   jmp FBB
2143     //
2144 
2145     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2146     // The requirement is that
2147     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2148     //     = TrueProb for original BB.
2149     // Assuming the original probabilities are A and B, one choice is to set
2150     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2151     // A/(1+B) and 2B/(1+B). This choice assumes that
2152     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2153     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2154     // TmpBB, but the math is more complicated.
2155 
2156     auto NewTrueProb = TProb / 2;
2157     auto NewFalseProb = TProb / 2 + FProb;
2158     // Emit the LHS condition.
2159     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2160                          NewTrueProb, NewFalseProb, InvertCond);
2161 
2162     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2163     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2164     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2165     // Emit the RHS condition into TmpBB.
2166     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2167                          Probs[0], Probs[1], InvertCond);
2168   } else {
2169     assert(Opc == Instruction::And && "Unknown merge op!");
2170     // Codegen X & Y as:
2171     // BB1:
2172     //   jmp_if_X TmpBB
2173     //   jmp FBB
2174     // TmpBB:
2175     //   jmp_if_Y TBB
2176     //   jmp FBB
2177     //
2178     //  This requires creation of TmpBB after CurBB.
2179 
2180     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2181     // The requirement is that
2182     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2183     //     = FalseProb for original BB.
2184     // Assuming the original probabilities are A and B, one choice is to set
2185     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2186     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2187     // TrueProb for BB1 * FalseProb for TmpBB.
2188 
2189     auto NewTrueProb = TProb + FProb / 2;
2190     auto NewFalseProb = FProb / 2;
2191     // Emit the LHS condition.
2192     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2193                          NewTrueProb, NewFalseProb, InvertCond);
2194 
2195     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2196     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2197     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2198     // Emit the RHS condition into TmpBB.
2199     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2200                          Probs[0], Probs[1], InvertCond);
2201   }
2202 }
2203 
2204 /// If the set of cases should be emitted as a series of branches, return true.
2205 /// If we should emit this as a bunch of and/or'd together conditions, return
2206 /// false.
2207 bool
2208 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2209   if (Cases.size() != 2) return true;
2210 
2211   // If this is two comparisons of the same values or'd or and'd together, they
2212   // will get folded into a single comparison, so don't emit two blocks.
2213   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2214        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2215       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2216        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2217     return false;
2218   }
2219 
2220   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2221   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2222   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2223       Cases[0].CC == Cases[1].CC &&
2224       isa<Constant>(Cases[0].CmpRHS) &&
2225       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2226     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2227       return false;
2228     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2229       return false;
2230   }
2231 
2232   return true;
2233 }
2234 
2235 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2236   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2237 
2238   // Update machine-CFG edges.
2239   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2240 
2241   if (I.isUnconditional()) {
2242     // Update machine-CFG edges.
2243     BrMBB->addSuccessor(Succ0MBB);
2244 
2245     // If this is not a fall-through branch or optimizations are switched off,
2246     // emit the branch.
2247     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2248       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2249                               MVT::Other, getControlRoot(),
2250                               DAG.getBasicBlock(Succ0MBB)));
2251 
2252     return;
2253   }
2254 
2255   // If this condition is one of the special cases we handle, do special stuff
2256   // now.
2257   const Value *CondVal = I.getCondition();
2258   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2259 
2260   // If this is a series of conditions that are or'd or and'd together, emit
2261   // this as a sequence of branches instead of setcc's with and/or operations.
2262   // As long as jumps are not expensive, this should improve performance.
2263   // For example, instead of something like:
2264   //     cmp A, B
2265   //     C = seteq
2266   //     cmp D, E
2267   //     F = setle
2268   //     or C, F
2269   //     jnz foo
2270   // Emit:
2271   //     cmp A, B
2272   //     je foo
2273   //     cmp D, E
2274   //     jle foo
2275   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2276     Instruction::BinaryOps Opcode = BOp->getOpcode();
2277     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2278         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2279         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2280       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2281                            Opcode,
2282                            getEdgeProbability(BrMBB, Succ0MBB),
2283                            getEdgeProbability(BrMBB, Succ1MBB),
2284                            /*InvertCond=*/false);
2285       // If the compares in later blocks need to use values not currently
2286       // exported from this block, export them now.  This block should always
2287       // be the first entry.
2288       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2289 
2290       // Allow some cases to be rejected.
2291       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2292         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2293           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2294           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2295         }
2296 
2297         // Emit the branch for this block.
2298         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2299         SL->SwitchCases.erase(SL->SwitchCases.begin());
2300         return;
2301       }
2302 
2303       // Okay, we decided not to do this, remove any inserted MBB's and clear
2304       // SwitchCases.
2305       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2306         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2307 
2308       SL->SwitchCases.clear();
2309     }
2310   }
2311 
2312   // Create a CaseBlock record representing this branch.
2313   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2314                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2315 
2316   // Use visitSwitchCase to actually insert the fast branch sequence for this
2317   // cond branch.
2318   visitSwitchCase(CB, BrMBB);
2319 }
2320 
2321 /// visitSwitchCase - Emits the necessary code to represent a single node in
2322 /// the binary search tree resulting from lowering a switch instruction.
2323 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2324                                           MachineBasicBlock *SwitchBB) {
2325   SDValue Cond;
2326   SDValue CondLHS = getValue(CB.CmpLHS);
2327   SDLoc dl = CB.DL;
2328 
2329   if (CB.CC == ISD::SETTRUE) {
2330     // Branch or fall through to TrueBB.
2331     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2332     SwitchBB->normalizeSuccProbs();
2333     if (CB.TrueBB != NextBlock(SwitchBB)) {
2334       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2335                               DAG.getBasicBlock(CB.TrueBB)));
2336     }
2337     return;
2338   }
2339 
2340   auto &TLI = DAG.getTargetLoweringInfo();
2341   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2342 
2343   // Build the setcc now.
2344   if (!CB.CmpMHS) {
2345     // Fold "(X == true)" to X and "(X == false)" to !X to
2346     // handle common cases produced by branch lowering.
2347     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2348         CB.CC == ISD::SETEQ)
2349       Cond = CondLHS;
2350     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2351              CB.CC == ISD::SETEQ) {
2352       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2353       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2354     } else {
2355       SDValue CondRHS = getValue(CB.CmpRHS);
2356 
2357       // If a pointer's DAG type is larger than its memory type then the DAG
2358       // values are zero-extended. This breaks signed comparisons so truncate
2359       // back to the underlying type before doing the compare.
2360       if (CondLHS.getValueType() != MemVT) {
2361         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2362         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2363       }
2364       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2365     }
2366   } else {
2367     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2368 
2369     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2370     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2371 
2372     SDValue CmpOp = getValue(CB.CmpMHS);
2373     EVT VT = CmpOp.getValueType();
2374 
2375     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2376       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2377                           ISD::SETLE);
2378     } else {
2379       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2380                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2381       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2382                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2383     }
2384   }
2385 
2386   // Update successor info
2387   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2388   // TrueBB and FalseBB are always different unless the incoming IR is
2389   // degenerate. This only happens when running llc on weird IR.
2390   if (CB.TrueBB != CB.FalseBB)
2391     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2392   SwitchBB->normalizeSuccProbs();
2393 
2394   // If the lhs block is the next block, invert the condition so that we can
2395   // fall through to the lhs instead of the rhs block.
2396   if (CB.TrueBB == NextBlock(SwitchBB)) {
2397     std::swap(CB.TrueBB, CB.FalseBB);
2398     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2399     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2400   }
2401 
2402   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2403                                MVT::Other, getControlRoot(), Cond,
2404                                DAG.getBasicBlock(CB.TrueBB));
2405 
2406   // Insert the false branch. Do this even if it's a fall through branch,
2407   // this makes it easier to do DAG optimizations which require inverting
2408   // the branch condition.
2409   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2410                        DAG.getBasicBlock(CB.FalseBB));
2411 
2412   DAG.setRoot(BrCond);
2413 }
2414 
2415 /// visitJumpTable - Emit JumpTable node in the current MBB
2416 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2417   // Emit the code for the jump table
2418   assert(JT.Reg != -1U && "Should lower JT Header first!");
2419   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2420   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2421                                      JT.Reg, PTy);
2422   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2423   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2424                                     MVT::Other, Index.getValue(1),
2425                                     Table, Index);
2426   DAG.setRoot(BrJumpTable);
2427 }
2428 
2429 /// visitJumpTableHeader - This function emits necessary code to produce index
2430 /// in the JumpTable from switch case.
2431 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2432                                                JumpTableHeader &JTH,
2433                                                MachineBasicBlock *SwitchBB) {
2434   SDLoc dl = getCurSDLoc();
2435 
2436   // Subtract the lowest switch case value from the value being switched on.
2437   SDValue SwitchOp = getValue(JTH.SValue);
2438   EVT VT = SwitchOp.getValueType();
2439   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2440                             DAG.getConstant(JTH.First, dl, VT));
2441 
2442   // The SDNode we just created, which holds the value being switched on minus
2443   // the smallest case value, needs to be copied to a virtual register so it
2444   // can be used as an index into the jump table in a subsequent basic block.
2445   // This value may be smaller or larger than the target's pointer type, and
2446   // therefore require extension or truncating.
2447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2448   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2449 
2450   unsigned JumpTableReg =
2451       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2452   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2453                                     JumpTableReg, SwitchOp);
2454   JT.Reg = JumpTableReg;
2455 
2456   if (!JTH.OmitRangeCheck) {
2457     // Emit the range check for the jump table, and branch to the default block
2458     // for the switch statement if the value being switched on exceeds the
2459     // largest case in the switch.
2460     SDValue CMP = DAG.getSetCC(
2461         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2462                                    Sub.getValueType()),
2463         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2464 
2465     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2466                                  MVT::Other, CopyTo, CMP,
2467                                  DAG.getBasicBlock(JT.Default));
2468 
2469     // Avoid emitting unnecessary branches to the next block.
2470     if (JT.MBB != NextBlock(SwitchBB))
2471       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2472                            DAG.getBasicBlock(JT.MBB));
2473 
2474     DAG.setRoot(BrCond);
2475   } else {
2476     // Avoid emitting unnecessary branches to the next block.
2477     if (JT.MBB != NextBlock(SwitchBB))
2478       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2479                               DAG.getBasicBlock(JT.MBB)));
2480     else
2481       DAG.setRoot(CopyTo);
2482   }
2483 }
2484 
2485 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2486 /// variable if there exists one.
2487 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2488                                  SDValue &Chain) {
2489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2490   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2491   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2494   MachineSDNode *Node =
2495       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2496   if (Global) {
2497     MachinePointerInfo MPInfo(Global);
2498     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2499                  MachineMemOperand::MODereferenceable;
2500     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2501         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2502     DAG.setNodeMemRefs(Node, {MemRef});
2503   }
2504   if (PtrTy != PtrMemTy)
2505     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2506   return SDValue(Node, 0);
2507 }
2508 
2509 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2510 /// tail spliced into a stack protector check success bb.
2511 ///
2512 /// For a high level explanation of how this fits into the stack protector
2513 /// generation see the comment on the declaration of class
2514 /// StackProtectorDescriptor.
2515 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2516                                                   MachineBasicBlock *ParentBB) {
2517 
2518   // First create the loads to the guard/stack slot for the comparison.
2519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2520   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2521   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2522 
2523   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2524   int FI = MFI.getStackProtectorIndex();
2525 
2526   SDValue Guard;
2527   SDLoc dl = getCurSDLoc();
2528   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2529   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2530   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2531 
2532   // Generate code to load the content of the guard slot.
2533   SDValue GuardVal = DAG.getLoad(
2534       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2535       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2536       MachineMemOperand::MOVolatile);
2537 
2538   if (TLI.useStackGuardXorFP())
2539     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2540 
2541   // Retrieve guard check function, nullptr if instrumentation is inlined.
2542   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2543     // The target provides a guard check function to validate the guard value.
2544     // Generate a call to that function with the content of the guard slot as
2545     // argument.
2546     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2547     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2548 
2549     TargetLowering::ArgListTy Args;
2550     TargetLowering::ArgListEntry Entry;
2551     Entry.Node = GuardVal;
2552     Entry.Ty = FnTy->getParamType(0);
2553     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2554       Entry.IsInReg = true;
2555     Args.push_back(Entry);
2556 
2557     TargetLowering::CallLoweringInfo CLI(DAG);
2558     CLI.setDebugLoc(getCurSDLoc())
2559         .setChain(DAG.getEntryNode())
2560         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2561                    getValue(GuardCheckFn), std::move(Args));
2562 
2563     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2564     DAG.setRoot(Result.second);
2565     return;
2566   }
2567 
2568   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2569   // Otherwise, emit a volatile load to retrieve the stack guard value.
2570   SDValue Chain = DAG.getEntryNode();
2571   if (TLI.useLoadStackGuardNode()) {
2572     Guard = getLoadStackGuard(DAG, dl, Chain);
2573   } else {
2574     const Value *IRGuard = TLI.getSDagStackGuard(M);
2575     SDValue GuardPtr = getValue(IRGuard);
2576 
2577     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2578                         MachinePointerInfo(IRGuard, 0), Align,
2579                         MachineMemOperand::MOVolatile);
2580   }
2581 
2582   // Perform the comparison via a subtract/getsetcc.
2583   EVT VT = Guard.getValueType();
2584   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2585 
2586   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2587                                                         *DAG.getContext(),
2588                                                         Sub.getValueType()),
2589                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2590 
2591   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2592   // branch to failure MBB.
2593   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2594                                MVT::Other, GuardVal.getOperand(0),
2595                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2596   // Otherwise branch to success MBB.
2597   SDValue Br = DAG.getNode(ISD::BR, dl,
2598                            MVT::Other, BrCond,
2599                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2600 
2601   DAG.setRoot(Br);
2602 }
2603 
2604 /// Codegen the failure basic block for a stack protector check.
2605 ///
2606 /// A failure stack protector machine basic block consists simply of a call to
2607 /// __stack_chk_fail().
2608 ///
2609 /// For a high level explanation of how this fits into the stack protector
2610 /// generation see the comment on the declaration of class
2611 /// StackProtectorDescriptor.
2612 void
2613 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2615   TargetLowering::MakeLibCallOptions CallOptions;
2616   CallOptions.setDiscardResult(true);
2617   SDValue Chain =
2618       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2619                       None, CallOptions, getCurSDLoc()).second;
2620   // On PS4, the "return address" must still be within the calling function,
2621   // even if it's at the very end, so emit an explicit TRAP here.
2622   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2623   if (TM.getTargetTriple().isPS4CPU())
2624     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2625 
2626   DAG.setRoot(Chain);
2627 }
2628 
2629 /// visitBitTestHeader - This function emits necessary code to produce value
2630 /// suitable for "bit tests"
2631 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2632                                              MachineBasicBlock *SwitchBB) {
2633   SDLoc dl = getCurSDLoc();
2634 
2635   // Subtract the minimum value.
2636   SDValue SwitchOp = getValue(B.SValue);
2637   EVT VT = SwitchOp.getValueType();
2638   SDValue RangeSub =
2639       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2640 
2641   // Determine the type of the test operands.
2642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2643   bool UsePtrType = false;
2644   if (!TLI.isTypeLegal(VT)) {
2645     UsePtrType = true;
2646   } else {
2647     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2648       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2649         // Switch table case range are encoded into series of masks.
2650         // Just use pointer type, it's guaranteed to fit.
2651         UsePtrType = true;
2652         break;
2653       }
2654   }
2655   SDValue Sub = RangeSub;
2656   if (UsePtrType) {
2657     VT = TLI.getPointerTy(DAG.getDataLayout());
2658     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2659   }
2660 
2661   B.RegVT = VT.getSimpleVT();
2662   B.Reg = FuncInfo.CreateReg(B.RegVT);
2663   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2664 
2665   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2666 
2667   if (!B.OmitRangeCheck)
2668     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2669   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2670   SwitchBB->normalizeSuccProbs();
2671 
2672   SDValue Root = CopyTo;
2673   if (!B.OmitRangeCheck) {
2674     // Conditional branch to the default block.
2675     SDValue RangeCmp = DAG.getSetCC(dl,
2676         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2677                                RangeSub.getValueType()),
2678         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2679         ISD::SETUGT);
2680 
2681     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2682                        DAG.getBasicBlock(B.Default));
2683   }
2684 
2685   // Avoid emitting unnecessary branches to the next block.
2686   if (MBB != NextBlock(SwitchBB))
2687     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2688 
2689   DAG.setRoot(Root);
2690 }
2691 
2692 /// visitBitTestCase - this function produces one "bit test"
2693 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2694                                            MachineBasicBlock* NextMBB,
2695                                            BranchProbability BranchProbToNext,
2696                                            unsigned Reg,
2697                                            BitTestCase &B,
2698                                            MachineBasicBlock *SwitchBB) {
2699   SDLoc dl = getCurSDLoc();
2700   MVT VT = BB.RegVT;
2701   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2702   SDValue Cmp;
2703   unsigned PopCount = countPopulation(B.Mask);
2704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2705   if (PopCount == 1) {
2706     // Testing for a single bit; just compare the shift count with what it
2707     // would need to be to shift a 1 bit in that position.
2708     Cmp = DAG.getSetCC(
2709         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2710         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2711         ISD::SETEQ);
2712   } else if (PopCount == BB.Range) {
2713     // There is only one zero bit in the range, test for it directly.
2714     Cmp = DAG.getSetCC(
2715         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2716         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2717         ISD::SETNE);
2718   } else {
2719     // Make desired shift
2720     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2721                                     DAG.getConstant(1, dl, VT), ShiftOp);
2722 
2723     // Emit bit tests and jumps
2724     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2725                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2726     Cmp = DAG.getSetCC(
2727         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2728         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2729   }
2730 
2731   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2732   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2733   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2734   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2735   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2736   // one as they are relative probabilities (and thus work more like weights),
2737   // and hence we need to normalize them to let the sum of them become one.
2738   SwitchBB->normalizeSuccProbs();
2739 
2740   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2741                               MVT::Other, getControlRoot(),
2742                               Cmp, DAG.getBasicBlock(B.TargetBB));
2743 
2744   // Avoid emitting unnecessary branches to the next block.
2745   if (NextMBB != NextBlock(SwitchBB))
2746     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2747                         DAG.getBasicBlock(NextMBB));
2748 
2749   DAG.setRoot(BrAnd);
2750 }
2751 
2752 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2753   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2754 
2755   // Retrieve successors. Look through artificial IR level blocks like
2756   // catchswitch for successors.
2757   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2758   const BasicBlock *EHPadBB = I.getSuccessor(1);
2759 
2760   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2761   // have to do anything here to lower funclet bundles.
2762   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2763                                         LLVMContext::OB_funclet,
2764                                         LLVMContext::OB_cfguardtarget}) &&
2765          "Cannot lower invokes with arbitrary operand bundles yet!");
2766 
2767   const Value *Callee(I.getCalledValue());
2768   const Function *Fn = dyn_cast<Function>(Callee);
2769   if (isa<InlineAsm>(Callee))
2770     visitInlineAsm(&I);
2771   else if (Fn && Fn->isIntrinsic()) {
2772     switch (Fn->getIntrinsicID()) {
2773     default:
2774       llvm_unreachable("Cannot invoke this intrinsic");
2775     case Intrinsic::donothing:
2776       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2777       break;
2778     case Intrinsic::experimental_patchpoint_void:
2779     case Intrinsic::experimental_patchpoint_i64:
2780       visitPatchpoint(&I, EHPadBB);
2781       break;
2782     case Intrinsic::experimental_gc_statepoint:
2783       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2784       break;
2785     case Intrinsic::wasm_rethrow_in_catch: {
2786       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2787       // special because it can be invoked, so we manually lower it to a DAG
2788       // node here.
2789       SmallVector<SDValue, 8> Ops;
2790       Ops.push_back(getRoot()); // inchain
2791       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2792       Ops.push_back(
2793           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2794                                 TLI.getPointerTy(DAG.getDataLayout())));
2795       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2796       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2797       break;
2798     }
2799     }
2800   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2801     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2802     // Eventually we will support lowering the @llvm.experimental.deoptimize
2803     // intrinsic, and right now there are no plans to support other intrinsics
2804     // with deopt state.
2805     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2806   } else {
2807     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2808   }
2809 
2810   // If the value of the invoke is used outside of its defining block, make it
2811   // available as a virtual register.
2812   // We already took care of the exported value for the statepoint instruction
2813   // during call to the LowerStatepoint.
2814   if (!isStatepoint(I)) {
2815     CopyToExportRegsIfNeeded(&I);
2816   }
2817 
2818   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2819   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2820   BranchProbability EHPadBBProb =
2821       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2822           : BranchProbability::getZero();
2823   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2824 
2825   // Update successor info.
2826   addSuccessorWithProb(InvokeMBB, Return);
2827   for (auto &UnwindDest : UnwindDests) {
2828     UnwindDest.first->setIsEHPad();
2829     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2830   }
2831   InvokeMBB->normalizeSuccProbs();
2832 
2833   // Drop into normal successor.
2834   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2835                           DAG.getBasicBlock(Return)));
2836 }
2837 
2838 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2839   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2840 
2841   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2842   // have to do anything here to lower funclet bundles.
2843   assert(!I.hasOperandBundlesOtherThan(
2844              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2845          "Cannot lower callbrs with arbitrary operand bundles yet!");
2846 
2847   assert(isa<InlineAsm>(I.getCalledValue()) &&
2848          "Only know how to handle inlineasm callbr");
2849   visitInlineAsm(&I);
2850 
2851   // Retrieve successors.
2852   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2853 
2854   // Update successor info.
2855   addSuccessorWithProb(CallBrMBB, Return);
2856   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2857     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2858     addSuccessorWithProb(CallBrMBB, Target);
2859   }
2860   CallBrMBB->normalizeSuccProbs();
2861 
2862   // Drop into default successor.
2863   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2864                           MVT::Other, getControlRoot(),
2865                           DAG.getBasicBlock(Return)));
2866 }
2867 
2868 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2869   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2870 }
2871 
2872 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2873   assert(FuncInfo.MBB->isEHPad() &&
2874          "Call to landingpad not in landing pad!");
2875 
2876   // If there aren't registers to copy the values into (e.g., during SjLj
2877   // exceptions), then don't bother to create these DAG nodes.
2878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2879   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2880   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2881       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2882     return;
2883 
2884   // If landingpad's return type is token type, we don't create DAG nodes
2885   // for its exception pointer and selector value. The extraction of exception
2886   // pointer or selector value from token type landingpads is not currently
2887   // supported.
2888   if (LP.getType()->isTokenTy())
2889     return;
2890 
2891   SmallVector<EVT, 2> ValueVTs;
2892   SDLoc dl = getCurSDLoc();
2893   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2894   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2895 
2896   // Get the two live-in registers as SDValues. The physregs have already been
2897   // copied into virtual registers.
2898   SDValue Ops[2];
2899   if (FuncInfo.ExceptionPointerVirtReg) {
2900     Ops[0] = DAG.getZExtOrTrunc(
2901         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2902                            FuncInfo.ExceptionPointerVirtReg,
2903                            TLI.getPointerTy(DAG.getDataLayout())),
2904         dl, ValueVTs[0]);
2905   } else {
2906     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2907   }
2908   Ops[1] = DAG.getZExtOrTrunc(
2909       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2910                          FuncInfo.ExceptionSelectorVirtReg,
2911                          TLI.getPointerTy(DAG.getDataLayout())),
2912       dl, ValueVTs[1]);
2913 
2914   // Merge into one.
2915   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2916                             DAG.getVTList(ValueVTs), Ops);
2917   setValue(&LP, Res);
2918 }
2919 
2920 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2921                                            MachineBasicBlock *Last) {
2922   // Update JTCases.
2923   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2924     if (SL->JTCases[i].first.HeaderBB == First)
2925       SL->JTCases[i].first.HeaderBB = Last;
2926 
2927   // Update BitTestCases.
2928   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2929     if (SL->BitTestCases[i].Parent == First)
2930       SL->BitTestCases[i].Parent = Last;
2931 }
2932 
2933 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2934   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2935 
2936   // Update machine-CFG edges with unique successors.
2937   SmallSet<BasicBlock*, 32> Done;
2938   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2939     BasicBlock *BB = I.getSuccessor(i);
2940     bool Inserted = Done.insert(BB).second;
2941     if (!Inserted)
2942         continue;
2943 
2944     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2945     addSuccessorWithProb(IndirectBrMBB, Succ);
2946   }
2947   IndirectBrMBB->normalizeSuccProbs();
2948 
2949   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2950                           MVT::Other, getControlRoot(),
2951                           getValue(I.getAddress())));
2952 }
2953 
2954 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2955   if (!DAG.getTarget().Options.TrapUnreachable)
2956     return;
2957 
2958   // We may be able to ignore unreachable behind a noreturn call.
2959   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2960     const BasicBlock &BB = *I.getParent();
2961     if (&I != &BB.front()) {
2962       BasicBlock::const_iterator PredI =
2963         std::prev(BasicBlock::const_iterator(&I));
2964       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2965         if (Call->doesNotReturn())
2966           return;
2967       }
2968     }
2969   }
2970 
2971   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2972 }
2973 
2974 void SelectionDAGBuilder::visitFSub(const User &I) {
2975   // -0.0 - X --> fneg
2976   Type *Ty = I.getType();
2977   if (isa<Constant>(I.getOperand(0)) &&
2978       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2979     SDValue Op2 = getValue(I.getOperand(1));
2980     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2981                              Op2.getValueType(), Op2));
2982     return;
2983   }
2984 
2985   visitBinary(I, ISD::FSUB);
2986 }
2987 
2988 /// Checks if the given instruction performs a vector reduction, in which case
2989 /// we have the freedom to alter the elements in the result as long as the
2990 /// reduction of them stays unchanged.
2991 static bool isVectorReductionOp(const User *I) {
2992   const Instruction *Inst = dyn_cast<Instruction>(I);
2993   if (!Inst || !Inst->getType()->isVectorTy())
2994     return false;
2995 
2996   auto OpCode = Inst->getOpcode();
2997   switch (OpCode) {
2998   case Instruction::Add:
2999   case Instruction::Mul:
3000   case Instruction::And:
3001   case Instruction::Or:
3002   case Instruction::Xor:
3003     break;
3004   case Instruction::FAdd:
3005   case Instruction::FMul:
3006     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3007       if (FPOp->getFastMathFlags().isFast())
3008         break;
3009     LLVM_FALLTHROUGH;
3010   default:
3011     return false;
3012   }
3013 
3014   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3015   // Ensure the reduction size is a power of 2.
3016   if (!isPowerOf2_32(ElemNum))
3017     return false;
3018 
3019   unsigned ElemNumToReduce = ElemNum;
3020 
3021   // Do DFS search on the def-use chain from the given instruction. We only
3022   // allow four kinds of operations during the search until we reach the
3023   // instruction that extracts the first element from the vector:
3024   //
3025   //   1. The reduction operation of the same opcode as the given instruction.
3026   //
3027   //   2. PHI node.
3028   //
3029   //   3. ShuffleVector instruction together with a reduction operation that
3030   //      does a partial reduction.
3031   //
3032   //   4. ExtractElement that extracts the first element from the vector, and we
3033   //      stop searching the def-use chain here.
3034   //
3035   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3036   // from 1-3 to the stack to continue the DFS. The given instruction is not
3037   // a reduction operation if we meet any other instructions other than those
3038   // listed above.
3039 
3040   SmallVector<const User *, 16> UsersToVisit{Inst};
3041   SmallPtrSet<const User *, 16> Visited;
3042   bool ReduxExtracted = false;
3043 
3044   while (!UsersToVisit.empty()) {
3045     auto User = UsersToVisit.back();
3046     UsersToVisit.pop_back();
3047     if (!Visited.insert(User).second)
3048       continue;
3049 
3050     for (const auto *U : User->users()) {
3051       auto Inst = dyn_cast<Instruction>(U);
3052       if (!Inst)
3053         return false;
3054 
3055       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3056         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3057           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3058             return false;
3059         UsersToVisit.push_back(U);
3060       } else if (const ShuffleVectorInst *ShufInst =
3061                      dyn_cast<ShuffleVectorInst>(U)) {
3062         // Detect the following pattern: A ShuffleVector instruction together
3063         // with a reduction that do partial reduction on the first and second
3064         // ElemNumToReduce / 2 elements, and store the result in
3065         // ElemNumToReduce / 2 elements in another vector.
3066 
3067         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3068         if (ResultElements < ElemNum)
3069           return false;
3070 
3071         if (ElemNumToReduce == 1)
3072           return false;
3073         if (!isa<UndefValue>(U->getOperand(1)))
3074           return false;
3075         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3076           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3077             return false;
3078         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3079           if (ShufInst->getMaskValue(i) != -1)
3080             return false;
3081 
3082         // There is only one user of this ShuffleVector instruction, which
3083         // must be a reduction operation.
3084         if (!U->hasOneUse())
3085           return false;
3086 
3087         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3088         if (!U2 || U2->getOpcode() != OpCode)
3089           return false;
3090 
3091         // Check operands of the reduction operation.
3092         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3093             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3094           UsersToVisit.push_back(U2);
3095           ElemNumToReduce /= 2;
3096         } else
3097           return false;
3098       } else if (isa<ExtractElementInst>(U)) {
3099         // At this moment we should have reduced all elements in the vector.
3100         if (ElemNumToReduce != 1)
3101           return false;
3102 
3103         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3104         if (!Val || !Val->isZero())
3105           return false;
3106 
3107         ReduxExtracted = true;
3108       } else
3109         return false;
3110     }
3111   }
3112   return ReduxExtracted;
3113 }
3114 
3115 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3116   SDNodeFlags Flags;
3117 
3118   SDValue Op = getValue(I.getOperand(0));
3119   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3120                                     Op, Flags);
3121   setValue(&I, UnNodeValue);
3122 }
3123 
3124 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3125   SDNodeFlags Flags;
3126   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3127     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3128     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3129   }
3130   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3131     Flags.setExact(ExactOp->isExact());
3132   }
3133   if (isVectorReductionOp(&I)) {
3134     Flags.setVectorReduction(true);
3135     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3136 
3137     // If no flags are set we will propagate the incoming flags, if any flags
3138     // are set, we will intersect them with the incoming flag and so we need to
3139     // copy the FMF flags here.
3140     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3141       Flags.copyFMF(*FPOp);
3142     }
3143   }
3144 
3145   SDValue Op1 = getValue(I.getOperand(0));
3146   SDValue Op2 = getValue(I.getOperand(1));
3147   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3148                                      Op1, Op2, Flags);
3149   setValue(&I, BinNodeValue);
3150 }
3151 
3152 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3153   SDValue Op1 = getValue(I.getOperand(0));
3154   SDValue Op2 = getValue(I.getOperand(1));
3155 
3156   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3157       Op1.getValueType(), DAG.getDataLayout());
3158 
3159   // Coerce the shift amount to the right type if we can.
3160   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3161     unsigned ShiftSize = ShiftTy.getSizeInBits();
3162     unsigned Op2Size = Op2.getValueSizeInBits();
3163     SDLoc DL = getCurSDLoc();
3164 
3165     // If the operand is smaller than the shift count type, promote it.
3166     if (ShiftSize > Op2Size)
3167       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3168 
3169     // If the operand is larger than the shift count type but the shift
3170     // count type has enough bits to represent any shift value, truncate
3171     // it now. This is a common case and it exposes the truncate to
3172     // optimization early.
3173     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3174       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3175     // Otherwise we'll need to temporarily settle for some other convenient
3176     // type.  Type legalization will make adjustments once the shiftee is split.
3177     else
3178       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3179   }
3180 
3181   bool nuw = false;
3182   bool nsw = false;
3183   bool exact = false;
3184 
3185   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3186 
3187     if (const OverflowingBinaryOperator *OFBinOp =
3188             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3189       nuw = OFBinOp->hasNoUnsignedWrap();
3190       nsw = OFBinOp->hasNoSignedWrap();
3191     }
3192     if (const PossiblyExactOperator *ExactOp =
3193             dyn_cast<const PossiblyExactOperator>(&I))
3194       exact = ExactOp->isExact();
3195   }
3196   SDNodeFlags Flags;
3197   Flags.setExact(exact);
3198   Flags.setNoSignedWrap(nsw);
3199   Flags.setNoUnsignedWrap(nuw);
3200   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3201                             Flags);
3202   setValue(&I, Res);
3203 }
3204 
3205 void SelectionDAGBuilder::visitSDiv(const User &I) {
3206   SDValue Op1 = getValue(I.getOperand(0));
3207   SDValue Op2 = getValue(I.getOperand(1));
3208 
3209   SDNodeFlags Flags;
3210   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3211                  cast<PossiblyExactOperator>(&I)->isExact());
3212   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3213                            Op2, Flags));
3214 }
3215 
3216 void SelectionDAGBuilder::visitICmp(const User &I) {
3217   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3218   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3219     predicate = IC->getPredicate();
3220   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3221     predicate = ICmpInst::Predicate(IC->getPredicate());
3222   SDValue Op1 = getValue(I.getOperand(0));
3223   SDValue Op2 = getValue(I.getOperand(1));
3224   ISD::CondCode Opcode = getICmpCondCode(predicate);
3225 
3226   auto &TLI = DAG.getTargetLoweringInfo();
3227   EVT MemVT =
3228       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3229 
3230   // If a pointer's DAG type is larger than its memory type then the DAG values
3231   // are zero-extended. This breaks signed comparisons so truncate back to the
3232   // underlying type before doing the compare.
3233   if (Op1.getValueType() != MemVT) {
3234     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3235     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3236   }
3237 
3238   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3239                                                         I.getType());
3240   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3241 }
3242 
3243 void SelectionDAGBuilder::visitFCmp(const User &I) {
3244   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3245   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3246     predicate = FC->getPredicate();
3247   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3248     predicate = FCmpInst::Predicate(FC->getPredicate());
3249   SDValue Op1 = getValue(I.getOperand(0));
3250   SDValue Op2 = getValue(I.getOperand(1));
3251 
3252   ISD::CondCode Condition = getFCmpCondCode(predicate);
3253   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3254   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3255     Condition = getFCmpCodeWithoutNaN(Condition);
3256 
3257   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3258                                                         I.getType());
3259   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3260 }
3261 
3262 // Check if the condition of the select has one use or two users that are both
3263 // selects with the same condition.
3264 static bool hasOnlySelectUsers(const Value *Cond) {
3265   return llvm::all_of(Cond->users(), [](const Value *V) {
3266     return isa<SelectInst>(V);
3267   });
3268 }
3269 
3270 void SelectionDAGBuilder::visitSelect(const User &I) {
3271   SmallVector<EVT, 4> ValueVTs;
3272   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3273                   ValueVTs);
3274   unsigned NumValues = ValueVTs.size();
3275   if (NumValues == 0) return;
3276 
3277   SmallVector<SDValue, 4> Values(NumValues);
3278   SDValue Cond     = getValue(I.getOperand(0));
3279   SDValue LHSVal   = getValue(I.getOperand(1));
3280   SDValue RHSVal   = getValue(I.getOperand(2));
3281   auto BaseOps = {Cond};
3282   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3283     ISD::VSELECT : ISD::SELECT;
3284 
3285   bool IsUnaryAbs = false;
3286 
3287   // Min/max matching is only viable if all output VTs are the same.
3288   if (is_splat(ValueVTs)) {
3289     EVT VT = ValueVTs[0];
3290     LLVMContext &Ctx = *DAG.getContext();
3291     auto &TLI = DAG.getTargetLoweringInfo();
3292 
3293     // We care about the legality of the operation after it has been type
3294     // legalized.
3295     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3296       VT = TLI.getTypeToTransformTo(Ctx, VT);
3297 
3298     // If the vselect is legal, assume we want to leave this as a vector setcc +
3299     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3300     // min/max is legal on the scalar type.
3301     bool UseScalarMinMax = VT.isVector() &&
3302       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3303 
3304     Value *LHS, *RHS;
3305     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3306     ISD::NodeType Opc = ISD::DELETED_NODE;
3307     switch (SPR.Flavor) {
3308     case SPF_UMAX:    Opc = ISD::UMAX; break;
3309     case SPF_UMIN:    Opc = ISD::UMIN; break;
3310     case SPF_SMAX:    Opc = ISD::SMAX; break;
3311     case SPF_SMIN:    Opc = ISD::SMIN; break;
3312     case SPF_FMINNUM:
3313       switch (SPR.NaNBehavior) {
3314       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3315       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3316       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3317       case SPNB_RETURNS_ANY: {
3318         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3319           Opc = ISD::FMINNUM;
3320         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3321           Opc = ISD::FMINIMUM;
3322         else if (UseScalarMinMax)
3323           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3324             ISD::FMINNUM : ISD::FMINIMUM;
3325         break;
3326       }
3327       }
3328       break;
3329     case SPF_FMAXNUM:
3330       switch (SPR.NaNBehavior) {
3331       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3332       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3333       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3334       case SPNB_RETURNS_ANY:
3335 
3336         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3337           Opc = ISD::FMAXNUM;
3338         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3339           Opc = ISD::FMAXIMUM;
3340         else if (UseScalarMinMax)
3341           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3342             ISD::FMAXNUM : ISD::FMAXIMUM;
3343         break;
3344       }
3345       break;
3346     case SPF_ABS:
3347       IsUnaryAbs = true;
3348       Opc = ISD::ABS;
3349       break;
3350     case SPF_NABS:
3351       // TODO: we need to produce sub(0, abs(X)).
3352     default: break;
3353     }
3354 
3355     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3356         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3357          (UseScalarMinMax &&
3358           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3359         // If the underlying comparison instruction is used by any other
3360         // instruction, the consumed instructions won't be destroyed, so it is
3361         // not profitable to convert to a min/max.
3362         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3363       OpCode = Opc;
3364       LHSVal = getValue(LHS);
3365       RHSVal = getValue(RHS);
3366       BaseOps = {};
3367     }
3368 
3369     if (IsUnaryAbs) {
3370       OpCode = Opc;
3371       LHSVal = getValue(LHS);
3372       BaseOps = {};
3373     }
3374   }
3375 
3376   if (IsUnaryAbs) {
3377     for (unsigned i = 0; i != NumValues; ++i) {
3378       Values[i] =
3379           DAG.getNode(OpCode, getCurSDLoc(),
3380                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3381                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3382     }
3383   } else {
3384     for (unsigned i = 0; i != NumValues; ++i) {
3385       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3386       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3387       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3388       Values[i] = DAG.getNode(
3389           OpCode, getCurSDLoc(),
3390           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3391     }
3392   }
3393 
3394   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3395                            DAG.getVTList(ValueVTs), Values));
3396 }
3397 
3398 void SelectionDAGBuilder::visitTrunc(const User &I) {
3399   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3400   SDValue N = getValue(I.getOperand(0));
3401   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3402                                                         I.getType());
3403   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3404 }
3405 
3406 void SelectionDAGBuilder::visitZExt(const User &I) {
3407   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3408   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3409   SDValue N = getValue(I.getOperand(0));
3410   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3411                                                         I.getType());
3412   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3413 }
3414 
3415 void SelectionDAGBuilder::visitSExt(const User &I) {
3416   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3417   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3418   SDValue N = getValue(I.getOperand(0));
3419   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3420                                                         I.getType());
3421   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3422 }
3423 
3424 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3425   // FPTrunc is never a no-op cast, no need to check
3426   SDValue N = getValue(I.getOperand(0));
3427   SDLoc dl = getCurSDLoc();
3428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3429   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3430   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3431                            DAG.getTargetConstant(
3432                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3433 }
3434 
3435 void SelectionDAGBuilder::visitFPExt(const User &I) {
3436   // FPExt is never a no-op cast, no need to check
3437   SDValue N = getValue(I.getOperand(0));
3438   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3439                                                         I.getType());
3440   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3441 }
3442 
3443 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3444   // FPToUI is never a no-op cast, no need to check
3445   SDValue N = getValue(I.getOperand(0));
3446   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3447                                                         I.getType());
3448   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3449 }
3450 
3451 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3452   // FPToSI is never a no-op cast, no need to check
3453   SDValue N = getValue(I.getOperand(0));
3454   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3455                                                         I.getType());
3456   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3457 }
3458 
3459 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3460   // UIToFP is never a no-op cast, no need to check
3461   SDValue N = getValue(I.getOperand(0));
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3465 }
3466 
3467 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3468   // SIToFP is never a no-op cast, no need to check
3469   SDValue N = getValue(I.getOperand(0));
3470   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3471                                                         I.getType());
3472   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3473 }
3474 
3475 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3476   // What to do depends on the size of the integer and the size of the pointer.
3477   // We can either truncate, zero extend, or no-op, accordingly.
3478   SDValue N = getValue(I.getOperand(0));
3479   auto &TLI = DAG.getTargetLoweringInfo();
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482   EVT PtrMemVT =
3483       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3484   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3485   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3486   setValue(&I, N);
3487 }
3488 
3489 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3490   // What to do depends on the size of the integer and the size of the pointer.
3491   // We can either truncate, zero extend, or no-op, accordingly.
3492   SDValue N = getValue(I.getOperand(0));
3493   auto &TLI = DAG.getTargetLoweringInfo();
3494   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3495   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3496   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3497   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3498   setValue(&I, N);
3499 }
3500 
3501 void SelectionDAGBuilder::visitBitCast(const User &I) {
3502   SDValue N = getValue(I.getOperand(0));
3503   SDLoc dl = getCurSDLoc();
3504   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3505                                                         I.getType());
3506 
3507   // BitCast assures us that source and destination are the same size so this is
3508   // either a BITCAST or a no-op.
3509   if (DestVT != N.getValueType())
3510     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3511                              DestVT, N)); // convert types.
3512   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3513   // might fold any kind of constant expression to an integer constant and that
3514   // is not what we are looking for. Only recognize a bitcast of a genuine
3515   // constant integer as an opaque constant.
3516   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3517     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3518                                  /*isOpaque*/true));
3519   else
3520     setValue(&I, N);            // noop cast.
3521 }
3522 
3523 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3525   const Value *SV = I.getOperand(0);
3526   SDValue N = getValue(SV);
3527   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3528 
3529   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3530   unsigned DestAS = I.getType()->getPointerAddressSpace();
3531 
3532   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3533     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3534 
3535   setValue(&I, N);
3536 }
3537 
3538 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3540   SDValue InVec = getValue(I.getOperand(0));
3541   SDValue InVal = getValue(I.getOperand(1));
3542   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3543                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3544   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3545                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3546                            InVec, InVal, InIdx));
3547 }
3548 
3549 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3551   SDValue InVec = getValue(I.getOperand(0));
3552   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3553                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3554   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3555                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3556                            InVec, InIdx));
3557 }
3558 
3559 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3560   SDValue Src1 = getValue(I.getOperand(0));
3561   SDValue Src2 = getValue(I.getOperand(1));
3562   Constant *MaskV = cast<Constant>(I.getOperand(2));
3563   SDLoc DL = getCurSDLoc();
3564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3565   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3566   EVT SrcVT = Src1.getValueType();
3567   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3568 
3569   if (MaskV->isNullValue() && VT.isScalableVector()) {
3570     // Canonical splat form of first element of first input vector.
3571     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3572                                    SrcVT.getScalarType(), Src1,
3573                                    DAG.getConstant(0, DL,
3574                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3575     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3576     return;
3577   }
3578 
3579   // For now, we only handle splats for scalable vectors.
3580   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3581   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3582   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3583 
3584   SmallVector<int, 8> Mask;
3585   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3586   unsigned MaskNumElts = Mask.size();
3587 
3588   if (SrcNumElts == MaskNumElts) {
3589     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3590     return;
3591   }
3592 
3593   // Normalize the shuffle vector since mask and vector length don't match.
3594   if (SrcNumElts < MaskNumElts) {
3595     // Mask is longer than the source vectors. We can use concatenate vector to
3596     // make the mask and vectors lengths match.
3597 
3598     if (MaskNumElts % SrcNumElts == 0) {
3599       // Mask length is a multiple of the source vector length.
3600       // Check if the shuffle is some kind of concatenation of the input
3601       // vectors.
3602       unsigned NumConcat = MaskNumElts / SrcNumElts;
3603       bool IsConcat = true;
3604       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3605       for (unsigned i = 0; i != MaskNumElts; ++i) {
3606         int Idx = Mask[i];
3607         if (Idx < 0)
3608           continue;
3609         // Ensure the indices in each SrcVT sized piece are sequential and that
3610         // the same source is used for the whole piece.
3611         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3612             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3613              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3614           IsConcat = false;
3615           break;
3616         }
3617         // Remember which source this index came from.
3618         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3619       }
3620 
3621       // The shuffle is concatenating multiple vectors together. Just emit
3622       // a CONCAT_VECTORS operation.
3623       if (IsConcat) {
3624         SmallVector<SDValue, 8> ConcatOps;
3625         for (auto Src : ConcatSrcs) {
3626           if (Src < 0)
3627             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3628           else if (Src == 0)
3629             ConcatOps.push_back(Src1);
3630           else
3631             ConcatOps.push_back(Src2);
3632         }
3633         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3634         return;
3635       }
3636     }
3637 
3638     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3639     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3640     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3641                                     PaddedMaskNumElts);
3642 
3643     // Pad both vectors with undefs to make them the same length as the mask.
3644     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3645 
3646     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3647     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3648     MOps1[0] = Src1;
3649     MOps2[0] = Src2;
3650 
3651     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3652     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3653 
3654     // Readjust mask for new input vector length.
3655     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3656     for (unsigned i = 0; i != MaskNumElts; ++i) {
3657       int Idx = Mask[i];
3658       if (Idx >= (int)SrcNumElts)
3659         Idx -= SrcNumElts - PaddedMaskNumElts;
3660       MappedOps[i] = Idx;
3661     }
3662 
3663     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3664 
3665     // If the concatenated vector was padded, extract a subvector with the
3666     // correct number of elements.
3667     if (MaskNumElts != PaddedMaskNumElts)
3668       Result = DAG.getNode(
3669           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3670           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3671 
3672     setValue(&I, Result);
3673     return;
3674   }
3675 
3676   if (SrcNumElts > MaskNumElts) {
3677     // Analyze the access pattern of the vector to see if we can extract
3678     // two subvectors and do the shuffle.
3679     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3680     bool CanExtract = true;
3681     for (int Idx : Mask) {
3682       unsigned Input = 0;
3683       if (Idx < 0)
3684         continue;
3685 
3686       if (Idx >= (int)SrcNumElts) {
3687         Input = 1;
3688         Idx -= SrcNumElts;
3689       }
3690 
3691       // If all the indices come from the same MaskNumElts sized portion of
3692       // the sources we can use extract. Also make sure the extract wouldn't
3693       // extract past the end of the source.
3694       int NewStartIdx = alignDown(Idx, MaskNumElts);
3695       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3696           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3697         CanExtract = false;
3698       // Make sure we always update StartIdx as we use it to track if all
3699       // elements are undef.
3700       StartIdx[Input] = NewStartIdx;
3701     }
3702 
3703     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3704       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3705       return;
3706     }
3707     if (CanExtract) {
3708       // Extract appropriate subvector and generate a vector shuffle
3709       for (unsigned Input = 0; Input < 2; ++Input) {
3710         SDValue &Src = Input == 0 ? Src1 : Src2;
3711         if (StartIdx[Input] < 0)
3712           Src = DAG.getUNDEF(VT);
3713         else {
3714           Src = DAG.getNode(
3715               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3716               DAG.getConstant(StartIdx[Input], DL,
3717                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3718         }
3719       }
3720 
3721       // Calculate new mask.
3722       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3723       for (int &Idx : MappedOps) {
3724         if (Idx >= (int)SrcNumElts)
3725           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3726         else if (Idx >= 0)
3727           Idx -= StartIdx[0];
3728       }
3729 
3730       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3731       return;
3732     }
3733   }
3734 
3735   // We can't use either concat vectors or extract subvectors so fall back to
3736   // replacing the shuffle with extract and build vector.
3737   // to insert and build vector.
3738   EVT EltVT = VT.getVectorElementType();
3739   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3740   SmallVector<SDValue,8> Ops;
3741   for (int Idx : Mask) {
3742     SDValue Res;
3743 
3744     if (Idx < 0) {
3745       Res = DAG.getUNDEF(EltVT);
3746     } else {
3747       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3748       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3749 
3750       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3751                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3752     }
3753 
3754     Ops.push_back(Res);
3755   }
3756 
3757   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3758 }
3759 
3760 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3761   ArrayRef<unsigned> Indices;
3762   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3763     Indices = IV->getIndices();
3764   else
3765     Indices = cast<ConstantExpr>(&I)->getIndices();
3766 
3767   const Value *Op0 = I.getOperand(0);
3768   const Value *Op1 = I.getOperand(1);
3769   Type *AggTy = I.getType();
3770   Type *ValTy = Op1->getType();
3771   bool IntoUndef = isa<UndefValue>(Op0);
3772   bool FromUndef = isa<UndefValue>(Op1);
3773 
3774   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3775 
3776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3777   SmallVector<EVT, 4> AggValueVTs;
3778   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3779   SmallVector<EVT, 4> ValValueVTs;
3780   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3781 
3782   unsigned NumAggValues = AggValueVTs.size();
3783   unsigned NumValValues = ValValueVTs.size();
3784   SmallVector<SDValue, 4> Values(NumAggValues);
3785 
3786   // Ignore an insertvalue that produces an empty object
3787   if (!NumAggValues) {
3788     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3789     return;
3790   }
3791 
3792   SDValue Agg = getValue(Op0);
3793   unsigned i = 0;
3794   // Copy the beginning value(s) from the original aggregate.
3795   for (; i != LinearIndex; ++i)
3796     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3797                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3798   // Copy values from the inserted value(s).
3799   if (NumValValues) {
3800     SDValue Val = getValue(Op1);
3801     for (; i != LinearIndex + NumValValues; ++i)
3802       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3803                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3804   }
3805   // Copy remaining value(s) from the original aggregate.
3806   for (; i != NumAggValues; ++i)
3807     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3808                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3809 
3810   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3811                            DAG.getVTList(AggValueVTs), Values));
3812 }
3813 
3814 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3815   ArrayRef<unsigned> Indices;
3816   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3817     Indices = EV->getIndices();
3818   else
3819     Indices = cast<ConstantExpr>(&I)->getIndices();
3820 
3821   const Value *Op0 = I.getOperand(0);
3822   Type *AggTy = Op0->getType();
3823   Type *ValTy = I.getType();
3824   bool OutOfUndef = isa<UndefValue>(Op0);
3825 
3826   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3827 
3828   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3829   SmallVector<EVT, 4> ValValueVTs;
3830   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3831 
3832   unsigned NumValValues = ValValueVTs.size();
3833 
3834   // Ignore a extractvalue that produces an empty object
3835   if (!NumValValues) {
3836     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3837     return;
3838   }
3839 
3840   SmallVector<SDValue, 4> Values(NumValValues);
3841 
3842   SDValue Agg = getValue(Op0);
3843   // Copy out the selected value(s).
3844   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3845     Values[i - LinearIndex] =
3846       OutOfUndef ?
3847         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3848         SDValue(Agg.getNode(), Agg.getResNo() + i);
3849 
3850   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3851                            DAG.getVTList(ValValueVTs), Values));
3852 }
3853 
3854 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3855   Value *Op0 = I.getOperand(0);
3856   // Note that the pointer operand may be a vector of pointers. Take the scalar
3857   // element which holds a pointer.
3858   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3859   SDValue N = getValue(Op0);
3860   SDLoc dl = getCurSDLoc();
3861   auto &TLI = DAG.getTargetLoweringInfo();
3862   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3863   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3864 
3865   // Normalize Vector GEP - all scalar operands should be converted to the
3866   // splat vector.
3867   unsigned VectorWidth = I.getType()->isVectorTy() ?
3868     I.getType()->getVectorNumElements() : 0;
3869 
3870   if (VectorWidth && !N.getValueType().isVector()) {
3871     LLVMContext &Context = *DAG.getContext();
3872     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3873     N = DAG.getSplatBuildVector(VT, dl, N);
3874   }
3875 
3876   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3877        GTI != E; ++GTI) {
3878     const Value *Idx = GTI.getOperand();
3879     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3880       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3881       if (Field) {
3882         // N = N + Offset
3883         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3884 
3885         // In an inbounds GEP with an offset that is nonnegative even when
3886         // interpreted as signed, assume there is no unsigned overflow.
3887         SDNodeFlags Flags;
3888         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3889           Flags.setNoUnsignedWrap(true);
3890 
3891         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3892                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3893       }
3894     } else {
3895       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3896       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3897       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3898 
3899       // If this is a scalar constant or a splat vector of constants,
3900       // handle it quickly.
3901       const auto *C = dyn_cast<Constant>(Idx);
3902       if (C && isa<VectorType>(C->getType()))
3903         C = C->getSplatValue();
3904 
3905       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3906         if (CI->isZero())
3907           continue;
3908         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3909         LLVMContext &Context = *DAG.getContext();
3910         SDValue OffsVal = VectorWidth ?
3911           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3912           DAG.getConstant(Offs, dl, IdxTy);
3913 
3914         // In an inbounds GEP with an offset that is nonnegative even when
3915         // interpreted as signed, assume there is no unsigned overflow.
3916         SDNodeFlags Flags;
3917         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3918           Flags.setNoUnsignedWrap(true);
3919 
3920         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3921 
3922         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3923         continue;
3924       }
3925 
3926       // N = N + Idx * ElementSize;
3927       SDValue IdxN = getValue(Idx);
3928 
3929       if (!IdxN.getValueType().isVector() && VectorWidth) {
3930         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3931         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3932       }
3933 
3934       // If the index is smaller or larger than intptr_t, truncate or extend
3935       // it.
3936       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3937 
3938       // If this is a multiply by a power of two, turn it into a shl
3939       // immediately.  This is a very common case.
3940       if (ElementSize != 1) {
3941         if (ElementSize.isPowerOf2()) {
3942           unsigned Amt = ElementSize.logBase2();
3943           IdxN = DAG.getNode(ISD::SHL, dl,
3944                              N.getValueType(), IdxN,
3945                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3946         } else {
3947           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3948                                           IdxN.getValueType());
3949           IdxN = DAG.getNode(ISD::MUL, dl,
3950                              N.getValueType(), IdxN, Scale);
3951         }
3952       }
3953 
3954       N = DAG.getNode(ISD::ADD, dl,
3955                       N.getValueType(), N, IdxN);
3956     }
3957   }
3958 
3959   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3960     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3961 
3962   setValue(&I, N);
3963 }
3964 
3965 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3966   // If this is a fixed sized alloca in the entry block of the function,
3967   // allocate it statically on the stack.
3968   if (FuncInfo.StaticAllocaMap.count(&I))
3969     return;   // getValue will auto-populate this.
3970 
3971   SDLoc dl = getCurSDLoc();
3972   Type *Ty = I.getAllocatedType();
3973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3974   auto &DL = DAG.getDataLayout();
3975   uint64_t TySize = DL.getTypeAllocSize(Ty);
3976   unsigned Align =
3977       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3978 
3979   SDValue AllocSize = getValue(I.getArraySize());
3980 
3981   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3982   if (AllocSize.getValueType() != IntPtr)
3983     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3984 
3985   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3986                           AllocSize,
3987                           DAG.getConstant(TySize, dl, IntPtr));
3988 
3989   // Handle alignment.  If the requested alignment is less than or equal to
3990   // the stack alignment, ignore it.  If the size is greater than or equal to
3991   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3992   unsigned StackAlign =
3993       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3994   if (Align <= StackAlign)
3995     Align = 0;
3996 
3997   // Round the size of the allocation up to the stack alignment size
3998   // by add SA-1 to the size. This doesn't overflow because we're computing
3999   // an address inside an alloca.
4000   SDNodeFlags Flags;
4001   Flags.setNoUnsignedWrap(true);
4002   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4003                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4004 
4005   // Mask out the low bits for alignment purposes.
4006   AllocSize =
4007       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4008                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4009 
4010   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4011   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4012   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4013   setValue(&I, DSA);
4014   DAG.setRoot(DSA.getValue(1));
4015 
4016   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4017 }
4018 
4019 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4020   if (I.isAtomic())
4021     return visitAtomicLoad(I);
4022 
4023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4024   const Value *SV = I.getOperand(0);
4025   if (TLI.supportSwiftError()) {
4026     // Swifterror values can come from either a function parameter with
4027     // swifterror attribute or an alloca with swifterror attribute.
4028     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4029       if (Arg->hasSwiftErrorAttr())
4030         return visitLoadFromSwiftError(I);
4031     }
4032 
4033     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4034       if (Alloca->isSwiftError())
4035         return visitLoadFromSwiftError(I);
4036     }
4037   }
4038 
4039   SDValue Ptr = getValue(SV);
4040 
4041   Type *Ty = I.getType();
4042 
4043   bool isVolatile = I.isVolatile();
4044   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4045   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4046   bool isDereferenceable =
4047       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4048   unsigned Alignment = I.getAlignment();
4049 
4050   AAMDNodes AAInfo;
4051   I.getAAMetadata(AAInfo);
4052   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4053 
4054   SmallVector<EVT, 4> ValueVTs, MemVTs;
4055   SmallVector<uint64_t, 4> Offsets;
4056   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4057   unsigned NumValues = ValueVTs.size();
4058   if (NumValues == 0)
4059     return;
4060 
4061   SDValue Root;
4062   bool ConstantMemory = false;
4063   if (isVolatile || NumValues > MaxParallelChains)
4064     // Serialize volatile loads with other side effects.
4065     Root = getRoot();
4066   else if (AA &&
4067            AA->pointsToConstantMemory(MemoryLocation(
4068                SV,
4069                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4070                AAInfo))) {
4071     // Do not serialize (non-volatile) loads of constant memory with anything.
4072     Root = DAG.getEntryNode();
4073     ConstantMemory = true;
4074   } else {
4075     // Do not serialize non-volatile loads against each other.
4076     Root = DAG.getRoot();
4077   }
4078 
4079   SDLoc dl = getCurSDLoc();
4080 
4081   if (isVolatile)
4082     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4083 
4084   // An aggregate load cannot wrap around the address space, so offsets to its
4085   // parts don't wrap either.
4086   SDNodeFlags Flags;
4087   Flags.setNoUnsignedWrap(true);
4088 
4089   SmallVector<SDValue, 4> Values(NumValues);
4090   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4091   EVT PtrVT = Ptr.getValueType();
4092   unsigned ChainI = 0;
4093   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4094     // Serializing loads here may result in excessive register pressure, and
4095     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4096     // could recover a bit by hoisting nodes upward in the chain by recognizing
4097     // they are side-effect free or do not alias. The optimizer should really
4098     // avoid this case by converting large object/array copies to llvm.memcpy
4099     // (MaxParallelChains should always remain as failsafe).
4100     if (ChainI == MaxParallelChains) {
4101       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4102       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4103                                   makeArrayRef(Chains.data(), ChainI));
4104       Root = Chain;
4105       ChainI = 0;
4106     }
4107     SDValue A = DAG.getNode(ISD::ADD, dl,
4108                             PtrVT, Ptr,
4109                             DAG.getConstant(Offsets[i], dl, PtrVT),
4110                             Flags);
4111     auto MMOFlags = MachineMemOperand::MONone;
4112     if (isVolatile)
4113       MMOFlags |= MachineMemOperand::MOVolatile;
4114     if (isNonTemporal)
4115       MMOFlags |= MachineMemOperand::MONonTemporal;
4116     if (isInvariant)
4117       MMOFlags |= MachineMemOperand::MOInvariant;
4118     if (isDereferenceable)
4119       MMOFlags |= MachineMemOperand::MODereferenceable;
4120     MMOFlags |= TLI.getMMOFlags(I);
4121 
4122     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4123                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4124                             MMOFlags, AAInfo, Ranges);
4125     Chains[ChainI] = L.getValue(1);
4126 
4127     if (MemVTs[i] != ValueVTs[i])
4128       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4129 
4130     Values[i] = L;
4131   }
4132 
4133   if (!ConstantMemory) {
4134     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4135                                 makeArrayRef(Chains.data(), ChainI));
4136     if (isVolatile)
4137       DAG.setRoot(Chain);
4138     else
4139       PendingLoads.push_back(Chain);
4140   }
4141 
4142   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4143                            DAG.getVTList(ValueVTs), Values));
4144 }
4145 
4146 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4147   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4148          "call visitStoreToSwiftError when backend supports swifterror");
4149 
4150   SmallVector<EVT, 4> ValueVTs;
4151   SmallVector<uint64_t, 4> Offsets;
4152   const Value *SrcV = I.getOperand(0);
4153   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4154                   SrcV->getType(), ValueVTs, &Offsets);
4155   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4156          "expect a single EVT for swifterror");
4157 
4158   SDValue Src = getValue(SrcV);
4159   // Create a virtual register, then update the virtual register.
4160   Register VReg =
4161       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4162   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4163   // Chain can be getRoot or getControlRoot.
4164   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4165                                       SDValue(Src.getNode(), Src.getResNo()));
4166   DAG.setRoot(CopyNode);
4167 }
4168 
4169 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4170   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4171          "call visitLoadFromSwiftError when backend supports swifterror");
4172 
4173   assert(!I.isVolatile() &&
4174          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4175          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4176          "Support volatile, non temporal, invariant for load_from_swift_error");
4177 
4178   const Value *SV = I.getOperand(0);
4179   Type *Ty = I.getType();
4180   AAMDNodes AAInfo;
4181   I.getAAMetadata(AAInfo);
4182   assert(
4183       (!AA ||
4184        !AA->pointsToConstantMemory(MemoryLocation(
4185            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4186            AAInfo))) &&
4187       "load_from_swift_error should not be constant memory");
4188 
4189   SmallVector<EVT, 4> ValueVTs;
4190   SmallVector<uint64_t, 4> Offsets;
4191   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4192                   ValueVTs, &Offsets);
4193   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4194          "expect a single EVT for swifterror");
4195 
4196   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4197   SDValue L = DAG.getCopyFromReg(
4198       getRoot(), getCurSDLoc(),
4199       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4200 
4201   setValue(&I, L);
4202 }
4203 
4204 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4205   if (I.isAtomic())
4206     return visitAtomicStore(I);
4207 
4208   const Value *SrcV = I.getOperand(0);
4209   const Value *PtrV = I.getOperand(1);
4210 
4211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4212   if (TLI.supportSwiftError()) {
4213     // Swifterror values can come from either a function parameter with
4214     // swifterror attribute or an alloca with swifterror attribute.
4215     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4216       if (Arg->hasSwiftErrorAttr())
4217         return visitStoreToSwiftError(I);
4218     }
4219 
4220     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4221       if (Alloca->isSwiftError())
4222         return visitStoreToSwiftError(I);
4223     }
4224   }
4225 
4226   SmallVector<EVT, 4> ValueVTs, MemVTs;
4227   SmallVector<uint64_t, 4> Offsets;
4228   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4229                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4230   unsigned NumValues = ValueVTs.size();
4231   if (NumValues == 0)
4232     return;
4233 
4234   // Get the lowered operands. Note that we do this after
4235   // checking if NumResults is zero, because with zero results
4236   // the operands won't have values in the map.
4237   SDValue Src = getValue(SrcV);
4238   SDValue Ptr = getValue(PtrV);
4239 
4240   SDValue Root = getRoot();
4241   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4242   SDLoc dl = getCurSDLoc();
4243   unsigned Alignment = I.getAlignment();
4244   AAMDNodes AAInfo;
4245   I.getAAMetadata(AAInfo);
4246 
4247   auto MMOFlags = MachineMemOperand::MONone;
4248   if (I.isVolatile())
4249     MMOFlags |= MachineMemOperand::MOVolatile;
4250   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4251     MMOFlags |= MachineMemOperand::MONonTemporal;
4252   MMOFlags |= TLI.getMMOFlags(I);
4253 
4254   // An aggregate load cannot wrap around the address space, so offsets to its
4255   // parts don't wrap either.
4256   SDNodeFlags Flags;
4257   Flags.setNoUnsignedWrap(true);
4258 
4259   unsigned ChainI = 0;
4260   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4261     // See visitLoad comments.
4262     if (ChainI == MaxParallelChains) {
4263       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4264                                   makeArrayRef(Chains.data(), ChainI));
4265       Root = Chain;
4266       ChainI = 0;
4267     }
4268     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4269     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4270     if (MemVTs[i] != ValueVTs[i])
4271       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4272     SDValue St =
4273         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4274                      Alignment, MMOFlags, AAInfo);
4275     Chains[ChainI] = St;
4276   }
4277 
4278   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4279                                   makeArrayRef(Chains.data(), ChainI));
4280   DAG.setRoot(StoreNode);
4281 }
4282 
4283 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4284                                            bool IsCompressing) {
4285   SDLoc sdl = getCurSDLoc();
4286 
4287   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4288                            unsigned& Alignment) {
4289     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4290     Src0 = I.getArgOperand(0);
4291     Ptr = I.getArgOperand(1);
4292     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4293     Mask = I.getArgOperand(3);
4294   };
4295   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4296                            unsigned& Alignment) {
4297     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4298     Src0 = I.getArgOperand(0);
4299     Ptr = I.getArgOperand(1);
4300     Mask = I.getArgOperand(2);
4301     Alignment = 0;
4302   };
4303 
4304   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4305   unsigned Alignment;
4306   if (IsCompressing)
4307     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4308   else
4309     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4310 
4311   SDValue Ptr = getValue(PtrOperand);
4312   SDValue Src0 = getValue(Src0Operand);
4313   SDValue Mask = getValue(MaskOperand);
4314   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4315 
4316   EVT VT = Src0.getValueType();
4317   if (!Alignment)
4318     Alignment = DAG.getEVTAlignment(VT);
4319 
4320   AAMDNodes AAInfo;
4321   I.getAAMetadata(AAInfo);
4322 
4323   MachineMemOperand *MMO =
4324     DAG.getMachineFunction().
4325     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4326                           MachineMemOperand::MOStore,
4327                           // TODO: Make MachineMemOperands aware of scalable
4328                           // vectors.
4329                           VT.getStoreSize().getKnownMinSize(),
4330                           Alignment, AAInfo);
4331   SDValue StoreNode =
4332       DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4333                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4334   DAG.setRoot(StoreNode);
4335   setValue(&I, StoreNode);
4336 }
4337 
4338 // Get a uniform base for the Gather/Scatter intrinsic.
4339 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4340 // We try to represent it as a base pointer + vector of indices.
4341 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4342 // The first operand of the GEP may be a single pointer or a vector of pointers
4343 // Example:
4344 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4345 //  or
4346 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4347 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4348 //
4349 // When the first GEP operand is a single pointer - it is the uniform base we
4350 // are looking for. If first operand of the GEP is a splat vector - we
4351 // extract the splat value and use it as a uniform base.
4352 // In all other cases the function returns 'false'.
4353 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4354                            ISD::MemIndexType &IndexType, SDValue &Scale,
4355                            SelectionDAGBuilder *SDB) {
4356   SelectionDAG& DAG = SDB->DAG;
4357   LLVMContext &Context = *DAG.getContext();
4358 
4359   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4360   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4361   if (!GEP)
4362     return false;
4363 
4364   const Value *GEPPtr = GEP->getPointerOperand();
4365   if (!GEPPtr->getType()->isVectorTy())
4366     Ptr = GEPPtr;
4367   else if (!(Ptr = getSplatValue(GEPPtr)))
4368     return false;
4369 
4370   unsigned FinalIndex = GEP->getNumOperands() - 1;
4371   Value *IndexVal = GEP->getOperand(FinalIndex);
4372   gep_type_iterator GTI = gep_type_begin(*GEP);
4373 
4374   // Ensure all the other indices are 0.
4375   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4376     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4377     if (!C)
4378       return false;
4379     if (isa<VectorType>(C->getType()))
4380       C = C->getSplatValue();
4381     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4382     if (!CI || !CI->isZero())
4383       return false;
4384   }
4385 
4386   // The operands of the GEP may be defined in another basic block.
4387   // In this case we'll not find nodes for the operands.
4388   if (!SDB->findValue(Ptr))
4389     return false;
4390   Constant *C = dyn_cast<Constant>(IndexVal);
4391   if (!C && !SDB->findValue(IndexVal))
4392     return false;
4393 
4394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4395   const DataLayout &DL = DAG.getDataLayout();
4396   StructType *STy = GTI.getStructTypeOrNull();
4397 
4398   if (STy) {
4399     const StructLayout *SL = DL.getStructLayout(STy);
4400     if (isa<VectorType>(C->getType())) {
4401       C = C->getSplatValue();
4402       // FIXME: If getSplatValue may return nullptr for a structure?
4403       // If not, the following check can be removed.
4404       if (!C)
4405         return false;
4406     }
4407     auto *CI = cast<ConstantInt>(C);
4408     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4409     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4410                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4411   } else {
4412     Scale = DAG.getTargetConstant(
4413                 DL.getTypeAllocSize(GEP->getResultElementType()),
4414                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4415     Index = SDB->getValue(IndexVal);
4416   }
4417   Base = SDB->getValue(Ptr);
4418   IndexType = ISD::SIGNED_SCALED;
4419 
4420   if (STy || !Index.getValueType().isVector()) {
4421     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4422     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4423     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4424   }
4425   return true;
4426 }
4427 
4428 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4429   SDLoc sdl = getCurSDLoc();
4430 
4431   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4432   const Value *Ptr = I.getArgOperand(1);
4433   SDValue Src0 = getValue(I.getArgOperand(0));
4434   SDValue Mask = getValue(I.getArgOperand(3));
4435   EVT VT = Src0.getValueType();
4436   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4437   if (!Alignment)
4438     Alignment = DAG.getEVTAlignment(VT);
4439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4440 
4441   AAMDNodes AAInfo;
4442   I.getAAMetadata(AAInfo);
4443 
4444   SDValue Base;
4445   SDValue Index;
4446   ISD::MemIndexType IndexType;
4447   SDValue Scale;
4448   const Value *BasePtr = Ptr;
4449   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4450                                     this);
4451 
4452   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4453   MachineMemOperand *MMO = DAG.getMachineFunction().
4454     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4455                          MachineMemOperand::MOStore,
4456                          // TODO: Make MachineMemOperands aware of scalable
4457                          // vectors.
4458                          VT.getStoreSize().getKnownMinSize(),
4459                          Alignment, AAInfo);
4460   if (!UniformBase) {
4461     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4462     Index = getValue(Ptr);
4463     IndexType = ISD::SIGNED_SCALED;
4464     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4465   }
4466   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4467   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4468                                          Ops, MMO, IndexType);
4469   DAG.setRoot(Scatter);
4470   setValue(&I, Scatter);
4471 }
4472 
4473 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4474   SDLoc sdl = getCurSDLoc();
4475 
4476   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4477                            unsigned& Alignment) {
4478     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4479     Ptr = I.getArgOperand(0);
4480     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4481     Mask = I.getArgOperand(2);
4482     Src0 = I.getArgOperand(3);
4483   };
4484   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4485                            unsigned& Alignment) {
4486     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4487     Ptr = I.getArgOperand(0);
4488     Alignment = 0;
4489     Mask = I.getArgOperand(1);
4490     Src0 = I.getArgOperand(2);
4491   };
4492 
4493   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4494   unsigned Alignment;
4495   if (IsExpanding)
4496     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4497   else
4498     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4499 
4500   SDValue Ptr = getValue(PtrOperand);
4501   SDValue Src0 = getValue(Src0Operand);
4502   SDValue Mask = getValue(MaskOperand);
4503   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4504 
4505   EVT VT = Src0.getValueType();
4506   if (!Alignment)
4507     Alignment = DAG.getEVTAlignment(VT);
4508 
4509   AAMDNodes AAInfo;
4510   I.getAAMetadata(AAInfo);
4511   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4512 
4513   // Do not serialize masked loads of constant memory with anything.
4514   MemoryLocation ML;
4515   if (VT.isScalableVector())
4516     ML = MemoryLocation(PtrOperand);
4517   else
4518     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4519                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4520                            AAInfo);
4521   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4522 
4523   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4524 
4525   MachineMemOperand *MMO =
4526     DAG.getMachineFunction().
4527     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4528                           MachineMemOperand::MOLoad,
4529                           // TODO: Make MachineMemOperands aware of scalable
4530                           // vectors.
4531                           VT.getStoreSize().getKnownMinSize(),
4532                           Alignment, AAInfo, Ranges);
4533 
4534   SDValue Load =
4535       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4536                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4537   if (AddToChain)
4538     PendingLoads.push_back(Load.getValue(1));
4539   setValue(&I, Load);
4540 }
4541 
4542 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4543   SDLoc sdl = getCurSDLoc();
4544 
4545   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4546   const Value *Ptr = I.getArgOperand(0);
4547   SDValue Src0 = getValue(I.getArgOperand(3));
4548   SDValue Mask = getValue(I.getArgOperand(2));
4549 
4550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4551   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4552   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4553   if (!Alignment)
4554     Alignment = DAG.getEVTAlignment(VT);
4555 
4556   AAMDNodes AAInfo;
4557   I.getAAMetadata(AAInfo);
4558   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4559 
4560   SDValue Root = DAG.getRoot();
4561   SDValue Base;
4562   SDValue Index;
4563   ISD::MemIndexType IndexType;
4564   SDValue Scale;
4565   const Value *BasePtr = Ptr;
4566   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4567                                     this);
4568   bool ConstantMemory = false;
4569   if (UniformBase && AA &&
4570       AA->pointsToConstantMemory(
4571           MemoryLocation(BasePtr,
4572                          LocationSize::precise(
4573                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4574                          AAInfo))) {
4575     // Do not serialize (non-volatile) loads of constant memory with anything.
4576     Root = DAG.getEntryNode();
4577     ConstantMemory = true;
4578   }
4579 
4580   MachineMemOperand *MMO =
4581     DAG.getMachineFunction().
4582     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4583                          MachineMemOperand::MOLoad,
4584                          // TODO: Make MachineMemOperands aware of scalable
4585                          // vectors.
4586                          VT.getStoreSize().getKnownMinSize(),
4587                          Alignment, AAInfo, Ranges);
4588 
4589   if (!UniformBase) {
4590     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4591     Index = getValue(Ptr);
4592     IndexType = ISD::SIGNED_SCALED;
4593     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4594   }
4595   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4596   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4597                                        Ops, MMO, IndexType);
4598 
4599   SDValue OutChain = Gather.getValue(1);
4600   if (!ConstantMemory)
4601     PendingLoads.push_back(OutChain);
4602   setValue(&I, Gather);
4603 }
4604 
4605 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4606   SDLoc dl = getCurSDLoc();
4607   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4608   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4609   SyncScope::ID SSID = I.getSyncScopeID();
4610 
4611   SDValue InChain = getRoot();
4612 
4613   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4614   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4615 
4616   auto Alignment = DAG.getEVTAlignment(MemVT);
4617 
4618   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4619   if (I.isVolatile())
4620     Flags |= MachineMemOperand::MOVolatile;
4621   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4622 
4623   MachineFunction &MF = DAG.getMachineFunction();
4624   MachineMemOperand *MMO =
4625     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4626                             Flags, MemVT.getStoreSize(), Alignment,
4627                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4628                             FailureOrdering);
4629 
4630   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4631                                    dl, MemVT, VTs, InChain,
4632                                    getValue(I.getPointerOperand()),
4633                                    getValue(I.getCompareOperand()),
4634                                    getValue(I.getNewValOperand()), MMO);
4635 
4636   SDValue OutChain = L.getValue(2);
4637 
4638   setValue(&I, L);
4639   DAG.setRoot(OutChain);
4640 }
4641 
4642 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4643   SDLoc dl = getCurSDLoc();
4644   ISD::NodeType NT;
4645   switch (I.getOperation()) {
4646   default: llvm_unreachable("Unknown atomicrmw operation");
4647   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4648   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4649   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4650   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4651   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4652   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4653   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4654   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4655   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4656   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4657   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4658   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4659   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4660   }
4661   AtomicOrdering Ordering = I.getOrdering();
4662   SyncScope::ID SSID = I.getSyncScopeID();
4663 
4664   SDValue InChain = getRoot();
4665 
4666   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4667   auto Alignment = DAG.getEVTAlignment(MemVT);
4668 
4669   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4670   if (I.isVolatile())
4671     Flags |= MachineMemOperand::MOVolatile;
4672   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4673 
4674   MachineFunction &MF = DAG.getMachineFunction();
4675   MachineMemOperand *MMO =
4676     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4677                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4678                             nullptr, SSID, Ordering);
4679 
4680   SDValue L =
4681     DAG.getAtomic(NT, dl, MemVT, InChain,
4682                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4683                   MMO);
4684 
4685   SDValue OutChain = L.getValue(1);
4686 
4687   setValue(&I, L);
4688   DAG.setRoot(OutChain);
4689 }
4690 
4691 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4692   SDLoc dl = getCurSDLoc();
4693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4694   SDValue Ops[3];
4695   Ops[0] = getRoot();
4696   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4697                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4698   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4699                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4700   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4701 }
4702 
4703 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4704   SDLoc dl = getCurSDLoc();
4705   AtomicOrdering Order = I.getOrdering();
4706   SyncScope::ID SSID = I.getSyncScopeID();
4707 
4708   SDValue InChain = getRoot();
4709 
4710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4711   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4712   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4713 
4714   if (!TLI.supportsUnalignedAtomics() &&
4715       I.getAlignment() < MemVT.getSizeInBits() / 8)
4716     report_fatal_error("Cannot generate unaligned atomic load");
4717 
4718   auto Flags = MachineMemOperand::MOLoad;
4719   if (I.isVolatile())
4720     Flags |= MachineMemOperand::MOVolatile;
4721   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4722     Flags |= MachineMemOperand::MOInvariant;
4723   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4724                                DAG.getDataLayout()))
4725     Flags |= MachineMemOperand::MODereferenceable;
4726 
4727   Flags |= TLI.getMMOFlags(I);
4728 
4729   MachineMemOperand *MMO =
4730       DAG.getMachineFunction().
4731       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4732                            Flags, MemVT.getStoreSize(),
4733                            I.getAlignment() ? I.getAlignment() :
4734                                               DAG.getEVTAlignment(MemVT),
4735                            AAMDNodes(), nullptr, SSID, Order);
4736 
4737   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4738 
4739   SDValue Ptr = getValue(I.getPointerOperand());
4740 
4741   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4742     // TODO: Once this is better exercised by tests, it should be merged with
4743     // the normal path for loads to prevent future divergence.
4744     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4745     if (MemVT != VT)
4746       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4747 
4748     setValue(&I, L);
4749     SDValue OutChain = L.getValue(1);
4750     if (!I.isUnordered())
4751       DAG.setRoot(OutChain);
4752     else
4753       PendingLoads.push_back(OutChain);
4754     return;
4755   }
4756 
4757   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4758                             Ptr, MMO);
4759 
4760   SDValue OutChain = L.getValue(1);
4761   if (MemVT != VT)
4762     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4763 
4764   setValue(&I, L);
4765   DAG.setRoot(OutChain);
4766 }
4767 
4768 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4769   SDLoc dl = getCurSDLoc();
4770 
4771   AtomicOrdering Ordering = I.getOrdering();
4772   SyncScope::ID SSID = I.getSyncScopeID();
4773 
4774   SDValue InChain = getRoot();
4775 
4776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4777   EVT MemVT =
4778       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4779 
4780   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4781     report_fatal_error("Cannot generate unaligned atomic store");
4782 
4783   auto Flags = MachineMemOperand::MOStore;
4784   if (I.isVolatile())
4785     Flags |= MachineMemOperand::MOVolatile;
4786   Flags |= TLI.getMMOFlags(I);
4787 
4788   MachineFunction &MF = DAG.getMachineFunction();
4789   MachineMemOperand *MMO =
4790     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4791                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4792                             nullptr, SSID, Ordering);
4793 
4794   SDValue Val = getValue(I.getValueOperand());
4795   if (Val.getValueType() != MemVT)
4796     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4797   SDValue Ptr = getValue(I.getPointerOperand());
4798 
4799   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4800     // TODO: Once this is better exercised by tests, it should be merged with
4801     // the normal path for stores to prevent future divergence.
4802     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4803     DAG.setRoot(S);
4804     return;
4805   }
4806   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4807                                    Ptr, Val, MMO);
4808 
4809 
4810   DAG.setRoot(OutChain);
4811 }
4812 
4813 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4814 /// node.
4815 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4816                                                unsigned Intrinsic) {
4817   // Ignore the callsite's attributes. A specific call site may be marked with
4818   // readnone, but the lowering code will expect the chain based on the
4819   // definition.
4820   const Function *F = I.getCalledFunction();
4821   bool HasChain = !F->doesNotAccessMemory();
4822   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4823 
4824   // Build the operand list.
4825   SmallVector<SDValue, 8> Ops;
4826   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4827     if (OnlyLoad) {
4828       // We don't need to serialize loads against other loads.
4829       Ops.push_back(DAG.getRoot());
4830     } else {
4831       Ops.push_back(getRoot());
4832     }
4833   }
4834 
4835   // Info is set by getTgtMemInstrinsic
4836   TargetLowering::IntrinsicInfo Info;
4837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4838   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4839                                                DAG.getMachineFunction(),
4840                                                Intrinsic);
4841 
4842   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4843   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4844       Info.opc == ISD::INTRINSIC_W_CHAIN)
4845     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4846                                         TLI.getPointerTy(DAG.getDataLayout())));
4847 
4848   // Add all operands of the call to the operand list.
4849   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4850     const Value *Arg = I.getArgOperand(i);
4851     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4852       Ops.push_back(getValue(Arg));
4853       continue;
4854     }
4855 
4856     // Use TargetConstant instead of a regular constant for immarg.
4857     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4858     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4859       assert(CI->getBitWidth() <= 64 &&
4860              "large intrinsic immediates not handled");
4861       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4862     } else {
4863       Ops.push_back(
4864           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4865     }
4866   }
4867 
4868   SmallVector<EVT, 4> ValueVTs;
4869   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4870 
4871   if (HasChain)
4872     ValueVTs.push_back(MVT::Other);
4873 
4874   SDVTList VTs = DAG.getVTList(ValueVTs);
4875 
4876   // Create the node.
4877   SDValue Result;
4878   if (IsTgtIntrinsic) {
4879     // This is target intrinsic that touches memory
4880     AAMDNodes AAInfo;
4881     I.getAAMetadata(AAInfo);
4882     Result = DAG.getMemIntrinsicNode(
4883         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4884         MachinePointerInfo(Info.ptrVal, Info.offset),
4885         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4886   } else if (!HasChain) {
4887     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4888   } else if (!I.getType()->isVoidTy()) {
4889     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4890   } else {
4891     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4892   }
4893 
4894   if (HasChain) {
4895     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4896     if (OnlyLoad)
4897       PendingLoads.push_back(Chain);
4898     else
4899       DAG.setRoot(Chain);
4900   }
4901 
4902   if (!I.getType()->isVoidTy()) {
4903     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4904       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4905       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4906     } else
4907       Result = lowerRangeToAssertZExt(DAG, I, Result);
4908 
4909     setValue(&I, Result);
4910   }
4911 }
4912 
4913 /// GetSignificand - Get the significand and build it into a floating-point
4914 /// number with exponent of 1:
4915 ///
4916 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4917 ///
4918 /// where Op is the hexadecimal representation of floating point value.
4919 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4920   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4921                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4922   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4923                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4924   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4925 }
4926 
4927 /// GetExponent - Get the exponent:
4928 ///
4929 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4930 ///
4931 /// where Op is the hexadecimal representation of floating point value.
4932 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4933                            const TargetLowering &TLI, const SDLoc &dl) {
4934   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4935                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4936   SDValue t1 = DAG.getNode(
4937       ISD::SRL, dl, MVT::i32, t0,
4938       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4939   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4940                            DAG.getConstant(127, dl, MVT::i32));
4941   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4942 }
4943 
4944 /// getF32Constant - Get 32-bit floating point constant.
4945 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4946                               const SDLoc &dl) {
4947   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4948                            MVT::f32);
4949 }
4950 
4951 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4952                                        SelectionDAG &DAG) {
4953   // TODO: What fast-math-flags should be set on the floating-point nodes?
4954 
4955   //   IntegerPartOfX = ((int32_t)(t0);
4956   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4957 
4958   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4959   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4960   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4961 
4962   //   IntegerPartOfX <<= 23;
4963   IntegerPartOfX = DAG.getNode(
4964       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4965       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4966                                   DAG.getDataLayout())));
4967 
4968   SDValue TwoToFractionalPartOfX;
4969   if (LimitFloatPrecision <= 6) {
4970     // For floating-point precision of 6:
4971     //
4972     //   TwoToFractionalPartOfX =
4973     //     0.997535578f +
4974     //       (0.735607626f + 0.252464424f * x) * x;
4975     //
4976     // error 0.0144103317, which is 6 bits
4977     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4978                              getF32Constant(DAG, 0x3e814304, dl));
4979     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4980                              getF32Constant(DAG, 0x3f3c50c8, dl));
4981     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4982     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4983                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4984   } else if (LimitFloatPrecision <= 12) {
4985     // For floating-point precision of 12:
4986     //
4987     //   TwoToFractionalPartOfX =
4988     //     0.999892986f +
4989     //       (0.696457318f +
4990     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4991     //
4992     // error 0.000107046256, which is 13 to 14 bits
4993     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4994                              getF32Constant(DAG, 0x3da235e3, dl));
4995     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4996                              getF32Constant(DAG, 0x3e65b8f3, dl));
4997     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4998     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4999                              getF32Constant(DAG, 0x3f324b07, dl));
5000     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5001     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5002                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5003   } else { // LimitFloatPrecision <= 18
5004     // For floating-point precision of 18:
5005     //
5006     //   TwoToFractionalPartOfX =
5007     //     0.999999982f +
5008     //       (0.693148872f +
5009     //         (0.240227044f +
5010     //           (0.554906021e-1f +
5011     //             (0.961591928e-2f +
5012     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5013     // error 2.47208000*10^(-7), which is better than 18 bits
5014     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5015                              getF32Constant(DAG, 0x3924b03e, dl));
5016     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5017                              getF32Constant(DAG, 0x3ab24b87, dl));
5018     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5019     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5020                              getF32Constant(DAG, 0x3c1d8c17, dl));
5021     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5022     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5023                              getF32Constant(DAG, 0x3d634a1d, dl));
5024     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5025     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5026                              getF32Constant(DAG, 0x3e75fe14, dl));
5027     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5028     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5029                               getF32Constant(DAG, 0x3f317234, dl));
5030     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5031     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5032                                          getF32Constant(DAG, 0x3f800000, dl));
5033   }
5034 
5035   // Add the exponent into the result in integer domain.
5036   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5037   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5038                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5039 }
5040 
5041 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5042 /// limited-precision mode.
5043 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5044                          const TargetLowering &TLI) {
5045   if (Op.getValueType() == MVT::f32 &&
5046       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5047 
5048     // Put the exponent in the right bit position for later addition to the
5049     // final result:
5050     //
5051     // t0 = Op * log2(e)
5052 
5053     // TODO: What fast-math-flags should be set here?
5054     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5055                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5056     return getLimitedPrecisionExp2(t0, dl, DAG);
5057   }
5058 
5059   // No special expansion.
5060   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5061 }
5062 
5063 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5064 /// limited-precision mode.
5065 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5066                          const TargetLowering &TLI) {
5067   // TODO: What fast-math-flags should be set on the floating-point nodes?
5068 
5069   if (Op.getValueType() == MVT::f32 &&
5070       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5071     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5072 
5073     // Scale the exponent by log(2).
5074     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5075     SDValue LogOfExponent =
5076         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5077                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5078 
5079     // Get the significand and build it into a floating-point number with
5080     // exponent of 1.
5081     SDValue X = GetSignificand(DAG, Op1, dl);
5082 
5083     SDValue LogOfMantissa;
5084     if (LimitFloatPrecision <= 6) {
5085       // For floating-point precision of 6:
5086       //
5087       //   LogofMantissa =
5088       //     -1.1609546f +
5089       //       (1.4034025f - 0.23903021f * x) * x;
5090       //
5091       // error 0.0034276066, which is better than 8 bits
5092       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5093                                getF32Constant(DAG, 0xbe74c456, dl));
5094       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5095                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5096       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5097       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5098                                   getF32Constant(DAG, 0x3f949a29, dl));
5099     } else if (LimitFloatPrecision <= 12) {
5100       // For floating-point precision of 12:
5101       //
5102       //   LogOfMantissa =
5103       //     -1.7417939f +
5104       //       (2.8212026f +
5105       //         (-1.4699568f +
5106       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5107       //
5108       // error 0.000061011436, which is 14 bits
5109       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5110                                getF32Constant(DAG, 0xbd67b6d6, dl));
5111       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5112                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5113       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5114       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5115                                getF32Constant(DAG, 0x3fbc278b, dl));
5116       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5117       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5118                                getF32Constant(DAG, 0x40348e95, dl));
5119       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5120       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5121                                   getF32Constant(DAG, 0x3fdef31a, dl));
5122     } else { // LimitFloatPrecision <= 18
5123       // For floating-point precision of 18:
5124       //
5125       //   LogOfMantissa =
5126       //     -2.1072184f +
5127       //       (4.2372794f +
5128       //         (-3.7029485f +
5129       //           (2.2781945f +
5130       //             (-0.87823314f +
5131       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5132       //
5133       // error 0.0000023660568, which is better than 18 bits
5134       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5135                                getF32Constant(DAG, 0xbc91e5ac, dl));
5136       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5137                                getF32Constant(DAG, 0x3e4350aa, dl));
5138       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5139       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5140                                getF32Constant(DAG, 0x3f60d3e3, dl));
5141       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5142       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5143                                getF32Constant(DAG, 0x4011cdf0, dl));
5144       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5145       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5146                                getF32Constant(DAG, 0x406cfd1c, dl));
5147       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5148       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5149                                getF32Constant(DAG, 0x408797cb, dl));
5150       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5151       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5152                                   getF32Constant(DAG, 0x4006dcab, dl));
5153     }
5154 
5155     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5156   }
5157 
5158   // No special expansion.
5159   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5160 }
5161 
5162 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5163 /// limited-precision mode.
5164 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5165                           const TargetLowering &TLI) {
5166   // TODO: What fast-math-flags should be set on the floating-point nodes?
5167 
5168   if (Op.getValueType() == MVT::f32 &&
5169       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5170     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5171 
5172     // Get the exponent.
5173     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5174 
5175     // Get the significand and build it into a floating-point number with
5176     // exponent of 1.
5177     SDValue X = GetSignificand(DAG, Op1, dl);
5178 
5179     // Different possible minimax approximations of significand in
5180     // floating-point for various degrees of accuracy over [1,2].
5181     SDValue Log2ofMantissa;
5182     if (LimitFloatPrecision <= 6) {
5183       // For floating-point precision of 6:
5184       //
5185       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5186       //
5187       // error 0.0049451742, which is more than 7 bits
5188       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5189                                getF32Constant(DAG, 0xbeb08fe0, dl));
5190       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5191                                getF32Constant(DAG, 0x40019463, dl));
5192       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5193       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5194                                    getF32Constant(DAG, 0x3fd6633d, dl));
5195     } else if (LimitFloatPrecision <= 12) {
5196       // For floating-point precision of 12:
5197       //
5198       //   Log2ofMantissa =
5199       //     -2.51285454f +
5200       //       (4.07009056f +
5201       //         (-2.12067489f +
5202       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5203       //
5204       // error 0.0000876136000, which is better than 13 bits
5205       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5206                                getF32Constant(DAG, 0xbda7262e, dl));
5207       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5208                                getF32Constant(DAG, 0x3f25280b, dl));
5209       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5210       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5211                                getF32Constant(DAG, 0x4007b923, dl));
5212       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5213       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5214                                getF32Constant(DAG, 0x40823e2f, dl));
5215       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5216       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5217                                    getF32Constant(DAG, 0x4020d29c, dl));
5218     } else { // LimitFloatPrecision <= 18
5219       // For floating-point precision of 18:
5220       //
5221       //   Log2ofMantissa =
5222       //     -3.0400495f +
5223       //       (6.1129976f +
5224       //         (-5.3420409f +
5225       //           (3.2865683f +
5226       //             (-1.2669343f +
5227       //               (0.27515199f -
5228       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5229       //
5230       // error 0.0000018516, which is better than 18 bits
5231       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5232                                getF32Constant(DAG, 0xbcd2769e, dl));
5233       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5234                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5235       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5236       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5237                                getF32Constant(DAG, 0x3fa22ae7, dl));
5238       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5239       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5240                                getF32Constant(DAG, 0x40525723, dl));
5241       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5242       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5243                                getF32Constant(DAG, 0x40aaf200, dl));
5244       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5245       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5246                                getF32Constant(DAG, 0x40c39dad, dl));
5247       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5248       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5249                                    getF32Constant(DAG, 0x4042902c, dl));
5250     }
5251 
5252     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5253   }
5254 
5255   // No special expansion.
5256   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5257 }
5258 
5259 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5260 /// limited-precision mode.
5261 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5262                            const TargetLowering &TLI) {
5263   // TODO: What fast-math-flags should be set on the floating-point nodes?
5264 
5265   if (Op.getValueType() == MVT::f32 &&
5266       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5267     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5268 
5269     // Scale the exponent by log10(2) [0.30102999f].
5270     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5271     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5272                                         getF32Constant(DAG, 0x3e9a209a, dl));
5273 
5274     // Get the significand and build it into a floating-point number with
5275     // exponent of 1.
5276     SDValue X = GetSignificand(DAG, Op1, dl);
5277 
5278     SDValue Log10ofMantissa;
5279     if (LimitFloatPrecision <= 6) {
5280       // For floating-point precision of 6:
5281       //
5282       //   Log10ofMantissa =
5283       //     -0.50419619f +
5284       //       (0.60948995f - 0.10380950f * x) * x;
5285       //
5286       // error 0.0014886165, which is 6 bits
5287       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5288                                getF32Constant(DAG, 0xbdd49a13, dl));
5289       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5290                                getF32Constant(DAG, 0x3f1c0789, dl));
5291       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5292       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5293                                     getF32Constant(DAG, 0x3f011300, dl));
5294     } else if (LimitFloatPrecision <= 12) {
5295       // For floating-point precision of 12:
5296       //
5297       //   Log10ofMantissa =
5298       //     -0.64831180f +
5299       //       (0.91751397f +
5300       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5301       //
5302       // error 0.00019228036, which is better than 12 bits
5303       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5304                                getF32Constant(DAG, 0x3d431f31, dl));
5305       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5306                                getF32Constant(DAG, 0x3ea21fb2, dl));
5307       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5308       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5309                                getF32Constant(DAG, 0x3f6ae232, dl));
5310       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5311       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5312                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5313     } else { // LimitFloatPrecision <= 18
5314       // For floating-point precision of 18:
5315       //
5316       //   Log10ofMantissa =
5317       //     -0.84299375f +
5318       //       (1.5327582f +
5319       //         (-1.0688956f +
5320       //           (0.49102474f +
5321       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5322       //
5323       // error 0.0000037995730, which is better than 18 bits
5324       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5325                                getF32Constant(DAG, 0x3c5d51ce, dl));
5326       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5327                                getF32Constant(DAG, 0x3e00685a, dl));
5328       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5329       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5330                                getF32Constant(DAG, 0x3efb6798, dl));
5331       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5332       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5333                                getF32Constant(DAG, 0x3f88d192, dl));
5334       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5335       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5336                                getF32Constant(DAG, 0x3fc4316c, dl));
5337       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5338       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5339                                     getF32Constant(DAG, 0x3f57ce70, dl));
5340     }
5341 
5342     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5343   }
5344 
5345   // No special expansion.
5346   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5347 }
5348 
5349 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5350 /// limited-precision mode.
5351 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5352                           const TargetLowering &TLI) {
5353   if (Op.getValueType() == MVT::f32 &&
5354       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5355     return getLimitedPrecisionExp2(Op, dl, DAG);
5356 
5357   // No special expansion.
5358   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5359 }
5360 
5361 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5362 /// limited-precision mode with x == 10.0f.
5363 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5364                          SelectionDAG &DAG, const TargetLowering &TLI) {
5365   bool IsExp10 = false;
5366   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5367       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5368     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5369       APFloat Ten(10.0f);
5370       IsExp10 = LHSC->isExactlyValue(Ten);
5371     }
5372   }
5373 
5374   // TODO: What fast-math-flags should be set on the FMUL node?
5375   if (IsExp10) {
5376     // Put the exponent in the right bit position for later addition to the
5377     // final result:
5378     //
5379     //   #define LOG2OF10 3.3219281f
5380     //   t0 = Op * LOG2OF10;
5381     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5382                              getF32Constant(DAG, 0x40549a78, dl));
5383     return getLimitedPrecisionExp2(t0, dl, DAG);
5384   }
5385 
5386   // No special expansion.
5387   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5388 }
5389 
5390 /// ExpandPowI - Expand a llvm.powi intrinsic.
5391 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5392                           SelectionDAG &DAG) {
5393   // If RHS is a constant, we can expand this out to a multiplication tree,
5394   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5395   // optimizing for size, we only want to do this if the expansion would produce
5396   // a small number of multiplies, otherwise we do the full expansion.
5397   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5398     // Get the exponent as a positive value.
5399     unsigned Val = RHSC->getSExtValue();
5400     if ((int)Val < 0) Val = -Val;
5401 
5402     // powi(x, 0) -> 1.0
5403     if (Val == 0)
5404       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5405 
5406     bool OptForSize = DAG.shouldOptForSize();
5407     if (!OptForSize ||
5408         // If optimizing for size, don't insert too many multiplies.
5409         // This inserts up to 5 multiplies.
5410         countPopulation(Val) + Log2_32(Val) < 7) {
5411       // We use the simple binary decomposition method to generate the multiply
5412       // sequence.  There are more optimal ways to do this (for example,
5413       // powi(x,15) generates one more multiply than it should), but this has
5414       // the benefit of being both really simple and much better than a libcall.
5415       SDValue Res;  // Logically starts equal to 1.0
5416       SDValue CurSquare = LHS;
5417       // TODO: Intrinsics should have fast-math-flags that propagate to these
5418       // nodes.
5419       while (Val) {
5420         if (Val & 1) {
5421           if (Res.getNode())
5422             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5423           else
5424             Res = CurSquare;  // 1.0*CurSquare.
5425         }
5426 
5427         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5428                                 CurSquare, CurSquare);
5429         Val >>= 1;
5430       }
5431 
5432       // If the original was negative, invert the result, producing 1/(x*x*x).
5433       if (RHSC->getSExtValue() < 0)
5434         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5435                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5436       return Res;
5437     }
5438   }
5439 
5440   // Otherwise, expand to a libcall.
5441   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5442 }
5443 
5444 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5445 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5446 static void
5447 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5448                      const SDValue &N) {
5449   switch (N.getOpcode()) {
5450   case ISD::CopyFromReg: {
5451     SDValue Op = N.getOperand(1);
5452     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5453                       Op.getValueType().getSizeInBits());
5454     return;
5455   }
5456   case ISD::BITCAST:
5457   case ISD::AssertZext:
5458   case ISD::AssertSext:
5459   case ISD::TRUNCATE:
5460     getUnderlyingArgRegs(Regs, N.getOperand(0));
5461     return;
5462   case ISD::BUILD_PAIR:
5463   case ISD::BUILD_VECTOR:
5464   case ISD::CONCAT_VECTORS:
5465     for (SDValue Op : N->op_values())
5466       getUnderlyingArgRegs(Regs, Op);
5467     return;
5468   default:
5469     return;
5470   }
5471 }
5472 
5473 /// If the DbgValueInst is a dbg_value of a function argument, create the
5474 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5475 /// instruction selection, they will be inserted to the entry BB.
5476 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5477     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5478     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5479   const Argument *Arg = dyn_cast<Argument>(V);
5480   if (!Arg)
5481     return false;
5482 
5483   if (!IsDbgDeclare) {
5484     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5485     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5486     // the entry block.
5487     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5488     if (!IsInEntryBlock)
5489       return false;
5490 
5491     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5492     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5493     // variable that also is a param.
5494     //
5495     // Although, if we are at the top of the entry block already, we can still
5496     // emit using ArgDbgValue. This might catch some situations when the
5497     // dbg.value refers to an argument that isn't used in the entry block, so
5498     // any CopyToReg node would be optimized out and the only way to express
5499     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5500     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5501     // we should only emit as ArgDbgValue if the Variable is an argument to the
5502     // current function, and the dbg.value intrinsic is found in the entry
5503     // block.
5504     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5505         !DL->getInlinedAt();
5506     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5507     if (!IsInPrologue && !VariableIsFunctionInputArg)
5508       return false;
5509 
5510     // Here we assume that a function argument on IR level only can be used to
5511     // describe one input parameter on source level. If we for example have
5512     // source code like this
5513     //
5514     //    struct A { long x, y; };
5515     //    void foo(struct A a, long b) {
5516     //      ...
5517     //      b = a.x;
5518     //      ...
5519     //    }
5520     //
5521     // and IR like this
5522     //
5523     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5524     //  entry:
5525     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5526     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5527     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5528     //    ...
5529     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5530     //    ...
5531     //
5532     // then the last dbg.value is describing a parameter "b" using a value that
5533     // is an argument. But since we already has used %a1 to describe a parameter
5534     // we should not handle that last dbg.value here (that would result in an
5535     // incorrect hoisting of the DBG_VALUE to the function entry).
5536     // Notice that we allow one dbg.value per IR level argument, to accommodate
5537     // for the situation with fragments above.
5538     if (VariableIsFunctionInputArg) {
5539       unsigned ArgNo = Arg->getArgNo();
5540       if (ArgNo >= FuncInfo.DescribedArgs.size())
5541         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5542       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5543         return false;
5544       FuncInfo.DescribedArgs.set(ArgNo);
5545     }
5546   }
5547 
5548   MachineFunction &MF = DAG.getMachineFunction();
5549   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5550 
5551   Optional<MachineOperand> Op;
5552   // Some arguments' frame index is recorded during argument lowering.
5553   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5554   if (FI != std::numeric_limits<int>::max())
5555     Op = MachineOperand::CreateFI(FI);
5556 
5557   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5558   if (!Op && N.getNode()) {
5559     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5560     Register Reg;
5561     if (ArgRegsAndSizes.size() == 1)
5562       Reg = ArgRegsAndSizes.front().first;
5563 
5564     if (Reg && Reg.isVirtual()) {
5565       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5566       Register PR = RegInfo.getLiveInPhysReg(Reg);
5567       if (PR)
5568         Reg = PR;
5569     }
5570     if (Reg) {
5571       Op = MachineOperand::CreateReg(Reg, false);
5572     }
5573   }
5574 
5575   if (!Op && N.getNode()) {
5576     // Check if frame index is available.
5577     SDValue LCandidate = peekThroughBitcasts(N);
5578     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5579       if (FrameIndexSDNode *FINode =
5580           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5581         Op = MachineOperand::CreateFI(FINode->getIndex());
5582   }
5583 
5584   if (!Op) {
5585     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5586     auto splitMultiRegDbgValue
5587       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5588       unsigned Offset = 0;
5589       for (auto RegAndSize : SplitRegs) {
5590         // If the expression is already a fragment, the current register
5591         // offset+size might extend beyond the fragment. In this case, only
5592         // the register bits that are inside the fragment are relevant.
5593         int RegFragmentSizeInBits = RegAndSize.second;
5594         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5595           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5596           // The register is entirely outside the expression fragment,
5597           // so is irrelevant for debug info.
5598           if (Offset >= ExprFragmentSizeInBits)
5599             break;
5600           // The register is partially outside the expression fragment, only
5601           // the low bits within the fragment are relevant for debug info.
5602           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5603             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5604           }
5605         }
5606 
5607         auto FragmentExpr = DIExpression::createFragmentExpression(
5608             Expr, Offset, RegFragmentSizeInBits);
5609         Offset += RegAndSize.second;
5610         // If a valid fragment expression cannot be created, the variable's
5611         // correct value cannot be determined and so it is set as Undef.
5612         if (!FragmentExpr) {
5613           SDDbgValue *SDV = DAG.getConstantDbgValue(
5614               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5615           DAG.AddDbgValue(SDV, nullptr, false);
5616           continue;
5617         }
5618         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5619         FuncInfo.ArgDbgValues.push_back(
5620           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5621                   RegAndSize.first, Variable, *FragmentExpr));
5622       }
5623     };
5624 
5625     // Check if ValueMap has reg number.
5626     DenseMap<const Value *, unsigned>::const_iterator
5627       VMI = FuncInfo.ValueMap.find(V);
5628     if (VMI != FuncInfo.ValueMap.end()) {
5629       const auto &TLI = DAG.getTargetLoweringInfo();
5630       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5631                        V->getType(), getABIRegCopyCC(V));
5632       if (RFV.occupiesMultipleRegs()) {
5633         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5634         return true;
5635       }
5636 
5637       Op = MachineOperand::CreateReg(VMI->second, false);
5638     } else if (ArgRegsAndSizes.size() > 1) {
5639       // This was split due to the calling convention, and no virtual register
5640       // mapping exists for the value.
5641       splitMultiRegDbgValue(ArgRegsAndSizes);
5642       return true;
5643     }
5644   }
5645 
5646   if (!Op)
5647     return false;
5648 
5649   assert(Variable->isValidLocationForIntrinsic(DL) &&
5650          "Expected inlined-at fields to agree");
5651 
5652   // If the argument arrives in a stack slot, then what the IR thought was a
5653   // normal Value is actually in memory, and we must add a deref to load it.
5654   if (Op->isFI()) {
5655     int FI = Op->getIndex();
5656     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5657     if (Expr->isImplicit()) {
5658       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5659       Expr = DIExpression::prependOpcodes(Expr, Ops);
5660     } else {
5661       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5662     }
5663   }
5664 
5665   // If this location was specified with a dbg.declare, then it and its
5666   // expression calculate the address of the variable. Append a deref to
5667   // force it to be a memory location.
5668   if (IsDbgDeclare)
5669     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5670 
5671   FuncInfo.ArgDbgValues.push_back(
5672       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5673               *Op, Variable, Expr));
5674 
5675   return true;
5676 }
5677 
5678 /// Return the appropriate SDDbgValue based on N.
5679 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5680                                              DILocalVariable *Variable,
5681                                              DIExpression *Expr,
5682                                              const DebugLoc &dl,
5683                                              unsigned DbgSDNodeOrder) {
5684   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5685     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5686     // stack slot locations.
5687     //
5688     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5689     // debug values here after optimization:
5690     //
5691     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5692     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5693     //
5694     // Both describe the direct values of their associated variables.
5695     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5696                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5697   }
5698   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5699                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5700 }
5701 
5702 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5703   switch (Intrinsic) {
5704   case Intrinsic::smul_fix:
5705     return ISD::SMULFIX;
5706   case Intrinsic::umul_fix:
5707     return ISD::UMULFIX;
5708   default:
5709     llvm_unreachable("Unhandled fixed point intrinsic");
5710   }
5711 }
5712 
5713 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5714                                            const char *FunctionName) {
5715   assert(FunctionName && "FunctionName must not be nullptr");
5716   SDValue Callee = DAG.getExternalSymbol(
5717       FunctionName,
5718       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5719   LowerCallTo(&I, Callee, I.isTailCall());
5720 }
5721 
5722 /// Lower the call to the specified intrinsic function.
5723 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5724                                              unsigned Intrinsic) {
5725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5726   SDLoc sdl = getCurSDLoc();
5727   DebugLoc dl = getCurDebugLoc();
5728   SDValue Res;
5729 
5730   switch (Intrinsic) {
5731   default:
5732     // By default, turn this into a target intrinsic node.
5733     visitTargetIntrinsic(I, Intrinsic);
5734     return;
5735   case Intrinsic::vastart:  visitVAStart(I); return;
5736   case Intrinsic::vaend:    visitVAEnd(I); return;
5737   case Intrinsic::vacopy:   visitVACopy(I); return;
5738   case Intrinsic::returnaddress:
5739     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5740                              TLI.getPointerTy(DAG.getDataLayout()),
5741                              getValue(I.getArgOperand(0))));
5742     return;
5743   case Intrinsic::addressofreturnaddress:
5744     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5745                              TLI.getPointerTy(DAG.getDataLayout())));
5746     return;
5747   case Intrinsic::sponentry:
5748     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5749                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5750     return;
5751   case Intrinsic::frameaddress:
5752     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5753                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5754                              getValue(I.getArgOperand(0))));
5755     return;
5756   case Intrinsic::read_register: {
5757     Value *Reg = I.getArgOperand(0);
5758     SDValue Chain = getRoot();
5759     SDValue RegName =
5760         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5761     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5762     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5763       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5764     setValue(&I, Res);
5765     DAG.setRoot(Res.getValue(1));
5766     return;
5767   }
5768   case Intrinsic::write_register: {
5769     Value *Reg = I.getArgOperand(0);
5770     Value *RegValue = I.getArgOperand(1);
5771     SDValue Chain = getRoot();
5772     SDValue RegName =
5773         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5774     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5775                             RegName, getValue(RegValue)));
5776     return;
5777   }
5778   case Intrinsic::memcpy: {
5779     const auto &MCI = cast<MemCpyInst>(I);
5780     SDValue Op1 = getValue(I.getArgOperand(0));
5781     SDValue Op2 = getValue(I.getArgOperand(1));
5782     SDValue Op3 = getValue(I.getArgOperand(2));
5783     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5784     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5785     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5786     unsigned Align = MinAlign(DstAlign, SrcAlign);
5787     bool isVol = MCI.isVolatile();
5788     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5789     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5790     // node.
5791     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5792                                false, isTC,
5793                                MachinePointerInfo(I.getArgOperand(0)),
5794                                MachinePointerInfo(I.getArgOperand(1)));
5795     updateDAGForMaybeTailCall(MC);
5796     return;
5797   }
5798   case Intrinsic::memset: {
5799     const auto &MSI = cast<MemSetInst>(I);
5800     SDValue Op1 = getValue(I.getArgOperand(0));
5801     SDValue Op2 = getValue(I.getArgOperand(1));
5802     SDValue Op3 = getValue(I.getArgOperand(2));
5803     // @llvm.memset defines 0 and 1 to both mean no alignment.
5804     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5805     bool isVol = MSI.isVolatile();
5806     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5807     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5808                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5809     updateDAGForMaybeTailCall(MS);
5810     return;
5811   }
5812   case Intrinsic::memmove: {
5813     const auto &MMI = cast<MemMoveInst>(I);
5814     SDValue Op1 = getValue(I.getArgOperand(0));
5815     SDValue Op2 = getValue(I.getArgOperand(1));
5816     SDValue Op3 = getValue(I.getArgOperand(2));
5817     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5818     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5819     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5820     unsigned Align = MinAlign(DstAlign, SrcAlign);
5821     bool isVol = MMI.isVolatile();
5822     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5823     // FIXME: Support passing different dest/src alignments to the memmove DAG
5824     // node.
5825     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5826                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5827                                 MachinePointerInfo(I.getArgOperand(1)));
5828     updateDAGForMaybeTailCall(MM);
5829     return;
5830   }
5831   case Intrinsic::memcpy_element_unordered_atomic: {
5832     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5833     SDValue Dst = getValue(MI.getRawDest());
5834     SDValue Src = getValue(MI.getRawSource());
5835     SDValue Length = getValue(MI.getLength());
5836 
5837     unsigned DstAlign = MI.getDestAlignment();
5838     unsigned SrcAlign = MI.getSourceAlignment();
5839     Type *LengthTy = MI.getLength()->getType();
5840     unsigned ElemSz = MI.getElementSizeInBytes();
5841     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5842     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5843                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5844                                      MachinePointerInfo(MI.getRawDest()),
5845                                      MachinePointerInfo(MI.getRawSource()));
5846     updateDAGForMaybeTailCall(MC);
5847     return;
5848   }
5849   case Intrinsic::memmove_element_unordered_atomic: {
5850     auto &MI = cast<AtomicMemMoveInst>(I);
5851     SDValue Dst = getValue(MI.getRawDest());
5852     SDValue Src = getValue(MI.getRawSource());
5853     SDValue Length = getValue(MI.getLength());
5854 
5855     unsigned DstAlign = MI.getDestAlignment();
5856     unsigned SrcAlign = MI.getSourceAlignment();
5857     Type *LengthTy = MI.getLength()->getType();
5858     unsigned ElemSz = MI.getElementSizeInBytes();
5859     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5860     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5861                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5862                                       MachinePointerInfo(MI.getRawDest()),
5863                                       MachinePointerInfo(MI.getRawSource()));
5864     updateDAGForMaybeTailCall(MC);
5865     return;
5866   }
5867   case Intrinsic::memset_element_unordered_atomic: {
5868     auto &MI = cast<AtomicMemSetInst>(I);
5869     SDValue Dst = getValue(MI.getRawDest());
5870     SDValue Val = getValue(MI.getValue());
5871     SDValue Length = getValue(MI.getLength());
5872 
5873     unsigned DstAlign = MI.getDestAlignment();
5874     Type *LengthTy = MI.getLength()->getType();
5875     unsigned ElemSz = MI.getElementSizeInBytes();
5876     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5877     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5878                                      LengthTy, ElemSz, isTC,
5879                                      MachinePointerInfo(MI.getRawDest()));
5880     updateDAGForMaybeTailCall(MC);
5881     return;
5882   }
5883   case Intrinsic::dbg_addr:
5884   case Intrinsic::dbg_declare: {
5885     const auto &DI = cast<DbgVariableIntrinsic>(I);
5886     DILocalVariable *Variable = DI.getVariable();
5887     DIExpression *Expression = DI.getExpression();
5888     dropDanglingDebugInfo(Variable, Expression);
5889     assert(Variable && "Missing variable");
5890 
5891     // Check if address has undef value.
5892     const Value *Address = DI.getVariableLocation();
5893     if (!Address || isa<UndefValue>(Address) ||
5894         (Address->use_empty() && !isa<Argument>(Address))) {
5895       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5896       return;
5897     }
5898 
5899     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5900 
5901     // Check if this variable can be described by a frame index, typically
5902     // either as a static alloca or a byval parameter.
5903     int FI = std::numeric_limits<int>::max();
5904     if (const auto *AI =
5905             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5906       if (AI->isStaticAlloca()) {
5907         auto I = FuncInfo.StaticAllocaMap.find(AI);
5908         if (I != FuncInfo.StaticAllocaMap.end())
5909           FI = I->second;
5910       }
5911     } else if (const auto *Arg = dyn_cast<Argument>(
5912                    Address->stripInBoundsConstantOffsets())) {
5913       FI = FuncInfo.getArgumentFrameIndex(Arg);
5914     }
5915 
5916     // llvm.dbg.addr is control dependent and always generates indirect
5917     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5918     // the MachineFunction variable table.
5919     if (FI != std::numeric_limits<int>::max()) {
5920       if (Intrinsic == Intrinsic::dbg_addr) {
5921         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5922             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5923         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5924       }
5925       return;
5926     }
5927 
5928     SDValue &N = NodeMap[Address];
5929     if (!N.getNode() && isa<Argument>(Address))
5930       // Check unused arguments map.
5931       N = UnusedArgNodeMap[Address];
5932     SDDbgValue *SDV;
5933     if (N.getNode()) {
5934       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5935         Address = BCI->getOperand(0);
5936       // Parameters are handled specially.
5937       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5938       if (isParameter && FINode) {
5939         // Byval parameter. We have a frame index at this point.
5940         SDV =
5941             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5942                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5943       } else if (isa<Argument>(Address)) {
5944         // Address is an argument, so try to emit its dbg value using
5945         // virtual register info from the FuncInfo.ValueMap.
5946         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5947         return;
5948       } else {
5949         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5950                               true, dl, SDNodeOrder);
5951       }
5952       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5953     } else {
5954       // If Address is an argument then try to emit its dbg value using
5955       // virtual register info from the FuncInfo.ValueMap.
5956       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5957                                     N)) {
5958         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5959       }
5960     }
5961     return;
5962   }
5963   case Intrinsic::dbg_label: {
5964     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5965     DILabel *Label = DI.getLabel();
5966     assert(Label && "Missing label");
5967 
5968     SDDbgLabel *SDV;
5969     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5970     DAG.AddDbgLabel(SDV);
5971     return;
5972   }
5973   case Intrinsic::dbg_value: {
5974     const DbgValueInst &DI = cast<DbgValueInst>(I);
5975     assert(DI.getVariable() && "Missing variable");
5976 
5977     DILocalVariable *Variable = DI.getVariable();
5978     DIExpression *Expression = DI.getExpression();
5979     dropDanglingDebugInfo(Variable, Expression);
5980     const Value *V = DI.getValue();
5981     if (!V)
5982       return;
5983 
5984     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5985         SDNodeOrder))
5986       return;
5987 
5988     // TODO: Dangling debug info will eventually either be resolved or produce
5989     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5990     // between the original dbg.value location and its resolved DBG_VALUE, which
5991     // we should ideally fill with an extra Undef DBG_VALUE.
5992 
5993     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5994     return;
5995   }
5996 
5997   case Intrinsic::eh_typeid_for: {
5998     // Find the type id for the given typeinfo.
5999     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6000     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6001     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6002     setValue(&I, Res);
6003     return;
6004   }
6005 
6006   case Intrinsic::eh_return_i32:
6007   case Intrinsic::eh_return_i64:
6008     DAG.getMachineFunction().setCallsEHReturn(true);
6009     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6010                             MVT::Other,
6011                             getControlRoot(),
6012                             getValue(I.getArgOperand(0)),
6013                             getValue(I.getArgOperand(1))));
6014     return;
6015   case Intrinsic::eh_unwind_init:
6016     DAG.getMachineFunction().setCallsUnwindInit(true);
6017     return;
6018   case Intrinsic::eh_dwarf_cfa:
6019     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6020                              TLI.getPointerTy(DAG.getDataLayout()),
6021                              getValue(I.getArgOperand(0))));
6022     return;
6023   case Intrinsic::eh_sjlj_callsite: {
6024     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6025     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6026     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6027     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6028 
6029     MMI.setCurrentCallSite(CI->getZExtValue());
6030     return;
6031   }
6032   case Intrinsic::eh_sjlj_functioncontext: {
6033     // Get and store the index of the function context.
6034     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6035     AllocaInst *FnCtx =
6036       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6037     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6038     MFI.setFunctionContextIndex(FI);
6039     return;
6040   }
6041   case Intrinsic::eh_sjlj_setjmp: {
6042     SDValue Ops[2];
6043     Ops[0] = getRoot();
6044     Ops[1] = getValue(I.getArgOperand(0));
6045     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6046                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6047     setValue(&I, Op.getValue(0));
6048     DAG.setRoot(Op.getValue(1));
6049     return;
6050   }
6051   case Intrinsic::eh_sjlj_longjmp:
6052     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6053                             getRoot(), getValue(I.getArgOperand(0))));
6054     return;
6055   case Intrinsic::eh_sjlj_setup_dispatch:
6056     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6057                             getRoot()));
6058     return;
6059   case Intrinsic::masked_gather:
6060     visitMaskedGather(I);
6061     return;
6062   case Intrinsic::masked_load:
6063     visitMaskedLoad(I);
6064     return;
6065   case Intrinsic::masked_scatter:
6066     visitMaskedScatter(I);
6067     return;
6068   case Intrinsic::masked_store:
6069     visitMaskedStore(I);
6070     return;
6071   case Intrinsic::masked_expandload:
6072     visitMaskedLoad(I, true /* IsExpanding */);
6073     return;
6074   case Intrinsic::masked_compressstore:
6075     visitMaskedStore(I, true /* IsCompressing */);
6076     return;
6077   case Intrinsic::powi:
6078     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6079                             getValue(I.getArgOperand(1)), DAG));
6080     return;
6081   case Intrinsic::log:
6082     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6083     return;
6084   case Intrinsic::log2:
6085     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6086     return;
6087   case Intrinsic::log10:
6088     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6089     return;
6090   case Intrinsic::exp:
6091     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6092     return;
6093   case Intrinsic::exp2:
6094     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6095     return;
6096   case Intrinsic::pow:
6097     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6098                            getValue(I.getArgOperand(1)), DAG, TLI));
6099     return;
6100   case Intrinsic::sqrt:
6101   case Intrinsic::fabs:
6102   case Intrinsic::sin:
6103   case Intrinsic::cos:
6104   case Intrinsic::floor:
6105   case Intrinsic::ceil:
6106   case Intrinsic::trunc:
6107   case Intrinsic::rint:
6108   case Intrinsic::nearbyint:
6109   case Intrinsic::round:
6110   case Intrinsic::canonicalize: {
6111     unsigned Opcode;
6112     switch (Intrinsic) {
6113     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6114     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6115     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6116     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6117     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6118     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6119     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6120     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6121     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6122     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6123     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6124     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6125     }
6126 
6127     setValue(&I, DAG.getNode(Opcode, sdl,
6128                              getValue(I.getArgOperand(0)).getValueType(),
6129                              getValue(I.getArgOperand(0))));
6130     return;
6131   }
6132   case Intrinsic::lround:
6133   case Intrinsic::llround:
6134   case Intrinsic::lrint:
6135   case Intrinsic::llrint: {
6136     unsigned Opcode;
6137     switch (Intrinsic) {
6138     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6139     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6140     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6141     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6142     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6143     }
6144 
6145     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6146     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6147                              getValue(I.getArgOperand(0))));
6148     return;
6149   }
6150   case Intrinsic::minnum:
6151     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6152                              getValue(I.getArgOperand(0)).getValueType(),
6153                              getValue(I.getArgOperand(0)),
6154                              getValue(I.getArgOperand(1))));
6155     return;
6156   case Intrinsic::maxnum:
6157     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6158                              getValue(I.getArgOperand(0)).getValueType(),
6159                              getValue(I.getArgOperand(0)),
6160                              getValue(I.getArgOperand(1))));
6161     return;
6162   case Intrinsic::minimum:
6163     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6164                              getValue(I.getArgOperand(0)).getValueType(),
6165                              getValue(I.getArgOperand(0)),
6166                              getValue(I.getArgOperand(1))));
6167     return;
6168   case Intrinsic::maximum:
6169     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6170                              getValue(I.getArgOperand(0)).getValueType(),
6171                              getValue(I.getArgOperand(0)),
6172                              getValue(I.getArgOperand(1))));
6173     return;
6174   case Intrinsic::copysign:
6175     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6176                              getValue(I.getArgOperand(0)).getValueType(),
6177                              getValue(I.getArgOperand(0)),
6178                              getValue(I.getArgOperand(1))));
6179     return;
6180   case Intrinsic::fma:
6181     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6182                              getValue(I.getArgOperand(0)).getValueType(),
6183                              getValue(I.getArgOperand(0)),
6184                              getValue(I.getArgOperand(1)),
6185                              getValue(I.getArgOperand(2))));
6186     return;
6187 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6188   case Intrinsic::INTRINSIC:
6189 #include "llvm/IR/ConstrainedOps.def"
6190     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6191     return;
6192   case Intrinsic::fmuladd: {
6193     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6194     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6195         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6196       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6197                                getValue(I.getArgOperand(0)).getValueType(),
6198                                getValue(I.getArgOperand(0)),
6199                                getValue(I.getArgOperand(1)),
6200                                getValue(I.getArgOperand(2))));
6201     } else {
6202       // TODO: Intrinsic calls should have fast-math-flags.
6203       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6204                                 getValue(I.getArgOperand(0)).getValueType(),
6205                                 getValue(I.getArgOperand(0)),
6206                                 getValue(I.getArgOperand(1)));
6207       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6208                                 getValue(I.getArgOperand(0)).getValueType(),
6209                                 Mul,
6210                                 getValue(I.getArgOperand(2)));
6211       setValue(&I, Add);
6212     }
6213     return;
6214   }
6215   case Intrinsic::convert_to_fp16:
6216     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6217                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6218                                          getValue(I.getArgOperand(0)),
6219                                          DAG.getTargetConstant(0, sdl,
6220                                                                MVT::i32))));
6221     return;
6222   case Intrinsic::convert_from_fp16:
6223     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6224                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6225                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6226                                          getValue(I.getArgOperand(0)))));
6227     return;
6228   case Intrinsic::pcmarker: {
6229     SDValue Tmp = getValue(I.getArgOperand(0));
6230     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6231     return;
6232   }
6233   case Intrinsic::readcyclecounter: {
6234     SDValue Op = getRoot();
6235     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6236                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6237     setValue(&I, Res);
6238     DAG.setRoot(Res.getValue(1));
6239     return;
6240   }
6241   case Intrinsic::bitreverse:
6242     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6243                              getValue(I.getArgOperand(0)).getValueType(),
6244                              getValue(I.getArgOperand(0))));
6245     return;
6246   case Intrinsic::bswap:
6247     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6248                              getValue(I.getArgOperand(0)).getValueType(),
6249                              getValue(I.getArgOperand(0))));
6250     return;
6251   case Intrinsic::cttz: {
6252     SDValue Arg = getValue(I.getArgOperand(0));
6253     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6254     EVT Ty = Arg.getValueType();
6255     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6256                              sdl, Ty, Arg));
6257     return;
6258   }
6259   case Intrinsic::ctlz: {
6260     SDValue Arg = getValue(I.getArgOperand(0));
6261     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6262     EVT Ty = Arg.getValueType();
6263     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6264                              sdl, Ty, Arg));
6265     return;
6266   }
6267   case Intrinsic::ctpop: {
6268     SDValue Arg = getValue(I.getArgOperand(0));
6269     EVT Ty = Arg.getValueType();
6270     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6271     return;
6272   }
6273   case Intrinsic::fshl:
6274   case Intrinsic::fshr: {
6275     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6276     SDValue X = getValue(I.getArgOperand(0));
6277     SDValue Y = getValue(I.getArgOperand(1));
6278     SDValue Z = getValue(I.getArgOperand(2));
6279     EVT VT = X.getValueType();
6280     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6281     SDValue Zero = DAG.getConstant(0, sdl, VT);
6282     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6283 
6284     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6285     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6286       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6287       return;
6288     }
6289 
6290     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6291     // avoid the select that is necessary in the general case to filter out
6292     // the 0-shift possibility that leads to UB.
6293     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6294       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6295       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6296         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6297         return;
6298       }
6299 
6300       // Some targets only rotate one way. Try the opposite direction.
6301       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6302       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6303         // Negate the shift amount because it is safe to ignore the high bits.
6304         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6305         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6306         return;
6307       }
6308 
6309       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6310       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6311       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6312       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6313       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6314       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6315       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6316       return;
6317     }
6318 
6319     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6320     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6321     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6322     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6323     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6324     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6325 
6326     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6327     // and that is undefined. We must compare and select to avoid UB.
6328     EVT CCVT = MVT::i1;
6329     if (VT.isVector())
6330       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6331 
6332     // For fshl, 0-shift returns the 1st arg (X).
6333     // For fshr, 0-shift returns the 2nd arg (Y).
6334     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6335     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6336     return;
6337   }
6338   case Intrinsic::sadd_sat: {
6339     SDValue Op1 = getValue(I.getArgOperand(0));
6340     SDValue Op2 = getValue(I.getArgOperand(1));
6341     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6342     return;
6343   }
6344   case Intrinsic::uadd_sat: {
6345     SDValue Op1 = getValue(I.getArgOperand(0));
6346     SDValue Op2 = getValue(I.getArgOperand(1));
6347     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6348     return;
6349   }
6350   case Intrinsic::ssub_sat: {
6351     SDValue Op1 = getValue(I.getArgOperand(0));
6352     SDValue Op2 = getValue(I.getArgOperand(1));
6353     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6354     return;
6355   }
6356   case Intrinsic::usub_sat: {
6357     SDValue Op1 = getValue(I.getArgOperand(0));
6358     SDValue Op2 = getValue(I.getArgOperand(1));
6359     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6360     return;
6361   }
6362   case Intrinsic::smul_fix:
6363   case Intrinsic::umul_fix: {
6364     SDValue Op1 = getValue(I.getArgOperand(0));
6365     SDValue Op2 = getValue(I.getArgOperand(1));
6366     SDValue Op3 = getValue(I.getArgOperand(2));
6367     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6368                              Op1.getValueType(), Op1, Op2, Op3));
6369     return;
6370   }
6371   case Intrinsic::smul_fix_sat: {
6372     SDValue Op1 = getValue(I.getArgOperand(0));
6373     SDValue Op2 = getValue(I.getArgOperand(1));
6374     SDValue Op3 = getValue(I.getArgOperand(2));
6375     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6376                              Op3));
6377     return;
6378   }
6379   case Intrinsic::umul_fix_sat: {
6380     SDValue Op1 = getValue(I.getArgOperand(0));
6381     SDValue Op2 = getValue(I.getArgOperand(1));
6382     SDValue Op3 = getValue(I.getArgOperand(2));
6383     setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6384                              Op3));
6385     return;
6386   }
6387   case Intrinsic::stacksave: {
6388     SDValue Op = getRoot();
6389     Res = DAG.getNode(
6390         ISD::STACKSAVE, sdl,
6391         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6392     setValue(&I, Res);
6393     DAG.setRoot(Res.getValue(1));
6394     return;
6395   }
6396   case Intrinsic::stackrestore:
6397     Res = getValue(I.getArgOperand(0));
6398     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6399     return;
6400   case Intrinsic::get_dynamic_area_offset: {
6401     SDValue Op = getRoot();
6402     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6403     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6404     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6405     // target.
6406     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6407       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6408                          " intrinsic!");
6409     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6410                       Op);
6411     DAG.setRoot(Op);
6412     setValue(&I, Res);
6413     return;
6414   }
6415   case Intrinsic::stackguard: {
6416     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6417     MachineFunction &MF = DAG.getMachineFunction();
6418     const Module &M = *MF.getFunction().getParent();
6419     SDValue Chain = getRoot();
6420     if (TLI.useLoadStackGuardNode()) {
6421       Res = getLoadStackGuard(DAG, sdl, Chain);
6422     } else {
6423       const Value *Global = TLI.getSDagStackGuard(M);
6424       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6425       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6426                         MachinePointerInfo(Global, 0), Align,
6427                         MachineMemOperand::MOVolatile);
6428     }
6429     if (TLI.useStackGuardXorFP())
6430       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6431     DAG.setRoot(Chain);
6432     setValue(&I, Res);
6433     return;
6434   }
6435   case Intrinsic::stackprotector: {
6436     // Emit code into the DAG to store the stack guard onto the stack.
6437     MachineFunction &MF = DAG.getMachineFunction();
6438     MachineFrameInfo &MFI = MF.getFrameInfo();
6439     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6440     SDValue Src, Chain = getRoot();
6441 
6442     if (TLI.useLoadStackGuardNode())
6443       Src = getLoadStackGuard(DAG, sdl, Chain);
6444     else
6445       Src = getValue(I.getArgOperand(0));   // The guard's value.
6446 
6447     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6448 
6449     int FI = FuncInfo.StaticAllocaMap[Slot];
6450     MFI.setStackProtectorIndex(FI);
6451 
6452     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6453 
6454     // Store the stack protector onto the stack.
6455     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6456                                                  DAG.getMachineFunction(), FI),
6457                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6458     setValue(&I, Res);
6459     DAG.setRoot(Res);
6460     return;
6461   }
6462   case Intrinsic::objectsize:
6463     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6464 
6465   case Intrinsic::is_constant:
6466     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6467 
6468   case Intrinsic::annotation:
6469   case Intrinsic::ptr_annotation:
6470   case Intrinsic::launder_invariant_group:
6471   case Intrinsic::strip_invariant_group:
6472     // Drop the intrinsic, but forward the value
6473     setValue(&I, getValue(I.getOperand(0)));
6474     return;
6475   case Intrinsic::assume:
6476   case Intrinsic::var_annotation:
6477   case Intrinsic::sideeffect:
6478     // Discard annotate attributes, assumptions, and artificial side-effects.
6479     return;
6480 
6481   case Intrinsic::codeview_annotation: {
6482     // Emit a label associated with this metadata.
6483     MachineFunction &MF = DAG.getMachineFunction();
6484     MCSymbol *Label =
6485         MF.getMMI().getContext().createTempSymbol("annotation", true);
6486     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6487     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6488     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6489     DAG.setRoot(Res);
6490     return;
6491   }
6492 
6493   case Intrinsic::init_trampoline: {
6494     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6495 
6496     SDValue Ops[6];
6497     Ops[0] = getRoot();
6498     Ops[1] = getValue(I.getArgOperand(0));
6499     Ops[2] = getValue(I.getArgOperand(1));
6500     Ops[3] = getValue(I.getArgOperand(2));
6501     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6502     Ops[5] = DAG.getSrcValue(F);
6503 
6504     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6505 
6506     DAG.setRoot(Res);
6507     return;
6508   }
6509   case Intrinsic::adjust_trampoline:
6510     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6511                              TLI.getPointerTy(DAG.getDataLayout()),
6512                              getValue(I.getArgOperand(0))));
6513     return;
6514   case Intrinsic::gcroot: {
6515     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6516            "only valid in functions with gc specified, enforced by Verifier");
6517     assert(GFI && "implied by previous");
6518     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6519     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6520 
6521     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6522     GFI->addStackRoot(FI->getIndex(), TypeMap);
6523     return;
6524   }
6525   case Intrinsic::gcread:
6526   case Intrinsic::gcwrite:
6527     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6528   case Intrinsic::flt_rounds:
6529     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6530     return;
6531 
6532   case Intrinsic::expect:
6533     // Just replace __builtin_expect(exp, c) with EXP.
6534     setValue(&I, getValue(I.getArgOperand(0)));
6535     return;
6536 
6537   case Intrinsic::debugtrap:
6538   case Intrinsic::trap: {
6539     StringRef TrapFuncName =
6540         I.getAttributes()
6541             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6542             .getValueAsString();
6543     if (TrapFuncName.empty()) {
6544       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6545         ISD::TRAP : ISD::DEBUGTRAP;
6546       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6547       return;
6548     }
6549     TargetLowering::ArgListTy Args;
6550 
6551     TargetLowering::CallLoweringInfo CLI(DAG);
6552     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6553         CallingConv::C, I.getType(),
6554         DAG.getExternalSymbol(TrapFuncName.data(),
6555                               TLI.getPointerTy(DAG.getDataLayout())),
6556         std::move(Args));
6557 
6558     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6559     DAG.setRoot(Result.second);
6560     return;
6561   }
6562 
6563   case Intrinsic::uadd_with_overflow:
6564   case Intrinsic::sadd_with_overflow:
6565   case Intrinsic::usub_with_overflow:
6566   case Intrinsic::ssub_with_overflow:
6567   case Intrinsic::umul_with_overflow:
6568   case Intrinsic::smul_with_overflow: {
6569     ISD::NodeType Op;
6570     switch (Intrinsic) {
6571     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6572     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6573     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6574     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6575     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6576     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6577     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6578     }
6579     SDValue Op1 = getValue(I.getArgOperand(0));
6580     SDValue Op2 = getValue(I.getArgOperand(1));
6581 
6582     EVT ResultVT = Op1.getValueType();
6583     EVT OverflowVT = MVT::i1;
6584     if (ResultVT.isVector())
6585       OverflowVT = EVT::getVectorVT(
6586           *Context, OverflowVT, ResultVT.getVectorNumElements());
6587 
6588     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6589     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6590     return;
6591   }
6592   case Intrinsic::prefetch: {
6593     SDValue Ops[5];
6594     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6595     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6596     Ops[0] = DAG.getRoot();
6597     Ops[1] = getValue(I.getArgOperand(0));
6598     Ops[2] = getValue(I.getArgOperand(1));
6599     Ops[3] = getValue(I.getArgOperand(2));
6600     Ops[4] = getValue(I.getArgOperand(3));
6601     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6602                                              DAG.getVTList(MVT::Other), Ops,
6603                                              EVT::getIntegerVT(*Context, 8),
6604                                              MachinePointerInfo(I.getArgOperand(0)),
6605                                              0, /* align */
6606                                              Flags);
6607 
6608     // Chain the prefetch in parallell with any pending loads, to stay out of
6609     // the way of later optimizations.
6610     PendingLoads.push_back(Result);
6611     Result = getRoot();
6612     DAG.setRoot(Result);
6613     return;
6614   }
6615   case Intrinsic::lifetime_start:
6616   case Intrinsic::lifetime_end: {
6617     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6618     // Stack coloring is not enabled in O0, discard region information.
6619     if (TM.getOptLevel() == CodeGenOpt::None)
6620       return;
6621 
6622     const int64_t ObjectSize =
6623         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6624     Value *const ObjectPtr = I.getArgOperand(1);
6625     SmallVector<const Value *, 4> Allocas;
6626     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6627 
6628     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6629            E = Allocas.end(); Object != E; ++Object) {
6630       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6631 
6632       // Could not find an Alloca.
6633       if (!LifetimeObject)
6634         continue;
6635 
6636       // First check that the Alloca is static, otherwise it won't have a
6637       // valid frame index.
6638       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6639       if (SI == FuncInfo.StaticAllocaMap.end())
6640         return;
6641 
6642       const int FrameIndex = SI->second;
6643       int64_t Offset;
6644       if (GetPointerBaseWithConstantOffset(
6645               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6646         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6647       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6648                                 Offset);
6649       DAG.setRoot(Res);
6650     }
6651     return;
6652   }
6653   case Intrinsic::invariant_start:
6654     // Discard region information.
6655     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6656     return;
6657   case Intrinsic::invariant_end:
6658     // Discard region information.
6659     return;
6660   case Intrinsic::clear_cache:
6661     /// FunctionName may be null.
6662     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6663       lowerCallToExternalSymbol(I, FunctionName);
6664     return;
6665   case Intrinsic::donothing:
6666     // ignore
6667     return;
6668   case Intrinsic::experimental_stackmap:
6669     visitStackmap(I);
6670     return;
6671   case Intrinsic::experimental_patchpoint_void:
6672   case Intrinsic::experimental_patchpoint_i64:
6673     visitPatchpoint(&I);
6674     return;
6675   case Intrinsic::experimental_gc_statepoint:
6676     LowerStatepoint(ImmutableStatepoint(&I));
6677     return;
6678   case Intrinsic::experimental_gc_result:
6679     visitGCResult(cast<GCResultInst>(I));
6680     return;
6681   case Intrinsic::experimental_gc_relocate:
6682     visitGCRelocate(cast<GCRelocateInst>(I));
6683     return;
6684   case Intrinsic::instrprof_increment:
6685     llvm_unreachable("instrprof failed to lower an increment");
6686   case Intrinsic::instrprof_value_profile:
6687     llvm_unreachable("instrprof failed to lower a value profiling call");
6688   case Intrinsic::localescape: {
6689     MachineFunction &MF = DAG.getMachineFunction();
6690     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6691 
6692     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6693     // is the same on all targets.
6694     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6695       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6696       if (isa<ConstantPointerNull>(Arg))
6697         continue; // Skip null pointers. They represent a hole in index space.
6698       AllocaInst *Slot = cast<AllocaInst>(Arg);
6699       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6700              "can only escape static allocas");
6701       int FI = FuncInfo.StaticAllocaMap[Slot];
6702       MCSymbol *FrameAllocSym =
6703           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6704               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6705       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6706               TII->get(TargetOpcode::LOCAL_ESCAPE))
6707           .addSym(FrameAllocSym)
6708           .addFrameIndex(FI);
6709     }
6710 
6711     return;
6712   }
6713 
6714   case Intrinsic::localrecover: {
6715     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6716     MachineFunction &MF = DAG.getMachineFunction();
6717     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6718 
6719     // Get the symbol that defines the frame offset.
6720     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6721     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6722     unsigned IdxVal =
6723         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6724     MCSymbol *FrameAllocSym =
6725         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6726             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6727 
6728     // Create a MCSymbol for the label to avoid any target lowering
6729     // that would make this PC relative.
6730     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6731     SDValue OffsetVal =
6732         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6733 
6734     // Add the offset to the FP.
6735     Value *FP = I.getArgOperand(1);
6736     SDValue FPVal = getValue(FP);
6737     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6738     setValue(&I, Add);
6739 
6740     return;
6741   }
6742 
6743   case Intrinsic::eh_exceptionpointer:
6744   case Intrinsic::eh_exceptioncode: {
6745     // Get the exception pointer vreg, copy from it, and resize it to fit.
6746     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6747     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6748     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6749     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6750     SDValue N =
6751         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6752     if (Intrinsic == Intrinsic::eh_exceptioncode)
6753       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6754     setValue(&I, N);
6755     return;
6756   }
6757   case Intrinsic::xray_customevent: {
6758     // Here we want to make sure that the intrinsic behaves as if it has a
6759     // specific calling convention, and only for x86_64.
6760     // FIXME: Support other platforms later.
6761     const auto &Triple = DAG.getTarget().getTargetTriple();
6762     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6763       return;
6764 
6765     SDLoc DL = getCurSDLoc();
6766     SmallVector<SDValue, 8> Ops;
6767 
6768     // We want to say that we always want the arguments in registers.
6769     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6770     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6771     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6772     SDValue Chain = getRoot();
6773     Ops.push_back(LogEntryVal);
6774     Ops.push_back(StrSizeVal);
6775     Ops.push_back(Chain);
6776 
6777     // We need to enforce the calling convention for the callsite, so that
6778     // argument ordering is enforced correctly, and that register allocation can
6779     // see that some registers may be assumed clobbered and have to preserve
6780     // them across calls to the intrinsic.
6781     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6782                                            DL, NodeTys, Ops);
6783     SDValue patchableNode = SDValue(MN, 0);
6784     DAG.setRoot(patchableNode);
6785     setValue(&I, patchableNode);
6786     return;
6787   }
6788   case Intrinsic::xray_typedevent: {
6789     // Here we want to make sure that the intrinsic behaves as if it has a
6790     // specific calling convention, and only for x86_64.
6791     // FIXME: Support other platforms later.
6792     const auto &Triple = DAG.getTarget().getTargetTriple();
6793     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6794       return;
6795 
6796     SDLoc DL = getCurSDLoc();
6797     SmallVector<SDValue, 8> Ops;
6798 
6799     // We want to say that we always want the arguments in registers.
6800     // It's unclear to me how manipulating the selection DAG here forces callers
6801     // to provide arguments in registers instead of on the stack.
6802     SDValue LogTypeId = getValue(I.getArgOperand(0));
6803     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6804     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6805     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6806     SDValue Chain = getRoot();
6807     Ops.push_back(LogTypeId);
6808     Ops.push_back(LogEntryVal);
6809     Ops.push_back(StrSizeVal);
6810     Ops.push_back(Chain);
6811 
6812     // We need to enforce the calling convention for the callsite, so that
6813     // argument ordering is enforced correctly, and that register allocation can
6814     // see that some registers may be assumed clobbered and have to preserve
6815     // them across calls to the intrinsic.
6816     MachineSDNode *MN = DAG.getMachineNode(
6817         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6818     SDValue patchableNode = SDValue(MN, 0);
6819     DAG.setRoot(patchableNode);
6820     setValue(&I, patchableNode);
6821     return;
6822   }
6823   case Intrinsic::experimental_deoptimize:
6824     LowerDeoptimizeCall(&I);
6825     return;
6826 
6827   case Intrinsic::experimental_vector_reduce_v2_fadd:
6828   case Intrinsic::experimental_vector_reduce_v2_fmul:
6829   case Intrinsic::experimental_vector_reduce_add:
6830   case Intrinsic::experimental_vector_reduce_mul:
6831   case Intrinsic::experimental_vector_reduce_and:
6832   case Intrinsic::experimental_vector_reduce_or:
6833   case Intrinsic::experimental_vector_reduce_xor:
6834   case Intrinsic::experimental_vector_reduce_smax:
6835   case Intrinsic::experimental_vector_reduce_smin:
6836   case Intrinsic::experimental_vector_reduce_umax:
6837   case Intrinsic::experimental_vector_reduce_umin:
6838   case Intrinsic::experimental_vector_reduce_fmax:
6839   case Intrinsic::experimental_vector_reduce_fmin:
6840     visitVectorReduce(I, Intrinsic);
6841     return;
6842 
6843   case Intrinsic::icall_branch_funnel: {
6844     SmallVector<SDValue, 16> Ops;
6845     Ops.push_back(getValue(I.getArgOperand(0)));
6846 
6847     int64_t Offset;
6848     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6849         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6850     if (!Base)
6851       report_fatal_error(
6852           "llvm.icall.branch.funnel operand must be a GlobalValue");
6853     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6854 
6855     struct BranchFunnelTarget {
6856       int64_t Offset;
6857       SDValue Target;
6858     };
6859     SmallVector<BranchFunnelTarget, 8> Targets;
6860 
6861     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6862       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6863           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6864       if (ElemBase != Base)
6865         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6866                            "to the same GlobalValue");
6867 
6868       SDValue Val = getValue(I.getArgOperand(Op + 1));
6869       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6870       if (!GA)
6871         report_fatal_error(
6872             "llvm.icall.branch.funnel operand must be a GlobalValue");
6873       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6874                                      GA->getGlobal(), getCurSDLoc(),
6875                                      Val.getValueType(), GA->getOffset())});
6876     }
6877     llvm::sort(Targets,
6878                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6879                  return T1.Offset < T2.Offset;
6880                });
6881 
6882     for (auto &T : Targets) {
6883       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6884       Ops.push_back(T.Target);
6885     }
6886 
6887     Ops.push_back(DAG.getRoot()); // Chain
6888     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6889                                  getCurSDLoc(), MVT::Other, Ops),
6890               0);
6891     DAG.setRoot(N);
6892     setValue(&I, N);
6893     HasTailCall = true;
6894     return;
6895   }
6896 
6897   case Intrinsic::wasm_landingpad_index:
6898     // Information this intrinsic contained has been transferred to
6899     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6900     // delete it now.
6901     return;
6902 
6903   case Intrinsic::aarch64_settag:
6904   case Intrinsic::aarch64_settag_zero: {
6905     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6906     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6907     SDValue Val = TSI.EmitTargetCodeForSetTag(
6908         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6909         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6910         ZeroMemory);
6911     DAG.setRoot(Val);
6912     setValue(&I, Val);
6913     return;
6914   }
6915   case Intrinsic::ptrmask: {
6916     SDValue Ptr = getValue(I.getOperand(0));
6917     SDValue Const = getValue(I.getOperand(1));
6918 
6919     EVT DestVT =
6920         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6921 
6922     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6923                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6924     return;
6925   }
6926   }
6927 }
6928 
6929 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6930     const ConstrainedFPIntrinsic &FPI) {
6931   SDLoc sdl = getCurSDLoc();
6932 
6933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6934   SmallVector<EVT, 4> ValueVTs;
6935   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6936   ValueVTs.push_back(MVT::Other); // Out chain
6937 
6938   // We do not need to serialize constrained FP intrinsics against
6939   // each other or against (nonvolatile) loads, so they can be
6940   // chained like loads.
6941   SDValue Chain = DAG.getRoot();
6942   SmallVector<SDValue, 4> Opers;
6943   Opers.push_back(Chain);
6944   if (FPI.isUnaryOp()) {
6945     Opers.push_back(getValue(FPI.getArgOperand(0)));
6946   } else if (FPI.isTernaryOp()) {
6947     Opers.push_back(getValue(FPI.getArgOperand(0)));
6948     Opers.push_back(getValue(FPI.getArgOperand(1)));
6949     Opers.push_back(getValue(FPI.getArgOperand(2)));
6950   } else {
6951     Opers.push_back(getValue(FPI.getArgOperand(0)));
6952     Opers.push_back(getValue(FPI.getArgOperand(1)));
6953   }
6954 
6955   unsigned Opcode;
6956   switch (FPI.getIntrinsicID()) {
6957   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6958 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6959   case Intrinsic::INTRINSIC:                                                   \
6960     Opcode = ISD::STRICT_##DAGN;                                               \
6961     break;
6962 #include "llvm/IR/ConstrainedOps.def"
6963   }
6964 
6965   // A few strict DAG nodes carry additional operands that are not
6966   // set up by the default code above.
6967   switch (Opcode) {
6968   default: break;
6969   case ISD::STRICT_FP_ROUND:
6970     Opers.push_back(
6971         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6972     break;
6973   case ISD::STRICT_FSETCC:
6974   case ISD::STRICT_FSETCCS: {
6975     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6976     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6977     break;
6978   }
6979   }
6980 
6981   SDVTList VTs = DAG.getVTList(ValueVTs);
6982   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
6983 
6984   assert(Result.getNode()->getNumValues() == 2);
6985   // See above -- chain is handled like for loads here.
6986   SDValue OutChain = Result.getValue(1);
6987   PendingLoads.push_back(OutChain);
6988   SDValue FPResult = Result.getValue(0);
6989   setValue(&FPI, FPResult);
6990 }
6991 
6992 std::pair<SDValue, SDValue>
6993 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6994                                     const BasicBlock *EHPadBB) {
6995   MachineFunction &MF = DAG.getMachineFunction();
6996   MachineModuleInfo &MMI = MF.getMMI();
6997   MCSymbol *BeginLabel = nullptr;
6998 
6999   if (EHPadBB) {
7000     // Insert a label before the invoke call to mark the try range.  This can be
7001     // used to detect deletion of the invoke via the MachineModuleInfo.
7002     BeginLabel = MMI.getContext().createTempSymbol();
7003 
7004     // For SjLj, keep track of which landing pads go with which invokes
7005     // so as to maintain the ordering of pads in the LSDA.
7006     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7007     if (CallSiteIndex) {
7008       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7009       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7010 
7011       // Now that the call site is handled, stop tracking it.
7012       MMI.setCurrentCallSite(0);
7013     }
7014 
7015     // Both PendingLoads and PendingExports must be flushed here;
7016     // this call might not return.
7017     (void)getRoot();
7018     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7019 
7020     CLI.setChain(getRoot());
7021   }
7022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7023   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7024 
7025   assert((CLI.IsTailCall || Result.second.getNode()) &&
7026          "Non-null chain expected with non-tail call!");
7027   assert((Result.second.getNode() || !Result.first.getNode()) &&
7028          "Null value expected with tail call!");
7029 
7030   if (!Result.second.getNode()) {
7031     // As a special case, a null chain means that a tail call has been emitted
7032     // and the DAG root is already updated.
7033     HasTailCall = true;
7034 
7035     // Since there's no actual continuation from this block, nothing can be
7036     // relying on us setting vregs for them.
7037     PendingExports.clear();
7038   } else {
7039     DAG.setRoot(Result.second);
7040   }
7041 
7042   if (EHPadBB) {
7043     // Insert a label at the end of the invoke call to mark the try range.  This
7044     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7045     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7046     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7047 
7048     // Inform MachineModuleInfo of range.
7049     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7050     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7051     // actually use outlined funclets and their LSDA info style.
7052     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7053       assert(CLI.CS);
7054       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7055       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7056                                 BeginLabel, EndLabel);
7057     } else if (!isScopedEHPersonality(Pers)) {
7058       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7059     }
7060   }
7061 
7062   return Result;
7063 }
7064 
7065 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7066                                       bool isTailCall,
7067                                       const BasicBlock *EHPadBB) {
7068   auto &DL = DAG.getDataLayout();
7069   FunctionType *FTy = CS.getFunctionType();
7070   Type *RetTy = CS.getType();
7071 
7072   TargetLowering::ArgListTy Args;
7073   Args.reserve(CS.arg_size());
7074 
7075   const Value *SwiftErrorVal = nullptr;
7076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7077 
7078   // We can't tail call inside a function with a swifterror argument. Lowering
7079   // does not support this yet. It would have to move into the swifterror
7080   // register before the call.
7081   auto *Caller = CS.getInstruction()->getParent()->getParent();
7082   if (TLI.supportSwiftError() &&
7083       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7084     isTailCall = false;
7085 
7086   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7087        i != e; ++i) {
7088     TargetLowering::ArgListEntry Entry;
7089     const Value *V = *i;
7090 
7091     // Skip empty types
7092     if (V->getType()->isEmptyTy())
7093       continue;
7094 
7095     SDValue ArgNode = getValue(V);
7096     Entry.Node = ArgNode; Entry.Ty = V->getType();
7097 
7098     Entry.setAttributes(&CS, i - CS.arg_begin());
7099 
7100     // Use swifterror virtual register as input to the call.
7101     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7102       SwiftErrorVal = V;
7103       // We find the virtual register for the actual swifterror argument.
7104       // Instead of using the Value, we use the virtual register instead.
7105       Entry.Node = DAG.getRegister(
7106           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7107           EVT(TLI.getPointerTy(DL)));
7108     }
7109 
7110     Args.push_back(Entry);
7111 
7112     // If we have an explicit sret argument that is an Instruction, (i.e., it
7113     // might point to function-local memory), we can't meaningfully tail-call.
7114     if (Entry.IsSRet && isa<Instruction>(V))
7115       isTailCall = false;
7116   }
7117 
7118   // If call site has a cfguardtarget operand bundle, create and add an
7119   // additional ArgListEntry.
7120   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7121     TargetLowering::ArgListEntry Entry;
7122     Value *V = Bundle->Inputs[0];
7123     SDValue ArgNode = getValue(V);
7124     Entry.Node = ArgNode;
7125     Entry.Ty = V->getType();
7126     Entry.IsCFGuardTarget = true;
7127     Args.push_back(Entry);
7128   }
7129 
7130   // Check if target-independent constraints permit a tail call here.
7131   // Target-dependent constraints are checked within TLI->LowerCallTo.
7132   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7133     isTailCall = false;
7134 
7135   // Disable tail calls if there is an swifterror argument. Targets have not
7136   // been updated to support tail calls.
7137   if (TLI.supportSwiftError() && SwiftErrorVal)
7138     isTailCall = false;
7139 
7140   TargetLowering::CallLoweringInfo CLI(DAG);
7141   CLI.setDebugLoc(getCurSDLoc())
7142       .setChain(getRoot())
7143       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7144       .setTailCall(isTailCall)
7145       .setConvergent(CS.isConvergent());
7146   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7147 
7148   if (Result.first.getNode()) {
7149     const Instruction *Inst = CS.getInstruction();
7150     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7151     setValue(Inst, Result.first);
7152   }
7153 
7154   // The last element of CLI.InVals has the SDValue for swifterror return.
7155   // Here we copy it to a virtual register and update SwiftErrorMap for
7156   // book-keeping.
7157   if (SwiftErrorVal && TLI.supportSwiftError()) {
7158     // Get the last element of InVals.
7159     SDValue Src = CLI.InVals.back();
7160     Register VReg = SwiftError.getOrCreateVRegDefAt(
7161         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7162     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7163     DAG.setRoot(CopyNode);
7164   }
7165 }
7166 
7167 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7168                              SelectionDAGBuilder &Builder) {
7169   // Check to see if this load can be trivially constant folded, e.g. if the
7170   // input is from a string literal.
7171   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7172     // Cast pointer to the type we really want to load.
7173     Type *LoadTy =
7174         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7175     if (LoadVT.isVector())
7176       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7177 
7178     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7179                                          PointerType::getUnqual(LoadTy));
7180 
7181     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7182             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7183       return Builder.getValue(LoadCst);
7184   }
7185 
7186   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7187   // still constant memory, the input chain can be the entry node.
7188   SDValue Root;
7189   bool ConstantMemory = false;
7190 
7191   // Do not serialize (non-volatile) loads of constant memory with anything.
7192   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7193     Root = Builder.DAG.getEntryNode();
7194     ConstantMemory = true;
7195   } else {
7196     // Do not serialize non-volatile loads against each other.
7197     Root = Builder.DAG.getRoot();
7198   }
7199 
7200   SDValue Ptr = Builder.getValue(PtrVal);
7201   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7202                                         Ptr, MachinePointerInfo(PtrVal),
7203                                         /* Alignment = */ 1);
7204 
7205   if (!ConstantMemory)
7206     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7207   return LoadVal;
7208 }
7209 
7210 /// Record the value for an instruction that produces an integer result,
7211 /// converting the type where necessary.
7212 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7213                                                   SDValue Value,
7214                                                   bool IsSigned) {
7215   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7216                                                     I.getType(), true);
7217   if (IsSigned)
7218     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7219   else
7220     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7221   setValue(&I, Value);
7222 }
7223 
7224 /// See if we can lower a memcmp call into an optimized form. If so, return
7225 /// true and lower it. Otherwise return false, and it will be lowered like a
7226 /// normal call.
7227 /// The caller already checked that \p I calls the appropriate LibFunc with a
7228 /// correct prototype.
7229 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7230   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7231   const Value *Size = I.getArgOperand(2);
7232   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7233   if (CSize && CSize->getZExtValue() == 0) {
7234     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7235                                                           I.getType(), true);
7236     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7237     return true;
7238   }
7239 
7240   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7241   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7242       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7243       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7244   if (Res.first.getNode()) {
7245     processIntegerCallValue(I, Res.first, true);
7246     PendingLoads.push_back(Res.second);
7247     return true;
7248   }
7249 
7250   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7251   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7252   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7253     return false;
7254 
7255   // If the target has a fast compare for the given size, it will return a
7256   // preferred load type for that size. Require that the load VT is legal and
7257   // that the target supports unaligned loads of that type. Otherwise, return
7258   // INVALID.
7259   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7260     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7261     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7262     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7263       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7264       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7265       // TODO: Check alignment of src and dest ptrs.
7266       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7267       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7268       if (!TLI.isTypeLegal(LVT) ||
7269           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7270           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7271         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7272     }
7273 
7274     return LVT;
7275   };
7276 
7277   // This turns into unaligned loads. We only do this if the target natively
7278   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7279   // we'll only produce a small number of byte loads.
7280   MVT LoadVT;
7281   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7282   switch (NumBitsToCompare) {
7283   default:
7284     return false;
7285   case 16:
7286     LoadVT = MVT::i16;
7287     break;
7288   case 32:
7289     LoadVT = MVT::i32;
7290     break;
7291   case 64:
7292   case 128:
7293   case 256:
7294     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7295     break;
7296   }
7297 
7298   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7299     return false;
7300 
7301   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7302   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7303 
7304   // Bitcast to a wide integer type if the loads are vectors.
7305   if (LoadVT.isVector()) {
7306     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7307     LoadL = DAG.getBitcast(CmpVT, LoadL);
7308     LoadR = DAG.getBitcast(CmpVT, LoadR);
7309   }
7310 
7311   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7312   processIntegerCallValue(I, Cmp, false);
7313   return true;
7314 }
7315 
7316 /// See if we can lower a memchr call into an optimized form. If so, return
7317 /// true and lower it. Otherwise return false, and it will be lowered like a
7318 /// normal call.
7319 /// The caller already checked that \p I calls the appropriate LibFunc with a
7320 /// correct prototype.
7321 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7322   const Value *Src = I.getArgOperand(0);
7323   const Value *Char = I.getArgOperand(1);
7324   const Value *Length = I.getArgOperand(2);
7325 
7326   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7327   std::pair<SDValue, SDValue> Res =
7328     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7329                                 getValue(Src), getValue(Char), getValue(Length),
7330                                 MachinePointerInfo(Src));
7331   if (Res.first.getNode()) {
7332     setValue(&I, Res.first);
7333     PendingLoads.push_back(Res.second);
7334     return true;
7335   }
7336 
7337   return false;
7338 }
7339 
7340 /// See if we can lower a mempcpy call into an optimized form. If so, return
7341 /// true and lower it. Otherwise return false, and it will be lowered like a
7342 /// normal call.
7343 /// The caller already checked that \p I calls the appropriate LibFunc with a
7344 /// correct prototype.
7345 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7346   SDValue Dst = getValue(I.getArgOperand(0));
7347   SDValue Src = getValue(I.getArgOperand(1));
7348   SDValue Size = getValue(I.getArgOperand(2));
7349 
7350   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7351   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7352   unsigned Align = std::min(DstAlign, SrcAlign);
7353   if (Align == 0) // Alignment of one or both could not be inferred.
7354     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7355 
7356   bool isVol = false;
7357   SDLoc sdl = getCurSDLoc();
7358 
7359   // In the mempcpy context we need to pass in a false value for isTailCall
7360   // because the return pointer needs to be adjusted by the size of
7361   // the copied memory.
7362   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7363                              false, /*isTailCall=*/false,
7364                              MachinePointerInfo(I.getArgOperand(0)),
7365                              MachinePointerInfo(I.getArgOperand(1)));
7366   assert(MC.getNode() != nullptr &&
7367          "** memcpy should not be lowered as TailCall in mempcpy context **");
7368   DAG.setRoot(MC);
7369 
7370   // Check if Size needs to be truncated or extended.
7371   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7372 
7373   // Adjust return pointer to point just past the last dst byte.
7374   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7375                                     Dst, Size);
7376   setValue(&I, DstPlusSize);
7377   return true;
7378 }
7379 
7380 /// See if we can lower a strcpy call into an optimized form.  If so, return
7381 /// true and lower it, otherwise return false and it will be lowered like a
7382 /// normal call.
7383 /// The caller already checked that \p I calls the appropriate LibFunc with a
7384 /// correct prototype.
7385 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7386   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7387 
7388   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7389   std::pair<SDValue, SDValue> Res =
7390     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7391                                 getValue(Arg0), getValue(Arg1),
7392                                 MachinePointerInfo(Arg0),
7393                                 MachinePointerInfo(Arg1), isStpcpy);
7394   if (Res.first.getNode()) {
7395     setValue(&I, Res.first);
7396     DAG.setRoot(Res.second);
7397     return true;
7398   }
7399 
7400   return false;
7401 }
7402 
7403 /// See if we can lower a strcmp call into an optimized form.  If so, return
7404 /// true and lower it, otherwise return false and it will be lowered like a
7405 /// normal call.
7406 /// The caller already checked that \p I calls the appropriate LibFunc with a
7407 /// correct prototype.
7408 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7409   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7410 
7411   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7412   std::pair<SDValue, SDValue> Res =
7413     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7414                                 getValue(Arg0), getValue(Arg1),
7415                                 MachinePointerInfo(Arg0),
7416                                 MachinePointerInfo(Arg1));
7417   if (Res.first.getNode()) {
7418     processIntegerCallValue(I, Res.first, true);
7419     PendingLoads.push_back(Res.second);
7420     return true;
7421   }
7422 
7423   return false;
7424 }
7425 
7426 /// See if we can lower a strlen call into an optimized form.  If so, return
7427 /// true and lower it, otherwise return false and it will be lowered like a
7428 /// normal call.
7429 /// The caller already checked that \p I calls the appropriate LibFunc with a
7430 /// correct prototype.
7431 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7432   const Value *Arg0 = I.getArgOperand(0);
7433 
7434   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7435   std::pair<SDValue, SDValue> Res =
7436     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7437                                 getValue(Arg0), MachinePointerInfo(Arg0));
7438   if (Res.first.getNode()) {
7439     processIntegerCallValue(I, Res.first, false);
7440     PendingLoads.push_back(Res.second);
7441     return true;
7442   }
7443 
7444   return false;
7445 }
7446 
7447 /// See if we can lower a strnlen call into an optimized form.  If so, return
7448 /// true and lower it, otherwise return false and it will be lowered like a
7449 /// normal call.
7450 /// The caller already checked that \p I calls the appropriate LibFunc with a
7451 /// correct prototype.
7452 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7453   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7454 
7455   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7456   std::pair<SDValue, SDValue> Res =
7457     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7458                                  getValue(Arg0), getValue(Arg1),
7459                                  MachinePointerInfo(Arg0));
7460   if (Res.first.getNode()) {
7461     processIntegerCallValue(I, Res.first, false);
7462     PendingLoads.push_back(Res.second);
7463     return true;
7464   }
7465 
7466   return false;
7467 }
7468 
7469 /// See if we can lower a unary floating-point operation into an SDNode with
7470 /// the specified Opcode.  If so, return true and lower it, otherwise return
7471 /// false and it will be lowered like a normal call.
7472 /// The caller already checked that \p I calls the appropriate LibFunc with a
7473 /// correct prototype.
7474 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7475                                               unsigned Opcode) {
7476   // We already checked this call's prototype; verify it doesn't modify errno.
7477   if (!I.onlyReadsMemory())
7478     return false;
7479 
7480   SDValue Tmp = getValue(I.getArgOperand(0));
7481   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7482   return true;
7483 }
7484 
7485 /// See if we can lower a binary floating-point operation into an SDNode with
7486 /// the specified Opcode. If so, return true and lower it. Otherwise return
7487 /// false, and it will be lowered like a normal call.
7488 /// The caller already checked that \p I calls the appropriate LibFunc with a
7489 /// correct prototype.
7490 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7491                                                unsigned Opcode) {
7492   // We already checked this call's prototype; verify it doesn't modify errno.
7493   if (!I.onlyReadsMemory())
7494     return false;
7495 
7496   SDValue Tmp0 = getValue(I.getArgOperand(0));
7497   SDValue Tmp1 = getValue(I.getArgOperand(1));
7498   EVT VT = Tmp0.getValueType();
7499   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7500   return true;
7501 }
7502 
7503 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7504   // Handle inline assembly differently.
7505   if (isa<InlineAsm>(I.getCalledValue())) {
7506     visitInlineAsm(&I);
7507     return;
7508   }
7509 
7510   if (Function *F = I.getCalledFunction()) {
7511     if (F->isDeclaration()) {
7512       // Is this an LLVM intrinsic or a target-specific intrinsic?
7513       unsigned IID = F->getIntrinsicID();
7514       if (!IID)
7515         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7516           IID = II->getIntrinsicID(F);
7517 
7518       if (IID) {
7519         visitIntrinsicCall(I, IID);
7520         return;
7521       }
7522     }
7523 
7524     // Check for well-known libc/libm calls.  If the function is internal, it
7525     // can't be a library call.  Don't do the check if marked as nobuiltin for
7526     // some reason or the call site requires strict floating point semantics.
7527     LibFunc Func;
7528     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7529         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7530         LibInfo->hasOptimizedCodeGen(Func)) {
7531       switch (Func) {
7532       default: break;
7533       case LibFunc_copysign:
7534       case LibFunc_copysignf:
7535       case LibFunc_copysignl:
7536         // We already checked this call's prototype; verify it doesn't modify
7537         // errno.
7538         if (I.onlyReadsMemory()) {
7539           SDValue LHS = getValue(I.getArgOperand(0));
7540           SDValue RHS = getValue(I.getArgOperand(1));
7541           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7542                                    LHS.getValueType(), LHS, RHS));
7543           return;
7544         }
7545         break;
7546       case LibFunc_fabs:
7547       case LibFunc_fabsf:
7548       case LibFunc_fabsl:
7549         if (visitUnaryFloatCall(I, ISD::FABS))
7550           return;
7551         break;
7552       case LibFunc_fmin:
7553       case LibFunc_fminf:
7554       case LibFunc_fminl:
7555         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7556           return;
7557         break;
7558       case LibFunc_fmax:
7559       case LibFunc_fmaxf:
7560       case LibFunc_fmaxl:
7561         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7562           return;
7563         break;
7564       case LibFunc_sin:
7565       case LibFunc_sinf:
7566       case LibFunc_sinl:
7567         if (visitUnaryFloatCall(I, ISD::FSIN))
7568           return;
7569         break;
7570       case LibFunc_cos:
7571       case LibFunc_cosf:
7572       case LibFunc_cosl:
7573         if (visitUnaryFloatCall(I, ISD::FCOS))
7574           return;
7575         break;
7576       case LibFunc_sqrt:
7577       case LibFunc_sqrtf:
7578       case LibFunc_sqrtl:
7579       case LibFunc_sqrt_finite:
7580       case LibFunc_sqrtf_finite:
7581       case LibFunc_sqrtl_finite:
7582         if (visitUnaryFloatCall(I, ISD::FSQRT))
7583           return;
7584         break;
7585       case LibFunc_floor:
7586       case LibFunc_floorf:
7587       case LibFunc_floorl:
7588         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7589           return;
7590         break;
7591       case LibFunc_nearbyint:
7592       case LibFunc_nearbyintf:
7593       case LibFunc_nearbyintl:
7594         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7595           return;
7596         break;
7597       case LibFunc_ceil:
7598       case LibFunc_ceilf:
7599       case LibFunc_ceill:
7600         if (visitUnaryFloatCall(I, ISD::FCEIL))
7601           return;
7602         break;
7603       case LibFunc_rint:
7604       case LibFunc_rintf:
7605       case LibFunc_rintl:
7606         if (visitUnaryFloatCall(I, ISD::FRINT))
7607           return;
7608         break;
7609       case LibFunc_round:
7610       case LibFunc_roundf:
7611       case LibFunc_roundl:
7612         if (visitUnaryFloatCall(I, ISD::FROUND))
7613           return;
7614         break;
7615       case LibFunc_trunc:
7616       case LibFunc_truncf:
7617       case LibFunc_truncl:
7618         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7619           return;
7620         break;
7621       case LibFunc_log2:
7622       case LibFunc_log2f:
7623       case LibFunc_log2l:
7624         if (visitUnaryFloatCall(I, ISD::FLOG2))
7625           return;
7626         break;
7627       case LibFunc_exp2:
7628       case LibFunc_exp2f:
7629       case LibFunc_exp2l:
7630         if (visitUnaryFloatCall(I, ISD::FEXP2))
7631           return;
7632         break;
7633       case LibFunc_memcmp:
7634         if (visitMemCmpCall(I))
7635           return;
7636         break;
7637       case LibFunc_mempcpy:
7638         if (visitMemPCpyCall(I))
7639           return;
7640         break;
7641       case LibFunc_memchr:
7642         if (visitMemChrCall(I))
7643           return;
7644         break;
7645       case LibFunc_strcpy:
7646         if (visitStrCpyCall(I, false))
7647           return;
7648         break;
7649       case LibFunc_stpcpy:
7650         if (visitStrCpyCall(I, true))
7651           return;
7652         break;
7653       case LibFunc_strcmp:
7654         if (visitStrCmpCall(I))
7655           return;
7656         break;
7657       case LibFunc_strlen:
7658         if (visitStrLenCall(I))
7659           return;
7660         break;
7661       case LibFunc_strnlen:
7662         if (visitStrNLenCall(I))
7663           return;
7664         break;
7665       }
7666     }
7667   }
7668 
7669   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7670   // have to do anything here to lower funclet bundles.
7671   // CFGuardTarget bundles are lowered in LowerCallTo.
7672   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7673                                         LLVMContext::OB_funclet,
7674                                         LLVMContext::OB_cfguardtarget}) &&
7675          "Cannot lower calls with arbitrary operand bundles!");
7676 
7677   SDValue Callee = getValue(I.getCalledValue());
7678 
7679   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7680     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7681   else
7682     // Check if we can potentially perform a tail call. More detailed checking
7683     // is be done within LowerCallTo, after more information about the call is
7684     // known.
7685     LowerCallTo(&I, Callee, I.isTailCall());
7686 }
7687 
7688 namespace {
7689 
7690 /// AsmOperandInfo - This contains information for each constraint that we are
7691 /// lowering.
7692 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7693 public:
7694   /// CallOperand - If this is the result output operand or a clobber
7695   /// this is null, otherwise it is the incoming operand to the CallInst.
7696   /// This gets modified as the asm is processed.
7697   SDValue CallOperand;
7698 
7699   /// AssignedRegs - If this is a register or register class operand, this
7700   /// contains the set of register corresponding to the operand.
7701   RegsForValue AssignedRegs;
7702 
7703   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7704     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7705   }
7706 
7707   /// Whether or not this operand accesses memory
7708   bool hasMemory(const TargetLowering &TLI) const {
7709     // Indirect operand accesses access memory.
7710     if (isIndirect)
7711       return true;
7712 
7713     for (const auto &Code : Codes)
7714       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7715         return true;
7716 
7717     return false;
7718   }
7719 
7720   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7721   /// corresponds to.  If there is no Value* for this operand, it returns
7722   /// MVT::Other.
7723   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7724                            const DataLayout &DL) const {
7725     if (!CallOperandVal) return MVT::Other;
7726 
7727     if (isa<BasicBlock>(CallOperandVal))
7728       return TLI.getPointerTy(DL);
7729 
7730     llvm::Type *OpTy = CallOperandVal->getType();
7731 
7732     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7733     // If this is an indirect operand, the operand is a pointer to the
7734     // accessed type.
7735     if (isIndirect) {
7736       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7737       if (!PtrTy)
7738         report_fatal_error("Indirect operand for inline asm not a pointer!");
7739       OpTy = PtrTy->getElementType();
7740     }
7741 
7742     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7743     if (StructType *STy = dyn_cast<StructType>(OpTy))
7744       if (STy->getNumElements() == 1)
7745         OpTy = STy->getElementType(0);
7746 
7747     // If OpTy is not a single value, it may be a struct/union that we
7748     // can tile with integers.
7749     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7750       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7751       switch (BitSize) {
7752       default: break;
7753       case 1:
7754       case 8:
7755       case 16:
7756       case 32:
7757       case 64:
7758       case 128:
7759         OpTy = IntegerType::get(Context, BitSize);
7760         break;
7761       }
7762     }
7763 
7764     return TLI.getValueType(DL, OpTy, true);
7765   }
7766 };
7767 
7768 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7769 
7770 } // end anonymous namespace
7771 
7772 /// Make sure that the output operand \p OpInfo and its corresponding input
7773 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7774 /// out).
7775 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7776                                SDISelAsmOperandInfo &MatchingOpInfo,
7777                                SelectionDAG &DAG) {
7778   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7779     return;
7780 
7781   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7782   const auto &TLI = DAG.getTargetLoweringInfo();
7783 
7784   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7785       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7786                                        OpInfo.ConstraintVT);
7787   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7788       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7789                                        MatchingOpInfo.ConstraintVT);
7790   if ((OpInfo.ConstraintVT.isInteger() !=
7791        MatchingOpInfo.ConstraintVT.isInteger()) ||
7792       (MatchRC.second != InputRC.second)) {
7793     // FIXME: error out in a more elegant fashion
7794     report_fatal_error("Unsupported asm: input constraint"
7795                        " with a matching output constraint of"
7796                        " incompatible type!");
7797   }
7798   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7799 }
7800 
7801 /// Get a direct memory input to behave well as an indirect operand.
7802 /// This may introduce stores, hence the need for a \p Chain.
7803 /// \return The (possibly updated) chain.
7804 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7805                                         SDISelAsmOperandInfo &OpInfo,
7806                                         SelectionDAG &DAG) {
7807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7808 
7809   // If we don't have an indirect input, put it in the constpool if we can,
7810   // otherwise spill it to a stack slot.
7811   // TODO: This isn't quite right. We need to handle these according to
7812   // the addressing mode that the constraint wants. Also, this may take
7813   // an additional register for the computation and we don't want that
7814   // either.
7815 
7816   // If the operand is a float, integer, or vector constant, spill to a
7817   // constant pool entry to get its address.
7818   const Value *OpVal = OpInfo.CallOperandVal;
7819   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7820       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7821     OpInfo.CallOperand = DAG.getConstantPool(
7822         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7823     return Chain;
7824   }
7825 
7826   // Otherwise, create a stack slot and emit a store to it before the asm.
7827   Type *Ty = OpVal->getType();
7828   auto &DL = DAG.getDataLayout();
7829   uint64_t TySize = DL.getTypeAllocSize(Ty);
7830   unsigned Align = DL.getPrefTypeAlignment(Ty);
7831   MachineFunction &MF = DAG.getMachineFunction();
7832   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7833   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7834   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7835                             MachinePointerInfo::getFixedStack(MF, SSFI),
7836                             TLI.getMemValueType(DL, Ty));
7837   OpInfo.CallOperand = StackSlot;
7838 
7839   return Chain;
7840 }
7841 
7842 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7843 /// specified operand.  We prefer to assign virtual registers, to allow the
7844 /// register allocator to handle the assignment process.  However, if the asm
7845 /// uses features that we can't model on machineinstrs, we have SDISel do the
7846 /// allocation.  This produces generally horrible, but correct, code.
7847 ///
7848 ///   OpInfo describes the operand
7849 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7850 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7851                                  SDISelAsmOperandInfo &OpInfo,
7852                                  SDISelAsmOperandInfo &RefOpInfo) {
7853   LLVMContext &Context = *DAG.getContext();
7854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7855 
7856   MachineFunction &MF = DAG.getMachineFunction();
7857   SmallVector<unsigned, 4> Regs;
7858   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7859 
7860   // No work to do for memory operations.
7861   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7862     return;
7863 
7864   // If this is a constraint for a single physreg, or a constraint for a
7865   // register class, find it.
7866   unsigned AssignedReg;
7867   const TargetRegisterClass *RC;
7868   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7869       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7870   // RC is unset only on failure. Return immediately.
7871   if (!RC)
7872     return;
7873 
7874   // Get the actual register value type.  This is important, because the user
7875   // may have asked for (e.g.) the AX register in i32 type.  We need to
7876   // remember that AX is actually i16 to get the right extension.
7877   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7878 
7879   if (OpInfo.ConstraintVT != MVT::Other) {
7880     // If this is an FP operand in an integer register (or visa versa), or more
7881     // generally if the operand value disagrees with the register class we plan
7882     // to stick it in, fix the operand type.
7883     //
7884     // If this is an input value, the bitcast to the new type is done now.
7885     // Bitcast for output value is done at the end of visitInlineAsm().
7886     if ((OpInfo.Type == InlineAsm::isOutput ||
7887          OpInfo.Type == InlineAsm::isInput) &&
7888         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7889       // Try to convert to the first EVT that the reg class contains.  If the
7890       // types are identical size, use a bitcast to convert (e.g. two differing
7891       // vector types).  Note: output bitcast is done at the end of
7892       // visitInlineAsm().
7893       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7894         // Exclude indirect inputs while they are unsupported because the code
7895         // to perform the load is missing and thus OpInfo.CallOperand still
7896         // refers to the input address rather than the pointed-to value.
7897         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7898           OpInfo.CallOperand =
7899               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7900         OpInfo.ConstraintVT = RegVT;
7901         // If the operand is an FP value and we want it in integer registers,
7902         // use the corresponding integer type. This turns an f64 value into
7903         // i64, which can be passed with two i32 values on a 32-bit machine.
7904       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7905         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7906         if (OpInfo.Type == InlineAsm::isInput)
7907           OpInfo.CallOperand =
7908               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7909         OpInfo.ConstraintVT = VT;
7910       }
7911     }
7912   }
7913 
7914   // No need to allocate a matching input constraint since the constraint it's
7915   // matching to has already been allocated.
7916   if (OpInfo.isMatchingInputConstraint())
7917     return;
7918 
7919   EVT ValueVT = OpInfo.ConstraintVT;
7920   if (OpInfo.ConstraintVT == MVT::Other)
7921     ValueVT = RegVT;
7922 
7923   // Initialize NumRegs.
7924   unsigned NumRegs = 1;
7925   if (OpInfo.ConstraintVT != MVT::Other)
7926     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7927 
7928   // If this is a constraint for a specific physical register, like {r17},
7929   // assign it now.
7930 
7931   // If this associated to a specific register, initialize iterator to correct
7932   // place. If virtual, make sure we have enough registers
7933 
7934   // Initialize iterator if necessary
7935   TargetRegisterClass::iterator I = RC->begin();
7936   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7937 
7938   // Do not check for single registers.
7939   if (AssignedReg) {
7940       for (; *I != AssignedReg; ++I)
7941         assert(I != RC->end() && "AssignedReg should be member of RC");
7942   }
7943 
7944   for (; NumRegs; --NumRegs, ++I) {
7945     assert(I != RC->end() && "Ran out of registers to allocate!");
7946     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7947     Regs.push_back(R);
7948   }
7949 
7950   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7951 }
7952 
7953 static unsigned
7954 findMatchingInlineAsmOperand(unsigned OperandNo,
7955                              const std::vector<SDValue> &AsmNodeOperands) {
7956   // Scan until we find the definition we already emitted of this operand.
7957   unsigned CurOp = InlineAsm::Op_FirstOperand;
7958   for (; OperandNo; --OperandNo) {
7959     // Advance to the next operand.
7960     unsigned OpFlag =
7961         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7962     assert((InlineAsm::isRegDefKind(OpFlag) ||
7963             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7964             InlineAsm::isMemKind(OpFlag)) &&
7965            "Skipped past definitions?");
7966     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7967   }
7968   return CurOp;
7969 }
7970 
7971 namespace {
7972 
7973 class ExtraFlags {
7974   unsigned Flags = 0;
7975 
7976 public:
7977   explicit ExtraFlags(ImmutableCallSite CS) {
7978     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7979     if (IA->hasSideEffects())
7980       Flags |= InlineAsm::Extra_HasSideEffects;
7981     if (IA->isAlignStack())
7982       Flags |= InlineAsm::Extra_IsAlignStack;
7983     if (CS.isConvergent())
7984       Flags |= InlineAsm::Extra_IsConvergent;
7985     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7986   }
7987 
7988   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7989     // Ideally, we would only check against memory constraints.  However, the
7990     // meaning of an Other constraint can be target-specific and we can't easily
7991     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7992     // for Other constraints as well.
7993     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7994         OpInfo.ConstraintType == TargetLowering::C_Other) {
7995       if (OpInfo.Type == InlineAsm::isInput)
7996         Flags |= InlineAsm::Extra_MayLoad;
7997       else if (OpInfo.Type == InlineAsm::isOutput)
7998         Flags |= InlineAsm::Extra_MayStore;
7999       else if (OpInfo.Type == InlineAsm::isClobber)
8000         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8001     }
8002   }
8003 
8004   unsigned get() const { return Flags; }
8005 };
8006 
8007 } // end anonymous namespace
8008 
8009 /// visitInlineAsm - Handle a call to an InlineAsm object.
8010 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8011   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8012 
8013   /// ConstraintOperands - Information about all of the constraints.
8014   SDISelAsmOperandInfoVector ConstraintOperands;
8015 
8016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8017   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8018       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8019 
8020   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8021   // AsmDialect, MayLoad, MayStore).
8022   bool HasSideEffect = IA->hasSideEffects();
8023   ExtraFlags ExtraInfo(CS);
8024 
8025   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8026   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8027   for (auto &T : TargetConstraints) {
8028     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8029     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8030 
8031     // Compute the value type for each operand.
8032     if (OpInfo.Type == InlineAsm::isInput ||
8033         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8034       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8035 
8036       // Process the call argument. BasicBlocks are labels, currently appearing
8037       // only in asm's.
8038       const Instruction *I = CS.getInstruction();
8039       if (isa<CallBrInst>(I) &&
8040           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8041                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8042         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8043         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8044         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8045       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8046         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8047       } else {
8048         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8049       }
8050 
8051       OpInfo.ConstraintVT =
8052           OpInfo
8053               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8054               .getSimpleVT();
8055     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8056       // The return value of the call is this value.  As such, there is no
8057       // corresponding argument.
8058       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8059       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8060         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8061             DAG.getDataLayout(), STy->getElementType(ResNo));
8062       } else {
8063         assert(ResNo == 0 && "Asm only has one result!");
8064         OpInfo.ConstraintVT =
8065             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8066       }
8067       ++ResNo;
8068     } else {
8069       OpInfo.ConstraintVT = MVT::Other;
8070     }
8071 
8072     if (!HasSideEffect)
8073       HasSideEffect = OpInfo.hasMemory(TLI);
8074 
8075     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8076     // FIXME: Could we compute this on OpInfo rather than T?
8077 
8078     // Compute the constraint code and ConstraintType to use.
8079     TLI.ComputeConstraintToUse(T, SDValue());
8080 
8081     if (T.ConstraintType == TargetLowering::C_Immediate &&
8082         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8083       // We've delayed emitting a diagnostic like the "n" constraint because
8084       // inlining could cause an integer showing up.
8085       return emitInlineAsmError(
8086           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8087                   "integer constant expression");
8088 
8089     ExtraInfo.update(T);
8090   }
8091 
8092 
8093   // We won't need to flush pending loads if this asm doesn't touch
8094   // memory and is nonvolatile.
8095   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8096 
8097   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8098   if (IsCallBr) {
8099     // If this is a callbr we need to flush pending exports since inlineasm_br
8100     // is a terminator. We need to do this before nodes are glued to
8101     // the inlineasm_br node.
8102     Chain = getControlRoot();
8103   }
8104 
8105   // Second pass over the constraints: compute which constraint option to use.
8106   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8107     // If this is an output operand with a matching input operand, look up the
8108     // matching input. If their types mismatch, e.g. one is an integer, the
8109     // other is floating point, or their sizes are different, flag it as an
8110     // error.
8111     if (OpInfo.hasMatchingInput()) {
8112       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8113       patchMatchingInput(OpInfo, Input, DAG);
8114     }
8115 
8116     // Compute the constraint code and ConstraintType to use.
8117     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8118 
8119     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8120         OpInfo.Type == InlineAsm::isClobber)
8121       continue;
8122 
8123     // If this is a memory input, and if the operand is not indirect, do what we
8124     // need to provide an address for the memory input.
8125     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8126         !OpInfo.isIndirect) {
8127       assert((OpInfo.isMultipleAlternative ||
8128               (OpInfo.Type == InlineAsm::isInput)) &&
8129              "Can only indirectify direct input operands!");
8130 
8131       // Memory operands really want the address of the value.
8132       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8133 
8134       // There is no longer a Value* corresponding to this operand.
8135       OpInfo.CallOperandVal = nullptr;
8136 
8137       // It is now an indirect operand.
8138       OpInfo.isIndirect = true;
8139     }
8140 
8141   }
8142 
8143   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8144   std::vector<SDValue> AsmNodeOperands;
8145   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8146   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8147       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8148 
8149   // If we have a !srcloc metadata node associated with it, we want to attach
8150   // this to the ultimately generated inline asm machineinstr.  To do this, we
8151   // pass in the third operand as this (potentially null) inline asm MDNode.
8152   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8153   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8154 
8155   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8156   // bits as operand 3.
8157   AsmNodeOperands.push_back(DAG.getTargetConstant(
8158       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8159 
8160   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8161   // this, assign virtual and physical registers for inputs and otput.
8162   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8163     // Assign Registers.
8164     SDISelAsmOperandInfo &RefOpInfo =
8165         OpInfo.isMatchingInputConstraint()
8166             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8167             : OpInfo;
8168     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8169 
8170     switch (OpInfo.Type) {
8171     case InlineAsm::isOutput:
8172       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8173         unsigned ConstraintID =
8174             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8175         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8176                "Failed to convert memory constraint code to constraint id.");
8177 
8178         // Add information to the INLINEASM node to know about this output.
8179         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8180         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8181         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8182                                                         MVT::i32));
8183         AsmNodeOperands.push_back(OpInfo.CallOperand);
8184       } else {
8185         // Otherwise, this outputs to a register (directly for C_Register /
8186         // C_RegisterClass, and a target-defined fashion for
8187         // C_Immediate/C_Other). Find a register that we can use.
8188         if (OpInfo.AssignedRegs.Regs.empty()) {
8189           emitInlineAsmError(
8190               CS, "couldn't allocate output register for constraint '" +
8191                       Twine(OpInfo.ConstraintCode) + "'");
8192           return;
8193         }
8194 
8195         // Add information to the INLINEASM node to know that this register is
8196         // set.
8197         OpInfo.AssignedRegs.AddInlineAsmOperands(
8198             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8199                                   : InlineAsm::Kind_RegDef,
8200             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8201       }
8202       break;
8203 
8204     case InlineAsm::isInput: {
8205       SDValue InOperandVal = OpInfo.CallOperand;
8206 
8207       if (OpInfo.isMatchingInputConstraint()) {
8208         // If this is required to match an output register we have already set,
8209         // just use its register.
8210         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8211                                                   AsmNodeOperands);
8212         unsigned OpFlag =
8213           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8214         if (InlineAsm::isRegDefKind(OpFlag) ||
8215             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8216           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8217           if (OpInfo.isIndirect) {
8218             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8219             emitInlineAsmError(CS, "inline asm not supported yet:"
8220                                    " don't know how to handle tied "
8221                                    "indirect register inputs");
8222             return;
8223           }
8224 
8225           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8226           SmallVector<unsigned, 4> Regs;
8227 
8228           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8229             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8230             MachineRegisterInfo &RegInfo =
8231                 DAG.getMachineFunction().getRegInfo();
8232             for (unsigned i = 0; i != NumRegs; ++i)
8233               Regs.push_back(RegInfo.createVirtualRegister(RC));
8234           } else {
8235             emitInlineAsmError(CS, "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,
8245                                     CS.getInstruction());
8246           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8247                                            true, OpInfo.getMatchedOperand(), dl,
8248                                            DAG, AsmNodeOperands);
8249           break;
8250         }
8251 
8252         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8253         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8254                "Unexpected number of operands");
8255         // Add information to the INLINEASM node to know about this input.
8256         // See InlineAsm.h isUseOperandTiedToDef.
8257         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8258         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8259                                                     OpInfo.getMatchedOperand());
8260         AsmNodeOperands.push_back(DAG.getTargetConstant(
8261             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8262         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8263         break;
8264       }
8265 
8266       // Treat indirect 'X' constraint as memory.
8267       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8268           OpInfo.isIndirect)
8269         OpInfo.ConstraintType = TargetLowering::C_Memory;
8270 
8271       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8272           OpInfo.ConstraintType == TargetLowering::C_Other) {
8273         std::vector<SDValue> Ops;
8274         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8275                                           Ops, DAG);
8276         if (Ops.empty()) {
8277           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8278             if (isa<ConstantSDNode>(InOperandVal)) {
8279               emitInlineAsmError(CS, "value out of range for constraint '" +
8280                                  Twine(OpInfo.ConstraintCode) + "'");
8281               return;
8282             }
8283 
8284           emitInlineAsmError(CS, "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             CS, "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(CS, "couldn't allocate input reg for constraint '" +
8335                                    Twine(OpInfo.ConstraintCode) + "'");
8336         return;
8337       }
8338 
8339       SDLoc dl = getCurSDLoc();
8340 
8341       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8342                                         Chain, &Flag, CS.getInstruction());
8343 
8344       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8345                                                dl, DAG, AsmNodeOperands);
8346       break;
8347     }
8348     case InlineAsm::isClobber:
8349       // Add the clobbered value to the operand list, so that the register
8350       // allocator is aware that the physreg got clobbered.
8351       if (!OpInfo.AssignedRegs.Regs.empty())
8352         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8353                                                  false, 0, getCurSDLoc(), DAG,
8354                                                  AsmNodeOperands);
8355       break;
8356     }
8357   }
8358 
8359   // Finish up input operands.  Set the input chain and add the flag last.
8360   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8361   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8362 
8363   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8364   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8365                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8366   Flag = Chain.getValue(1);
8367 
8368   // Do additional work to generate outputs.
8369 
8370   SmallVector<EVT, 1> ResultVTs;
8371   SmallVector<SDValue, 1> ResultValues;
8372   SmallVector<SDValue, 8> OutChains;
8373 
8374   llvm::Type *CSResultType = CS.getType();
8375   ArrayRef<Type *> ResultTypes;
8376   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8377     ResultTypes = StructResult->elements();
8378   else if (!CSResultType->isVoidTy())
8379     ResultTypes = makeArrayRef(CSResultType);
8380 
8381   auto CurResultType = ResultTypes.begin();
8382   auto handleRegAssign = [&](SDValue V) {
8383     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8384     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8385     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8386     ++CurResultType;
8387     // If the type of the inline asm call site return value is different but has
8388     // same size as the type of the asm output bitcast it.  One example of this
8389     // is for vectors with different width / number of elements.  This can
8390     // happen for register classes that can contain multiple different value
8391     // types.  The preg or vreg allocated may not have the same VT as was
8392     // expected.
8393     //
8394     // This can also happen for a return value that disagrees with the register
8395     // class it is put in, eg. a double in a general-purpose register on a
8396     // 32-bit machine.
8397     if (ResultVT != V.getValueType() &&
8398         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8399       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8400     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8401              V.getValueType().isInteger()) {
8402       // If a result value was tied to an input value, the computed result
8403       // may have a wider width than the expected result.  Extract the
8404       // relevant portion.
8405       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8406     }
8407     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8408     ResultVTs.push_back(ResultVT);
8409     ResultValues.push_back(V);
8410   };
8411 
8412   // Deal with output operands.
8413   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8414     if (OpInfo.Type == InlineAsm::isOutput) {
8415       SDValue Val;
8416       // Skip trivial output operands.
8417       if (OpInfo.AssignedRegs.Regs.empty())
8418         continue;
8419 
8420       switch (OpInfo.ConstraintType) {
8421       case TargetLowering::C_Register:
8422       case TargetLowering::C_RegisterClass:
8423         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8424             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8425         break;
8426       case TargetLowering::C_Immediate:
8427       case TargetLowering::C_Other:
8428         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8429                                               OpInfo, DAG);
8430         break;
8431       case TargetLowering::C_Memory:
8432         break; // Already handled.
8433       case TargetLowering::C_Unknown:
8434         assert(false && "Unexpected unknown constraint");
8435       }
8436 
8437       // Indirect output manifest as stores. Record output chains.
8438       if (OpInfo.isIndirect) {
8439         const Value *Ptr = OpInfo.CallOperandVal;
8440         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8441         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8442                                      MachinePointerInfo(Ptr));
8443         OutChains.push_back(Store);
8444       } else {
8445         // generate CopyFromRegs to associated registers.
8446         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8447         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8448           for (const SDValue &V : Val->op_values())
8449             handleRegAssign(V);
8450         } else
8451           handleRegAssign(Val);
8452       }
8453     }
8454   }
8455 
8456   // Set results.
8457   if (!ResultValues.empty()) {
8458     assert(CurResultType == ResultTypes.end() &&
8459            "Mismatch in number of ResultTypes");
8460     assert(ResultValues.size() == ResultTypes.size() &&
8461            "Mismatch in number of output operands in asm result");
8462 
8463     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8464                             DAG.getVTList(ResultVTs), ResultValues);
8465     setValue(CS.getInstruction(), V);
8466   }
8467 
8468   // Collect store chains.
8469   if (!OutChains.empty())
8470     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8471 
8472   // Only Update Root if inline assembly has a memory effect.
8473   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8474     DAG.setRoot(Chain);
8475 }
8476 
8477 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8478                                              const Twine &Message) {
8479   LLVMContext &Ctx = *DAG.getContext();
8480   Ctx.emitError(CS.getInstruction(), Message);
8481 
8482   // Make sure we leave the DAG in a valid state
8483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8484   SmallVector<EVT, 1> ValueVTs;
8485   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8486 
8487   if (ValueVTs.empty())
8488     return;
8489 
8490   SmallVector<SDValue, 1> Ops;
8491   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8492     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8493 
8494   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8495 }
8496 
8497 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8498   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8499                           MVT::Other, getRoot(),
8500                           getValue(I.getArgOperand(0)),
8501                           DAG.getSrcValue(I.getArgOperand(0))));
8502 }
8503 
8504 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8506   const DataLayout &DL = DAG.getDataLayout();
8507   SDValue V = DAG.getVAArg(
8508       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8509       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8510       DL.getABITypeAlignment(I.getType()));
8511   DAG.setRoot(V.getValue(1));
8512 
8513   if (I.getType()->isPointerTy())
8514     V = DAG.getPtrExtOrTrunc(
8515         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8516   setValue(&I, V);
8517 }
8518 
8519 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8520   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8521                           MVT::Other, getRoot(),
8522                           getValue(I.getArgOperand(0)),
8523                           DAG.getSrcValue(I.getArgOperand(0))));
8524 }
8525 
8526 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8527   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8528                           MVT::Other, getRoot(),
8529                           getValue(I.getArgOperand(0)),
8530                           getValue(I.getArgOperand(1)),
8531                           DAG.getSrcValue(I.getArgOperand(0)),
8532                           DAG.getSrcValue(I.getArgOperand(1))));
8533 }
8534 
8535 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8536                                                     const Instruction &I,
8537                                                     SDValue Op) {
8538   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8539   if (!Range)
8540     return Op;
8541 
8542   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8543   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8544     return Op;
8545 
8546   APInt Lo = CR.getUnsignedMin();
8547   if (!Lo.isMinValue())
8548     return Op;
8549 
8550   APInt Hi = CR.getUnsignedMax();
8551   unsigned Bits = std::max(Hi.getActiveBits(),
8552                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8553 
8554   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8555 
8556   SDLoc SL = getCurSDLoc();
8557 
8558   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8559                              DAG.getValueType(SmallVT));
8560   unsigned NumVals = Op.getNode()->getNumValues();
8561   if (NumVals == 1)
8562     return ZExt;
8563 
8564   SmallVector<SDValue, 4> Ops;
8565 
8566   Ops.push_back(ZExt);
8567   for (unsigned I = 1; I != NumVals; ++I)
8568     Ops.push_back(Op.getValue(I));
8569 
8570   return DAG.getMergeValues(Ops, SL);
8571 }
8572 
8573 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8574 /// the call being lowered.
8575 ///
8576 /// This is a helper for lowering intrinsics that follow a target calling
8577 /// convention or require stack pointer adjustment. Only a subset of the
8578 /// intrinsic's operands need to participate in the calling convention.
8579 void SelectionDAGBuilder::populateCallLoweringInfo(
8580     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8581     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8582     bool IsPatchPoint) {
8583   TargetLowering::ArgListTy Args;
8584   Args.reserve(NumArgs);
8585 
8586   // Populate the argument list.
8587   // Attributes for args start at offset 1, after the return attribute.
8588   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8589        ArgI != ArgE; ++ArgI) {
8590     const Value *V = Call->getOperand(ArgI);
8591 
8592     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8593 
8594     TargetLowering::ArgListEntry Entry;
8595     Entry.Node = getValue(V);
8596     Entry.Ty = V->getType();
8597     Entry.setAttributes(Call, ArgI);
8598     Args.push_back(Entry);
8599   }
8600 
8601   CLI.setDebugLoc(getCurSDLoc())
8602       .setChain(getRoot())
8603       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8604       .setDiscardResult(Call->use_empty())
8605       .setIsPatchPoint(IsPatchPoint);
8606 }
8607 
8608 /// Add a stack map intrinsic call's live variable operands to a stackmap
8609 /// or patchpoint target node's operand list.
8610 ///
8611 /// Constants are converted to TargetConstants purely as an optimization to
8612 /// avoid constant materialization and register allocation.
8613 ///
8614 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8615 /// generate addess computation nodes, and so FinalizeISel can convert the
8616 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8617 /// address materialization and register allocation, but may also be required
8618 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8619 /// alloca in the entry block, then the runtime may assume that the alloca's
8620 /// StackMap location can be read immediately after compilation and that the
8621 /// location is valid at any point during execution (this is similar to the
8622 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8623 /// only available in a register, then the runtime would need to trap when
8624 /// execution reaches the StackMap in order to read the alloca's location.
8625 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8626                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8627                                 SelectionDAGBuilder &Builder) {
8628   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8629     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8631       Ops.push_back(
8632         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8633       Ops.push_back(
8634         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8635     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8636       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8637       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8638           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8639     } else
8640       Ops.push_back(OpVal);
8641   }
8642 }
8643 
8644 /// Lower llvm.experimental.stackmap directly to its target opcode.
8645 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8646   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8647   //                                  [live variables...])
8648 
8649   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8650 
8651   SDValue Chain, InFlag, Callee, NullPtr;
8652   SmallVector<SDValue, 32> Ops;
8653 
8654   SDLoc DL = getCurSDLoc();
8655   Callee = getValue(CI.getCalledValue());
8656   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8657 
8658   // The stackmap intrinsic only records the live variables (the arguments
8659   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8660   // intrinsic, this won't be lowered to a function call. This means we don't
8661   // have to worry about calling conventions and target specific lowering code.
8662   // Instead we perform the call lowering right here.
8663   //
8664   // chain, flag = CALLSEQ_START(chain, 0, 0)
8665   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8666   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8667   //
8668   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8669   InFlag = Chain.getValue(1);
8670 
8671   // Add the <id> and <numBytes> constants.
8672   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8673   Ops.push_back(DAG.getTargetConstant(
8674                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8675   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8676   Ops.push_back(DAG.getTargetConstant(
8677                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8678                   MVT::i32));
8679 
8680   // Push live variables for the stack map.
8681   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8682 
8683   // We are not pushing any register mask info here on the operands list,
8684   // because the stackmap doesn't clobber anything.
8685 
8686   // Push the chain and the glue flag.
8687   Ops.push_back(Chain);
8688   Ops.push_back(InFlag);
8689 
8690   // Create the STACKMAP node.
8691   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8692   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8693   Chain = SDValue(SM, 0);
8694   InFlag = Chain.getValue(1);
8695 
8696   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8697 
8698   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8699 
8700   // Set the root to the target-lowered call chain.
8701   DAG.setRoot(Chain);
8702 
8703   // Inform the Frame Information that we have a stackmap in this function.
8704   FuncInfo.MF->getFrameInfo().setHasStackMap();
8705 }
8706 
8707 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8708 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8709                                           const BasicBlock *EHPadBB) {
8710   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8711   //                                                 i32 <numBytes>,
8712   //                                                 i8* <target>,
8713   //                                                 i32 <numArgs>,
8714   //                                                 [Args...],
8715   //                                                 [live variables...])
8716 
8717   CallingConv::ID CC = CS.getCallingConv();
8718   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8719   bool HasDef = !CS->getType()->isVoidTy();
8720   SDLoc dl = getCurSDLoc();
8721   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8722 
8723   // Handle immediate and symbolic callees.
8724   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8725     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8726                                    /*isTarget=*/true);
8727   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8728     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8729                                          SDLoc(SymbolicCallee),
8730                                          SymbolicCallee->getValueType(0));
8731 
8732   // Get the real number of arguments participating in the call <numArgs>
8733   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8734   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8735 
8736   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8737   // Intrinsics include all meta-operands up to but not including CC.
8738   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8739   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8740          "Not enough arguments provided to the patchpoint intrinsic");
8741 
8742   // For AnyRegCC the arguments are lowered later on manually.
8743   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8744   Type *ReturnTy =
8745     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8746 
8747   TargetLowering::CallLoweringInfo CLI(DAG);
8748   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8749                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8750   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8751 
8752   SDNode *CallEnd = Result.second.getNode();
8753   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8754     CallEnd = CallEnd->getOperand(0).getNode();
8755 
8756   /// Get a call instruction from the call sequence chain.
8757   /// Tail calls are not allowed.
8758   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8759          "Expected a callseq node.");
8760   SDNode *Call = CallEnd->getOperand(0).getNode();
8761   bool HasGlue = Call->getGluedNode();
8762 
8763   // Replace the target specific call node with the patchable intrinsic.
8764   SmallVector<SDValue, 8> Ops;
8765 
8766   // Add the <id> and <numBytes> constants.
8767   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8768   Ops.push_back(DAG.getTargetConstant(
8769                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8770   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8771   Ops.push_back(DAG.getTargetConstant(
8772                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8773                   MVT::i32));
8774 
8775   // Add the callee.
8776   Ops.push_back(Callee);
8777 
8778   // Adjust <numArgs> to account for any arguments that have been passed on the
8779   // stack instead.
8780   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8781   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8782   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8783   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8784 
8785   // Add the calling convention
8786   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8787 
8788   // Add the arguments we omitted previously. The register allocator should
8789   // place these in any free register.
8790   if (IsAnyRegCC)
8791     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8792       Ops.push_back(getValue(CS.getArgument(i)));
8793 
8794   // Push the arguments from the call instruction up to the register mask.
8795   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8796   Ops.append(Call->op_begin() + 2, e);
8797 
8798   // Push live variables for the stack map.
8799   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8800 
8801   // Push the register mask info.
8802   if (HasGlue)
8803     Ops.push_back(*(Call->op_end()-2));
8804   else
8805     Ops.push_back(*(Call->op_end()-1));
8806 
8807   // Push the chain (this is originally the first operand of the call, but
8808   // becomes now the last or second to last operand).
8809   Ops.push_back(*(Call->op_begin()));
8810 
8811   // Push the glue flag (last operand).
8812   if (HasGlue)
8813     Ops.push_back(*(Call->op_end()-1));
8814 
8815   SDVTList NodeTys;
8816   if (IsAnyRegCC && HasDef) {
8817     // Create the return types based on the intrinsic definition
8818     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8819     SmallVector<EVT, 3> ValueVTs;
8820     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8821     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8822 
8823     // There is always a chain and a glue type at the end
8824     ValueVTs.push_back(MVT::Other);
8825     ValueVTs.push_back(MVT::Glue);
8826     NodeTys = DAG.getVTList(ValueVTs);
8827   } else
8828     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8829 
8830   // Replace the target specific call node with a PATCHPOINT node.
8831   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8832                                          dl, NodeTys, Ops);
8833 
8834   // Update the NodeMap.
8835   if (HasDef) {
8836     if (IsAnyRegCC)
8837       setValue(CS.getInstruction(), SDValue(MN, 0));
8838     else
8839       setValue(CS.getInstruction(), Result.first);
8840   }
8841 
8842   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8843   // call sequence. Furthermore the location of the chain and glue can change
8844   // when the AnyReg calling convention is used and the intrinsic returns a
8845   // value.
8846   if (IsAnyRegCC && HasDef) {
8847     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8848     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8849     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8850   } else
8851     DAG.ReplaceAllUsesWith(Call, MN);
8852   DAG.DeleteNode(Call);
8853 
8854   // Inform the Frame Information that we have a patchpoint in this function.
8855   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8856 }
8857 
8858 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8859                                             unsigned Intrinsic) {
8860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8861   SDValue Op1 = getValue(I.getArgOperand(0));
8862   SDValue Op2;
8863   if (I.getNumArgOperands() > 1)
8864     Op2 = getValue(I.getArgOperand(1));
8865   SDLoc dl = getCurSDLoc();
8866   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8867   SDValue Res;
8868   FastMathFlags FMF;
8869   if (isa<FPMathOperator>(I))
8870     FMF = I.getFastMathFlags();
8871 
8872   switch (Intrinsic) {
8873   case Intrinsic::experimental_vector_reduce_v2_fadd:
8874     if (FMF.allowReassoc())
8875       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8876                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8877     else
8878       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8879     break;
8880   case Intrinsic::experimental_vector_reduce_v2_fmul:
8881     if (FMF.allowReassoc())
8882       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8883                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8884     else
8885       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8886     break;
8887   case Intrinsic::experimental_vector_reduce_add:
8888     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8889     break;
8890   case Intrinsic::experimental_vector_reduce_mul:
8891     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8892     break;
8893   case Intrinsic::experimental_vector_reduce_and:
8894     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8895     break;
8896   case Intrinsic::experimental_vector_reduce_or:
8897     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8898     break;
8899   case Intrinsic::experimental_vector_reduce_xor:
8900     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8901     break;
8902   case Intrinsic::experimental_vector_reduce_smax:
8903     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8904     break;
8905   case Intrinsic::experimental_vector_reduce_smin:
8906     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8907     break;
8908   case Intrinsic::experimental_vector_reduce_umax:
8909     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8910     break;
8911   case Intrinsic::experimental_vector_reduce_umin:
8912     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8913     break;
8914   case Intrinsic::experimental_vector_reduce_fmax:
8915     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8916     break;
8917   case Intrinsic::experimental_vector_reduce_fmin:
8918     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8919     break;
8920   default:
8921     llvm_unreachable("Unhandled vector reduce intrinsic");
8922   }
8923   setValue(&I, Res);
8924 }
8925 
8926 /// Returns an AttributeList representing the attributes applied to the return
8927 /// value of the given call.
8928 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8929   SmallVector<Attribute::AttrKind, 2> Attrs;
8930   if (CLI.RetSExt)
8931     Attrs.push_back(Attribute::SExt);
8932   if (CLI.RetZExt)
8933     Attrs.push_back(Attribute::ZExt);
8934   if (CLI.IsInReg)
8935     Attrs.push_back(Attribute::InReg);
8936 
8937   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8938                             Attrs);
8939 }
8940 
8941 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8942 /// implementation, which just calls LowerCall.
8943 /// FIXME: When all targets are
8944 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8945 std::pair<SDValue, SDValue>
8946 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8947   // Handle the incoming return values from the call.
8948   CLI.Ins.clear();
8949   Type *OrigRetTy = CLI.RetTy;
8950   SmallVector<EVT, 4> RetTys;
8951   SmallVector<uint64_t, 4> Offsets;
8952   auto &DL = CLI.DAG.getDataLayout();
8953   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8954 
8955   if (CLI.IsPostTypeLegalization) {
8956     // If we are lowering a libcall after legalization, split the return type.
8957     SmallVector<EVT, 4> OldRetTys;
8958     SmallVector<uint64_t, 4> OldOffsets;
8959     RetTys.swap(OldRetTys);
8960     Offsets.swap(OldOffsets);
8961 
8962     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8963       EVT RetVT = OldRetTys[i];
8964       uint64_t Offset = OldOffsets[i];
8965       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8966       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8967       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8968       RetTys.append(NumRegs, RegisterVT);
8969       for (unsigned j = 0; j != NumRegs; ++j)
8970         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8971     }
8972   }
8973 
8974   SmallVector<ISD::OutputArg, 4> Outs;
8975   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8976 
8977   bool CanLowerReturn =
8978       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8979                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8980 
8981   SDValue DemoteStackSlot;
8982   int DemoteStackIdx = -100;
8983   if (!CanLowerReturn) {
8984     // FIXME: equivalent assert?
8985     // assert(!CS.hasInAllocaArgument() &&
8986     //        "sret demotion is incompatible with inalloca");
8987     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8988     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8989     MachineFunction &MF = CLI.DAG.getMachineFunction();
8990     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8991     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8992                                               DL.getAllocaAddrSpace());
8993 
8994     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8995     ArgListEntry Entry;
8996     Entry.Node = DemoteStackSlot;
8997     Entry.Ty = StackSlotPtrType;
8998     Entry.IsSExt = false;
8999     Entry.IsZExt = false;
9000     Entry.IsInReg = false;
9001     Entry.IsSRet = true;
9002     Entry.IsNest = false;
9003     Entry.IsByVal = false;
9004     Entry.IsReturned = false;
9005     Entry.IsSwiftSelf = false;
9006     Entry.IsSwiftError = false;
9007     Entry.IsCFGuardTarget = false;
9008     Entry.Alignment = Align;
9009     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9010     CLI.NumFixedArgs += 1;
9011     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9012 
9013     // sret demotion isn't compatible with tail-calls, since the sret argument
9014     // points into the callers stack frame.
9015     CLI.IsTailCall = false;
9016   } else {
9017     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9018         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9019     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9020       ISD::ArgFlagsTy Flags;
9021       if (NeedsRegBlock) {
9022         Flags.setInConsecutiveRegs();
9023         if (I == RetTys.size() - 1)
9024           Flags.setInConsecutiveRegsLast();
9025       }
9026       EVT VT = RetTys[I];
9027       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9028                                                      CLI.CallConv, VT);
9029       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9030                                                        CLI.CallConv, VT);
9031       for (unsigned i = 0; i != NumRegs; ++i) {
9032         ISD::InputArg MyFlags;
9033         MyFlags.Flags = Flags;
9034         MyFlags.VT = RegisterVT;
9035         MyFlags.ArgVT = VT;
9036         MyFlags.Used = CLI.IsReturnValueUsed;
9037         if (CLI.RetTy->isPointerTy()) {
9038           MyFlags.Flags.setPointer();
9039           MyFlags.Flags.setPointerAddrSpace(
9040               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9041         }
9042         if (CLI.RetSExt)
9043           MyFlags.Flags.setSExt();
9044         if (CLI.RetZExt)
9045           MyFlags.Flags.setZExt();
9046         if (CLI.IsInReg)
9047           MyFlags.Flags.setInReg();
9048         CLI.Ins.push_back(MyFlags);
9049       }
9050     }
9051   }
9052 
9053   // We push in swifterror return as the last element of CLI.Ins.
9054   ArgListTy &Args = CLI.getArgs();
9055   if (supportSwiftError()) {
9056     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9057       if (Args[i].IsSwiftError) {
9058         ISD::InputArg MyFlags;
9059         MyFlags.VT = getPointerTy(DL);
9060         MyFlags.ArgVT = EVT(getPointerTy(DL));
9061         MyFlags.Flags.setSwiftError();
9062         CLI.Ins.push_back(MyFlags);
9063       }
9064     }
9065   }
9066 
9067   // Handle all of the outgoing arguments.
9068   CLI.Outs.clear();
9069   CLI.OutVals.clear();
9070   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9071     SmallVector<EVT, 4> ValueVTs;
9072     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9073     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9074     Type *FinalType = Args[i].Ty;
9075     if (Args[i].IsByVal)
9076       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9077     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9078         FinalType, CLI.CallConv, CLI.IsVarArg);
9079     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9080          ++Value) {
9081       EVT VT = ValueVTs[Value];
9082       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9083       SDValue Op = SDValue(Args[i].Node.getNode(),
9084                            Args[i].Node.getResNo() + Value);
9085       ISD::ArgFlagsTy Flags;
9086 
9087       // Certain targets (such as MIPS), may have a different ABI alignment
9088       // for a type depending on the context. Give the target a chance to
9089       // specify the alignment it wants.
9090       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9091 
9092       if (Args[i].Ty->isPointerTy()) {
9093         Flags.setPointer();
9094         Flags.setPointerAddrSpace(
9095             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9096       }
9097       if (Args[i].IsZExt)
9098         Flags.setZExt();
9099       if (Args[i].IsSExt)
9100         Flags.setSExt();
9101       if (Args[i].IsInReg) {
9102         // If we are using vectorcall calling convention, a structure that is
9103         // passed InReg - is surely an HVA
9104         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9105             isa<StructType>(FinalType)) {
9106           // The first value of a structure is marked
9107           if (0 == Value)
9108             Flags.setHvaStart();
9109           Flags.setHva();
9110         }
9111         // Set InReg Flag
9112         Flags.setInReg();
9113       }
9114       if (Args[i].IsSRet)
9115         Flags.setSRet();
9116       if (Args[i].IsSwiftSelf)
9117         Flags.setSwiftSelf();
9118       if (Args[i].IsSwiftError)
9119         Flags.setSwiftError();
9120       if (Args[i].IsCFGuardTarget)
9121         Flags.setCFGuardTarget();
9122       if (Args[i].IsByVal)
9123         Flags.setByVal();
9124       if (Args[i].IsInAlloca) {
9125         Flags.setInAlloca();
9126         // Set the byval flag for CCAssignFn callbacks that don't know about
9127         // inalloca.  This way we can know how many bytes we should've allocated
9128         // and how many bytes a callee cleanup function will pop.  If we port
9129         // inalloca to more targets, we'll have to add custom inalloca handling
9130         // in the various CC lowering callbacks.
9131         Flags.setByVal();
9132       }
9133       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9134         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9135         Type *ElementTy = Ty->getElementType();
9136 
9137         unsigned FrameSize = DL.getTypeAllocSize(
9138             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9139         Flags.setByValSize(FrameSize);
9140 
9141         // info is not there but there are cases it cannot get right.
9142         unsigned FrameAlign;
9143         if (Args[i].Alignment)
9144           FrameAlign = Args[i].Alignment;
9145         else
9146           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9147         Flags.setByValAlign(Align(FrameAlign));
9148       }
9149       if (Args[i].IsNest)
9150         Flags.setNest();
9151       if (NeedsRegBlock)
9152         Flags.setInConsecutiveRegs();
9153       Flags.setOrigAlign(OriginalAlignment);
9154 
9155       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9156                                                  CLI.CallConv, VT);
9157       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9158                                                         CLI.CallConv, VT);
9159       SmallVector<SDValue, 4> Parts(NumParts);
9160       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9161 
9162       if (Args[i].IsSExt)
9163         ExtendKind = ISD::SIGN_EXTEND;
9164       else if (Args[i].IsZExt)
9165         ExtendKind = ISD::ZERO_EXTEND;
9166 
9167       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9168       // for now.
9169       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9170           CanLowerReturn) {
9171         assert((CLI.RetTy == Args[i].Ty ||
9172                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9173                  CLI.RetTy->getPointerAddressSpace() ==
9174                      Args[i].Ty->getPointerAddressSpace())) &&
9175                RetTys.size() == NumValues && "unexpected use of 'returned'");
9176         // Before passing 'returned' to the target lowering code, ensure that
9177         // either the register MVT and the actual EVT are the same size or that
9178         // the return value and argument are extended in the same way; in these
9179         // cases it's safe to pass the argument register value unchanged as the
9180         // return register value (although it's at the target's option whether
9181         // to do so)
9182         // TODO: allow code generation to take advantage of partially preserved
9183         // registers rather than clobbering the entire register when the
9184         // parameter extension method is not compatible with the return
9185         // extension method
9186         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9187             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9188              CLI.RetZExt == Args[i].IsZExt))
9189           Flags.setReturned();
9190       }
9191 
9192       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9193                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9194 
9195       for (unsigned j = 0; j != NumParts; ++j) {
9196         // if it isn't first piece, alignment must be 1
9197         // For scalable vectors the scalable part is currently handled
9198         // by individual targets, so we just use the known minimum size here.
9199         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9200                     i < CLI.NumFixedArgs, i,
9201                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9202         if (NumParts > 1 && j == 0)
9203           MyFlags.Flags.setSplit();
9204         else if (j != 0) {
9205           MyFlags.Flags.setOrigAlign(Align::None());
9206           if (j == NumParts - 1)
9207             MyFlags.Flags.setSplitEnd();
9208         }
9209 
9210         CLI.Outs.push_back(MyFlags);
9211         CLI.OutVals.push_back(Parts[j]);
9212       }
9213 
9214       if (NeedsRegBlock && Value == NumValues - 1)
9215         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9216     }
9217   }
9218 
9219   SmallVector<SDValue, 4> InVals;
9220   CLI.Chain = LowerCall(CLI, InVals);
9221 
9222   // Update CLI.InVals to use outside of this function.
9223   CLI.InVals = InVals;
9224 
9225   // Verify that the target's LowerCall behaved as expected.
9226   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9227          "LowerCall didn't return a valid chain!");
9228   assert((!CLI.IsTailCall || InVals.empty()) &&
9229          "LowerCall emitted a return value for a tail call!");
9230   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9231          "LowerCall didn't emit the correct number of values!");
9232 
9233   // For a tail call, the return value is merely live-out and there aren't
9234   // any nodes in the DAG representing it. Return a special value to
9235   // indicate that a tail call has been emitted and no more Instructions
9236   // should be processed in the current block.
9237   if (CLI.IsTailCall) {
9238     CLI.DAG.setRoot(CLI.Chain);
9239     return std::make_pair(SDValue(), SDValue());
9240   }
9241 
9242 #ifndef NDEBUG
9243   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9244     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9245     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9246            "LowerCall emitted a value with the wrong type!");
9247   }
9248 #endif
9249 
9250   SmallVector<SDValue, 4> ReturnValues;
9251   if (!CanLowerReturn) {
9252     // The instruction result is the result of loading from the
9253     // hidden sret parameter.
9254     SmallVector<EVT, 1> PVTs;
9255     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9256 
9257     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9258     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9259     EVT PtrVT = PVTs[0];
9260 
9261     unsigned NumValues = RetTys.size();
9262     ReturnValues.resize(NumValues);
9263     SmallVector<SDValue, 4> Chains(NumValues);
9264 
9265     // An aggregate return value cannot wrap around the address space, so
9266     // offsets to its parts don't wrap either.
9267     SDNodeFlags Flags;
9268     Flags.setNoUnsignedWrap(true);
9269 
9270     for (unsigned i = 0; i < NumValues; ++i) {
9271       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9272                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9273                                                         PtrVT), Flags);
9274       SDValue L = CLI.DAG.getLoad(
9275           RetTys[i], CLI.DL, CLI.Chain, Add,
9276           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9277                                             DemoteStackIdx, Offsets[i]),
9278           /* Alignment = */ 1);
9279       ReturnValues[i] = L;
9280       Chains[i] = L.getValue(1);
9281     }
9282 
9283     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9284   } else {
9285     // Collect the legal value parts into potentially illegal values
9286     // that correspond to the original function's return values.
9287     Optional<ISD::NodeType> AssertOp;
9288     if (CLI.RetSExt)
9289       AssertOp = ISD::AssertSext;
9290     else if (CLI.RetZExt)
9291       AssertOp = ISD::AssertZext;
9292     unsigned CurReg = 0;
9293     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9294       EVT VT = RetTys[I];
9295       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9296                                                      CLI.CallConv, VT);
9297       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9298                                                        CLI.CallConv, VT);
9299 
9300       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9301                                               NumRegs, RegisterVT, VT, nullptr,
9302                                               CLI.CallConv, AssertOp));
9303       CurReg += NumRegs;
9304     }
9305 
9306     // For a function returning void, there is no return value. We can't create
9307     // such a node, so we just return a null return value in that case. In
9308     // that case, nothing will actually look at the value.
9309     if (ReturnValues.empty())
9310       return std::make_pair(SDValue(), CLI.Chain);
9311   }
9312 
9313   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9314                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9315   return std::make_pair(Res, CLI.Chain);
9316 }
9317 
9318 void TargetLowering::LowerOperationWrapper(SDNode *N,
9319                                            SmallVectorImpl<SDValue> &Results,
9320                                            SelectionDAG &DAG) const {
9321   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9322     Results.push_back(Res);
9323 }
9324 
9325 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9326   llvm_unreachable("LowerOperation not implemented for this target!");
9327 }
9328 
9329 void
9330 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9331   SDValue Op = getNonRegisterValue(V);
9332   assert((Op.getOpcode() != ISD::CopyFromReg ||
9333           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9334          "Copy from a reg to the same reg!");
9335   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9336 
9337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9338   // If this is an InlineAsm we have to match the registers required, not the
9339   // notional registers required by the type.
9340 
9341   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9342                    None); // This is not an ABI copy.
9343   SDValue Chain = DAG.getEntryNode();
9344 
9345   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9346                               FuncInfo.PreferredExtendType.end())
9347                                  ? ISD::ANY_EXTEND
9348                                  : FuncInfo.PreferredExtendType[V];
9349   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9350   PendingExports.push_back(Chain);
9351 }
9352 
9353 #include "llvm/CodeGen/SelectionDAGISel.h"
9354 
9355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9356 /// entry block, return true.  This includes arguments used by switches, since
9357 /// the switch may expand into multiple basic blocks.
9358 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9359   // With FastISel active, we may be splitting blocks, so force creation
9360   // of virtual registers for all non-dead arguments.
9361   if (FastISel)
9362     return A->use_empty();
9363 
9364   const BasicBlock &Entry = A->getParent()->front();
9365   for (const User *U : A->users())
9366     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9367       return false;  // Use not in entry block.
9368 
9369   return true;
9370 }
9371 
9372 using ArgCopyElisionMapTy =
9373     DenseMap<const Argument *,
9374              std::pair<const AllocaInst *, const StoreInst *>>;
9375 
9376 /// Scan the entry block of the function in FuncInfo for arguments that look
9377 /// like copies into a local alloca. Record any copied arguments in
9378 /// ArgCopyElisionCandidates.
9379 static void
9380 findArgumentCopyElisionCandidates(const DataLayout &DL,
9381                                   FunctionLoweringInfo *FuncInfo,
9382                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9383   // Record the state of every static alloca used in the entry block. Argument
9384   // allocas are all used in the entry block, so we need approximately as many
9385   // entries as we have arguments.
9386   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9387   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9388   unsigned NumArgs = FuncInfo->Fn->arg_size();
9389   StaticAllocas.reserve(NumArgs * 2);
9390 
9391   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9392     if (!V)
9393       return nullptr;
9394     V = V->stripPointerCasts();
9395     const auto *AI = dyn_cast<AllocaInst>(V);
9396     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9397       return nullptr;
9398     auto Iter = StaticAllocas.insert({AI, Unknown});
9399     return &Iter.first->second;
9400   };
9401 
9402   // Look for stores of arguments to static allocas. Look through bitcasts and
9403   // GEPs to handle type coercions, as long as the alloca is fully initialized
9404   // by the store. Any non-store use of an alloca escapes it and any subsequent
9405   // unanalyzed store might write it.
9406   // FIXME: Handle structs initialized with multiple stores.
9407   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9408     // Look for stores, and handle non-store uses conservatively.
9409     const auto *SI = dyn_cast<StoreInst>(&I);
9410     if (!SI) {
9411       // We will look through cast uses, so ignore them completely.
9412       if (I.isCast())
9413         continue;
9414       // Ignore debug info intrinsics, they don't escape or store to allocas.
9415       if (isa<DbgInfoIntrinsic>(I))
9416         continue;
9417       // This is an unknown instruction. Assume it escapes or writes to all
9418       // static alloca operands.
9419       for (const Use &U : I.operands()) {
9420         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9421           *Info = StaticAllocaInfo::Clobbered;
9422       }
9423       continue;
9424     }
9425 
9426     // If the stored value is a static alloca, mark it as escaped.
9427     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9428       *Info = StaticAllocaInfo::Clobbered;
9429 
9430     // Check if the destination is a static alloca.
9431     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9432     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9433     if (!Info)
9434       continue;
9435     const AllocaInst *AI = cast<AllocaInst>(Dst);
9436 
9437     // Skip allocas that have been initialized or clobbered.
9438     if (*Info != StaticAllocaInfo::Unknown)
9439       continue;
9440 
9441     // Check if the stored value is an argument, and that this store fully
9442     // initializes the alloca. Don't elide copies from the same argument twice.
9443     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9444     const auto *Arg = dyn_cast<Argument>(Val);
9445     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9446         Arg->getType()->isEmptyTy() ||
9447         DL.getTypeStoreSize(Arg->getType()) !=
9448             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9449         ArgCopyElisionCandidates.count(Arg)) {
9450       *Info = StaticAllocaInfo::Clobbered;
9451       continue;
9452     }
9453 
9454     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9455                       << '\n');
9456 
9457     // Mark this alloca and store for argument copy elision.
9458     *Info = StaticAllocaInfo::Elidable;
9459     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9460 
9461     // Stop scanning if we've seen all arguments. This will happen early in -O0
9462     // builds, which is useful, because -O0 builds have large entry blocks and
9463     // many allocas.
9464     if (ArgCopyElisionCandidates.size() == NumArgs)
9465       break;
9466   }
9467 }
9468 
9469 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9470 /// ArgVal is a load from a suitable fixed stack object.
9471 static void tryToElideArgumentCopy(
9472     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9473     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9474     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9475     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9476     SDValue ArgVal, bool &ArgHasUses) {
9477   // Check if this is a load from a fixed stack object.
9478   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9479   if (!LNode)
9480     return;
9481   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9482   if (!FINode)
9483     return;
9484 
9485   // Check that the fixed stack object is the right size and alignment.
9486   // Look at the alignment that the user wrote on the alloca instead of looking
9487   // at the stack object.
9488   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9489   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9490   const AllocaInst *AI = ArgCopyIter->second.first;
9491   int FixedIndex = FINode->getIndex();
9492   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9493   int OldIndex = AllocaIndex;
9494   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9495   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9496     LLVM_DEBUG(
9497         dbgs() << "  argument copy elision failed due to bad fixed stack "
9498                   "object size\n");
9499     return;
9500   }
9501   unsigned RequiredAlignment = AI->getAlignment();
9502   if (!RequiredAlignment) {
9503     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9504         AI->getAllocatedType());
9505   }
9506   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9507     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9508                          "greater than stack argument alignment ("
9509                       << RequiredAlignment << " vs "
9510                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9511     return;
9512   }
9513 
9514   // Perform the elision. Delete the old stack object and replace its only use
9515   // in the variable info map. Mark the stack object as mutable.
9516   LLVM_DEBUG({
9517     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9518            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9519            << '\n';
9520   });
9521   MFI.RemoveStackObject(OldIndex);
9522   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9523   AllocaIndex = FixedIndex;
9524   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9525   Chains.push_back(ArgVal.getValue(1));
9526 
9527   // Avoid emitting code for the store implementing the copy.
9528   const StoreInst *SI = ArgCopyIter->second.second;
9529   ElidedArgCopyInstrs.insert(SI);
9530 
9531   // Check for uses of the argument again so that we can avoid exporting ArgVal
9532   // if it is't used by anything other than the store.
9533   for (const Value *U : Arg.users()) {
9534     if (U != SI) {
9535       ArgHasUses = true;
9536       break;
9537     }
9538   }
9539 }
9540 
9541 void SelectionDAGISel::LowerArguments(const Function &F) {
9542   SelectionDAG &DAG = SDB->DAG;
9543   SDLoc dl = SDB->getCurSDLoc();
9544   const DataLayout &DL = DAG.getDataLayout();
9545   SmallVector<ISD::InputArg, 16> Ins;
9546 
9547   if (!FuncInfo->CanLowerReturn) {
9548     // Put in an sret pointer parameter before all the other parameters.
9549     SmallVector<EVT, 1> ValueVTs;
9550     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9551                     F.getReturnType()->getPointerTo(
9552                         DAG.getDataLayout().getAllocaAddrSpace()),
9553                     ValueVTs);
9554 
9555     // NOTE: Assuming that a pointer will never break down to more than one VT
9556     // or one register.
9557     ISD::ArgFlagsTy Flags;
9558     Flags.setSRet();
9559     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9560     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9561                          ISD::InputArg::NoArgIndex, 0);
9562     Ins.push_back(RetArg);
9563   }
9564 
9565   // Look for stores of arguments to static allocas. Mark such arguments with a
9566   // flag to ask the target to give us the memory location of that argument if
9567   // available.
9568   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9569   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9570                                     ArgCopyElisionCandidates);
9571 
9572   // Set up the incoming argument description vector.
9573   for (const Argument &Arg : F.args()) {
9574     unsigned ArgNo = Arg.getArgNo();
9575     SmallVector<EVT, 4> ValueVTs;
9576     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9577     bool isArgValueUsed = !Arg.use_empty();
9578     unsigned PartBase = 0;
9579     Type *FinalType = Arg.getType();
9580     if (Arg.hasAttribute(Attribute::ByVal))
9581       FinalType = Arg.getParamByValType();
9582     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9583         FinalType, F.getCallingConv(), F.isVarArg());
9584     for (unsigned Value = 0, NumValues = ValueVTs.size();
9585          Value != NumValues; ++Value) {
9586       EVT VT = ValueVTs[Value];
9587       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9588       ISD::ArgFlagsTy Flags;
9589 
9590       // Certain targets (such as MIPS), may have a different ABI alignment
9591       // for a type depending on the context. Give the target a chance to
9592       // specify the alignment it wants.
9593       const Align OriginalAlignment(
9594           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9595 
9596       if (Arg.getType()->isPointerTy()) {
9597         Flags.setPointer();
9598         Flags.setPointerAddrSpace(
9599             cast<PointerType>(Arg.getType())->getAddressSpace());
9600       }
9601       if (Arg.hasAttribute(Attribute::ZExt))
9602         Flags.setZExt();
9603       if (Arg.hasAttribute(Attribute::SExt))
9604         Flags.setSExt();
9605       if (Arg.hasAttribute(Attribute::InReg)) {
9606         // If we are using vectorcall calling convention, a structure that is
9607         // passed InReg - is surely an HVA
9608         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9609             isa<StructType>(Arg.getType())) {
9610           // The first value of a structure is marked
9611           if (0 == Value)
9612             Flags.setHvaStart();
9613           Flags.setHva();
9614         }
9615         // Set InReg Flag
9616         Flags.setInReg();
9617       }
9618       if (Arg.hasAttribute(Attribute::StructRet))
9619         Flags.setSRet();
9620       if (Arg.hasAttribute(Attribute::SwiftSelf))
9621         Flags.setSwiftSelf();
9622       if (Arg.hasAttribute(Attribute::SwiftError))
9623         Flags.setSwiftError();
9624       if (Arg.hasAttribute(Attribute::ByVal))
9625         Flags.setByVal();
9626       if (Arg.hasAttribute(Attribute::InAlloca)) {
9627         Flags.setInAlloca();
9628         // Set the byval flag for CCAssignFn callbacks that don't know about
9629         // inalloca.  This way we can know how many bytes we should've allocated
9630         // and how many bytes a callee cleanup function will pop.  If we port
9631         // inalloca to more targets, we'll have to add custom inalloca handling
9632         // in the various CC lowering callbacks.
9633         Flags.setByVal();
9634       }
9635       if (F.getCallingConv() == CallingConv::X86_INTR) {
9636         // IA Interrupt passes frame (1st parameter) by value in the stack.
9637         if (ArgNo == 0)
9638           Flags.setByVal();
9639       }
9640       if (Flags.isByVal() || Flags.isInAlloca()) {
9641         Type *ElementTy = Arg.getParamByValType();
9642 
9643         // For ByVal, size and alignment should be passed from FE.  BE will
9644         // guess if this info is not there but there are cases it cannot get
9645         // right.
9646         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9647         Flags.setByValSize(FrameSize);
9648 
9649         unsigned FrameAlign;
9650         if (Arg.getParamAlignment())
9651           FrameAlign = Arg.getParamAlignment();
9652         else
9653           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9654         Flags.setByValAlign(Align(FrameAlign));
9655       }
9656       if (Arg.hasAttribute(Attribute::Nest))
9657         Flags.setNest();
9658       if (NeedsRegBlock)
9659         Flags.setInConsecutiveRegs();
9660       Flags.setOrigAlign(OriginalAlignment);
9661       if (ArgCopyElisionCandidates.count(&Arg))
9662         Flags.setCopyElisionCandidate();
9663       if (Arg.hasAttribute(Attribute::Returned))
9664         Flags.setReturned();
9665 
9666       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9667           *CurDAG->getContext(), F.getCallingConv(), VT);
9668       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9669           *CurDAG->getContext(), F.getCallingConv(), VT);
9670       for (unsigned i = 0; i != NumRegs; ++i) {
9671         // For scalable vectors, use the minimum size; individual targets
9672         // are responsible for handling scalable vector arguments and
9673         // return values.
9674         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9675                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9676         if (NumRegs > 1 && i == 0)
9677           MyFlags.Flags.setSplit();
9678         // if it isn't first piece, alignment must be 1
9679         else if (i > 0) {
9680           MyFlags.Flags.setOrigAlign(Align::None());
9681           if (i == NumRegs - 1)
9682             MyFlags.Flags.setSplitEnd();
9683         }
9684         Ins.push_back(MyFlags);
9685       }
9686       if (NeedsRegBlock && Value == NumValues - 1)
9687         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9688       PartBase += VT.getStoreSize().getKnownMinSize();
9689     }
9690   }
9691 
9692   // Call the target to set up the argument values.
9693   SmallVector<SDValue, 8> InVals;
9694   SDValue NewRoot = TLI->LowerFormalArguments(
9695       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9696 
9697   // Verify that the target's LowerFormalArguments behaved as expected.
9698   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9699          "LowerFormalArguments didn't return a valid chain!");
9700   assert(InVals.size() == Ins.size() &&
9701          "LowerFormalArguments didn't emit the correct number of values!");
9702   LLVM_DEBUG({
9703     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9704       assert(InVals[i].getNode() &&
9705              "LowerFormalArguments emitted a null value!");
9706       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9707              "LowerFormalArguments emitted a value with the wrong type!");
9708     }
9709   });
9710 
9711   // Update the DAG with the new chain value resulting from argument lowering.
9712   DAG.setRoot(NewRoot);
9713 
9714   // Set up the argument values.
9715   unsigned i = 0;
9716   if (!FuncInfo->CanLowerReturn) {
9717     // Create a virtual register for the sret pointer, and put in a copy
9718     // from the sret argument into it.
9719     SmallVector<EVT, 1> ValueVTs;
9720     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9721                     F.getReturnType()->getPointerTo(
9722                         DAG.getDataLayout().getAllocaAddrSpace()),
9723                     ValueVTs);
9724     MVT VT = ValueVTs[0].getSimpleVT();
9725     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9726     Optional<ISD::NodeType> AssertOp = None;
9727     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9728                                         nullptr, F.getCallingConv(), AssertOp);
9729 
9730     MachineFunction& MF = SDB->DAG.getMachineFunction();
9731     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9732     Register SRetReg =
9733         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9734     FuncInfo->DemoteRegister = SRetReg;
9735     NewRoot =
9736         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9737     DAG.setRoot(NewRoot);
9738 
9739     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9740     ++i;
9741   }
9742 
9743   SmallVector<SDValue, 4> Chains;
9744   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9745   for (const Argument &Arg : F.args()) {
9746     SmallVector<SDValue, 4> ArgValues;
9747     SmallVector<EVT, 4> ValueVTs;
9748     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9749     unsigned NumValues = ValueVTs.size();
9750     if (NumValues == 0)
9751       continue;
9752 
9753     bool ArgHasUses = !Arg.use_empty();
9754 
9755     // Elide the copying store if the target loaded this argument from a
9756     // suitable fixed stack object.
9757     if (Ins[i].Flags.isCopyElisionCandidate()) {
9758       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9759                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9760                              InVals[i], ArgHasUses);
9761     }
9762 
9763     // If this argument is unused then remember its value. It is used to generate
9764     // debugging information.
9765     bool isSwiftErrorArg =
9766         TLI->supportSwiftError() &&
9767         Arg.hasAttribute(Attribute::SwiftError);
9768     if (!ArgHasUses && !isSwiftErrorArg) {
9769       SDB->setUnusedArgValue(&Arg, InVals[i]);
9770 
9771       // Also remember any frame index for use in FastISel.
9772       if (FrameIndexSDNode *FI =
9773           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9774         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9775     }
9776 
9777     for (unsigned Val = 0; Val != NumValues; ++Val) {
9778       EVT VT = ValueVTs[Val];
9779       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9780                                                       F.getCallingConv(), VT);
9781       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9782           *CurDAG->getContext(), F.getCallingConv(), VT);
9783 
9784       // Even an apparent 'unused' swifterror argument needs to be returned. So
9785       // we do generate a copy for it that can be used on return from the
9786       // function.
9787       if (ArgHasUses || isSwiftErrorArg) {
9788         Optional<ISD::NodeType> AssertOp;
9789         if (Arg.hasAttribute(Attribute::SExt))
9790           AssertOp = ISD::AssertSext;
9791         else if (Arg.hasAttribute(Attribute::ZExt))
9792           AssertOp = ISD::AssertZext;
9793 
9794         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9795                                              PartVT, VT, nullptr,
9796                                              F.getCallingConv(), AssertOp));
9797       }
9798 
9799       i += NumParts;
9800     }
9801 
9802     // We don't need to do anything else for unused arguments.
9803     if (ArgValues.empty())
9804       continue;
9805 
9806     // Note down frame index.
9807     if (FrameIndexSDNode *FI =
9808         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9809       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9810 
9811     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9812                                      SDB->getCurSDLoc());
9813 
9814     SDB->setValue(&Arg, Res);
9815     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9816       // We want to associate the argument with the frame index, among
9817       // involved operands, that correspond to the lowest address. The
9818       // getCopyFromParts function, called earlier, is swapping the order of
9819       // the operands to BUILD_PAIR depending on endianness. The result of
9820       // that swapping is that the least significant bits of the argument will
9821       // be in the first operand of the BUILD_PAIR node, and the most
9822       // significant bits will be in the second operand.
9823       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9824       if (LoadSDNode *LNode =
9825           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9826         if (FrameIndexSDNode *FI =
9827             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9828           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9829     }
9830 
9831     // Analyses past this point are naive and don't expect an assertion.
9832     if (Res.getOpcode() == ISD::AssertZext)
9833       Res = Res.getOperand(0);
9834 
9835     // Update the SwiftErrorVRegDefMap.
9836     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9837       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9838       if (Register::isVirtualRegister(Reg))
9839         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9840                                    Reg);
9841     }
9842 
9843     // If this argument is live outside of the entry block, insert a copy from
9844     // wherever we got it to the vreg that other BB's will reference it as.
9845     if (Res.getOpcode() == ISD::CopyFromReg) {
9846       // If we can, though, try to skip creating an unnecessary vreg.
9847       // FIXME: This isn't very clean... it would be nice to make this more
9848       // general.
9849       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9850       if (Register::isVirtualRegister(Reg)) {
9851         FuncInfo->ValueMap[&Arg] = Reg;
9852         continue;
9853       }
9854     }
9855     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9856       FuncInfo->InitializeRegForValue(&Arg);
9857       SDB->CopyToExportRegsIfNeeded(&Arg);
9858     }
9859   }
9860 
9861   if (!Chains.empty()) {
9862     Chains.push_back(NewRoot);
9863     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9864   }
9865 
9866   DAG.setRoot(NewRoot);
9867 
9868   assert(i == InVals.size() && "Argument register count mismatch!");
9869 
9870   // If any argument copy elisions occurred and we have debug info, update the
9871   // stale frame indices used in the dbg.declare variable info table.
9872   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9873   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9874     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9875       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9876       if (I != ArgCopyElisionFrameIndexMap.end())
9877         VI.Slot = I->second;
9878     }
9879   }
9880 
9881   // Finally, if the target has anything special to do, allow it to do so.
9882   EmitFunctionEntryCode();
9883 }
9884 
9885 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9886 /// ensure constants are generated when needed.  Remember the virtual registers
9887 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9888 /// directly add them, because expansion might result in multiple MBB's for one
9889 /// BB.  As such, the start of the BB might correspond to a different MBB than
9890 /// the end.
9891 void
9892 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9893   const Instruction *TI = LLVMBB->getTerminator();
9894 
9895   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9896 
9897   // Check PHI nodes in successors that expect a value to be available from this
9898   // block.
9899   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9900     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9901     if (!isa<PHINode>(SuccBB->begin())) continue;
9902     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9903 
9904     // If this terminator has multiple identical successors (common for
9905     // switches), only handle each succ once.
9906     if (!SuccsHandled.insert(SuccMBB).second)
9907       continue;
9908 
9909     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9910 
9911     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9912     // nodes and Machine PHI nodes, but the incoming operands have not been
9913     // emitted yet.
9914     for (const PHINode &PN : SuccBB->phis()) {
9915       // Ignore dead phi's.
9916       if (PN.use_empty())
9917         continue;
9918 
9919       // Skip empty types
9920       if (PN.getType()->isEmptyTy())
9921         continue;
9922 
9923       unsigned Reg;
9924       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9925 
9926       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9927         unsigned &RegOut = ConstantsOut[C];
9928         if (RegOut == 0) {
9929           RegOut = FuncInfo.CreateRegs(C);
9930           CopyValueToVirtualRegister(C, RegOut);
9931         }
9932         Reg = RegOut;
9933       } else {
9934         DenseMap<const Value *, unsigned>::iterator I =
9935           FuncInfo.ValueMap.find(PHIOp);
9936         if (I != FuncInfo.ValueMap.end())
9937           Reg = I->second;
9938         else {
9939           assert(isa<AllocaInst>(PHIOp) &&
9940                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9941                  "Didn't codegen value into a register!??");
9942           Reg = FuncInfo.CreateRegs(PHIOp);
9943           CopyValueToVirtualRegister(PHIOp, Reg);
9944         }
9945       }
9946 
9947       // Remember that this register needs to added to the machine PHI node as
9948       // the input for this MBB.
9949       SmallVector<EVT, 4> ValueVTs;
9950       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9951       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9952       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9953         EVT VT = ValueVTs[vti];
9954         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9955         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9956           FuncInfo.PHINodesToUpdate.push_back(
9957               std::make_pair(&*MBBI++, Reg + i));
9958         Reg += NumRegisters;
9959       }
9960     }
9961   }
9962 
9963   ConstantsOut.clear();
9964 }
9965 
9966 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9967 /// is 0.
9968 MachineBasicBlock *
9969 SelectionDAGBuilder::StackProtectorDescriptor::
9970 AddSuccessorMBB(const BasicBlock *BB,
9971                 MachineBasicBlock *ParentMBB,
9972                 bool IsLikely,
9973                 MachineBasicBlock *SuccMBB) {
9974   // If SuccBB has not been created yet, create it.
9975   if (!SuccMBB) {
9976     MachineFunction *MF = ParentMBB->getParent();
9977     MachineFunction::iterator BBI(ParentMBB);
9978     SuccMBB = MF->CreateMachineBasicBlock(BB);
9979     MF->insert(++BBI, SuccMBB);
9980   }
9981   // Add it as a successor of ParentMBB.
9982   ParentMBB->addSuccessor(
9983       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9984   return SuccMBB;
9985 }
9986 
9987 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9988   MachineFunction::iterator I(MBB);
9989   if (++I == FuncInfo.MF->end())
9990     return nullptr;
9991   return &*I;
9992 }
9993 
9994 /// During lowering new call nodes can be created (such as memset, etc.).
9995 /// Those will become new roots of the current DAG, but complications arise
9996 /// when they are tail calls. In such cases, the call lowering will update
9997 /// the root, but the builder still needs to know that a tail call has been
9998 /// lowered in order to avoid generating an additional return.
9999 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10000   // If the node is null, we do have a tail call.
10001   if (MaybeTC.getNode() != nullptr)
10002     DAG.setRoot(MaybeTC);
10003   else
10004     HasTailCall = true;
10005 }
10006 
10007 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10008                                         MachineBasicBlock *SwitchMBB,
10009                                         MachineBasicBlock *DefaultMBB) {
10010   MachineFunction *CurMF = FuncInfo.MF;
10011   MachineBasicBlock *NextMBB = nullptr;
10012   MachineFunction::iterator BBI(W.MBB);
10013   if (++BBI != FuncInfo.MF->end())
10014     NextMBB = &*BBI;
10015 
10016   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10017 
10018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10019 
10020   if (Size == 2 && W.MBB == SwitchMBB) {
10021     // If any two of the cases has the same destination, and if one value
10022     // is the same as the other, but has one bit unset that the other has set,
10023     // use bit manipulation to do two compares at once.  For example:
10024     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10025     // TODO: This could be extended to merge any 2 cases in switches with 3
10026     // cases.
10027     // TODO: Handle cases where W.CaseBB != SwitchBB.
10028     CaseCluster &Small = *W.FirstCluster;
10029     CaseCluster &Big = *W.LastCluster;
10030 
10031     if (Small.Low == Small.High && Big.Low == Big.High &&
10032         Small.MBB == Big.MBB) {
10033       const APInt &SmallValue = Small.Low->getValue();
10034       const APInt &BigValue = Big.Low->getValue();
10035 
10036       // Check that there is only one bit different.
10037       APInt CommonBit = BigValue ^ SmallValue;
10038       if (CommonBit.isPowerOf2()) {
10039         SDValue CondLHS = getValue(Cond);
10040         EVT VT = CondLHS.getValueType();
10041         SDLoc DL = getCurSDLoc();
10042 
10043         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10044                                  DAG.getConstant(CommonBit, DL, VT));
10045         SDValue Cond = DAG.getSetCC(
10046             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10047             ISD::SETEQ);
10048 
10049         // Update successor info.
10050         // Both Small and Big will jump to Small.BB, so we sum up the
10051         // probabilities.
10052         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10053         if (BPI)
10054           addSuccessorWithProb(
10055               SwitchMBB, DefaultMBB,
10056               // The default destination is the first successor in IR.
10057               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10058         else
10059           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10060 
10061         // Insert the true branch.
10062         SDValue BrCond =
10063             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10064                         DAG.getBasicBlock(Small.MBB));
10065         // Insert the false branch.
10066         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10067                              DAG.getBasicBlock(DefaultMBB));
10068 
10069         DAG.setRoot(BrCond);
10070         return;
10071       }
10072     }
10073   }
10074 
10075   if (TM.getOptLevel() != CodeGenOpt::None) {
10076     // Here, we order cases by probability so the most likely case will be
10077     // checked first. However, two clusters can have the same probability in
10078     // which case their relative ordering is non-deterministic. So we use Low
10079     // as a tie-breaker as clusters are guaranteed to never overlap.
10080     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10081                [](const CaseCluster &a, const CaseCluster &b) {
10082       return a.Prob != b.Prob ?
10083              a.Prob > b.Prob :
10084              a.Low->getValue().slt(b.Low->getValue());
10085     });
10086 
10087     // Rearrange the case blocks so that the last one falls through if possible
10088     // without changing the order of probabilities.
10089     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10090       --I;
10091       if (I->Prob > W.LastCluster->Prob)
10092         break;
10093       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10094         std::swap(*I, *W.LastCluster);
10095         break;
10096       }
10097     }
10098   }
10099 
10100   // Compute total probability.
10101   BranchProbability DefaultProb = W.DefaultProb;
10102   BranchProbability UnhandledProbs = DefaultProb;
10103   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10104     UnhandledProbs += I->Prob;
10105 
10106   MachineBasicBlock *CurMBB = W.MBB;
10107   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10108     bool FallthroughUnreachable = false;
10109     MachineBasicBlock *Fallthrough;
10110     if (I == W.LastCluster) {
10111       // For the last cluster, fall through to the default destination.
10112       Fallthrough = DefaultMBB;
10113       FallthroughUnreachable = isa<UnreachableInst>(
10114           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10115     } else {
10116       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10117       CurMF->insert(BBI, Fallthrough);
10118       // Put Cond in a virtual register to make it available from the new blocks.
10119       ExportFromCurrentBlock(Cond);
10120     }
10121     UnhandledProbs -= I->Prob;
10122 
10123     switch (I->Kind) {
10124       case CC_JumpTable: {
10125         // FIXME: Optimize away range check based on pivot comparisons.
10126         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10127         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10128 
10129         // The jump block hasn't been inserted yet; insert it here.
10130         MachineBasicBlock *JumpMBB = JT->MBB;
10131         CurMF->insert(BBI, JumpMBB);
10132 
10133         auto JumpProb = I->Prob;
10134         auto FallthroughProb = UnhandledProbs;
10135 
10136         // If the default statement is a target of the jump table, we evenly
10137         // distribute the default probability to successors of CurMBB. Also
10138         // update the probability on the edge from JumpMBB to Fallthrough.
10139         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10140                                               SE = JumpMBB->succ_end();
10141              SI != SE; ++SI) {
10142           if (*SI == DefaultMBB) {
10143             JumpProb += DefaultProb / 2;
10144             FallthroughProb -= DefaultProb / 2;
10145             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10146             JumpMBB->normalizeSuccProbs();
10147             break;
10148           }
10149         }
10150 
10151         if (FallthroughUnreachable) {
10152           // Skip the range check if the fallthrough block is unreachable.
10153           JTH->OmitRangeCheck = true;
10154         }
10155 
10156         if (!JTH->OmitRangeCheck)
10157           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10158         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10159         CurMBB->normalizeSuccProbs();
10160 
10161         // The jump table header will be inserted in our current block, do the
10162         // range check, and fall through to our fallthrough block.
10163         JTH->HeaderBB = CurMBB;
10164         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10165 
10166         // If we're in the right place, emit the jump table header right now.
10167         if (CurMBB == SwitchMBB) {
10168           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10169           JTH->Emitted = true;
10170         }
10171         break;
10172       }
10173       case CC_BitTests: {
10174         // FIXME: Optimize away range check based on pivot comparisons.
10175         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10176 
10177         // The bit test blocks haven't been inserted yet; insert them here.
10178         for (BitTestCase &BTC : BTB->Cases)
10179           CurMF->insert(BBI, BTC.ThisBB);
10180 
10181         // Fill in fields of the BitTestBlock.
10182         BTB->Parent = CurMBB;
10183         BTB->Default = Fallthrough;
10184 
10185         BTB->DefaultProb = UnhandledProbs;
10186         // If the cases in bit test don't form a contiguous range, we evenly
10187         // distribute the probability on the edge to Fallthrough to two
10188         // successors of CurMBB.
10189         if (!BTB->ContiguousRange) {
10190           BTB->Prob += DefaultProb / 2;
10191           BTB->DefaultProb -= DefaultProb / 2;
10192         }
10193 
10194         if (FallthroughUnreachable) {
10195           // Skip the range check if the fallthrough block is unreachable.
10196           BTB->OmitRangeCheck = true;
10197         }
10198 
10199         // If we're in the right place, emit the bit test header right now.
10200         if (CurMBB == SwitchMBB) {
10201           visitBitTestHeader(*BTB, SwitchMBB);
10202           BTB->Emitted = true;
10203         }
10204         break;
10205       }
10206       case CC_Range: {
10207         const Value *RHS, *LHS, *MHS;
10208         ISD::CondCode CC;
10209         if (I->Low == I->High) {
10210           // Check Cond == I->Low.
10211           CC = ISD::SETEQ;
10212           LHS = Cond;
10213           RHS=I->Low;
10214           MHS = nullptr;
10215         } else {
10216           // Check I->Low <= Cond <= I->High.
10217           CC = ISD::SETLE;
10218           LHS = I->Low;
10219           MHS = Cond;
10220           RHS = I->High;
10221         }
10222 
10223         // If Fallthrough is unreachable, fold away the comparison.
10224         if (FallthroughUnreachable)
10225           CC = ISD::SETTRUE;
10226 
10227         // The false probability is the sum of all unhandled cases.
10228         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10229                      getCurSDLoc(), I->Prob, UnhandledProbs);
10230 
10231         if (CurMBB == SwitchMBB)
10232           visitSwitchCase(CB, SwitchMBB);
10233         else
10234           SL->SwitchCases.push_back(CB);
10235 
10236         break;
10237       }
10238     }
10239     CurMBB = Fallthrough;
10240   }
10241 }
10242 
10243 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10244                                               CaseClusterIt First,
10245                                               CaseClusterIt Last) {
10246   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10247     if (X.Prob != CC.Prob)
10248       return X.Prob > CC.Prob;
10249 
10250     // Ties are broken by comparing the case value.
10251     return X.Low->getValue().slt(CC.Low->getValue());
10252   });
10253 }
10254 
10255 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10256                                         const SwitchWorkListItem &W,
10257                                         Value *Cond,
10258                                         MachineBasicBlock *SwitchMBB) {
10259   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10260          "Clusters not sorted?");
10261 
10262   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10263 
10264   // Balance the tree based on branch probabilities to create a near-optimal (in
10265   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10266   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10267   CaseClusterIt LastLeft = W.FirstCluster;
10268   CaseClusterIt FirstRight = W.LastCluster;
10269   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10270   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10271 
10272   // Move LastLeft and FirstRight towards each other from opposite directions to
10273   // find a partitioning of the clusters which balances the probability on both
10274   // sides. If LeftProb and RightProb are equal, alternate which side is
10275   // taken to ensure 0-probability nodes are distributed evenly.
10276   unsigned I = 0;
10277   while (LastLeft + 1 < FirstRight) {
10278     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10279       LeftProb += (++LastLeft)->Prob;
10280     else
10281       RightProb += (--FirstRight)->Prob;
10282     I++;
10283   }
10284 
10285   while (true) {
10286     // Our binary search tree differs from a typical BST in that ours can have up
10287     // to three values in each leaf. The pivot selection above doesn't take that
10288     // into account, which means the tree might require more nodes and be less
10289     // efficient. We compensate for this here.
10290 
10291     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10292     unsigned NumRight = W.LastCluster - FirstRight + 1;
10293 
10294     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10295       // If one side has less than 3 clusters, and the other has more than 3,
10296       // consider taking a cluster from the other side.
10297 
10298       if (NumLeft < NumRight) {
10299         // Consider moving the first cluster on the right to the left side.
10300         CaseCluster &CC = *FirstRight;
10301         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10302         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10303         if (LeftSideRank <= RightSideRank) {
10304           // Moving the cluster to the left does not demote it.
10305           ++LastLeft;
10306           ++FirstRight;
10307           continue;
10308         }
10309       } else {
10310         assert(NumRight < NumLeft);
10311         // Consider moving the last element on the left to the right side.
10312         CaseCluster &CC = *LastLeft;
10313         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10314         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10315         if (RightSideRank <= LeftSideRank) {
10316           // Moving the cluster to the right does not demot it.
10317           --LastLeft;
10318           --FirstRight;
10319           continue;
10320         }
10321       }
10322     }
10323     break;
10324   }
10325 
10326   assert(LastLeft + 1 == FirstRight);
10327   assert(LastLeft >= W.FirstCluster);
10328   assert(FirstRight <= W.LastCluster);
10329 
10330   // Use the first element on the right as pivot since we will make less-than
10331   // comparisons against it.
10332   CaseClusterIt PivotCluster = FirstRight;
10333   assert(PivotCluster > W.FirstCluster);
10334   assert(PivotCluster <= W.LastCluster);
10335 
10336   CaseClusterIt FirstLeft = W.FirstCluster;
10337   CaseClusterIt LastRight = W.LastCluster;
10338 
10339   const ConstantInt *Pivot = PivotCluster->Low;
10340 
10341   // New blocks will be inserted immediately after the current one.
10342   MachineFunction::iterator BBI(W.MBB);
10343   ++BBI;
10344 
10345   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10346   // we can branch to its destination directly if it's squeezed exactly in
10347   // between the known lower bound and Pivot - 1.
10348   MachineBasicBlock *LeftMBB;
10349   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10350       FirstLeft->Low == W.GE &&
10351       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10352     LeftMBB = FirstLeft->MBB;
10353   } else {
10354     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10355     FuncInfo.MF->insert(BBI, LeftMBB);
10356     WorkList.push_back(
10357         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10358     // Put Cond in a virtual register to make it available from the new blocks.
10359     ExportFromCurrentBlock(Cond);
10360   }
10361 
10362   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10363   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10364   // directly if RHS.High equals the current upper bound.
10365   MachineBasicBlock *RightMBB;
10366   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10367       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10368     RightMBB = FirstRight->MBB;
10369   } else {
10370     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10371     FuncInfo.MF->insert(BBI, RightMBB);
10372     WorkList.push_back(
10373         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10374     // Put Cond in a virtual register to make it available from the new blocks.
10375     ExportFromCurrentBlock(Cond);
10376   }
10377 
10378   // Create the CaseBlock record that will be used to lower the branch.
10379   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10380                getCurSDLoc(), LeftProb, RightProb);
10381 
10382   if (W.MBB == SwitchMBB)
10383     visitSwitchCase(CB, SwitchMBB);
10384   else
10385     SL->SwitchCases.push_back(CB);
10386 }
10387 
10388 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10389 // from the swith statement.
10390 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10391                                             BranchProbability PeeledCaseProb) {
10392   if (PeeledCaseProb == BranchProbability::getOne())
10393     return BranchProbability::getZero();
10394   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10395 
10396   uint32_t Numerator = CaseProb.getNumerator();
10397   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10398   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10399 }
10400 
10401 // Try to peel the top probability case if it exceeds the threshold.
10402 // Return current MachineBasicBlock for the switch statement if the peeling
10403 // does not occur.
10404 // If the peeling is performed, return the newly created MachineBasicBlock
10405 // for the peeled switch statement. Also update Clusters to remove the peeled
10406 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10407 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10408     const SwitchInst &SI, CaseClusterVector &Clusters,
10409     BranchProbability &PeeledCaseProb) {
10410   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10411   // Don't perform if there is only one cluster or optimizing for size.
10412   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10413       TM.getOptLevel() == CodeGenOpt::None ||
10414       SwitchMBB->getParent()->getFunction().hasMinSize())
10415     return SwitchMBB;
10416 
10417   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10418   unsigned PeeledCaseIndex = 0;
10419   bool SwitchPeeled = false;
10420   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10421     CaseCluster &CC = Clusters[Index];
10422     if (CC.Prob < TopCaseProb)
10423       continue;
10424     TopCaseProb = CC.Prob;
10425     PeeledCaseIndex = Index;
10426     SwitchPeeled = true;
10427   }
10428   if (!SwitchPeeled)
10429     return SwitchMBB;
10430 
10431   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10432                     << TopCaseProb << "\n");
10433 
10434   // Record the MBB for the peeled switch statement.
10435   MachineFunction::iterator BBI(SwitchMBB);
10436   ++BBI;
10437   MachineBasicBlock *PeeledSwitchMBB =
10438       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10439   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10440 
10441   ExportFromCurrentBlock(SI.getCondition());
10442   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10443   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10444                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10445   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10446 
10447   Clusters.erase(PeeledCaseIt);
10448   for (CaseCluster &CC : Clusters) {
10449     LLVM_DEBUG(
10450         dbgs() << "Scale the probablity for one cluster, before scaling: "
10451                << CC.Prob << "\n");
10452     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10453     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10454   }
10455   PeeledCaseProb = TopCaseProb;
10456   return PeeledSwitchMBB;
10457 }
10458 
10459 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10460   // Extract cases from the switch.
10461   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10462   CaseClusterVector Clusters;
10463   Clusters.reserve(SI.getNumCases());
10464   for (auto I : SI.cases()) {
10465     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10466     const ConstantInt *CaseVal = I.getCaseValue();
10467     BranchProbability Prob =
10468         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10469             : BranchProbability(1, SI.getNumCases() + 1);
10470     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10471   }
10472 
10473   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10474 
10475   // Cluster adjacent cases with the same destination. We do this at all
10476   // optimization levels because it's cheap to do and will make codegen faster
10477   // if there are many clusters.
10478   sortAndRangeify(Clusters);
10479 
10480   // The branch probablity of the peeled case.
10481   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10482   MachineBasicBlock *PeeledSwitchMBB =
10483       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10484 
10485   // If there is only the default destination, jump there directly.
10486   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10487   if (Clusters.empty()) {
10488     assert(PeeledSwitchMBB == SwitchMBB);
10489     SwitchMBB->addSuccessor(DefaultMBB);
10490     if (DefaultMBB != NextBlock(SwitchMBB)) {
10491       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10492                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10493     }
10494     return;
10495   }
10496 
10497   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10498   SL->findBitTestClusters(Clusters, &SI);
10499 
10500   LLVM_DEBUG({
10501     dbgs() << "Case clusters: ";
10502     for (const CaseCluster &C : Clusters) {
10503       if (C.Kind == CC_JumpTable)
10504         dbgs() << "JT:";
10505       if (C.Kind == CC_BitTests)
10506         dbgs() << "BT:";
10507 
10508       C.Low->getValue().print(dbgs(), true);
10509       if (C.Low != C.High) {
10510         dbgs() << '-';
10511         C.High->getValue().print(dbgs(), true);
10512       }
10513       dbgs() << ' ';
10514     }
10515     dbgs() << '\n';
10516   });
10517 
10518   assert(!Clusters.empty());
10519   SwitchWorkList WorkList;
10520   CaseClusterIt First = Clusters.begin();
10521   CaseClusterIt Last = Clusters.end() - 1;
10522   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10523   // Scale the branchprobability for DefaultMBB if the peel occurs and
10524   // DefaultMBB is not replaced.
10525   if (PeeledCaseProb != BranchProbability::getZero() &&
10526       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10527     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10528   WorkList.push_back(
10529       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10530 
10531   while (!WorkList.empty()) {
10532     SwitchWorkListItem W = WorkList.back();
10533     WorkList.pop_back();
10534     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10535 
10536     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10537         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10538       // For optimized builds, lower large range as a balanced binary tree.
10539       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10540       continue;
10541     }
10542 
10543     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10544   }
10545 }
10546 
10547 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10548   SDValue N = getValue(I.getOperand(0));
10549   setValue(&I, N);
10550 }
10551