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