xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision a9a11aac0f943ef7eccb31214f9fd9eeb340a78e)
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/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 using namespace PatternMatch;
125 
126 #define DEBUG_TYPE "isel"
127 
128 /// LimitFloatPrecision - Generate low-precision inline sequences for
129 /// some float libcalls (6, 8 or 12 bits).
130 static unsigned LimitFloatPrecision;
131 
132 static cl::opt<unsigned, true>
133     LimitFPPrecision("limit-float-precision",
134                      cl::desc("Generate low-precision inline sequences "
135                               "for some float libcalls"),
136                      cl::location(LimitFloatPrecision), cl::Hidden,
137                      cl::init(0));
138 
139 static cl::opt<unsigned> SwitchPeelThreshold(
140     "switch-peel-threshold", cl::Hidden, cl::init(66),
141     cl::desc("Set the case probability threshold for peeling the case from a "
142              "switch statement. A value greater than 100 will void this "
143              "optimization"));
144 
145 // Limit the width of DAG chains. This is important in general to prevent
146 // DAG-based analysis from blowing up. For example, alias analysis and
147 // load clustering may not complete in reasonable time. It is difficult to
148 // recognize and avoid this situation within each individual analysis, and
149 // future analyses are likely to have the same behavior. Limiting DAG width is
150 // the safe approach and will be especially important with global DAGs.
151 //
152 // MaxParallelChains default is arbitrarily high to avoid affecting
153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
154 // sequence over this should have been converted to llvm.memcpy by the
155 // frontend. It is easy to induce this behavior with .ll code such as:
156 // %buffer = alloca [4096 x i8]
157 // %data = load [4096 x i8]* %argPtr
158 // store [4096 x i8] %data, [4096 x i8]* %buffer
159 static const unsigned MaxParallelChains = 64;
160 
161 // Return the calling convention if the Value passed requires ABI mangling as it
162 // is a parameter to a function or a return value from a function which is not
163 // an intrinsic.
164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
165   if (auto *R = dyn_cast<ReturnInst>(V))
166     return R->getParent()->getParent()->getCallingConv();
167 
168   if (auto *CI = dyn_cast<CallInst>(V)) {
169     const bool IsInlineAsm = CI->isInlineAsm();
170     const bool IsIndirectFunctionCall =
171         !IsInlineAsm && !CI->getCalledFunction();
172 
173     // It is possible that the call instruction is an inline asm statement or an
174     // indirect function call in which case the return value of
175     // getCalledFunction() would be nullptr.
176     const bool IsInstrinsicCall =
177         !IsInlineAsm && !IsIndirectFunctionCall &&
178         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
179 
180     if (!IsInlineAsm && !IsInstrinsicCall)
181       return CI->getCallingConv();
182   }
183 
184   return None;
185 }
186 
187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
188                                       const SDValue *Parts, unsigned NumParts,
189                                       MVT PartVT, EVT ValueVT, const Value *V,
190                                       Optional<CallingConv::ID> CC);
191 
192 /// getCopyFromParts - Create a value that contains the specified legal parts
193 /// combined into the value they represent.  If the parts combine to a type
194 /// larger than ValueVT then AssertOp can be used to specify whether the extra
195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
196 /// (ISD::AssertSext).
197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
198                                 const SDValue *Parts, unsigned NumParts,
199                                 MVT PartVT, EVT ValueVT, const Value *V,
200                                 Optional<CallingConv::ID> CC = None,
201                                 Optional<ISD::NodeType> AssertOp = None) {
202   if (ValueVT.isVector())
203     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
204                                   CC);
205 
206   assert(NumParts > 0 && "No parts to assemble!");
207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
208   SDValue Val = Parts[0];
209 
210   if (NumParts > 1) {
211     // Assemble the value from multiple parts.
212     if (ValueVT.isInteger()) {
213       unsigned PartBits = PartVT.getSizeInBits();
214       unsigned ValueBits = ValueVT.getSizeInBits();
215 
216       // Assemble the power of 2 part.
217       unsigned RoundParts = NumParts & (NumParts - 1) ?
218         1 << Log2_32(NumParts) : NumParts;
219       unsigned RoundBits = PartBits * RoundParts;
220       EVT RoundVT = RoundBits == ValueBits ?
221         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
222       SDValue Lo, Hi;
223 
224       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
225 
226       if (RoundParts > 2) {
227         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
228                               PartVT, HalfVT, V);
229         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
230                               RoundParts / 2, PartVT, HalfVT, V);
231       } else {
232         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
233         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
234       }
235 
236       if (DAG.getDataLayout().isBigEndian())
237         std::swap(Lo, Hi);
238 
239       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
240 
241       if (RoundParts < NumParts) {
242         // Assemble the trailing non-power-of-2 part.
243         unsigned OddParts = NumParts - RoundParts;
244         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
246                               OddVT, V, CC);
247 
248         // Combine the round and odd parts.
249         Lo = Val;
250         if (DAG.getDataLayout().isBigEndian())
251           std::swap(Lo, Hi);
252         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
253         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
254         Hi =
255             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
256                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
257                                         TLI.getPointerTy(DAG.getDataLayout())));
258         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
259         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
260       }
261     } else if (PartVT.isFloatingPoint()) {
262       // FP split into multiple FP parts (for ppcf128)
263       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
264              "Unexpected split");
265       SDValue Lo, Hi;
266       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
267       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
268       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
269         std::swap(Lo, Hi);
270       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
271     } else {
272       // FP split into integer parts (soft fp)
273       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
274              !PartVT.isVector() && "Unexpected split");
275       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
276       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
277     }
278   }
279 
280   // There is now one part, held in Val.  Correct it to match ValueVT.
281   // PartEVT is the type of the register class that holds the value.
282   // ValueVT is the type of the inline asm operation.
283   EVT PartEVT = Val.getValueType();
284 
285   if (PartEVT == ValueVT)
286     return Val;
287 
288   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
289       ValueVT.bitsLT(PartEVT)) {
290     // For an FP value in an integer part, we need to truncate to the right
291     // width first.
292     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
293     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
294   }
295 
296   // Handle types that have the same size.
297   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
298     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
299 
300   // Handle types with different sizes.
301   if (PartEVT.isInteger() && ValueVT.isInteger()) {
302     if (ValueVT.bitsLT(PartEVT)) {
303       // For a truncate, see if we have any information to
304       // indicate whether the truncated bits will always be
305       // zero or sign-extension.
306       if (AssertOp.hasValue())
307         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
308                           DAG.getValueType(ValueVT));
309       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
310     }
311     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
312   }
313 
314   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
315     // FP_ROUND's are always exact here.
316     if (ValueVT.bitsLT(Val.getValueType()))
317       return DAG.getNode(
318           ISD::FP_ROUND, DL, ValueVT, Val,
319           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
320 
321     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
322   }
323 
324   llvm_unreachable("Unknown mismatch!");
325 }
326 
327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
328                                               const Twine &ErrMsg) {
329   const Instruction *I = dyn_cast_or_null<Instruction>(V);
330   if (!V)
331     return Ctx.emitError(ErrMsg);
332 
333   const char *AsmError = ", possible invalid constraint for vector type";
334   if (const CallInst *CI = dyn_cast<CallInst>(I))
335     if (isa<InlineAsm>(CI->getCalledValue()))
336       return Ctx.emitError(I, ErrMsg + AsmError);
337 
338   return Ctx.emitError(I, ErrMsg);
339 }
340 
341 /// getCopyFromPartsVector - Create a value that contains the specified legal
342 /// parts combined into the value they represent.  If the parts combine to a
343 /// type larger than ValueVT then AssertOp can be used to specify whether the
344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
345 /// ValueVT (ISD::AssertSext).
346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
347                                       const SDValue *Parts, unsigned NumParts,
348                                       MVT PartVT, EVT ValueVT, const Value *V,
349                                       Optional<CallingConv::ID> CallConv) {
350   assert(ValueVT.isVector() && "Not a vector value");
351   assert(NumParts > 0 && "No parts to assemble!");
352   const bool IsABIRegCopy = CallConv.hasValue();
353 
354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
355   SDValue Val = Parts[0];
356 
357   // Handle a multi-element vector.
358   if (NumParts > 1) {
359     EVT IntermediateVT;
360     MVT RegisterVT;
361     unsigned NumIntermediates;
362     unsigned NumRegs;
363 
364     if (IsABIRegCopy) {
365       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
366           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
367           NumIntermediates, RegisterVT);
368     } else {
369       NumRegs =
370           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
371                                      NumIntermediates, RegisterVT);
372     }
373 
374     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
375     NumParts = NumRegs; // Silence a compiler warning.
376     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
377     assert(RegisterVT.getSizeInBits() ==
378            Parts[0].getSimpleValueType().getSizeInBits() &&
379            "Part type sizes don't match!");
380 
381     // Assemble the parts into intermediate operands.
382     SmallVector<SDValue, 8> Ops(NumIntermediates);
383     if (NumIntermediates == NumParts) {
384       // If the register was not expanded, truncate or copy the value,
385       // as appropriate.
386       for (unsigned i = 0; i != NumParts; ++i)
387         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
388                                   PartVT, IntermediateVT, V);
389     } else if (NumParts > 0) {
390       // If the intermediate type was expanded, build the intermediate
391       // operands from the parts.
392       assert(NumParts % NumIntermediates == 0 &&
393              "Must expand into a divisible number of parts!");
394       unsigned Factor = NumParts / NumIntermediates;
395       for (unsigned i = 0; i != NumIntermediates; ++i)
396         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
397                                   PartVT, IntermediateVT, V);
398     }
399 
400     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
401     // intermediate operands.
402     EVT BuiltVectorTy =
403         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
404                          (IntermediateVT.isVector()
405                               ? IntermediateVT.getVectorNumElements() * NumParts
406                               : NumIntermediates));
407     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
408                                                 : ISD::BUILD_VECTOR,
409                       DL, BuiltVectorTy, Ops);
410   }
411 
412   // There is now one part, held in Val.  Correct it to match ValueVT.
413   EVT PartEVT = Val.getValueType();
414 
415   if (PartEVT == ValueVT)
416     return Val;
417 
418   if (PartEVT.isVector()) {
419     // If the element type of the source/dest vectors are the same, but the
420     // parts vector has more elements than the value vector, then we have a
421     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
422     // elements we want.
423     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
424       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
425              "Cannot narrow, it would be a lossy transformation");
426       return DAG.getNode(
427           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
428           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
429     }
430 
431     // Vector/Vector bitcast.
432     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
433       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434 
435     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
436       "Cannot handle this kind of promotion");
437     // Promoted vector extract
438     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
439 
440   }
441 
442   // Trivial bitcast if the types are the same size and the destination
443   // vector type is legal.
444   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
445       TLI.isTypeLegal(ValueVT))
446     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
447 
448   if (ValueVT.getVectorNumElements() != 1) {
449      // Certain ABIs require that vectors are passed as integers. For vectors
450      // are the same size, this is an obvious bitcast.
451      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
452        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
454        // Bitcast Val back the original type and extract the corresponding
455        // vector we want.
456        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
457        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
458                                            ValueVT.getVectorElementType(), Elts);
459        Val = DAG.getBitcast(WiderVecType, Val);
460        return DAG.getNode(
461            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
462            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
463      }
464 
465      diagnosePossiblyInvalidConstraint(
466          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
467      return DAG.getUNDEF(ValueVT);
468   }
469 
470   // Handle cases such as i8 -> <1 x i1>
471   EVT ValueSVT = ValueVT.getVectorElementType();
472   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
473     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
474                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
475 
476   return DAG.getBuildVector(ValueVT, DL, Val);
477 }
478 
479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
480                                  SDValue Val, SDValue *Parts, unsigned NumParts,
481                                  MVT PartVT, const Value *V,
482                                  Optional<CallingConv::ID> CallConv);
483 
484 /// getCopyToParts - Create a series of nodes that contain the specified value
485 /// split into legal parts.  If the parts contain more bits than Val, then, for
486 /// integers, ExtendKind can be used to specify how to generate the extra bits.
487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
488                            SDValue *Parts, unsigned NumParts, MVT PartVT,
489                            const Value *V,
490                            Optional<CallingConv::ID> CallConv = None,
491                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned PartBits = PartVT.getSizeInBits();
500   unsigned OrigNumParts = NumParts;
501   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
502          "Copying to an illegal type!");
503 
504   if (NumParts == 0)
505     return;
506 
507   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
508   EVT PartEVT = PartVT;
509   if (PartEVT == ValueVT) {
510     assert(NumParts == 1 && "No-op copy with multiple parts!");
511     Parts[0] = Val;
512     return;
513   }
514 
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = 1 << Log2_32(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575                                  DAG.getIntPtrConstant(RoundBits, DL));
576     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577                    CallConv);
578 
579     if (DAG.getDataLayout().isBigEndian())
580       // The odd parts were reversed by getCopyToParts - unreverse them.
581       std::reverse(Parts + RoundParts, Parts + NumParts);
582 
583     NumParts = RoundParts;
584     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586   }
587 
588   // The number of parts is a power of 2.  Repeatedly bisect the value using
589   // EXTRACT_ELEMENT.
590   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591                          EVT::getIntegerVT(*DAG.getContext(),
592                                            ValueVT.getSizeInBits()),
593                          Val);
594 
595   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596     for (unsigned i = 0; i < NumParts; i += StepSize) {
597       unsigned ThisBits = StepSize * PartBits / 2;
598       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599       SDValue &Part0 = Parts[i];
600       SDValue &Part1 = Parts[i+StepSize/2];
601 
602       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606 
607       if (ThisBits == PartBits && ThisVT != PartVT) {
608         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610       }
611     }
612   }
613 
614   if (DAG.getDataLayout().isBigEndian())
615     std::reverse(Parts, Parts + OrigNumParts);
616 }
617 
618 static SDValue widenVectorToPartType(SelectionDAG &DAG,
619                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
620   if (!PartVT.isVector())
621     return SDValue();
622 
623   EVT ValueVT = Val.getValueType();
624   unsigned PartNumElts = PartVT.getVectorNumElements();
625   unsigned ValueNumElts = ValueVT.getVectorNumElements();
626   if (PartNumElts > ValueNumElts &&
627       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
628     EVT ElementVT = PartVT.getVectorElementType();
629     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630     // undef elements.
631     SmallVector<SDValue, 16> Ops;
632     DAG.ExtractVectorElements(Val, Ops);
633     SDValue EltUndef = DAG.getUNDEF(ElementVT);
634     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
635       Ops.push_back(EltUndef);
636 
637     // FIXME: Use CONCAT for 2x -> 4x.
638     return DAG.getBuildVector(PartVT, DL, Ops);
639   }
640 
641   return SDValue();
642 }
643 
644 /// getCopyToPartsVector - Create a series of nodes that contain the specified
645 /// value split into legal parts.
646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
647                                  SDValue Val, SDValue *Parts, unsigned NumParts,
648                                  MVT PartVT, const Value *V,
649                                  Optional<CallingConv::ID> CallConv) {
650   EVT ValueVT = Val.getValueType();
651   assert(ValueVT.isVector() && "Not a vector");
652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
653   const bool IsABIRegCopy = CallConv.hasValue();
654 
655   if (NumParts == 1) {
656     EVT PartEVT = PartVT;
657     if (PartEVT == ValueVT) {
658       // Nothing to do.
659     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
660       // Bitconvert vector->vector case.
661       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
662     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
663       Val = Widened;
664     } else if (PartVT.isVector() &&
665                PartEVT.getVectorElementType().bitsGE(
666                  ValueVT.getVectorElementType()) &&
667                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
668 
669       // Promoted vector extract
670       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
671     } else {
672       if (ValueVT.getVectorNumElements() == 1) {
673         Val = DAG.getNode(
674             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
675             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
676       } else {
677         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
678                "lossy conversion of vector to scalar type");
679         EVT IntermediateType =
680             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
681         Val = DAG.getBitcast(IntermediateType, Val);
682         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683       }
684     }
685 
686     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
687     Parts[0] = Val;
688     return;
689   }
690 
691   // Handle a multi-element vector.
692   EVT IntermediateVT;
693   MVT RegisterVT;
694   unsigned NumIntermediates;
695   unsigned NumRegs;
696   if (IsABIRegCopy) {
697     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
698         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
699         NumIntermediates, RegisterVT);
700   } else {
701     NumRegs =
702         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
703                                    NumIntermediates, RegisterVT);
704   }
705 
706   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
707   NumParts = NumRegs; // Silence a compiler warning.
708   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
709 
710   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
711     IntermediateVT.getVectorNumElements() : 1;
712 
713   // Convert the vector to the appropiate type if necessary.
714   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
715 
716   EVT BuiltVectorTy = EVT::getVectorVT(
717       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
718   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
719   if (ValueVT != BuiltVectorTy) {
720     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
721       Val = Widened;
722 
723     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
724   }
725 
726   // Split the vector into intermediate operands.
727   SmallVector<SDValue, 8> Ops(NumIntermediates);
728   for (unsigned i = 0; i != NumIntermediates; ++i) {
729     if (IntermediateVT.isVector()) {
730       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
731                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
732     } else {
733       Ops[i] = DAG.getNode(
734           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
735           DAG.getConstant(i, DL, IdxVT));
736     }
737   }
738 
739   // Split the intermediate operands into legal parts.
740   if (NumParts == NumIntermediates) {
741     // If the register was not expanded, promote or copy the value,
742     // as appropriate.
743     for (unsigned i = 0; i != NumParts; ++i)
744       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
745   } else if (NumParts > 0) {
746     // If the intermediate type was expanded, split each the value into
747     // legal parts.
748     assert(NumIntermediates != 0 && "division by zero");
749     assert(NumParts % NumIntermediates == 0 &&
750            "Must expand into a divisible number of parts!");
751     unsigned Factor = NumParts / NumIntermediates;
752     for (unsigned i = 0; i != NumIntermediates; ++i)
753       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
754                      CallConv);
755   }
756 }
757 
758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
759                            EVT valuevt, Optional<CallingConv::ID> CC)
760     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
761       RegCount(1, regs.size()), CallConv(CC) {}
762 
763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
764                            const DataLayout &DL, unsigned Reg, Type *Ty,
765                            Optional<CallingConv::ID> CC) {
766   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
767 
768   CallConv = CC;
769 
770   for (EVT ValueVT : ValueVTs) {
771     unsigned NumRegs =
772         isABIMangled()
773             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
774             : TLI.getNumRegisters(Context, ValueVT);
775     MVT RegisterVT =
776         isABIMangled()
777             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
778             : TLI.getRegisterType(Context, ValueVT);
779     for (unsigned i = 0; i != NumRegs; ++i)
780       Regs.push_back(Reg + i);
781     RegVTs.push_back(RegisterVT);
782     RegCount.push_back(NumRegs);
783     Reg += NumRegs;
784   }
785 }
786 
787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
788                                       FunctionLoweringInfo &FuncInfo,
789                                       const SDLoc &dl, SDValue &Chain,
790                                       SDValue *Flag, const Value *V) const {
791   // A Value with type {} or [0 x %t] needs no registers.
792   if (ValueVTs.empty())
793     return SDValue();
794 
795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
796 
797   // Assemble the legal parts into the final values.
798   SmallVector<SDValue, 4> Values(ValueVTs.size());
799   SmallVector<SDValue, 8> Parts;
800   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
801     // Copy the legal parts from the registers.
802     EVT ValueVT = ValueVTs[Value];
803     unsigned NumRegs = RegCount[Value];
804     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
805                                           *DAG.getContext(),
806                                           CallConv.getValue(), RegVTs[Value])
807                                     : RegVTs[Value];
808 
809     Parts.resize(NumRegs);
810     for (unsigned i = 0; i != NumRegs; ++i) {
811       SDValue P;
812       if (!Flag) {
813         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
814       } else {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
816         *Flag = P.getValue(2);
817       }
818 
819       Chain = P.getValue(1);
820       Parts[i] = P;
821 
822       // If the source register was virtual and if we know something about it,
823       // add an assert node.
824       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
825           !RegisterVT.isInteger())
826         continue;
827 
828       const FunctionLoweringInfo::LiveOutInfo *LOI =
829         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
830       if (!LOI)
831         continue;
832 
833       unsigned RegSize = RegisterVT.getScalarSizeInBits();
834       unsigned NumSignBits = LOI->NumSignBits;
835       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
836 
837       if (NumZeroBits == RegSize) {
838         // The current value is a zero.
839         // Explicitly express that as it would be easier for
840         // optimizations to kick in.
841         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
842         continue;
843       }
844 
845       // FIXME: We capture more information than the dag can represent.  For
846       // now, just use the tightest assertzext/assertsext possible.
847       bool isSExt;
848       EVT FromVT(MVT::Other);
849       if (NumZeroBits) {
850         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
851         isSExt = false;
852       } else if (NumSignBits > 1) {
853         FromVT =
854             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
855         isSExt = true;
856       } else {
857         continue;
858       }
859       // Add an assertion node.
860       assert(FromVT != MVT::Other);
861       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
862                              RegisterVT, P, DAG.getValueType(FromVT));
863     }
864 
865     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
866                                      RegisterVT, ValueVT, V, CallConv);
867     Part += NumRegs;
868     Parts.clear();
869   }
870 
871   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
872 }
873 
874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
875                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
876                                  const Value *V,
877                                  ISD::NodeType PreferredExtendType) const {
878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
879   ISD::NodeType ExtendKind = PreferredExtendType;
880 
881   // Get the list of the values's legal parts.
882   unsigned NumRegs = Regs.size();
883   SmallVector<SDValue, 8> Parts(NumRegs);
884   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
885     unsigned NumParts = RegCount[Value];
886 
887     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
888                                           *DAG.getContext(),
889                                           CallConv.getValue(), RegVTs[Value])
890                                     : RegVTs[Value];
891 
892     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
893       ExtendKind = ISD::ZERO_EXTEND;
894 
895     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
896                    NumParts, RegisterVT, V, CallConv, ExtendKind);
897     Part += NumParts;
898   }
899 
900   // Copy the parts into the registers.
901   SmallVector<SDValue, 8> Chains(NumRegs);
902   for (unsigned i = 0; i != NumRegs; ++i) {
903     SDValue Part;
904     if (!Flag) {
905       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
906     } else {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
908       *Flag = Part.getValue(1);
909     }
910 
911     Chains[i] = Part.getValue(0);
912   }
913 
914   if (NumRegs == 1 || Flag)
915     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
916     // flagged to it. That is the CopyToReg nodes and the user are considered
917     // a single scheduling unit. If we create a TokenFactor and return it as
918     // chain, then the TokenFactor is both a predecessor (operand) of the
919     // user as well as a successor (the TF operands are flagged to the user).
920     // c1, f1 = CopyToReg
921     // c2, f2 = CopyToReg
922     // c3     = TokenFactor c1, c2
923     // ...
924     //        = op c3, ..., f2
925     Chain = Chains[NumRegs-1];
926   else
927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
928 }
929 
930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
931                                         unsigned MatchingIdx, const SDLoc &dl,
932                                         SelectionDAG &DAG,
933                                         std::vector<SDValue> &Ops) const {
934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
935 
936   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
937   if (HasMatching)
938     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
939   else if (!Regs.empty() &&
940            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, unsigned>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     unsigned RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005 }
1006 
1007 void SelectionDAGBuilder::clear() {
1008   NodeMap.clear();
1009   UnusedArgNodeMap.clear();
1010   PendingLoads.clear();
1011   PendingExports.clear();
1012   CurInst = nullptr;
1013   HasTailCall = false;
1014   SDNodeOrder = LowestSDNodeOrder;
1015   StatepointLowering.clear();
1016 }
1017 
1018 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1019   DanglingDebugInfoMap.clear();
1020 }
1021 
1022 SDValue SelectionDAGBuilder::getRoot() {
1023   if (PendingLoads.empty())
1024     return DAG.getRoot();
1025 
1026   if (PendingLoads.size() == 1) {
1027     SDValue Root = PendingLoads[0];
1028     DAG.setRoot(Root);
1029     PendingLoads.clear();
1030     return Root;
1031   }
1032 
1033   // Otherwise, we have to make a token factor node.
1034   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1035   PendingLoads.clear();
1036   DAG.setRoot(Root);
1037   return Root;
1038 }
1039 
1040 SDValue SelectionDAGBuilder::getControlRoot() {
1041   SDValue Root = DAG.getRoot();
1042 
1043   if (PendingExports.empty())
1044     return Root;
1045 
1046   // Turn all of the CopyToReg chains into one factored node.
1047   if (Root.getOpcode() != ISD::EntryToken) {
1048     unsigned i = 0, e = PendingExports.size();
1049     for (; i != e; ++i) {
1050       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1051       if (PendingExports[i].getNode()->getOperand(0) == Root)
1052         break;  // Don't add the root if we already indirectly depend on it.
1053     }
1054 
1055     if (i == e)
1056       PendingExports.push_back(Root);
1057   }
1058 
1059   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1060                      PendingExports);
1061   PendingExports.clear();
1062   DAG.setRoot(Root);
1063   return Root;
1064 }
1065 
1066 void SelectionDAGBuilder::visit(const Instruction &I) {
1067   // Set up outgoing PHI node register values before emitting the terminator.
1068   if (I.isTerminator()) {
1069     HandlePHINodesInSuccessorBlocks(I.getParent());
1070   }
1071 
1072   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1073   if (!isa<DbgInfoIntrinsic>(I))
1074     ++SDNodeOrder;
1075 
1076   CurInst = &I;
1077 
1078   visit(I.getOpcode(), I);
1079 
1080   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1081     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1082     // maps to this instruction.
1083     // TODO: We could handle all flags (nsw, etc) here.
1084     // TODO: If an IR instruction maps to >1 node, only the final node will have
1085     //       flags set.
1086     if (SDNode *Node = getNodeForIRValue(&I)) {
1087       SDNodeFlags IncomingFlags;
1088       IncomingFlags.copyFMF(*FPMO);
1089       if (!Node->getFlags().isDefined())
1090         Node->setFlags(IncomingFlags);
1091       else
1092         Node->intersectFlagsWith(IncomingFlags);
1093     }
1094   }
1095 
1096   if (!I.isTerminator() && !HasTailCall &&
1097       !isStatepoint(&I)) // statepoints handle their exports internally
1098     CopyToExportRegsIfNeeded(&I);
1099 
1100   CurInst = nullptr;
1101 }
1102 
1103 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1104   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1105 }
1106 
1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1108   // Note: this doesn't use InstVisitor, because it has to work with
1109   // ConstantExpr's in addition to instructions.
1110   switch (Opcode) {
1111   default: llvm_unreachable("Unknown instruction type encountered!");
1112     // Build the switch statement using the Instruction.def file.
1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1114     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1115 #include "llvm/IR/Instruction.def"
1116   }
1117 }
1118 
1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1120                                                 const DIExpression *Expr) {
1121   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1122     const DbgValueInst *DI = DDI.getDI();
1123     DIVariable *DanglingVariable = DI->getVariable();
1124     DIExpression *DanglingExpr = DI->getExpression();
1125     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1126       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1127       return true;
1128     }
1129     return false;
1130   };
1131 
1132   for (auto &DDIMI : DanglingDebugInfoMap) {
1133     DanglingDebugInfoVector &DDIV = DDIMI.second;
1134     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1135   }
1136 }
1137 
1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1139 // generate the debug data structures now that we've seen its definition.
1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1141                                                    SDValue Val) {
1142   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1143   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1144     return;
1145 
1146   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1147   for (auto &DDI : DDIV) {
1148     const DbgValueInst *DI = DDI.getDI();
1149     assert(DI && "Ill-formed DanglingDebugInfo");
1150     DebugLoc dl = DDI.getdl();
1151     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1152     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1153     DILocalVariable *Variable = DI->getVariable();
1154     DIExpression *Expr = DI->getExpression();
1155     assert(Variable->isValidLocationForIntrinsic(dl) &&
1156            "Expected inlined-at fields to agree");
1157     SDDbgValue *SDV;
1158     if (Val.getNode()) {
1159       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1160       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1161       // we couldn't resolve it directly when examining the DbgValue intrinsic
1162       // in the first place we should not be more successful here). Unless we
1163       // have some test case that prove this to be correct we should avoid
1164       // calling EmitFuncArgumentDbgValue here.
1165       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1166         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1167                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1168         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1169         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1170         // inserted after the definition of Val when emitting the instructions
1171         // after ISel. An alternative could be to teach
1172         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1173         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1174                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1175                    << ValSDNodeOrder << "\n");
1176         SDV = getDbgValue(Val, Variable, Expr, dl,
1177                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1178         DAG.AddDbgValue(SDV, Val.getNode(), false);
1179       } else
1180         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1181                           << "in EmitFuncArgumentDbgValue\n");
1182     } else
1183       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1184   }
1185   DDIV.clear();
1186 }
1187 
1188 /// getCopyFromRegs - If there was virtual register allocated for the value V
1189 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1190 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1191   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1192   SDValue Result;
1193 
1194   if (It != FuncInfo.ValueMap.end()) {
1195     unsigned InReg = It->second;
1196 
1197     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1198                      DAG.getDataLayout(), InReg, Ty,
1199                      None); // This is not an ABI copy.
1200     SDValue Chain = DAG.getEntryNode();
1201     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1202                                  V);
1203     resolveDanglingDebugInfo(V, Result);
1204   }
1205 
1206   return Result;
1207 }
1208 
1209 /// getValue - Return an SDValue for the given Value.
1210 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1211   // If we already have an SDValue for this value, use it. It's important
1212   // to do this first, so that we don't create a CopyFromReg if we already
1213   // have a regular SDValue.
1214   SDValue &N = NodeMap[V];
1215   if (N.getNode()) return N;
1216 
1217   // If there's a virtual register allocated and initialized for this
1218   // value, use it.
1219   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1220     return copyFromReg;
1221 
1222   // Otherwise create a new SDValue and remember it.
1223   SDValue Val = getValueImpl(V);
1224   NodeMap[V] = Val;
1225   resolveDanglingDebugInfo(V, Val);
1226   return Val;
1227 }
1228 
1229 // Return true if SDValue exists for the given Value
1230 bool SelectionDAGBuilder::findValue(const Value *V) const {
1231   return (NodeMap.find(V) != NodeMap.end()) ||
1232     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1233 }
1234 
1235 /// getNonRegisterValue - Return an SDValue for the given Value, but
1236 /// don't look in FuncInfo.ValueMap for a virtual register.
1237 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1238   // If we already have an SDValue for this value, use it.
1239   SDValue &N = NodeMap[V];
1240   if (N.getNode()) {
1241     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1242       // Remove the debug location from the node as the node is about to be used
1243       // in a location which may differ from the original debug location.  This
1244       // is relevant to Constant and ConstantFP nodes because they can appear
1245       // as constant expressions inside PHI nodes.
1246       N->setDebugLoc(DebugLoc());
1247     }
1248     return N;
1249   }
1250 
1251   // Otherwise create a new SDValue and remember it.
1252   SDValue Val = getValueImpl(V);
1253   NodeMap[V] = Val;
1254   resolveDanglingDebugInfo(V, Val);
1255   return Val;
1256 }
1257 
1258 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1259 /// Create an SDValue for the given value.
1260 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1262 
1263   if (const Constant *C = dyn_cast<Constant>(V)) {
1264     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1265 
1266     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1267       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1268 
1269     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1270       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1271 
1272     if (isa<ConstantPointerNull>(C)) {
1273       unsigned AS = V->getType()->getPointerAddressSpace();
1274       return DAG.getConstant(0, getCurSDLoc(),
1275                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1276     }
1277 
1278     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1279       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1280 
1281     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1282       return DAG.getUNDEF(VT);
1283 
1284     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1285       visit(CE->getOpcode(), *CE);
1286       SDValue N1 = NodeMap[V];
1287       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1288       return N1;
1289     }
1290 
1291     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1292       SmallVector<SDValue, 4> Constants;
1293       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1294            OI != OE; ++OI) {
1295         SDNode *Val = getValue(*OI).getNode();
1296         // If the operand is an empty aggregate, there are no values.
1297         if (!Val) continue;
1298         // Add each leaf value from the operand to the Constants list
1299         // to form a flattened list of all the values.
1300         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1301           Constants.push_back(SDValue(Val, i));
1302       }
1303 
1304       return DAG.getMergeValues(Constants, getCurSDLoc());
1305     }
1306 
1307     if (const ConstantDataSequential *CDS =
1308           dyn_cast<ConstantDataSequential>(C)) {
1309       SmallVector<SDValue, 4> Ops;
1310       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1311         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1312         // Add each leaf value from the operand to the Constants list
1313         // to form a flattened list of all the values.
1314         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1315           Ops.push_back(SDValue(Val, i));
1316       }
1317 
1318       if (isa<ArrayType>(CDS->getType()))
1319         return DAG.getMergeValues(Ops, getCurSDLoc());
1320       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1321     }
1322 
1323     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1324       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1325              "Unknown struct or array constant!");
1326 
1327       SmallVector<EVT, 4> ValueVTs;
1328       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1329       unsigned NumElts = ValueVTs.size();
1330       if (NumElts == 0)
1331         return SDValue(); // empty struct
1332       SmallVector<SDValue, 4> Constants(NumElts);
1333       for (unsigned i = 0; i != NumElts; ++i) {
1334         EVT EltVT = ValueVTs[i];
1335         if (isa<UndefValue>(C))
1336           Constants[i] = DAG.getUNDEF(EltVT);
1337         else if (EltVT.isFloatingPoint())
1338           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1339         else
1340           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1341       }
1342 
1343       return DAG.getMergeValues(Constants, getCurSDLoc());
1344     }
1345 
1346     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1347       return DAG.getBlockAddress(BA, VT);
1348 
1349     VectorType *VecTy = cast<VectorType>(V->getType());
1350     unsigned NumElements = VecTy->getNumElements();
1351 
1352     // Now that we know the number and type of the elements, get that number of
1353     // elements into the Ops array based on what kind of constant it is.
1354     SmallVector<SDValue, 16> Ops;
1355     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1356       for (unsigned i = 0; i != NumElements; ++i)
1357         Ops.push_back(getValue(CV->getOperand(i)));
1358     } else {
1359       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1360       EVT EltVT =
1361           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1362 
1363       SDValue Op;
1364       if (EltVT.isFloatingPoint())
1365         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1366       else
1367         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1368       Ops.assign(NumElements, Op);
1369     }
1370 
1371     // Create a BUILD_VECTOR node.
1372     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1373   }
1374 
1375   // If this is a static alloca, generate it as the frameindex instead of
1376   // computation.
1377   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1378     DenseMap<const AllocaInst*, int>::iterator SI =
1379       FuncInfo.StaticAllocaMap.find(AI);
1380     if (SI != FuncInfo.StaticAllocaMap.end())
1381       return DAG.getFrameIndex(SI->second,
1382                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1383   }
1384 
1385   // If this is an instruction which fast-isel has deferred, select it now.
1386   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1387     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1388 
1389     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1390                      Inst->getType(), getABIRegCopyCC(V));
1391     SDValue Chain = DAG.getEntryNode();
1392     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1393   }
1394 
1395   llvm_unreachable("Can't get register for value!");
1396 }
1397 
1398 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1399   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1400   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1401   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1402   bool IsSEH = isAsynchronousEHPersonality(Pers);
1403   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1404   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1405   if (!IsSEH)
1406     CatchPadMBB->setIsEHScopeEntry();
1407   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1408   if (IsMSVCCXX || IsCoreCLR)
1409     CatchPadMBB->setIsEHFuncletEntry();
1410   // Wasm does not need catchpads anymore
1411   if (!IsWasmCXX)
1412     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1413                             getControlRoot()));
1414 }
1415 
1416 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1417   // Update machine-CFG edge.
1418   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1419   FuncInfo.MBB->addSuccessor(TargetMBB);
1420 
1421   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1422   bool IsSEH = isAsynchronousEHPersonality(Pers);
1423   if (IsSEH) {
1424     // If this is not a fall-through branch or optimizations are switched off,
1425     // emit the branch.
1426     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1427         TM.getOptLevel() == CodeGenOpt::None)
1428       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1429                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1430     return;
1431   }
1432 
1433   // Figure out the funclet membership for the catchret's successor.
1434   // This will be used by the FuncletLayout pass to determine how to order the
1435   // BB's.
1436   // A 'catchret' returns to the outer scope's color.
1437   Value *ParentPad = I.getCatchSwitchParentPad();
1438   const BasicBlock *SuccessorColor;
1439   if (isa<ConstantTokenNone>(ParentPad))
1440     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1441   else
1442     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1443   assert(SuccessorColor && "No parent funclet for catchret!");
1444   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1445   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1446 
1447   // Create the terminator node.
1448   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1449                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1450                             DAG.getBasicBlock(SuccessorColorMBB));
1451   DAG.setRoot(Ret);
1452 }
1453 
1454 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1455   // Don't emit any special code for the cleanuppad instruction. It just marks
1456   // the start of an EH scope/funclet.
1457   FuncInfo.MBB->setIsEHScopeEntry();
1458   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1459   if (Pers != EHPersonality::Wasm_CXX) {
1460     FuncInfo.MBB->setIsEHFuncletEntry();
1461     FuncInfo.MBB->setIsCleanupFuncletEntry();
1462   }
1463 }
1464 
1465 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1466 // the control flow always stops at the single catch pad, as it does for a
1467 // cleanup pad. In case the exception caught is not of the types the catch pad
1468 // catches, it will be rethrown by a rethrow.
1469 static void findWasmUnwindDestinations(
1470     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1471     BranchProbability Prob,
1472     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1473         &UnwindDests) {
1474   while (EHPadBB) {
1475     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1476     if (isa<CleanupPadInst>(Pad)) {
1477       // Stop on cleanup pads.
1478       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1479       UnwindDests.back().first->setIsEHScopeEntry();
1480       break;
1481     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1482       // Add the catchpad handlers to the possible destinations. We don't
1483       // continue to the unwind destination of the catchswitch for wasm.
1484       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1485         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1486         UnwindDests.back().first->setIsEHScopeEntry();
1487       }
1488       break;
1489     } else {
1490       continue;
1491     }
1492   }
1493 }
1494 
1495 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1496 /// many places it could ultimately go. In the IR, we have a single unwind
1497 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1498 /// This function skips over imaginary basic blocks that hold catchswitch
1499 /// instructions, and finds all the "real" machine
1500 /// basic block destinations. As those destinations may not be successors of
1501 /// EHPadBB, here we also calculate the edge probability to those destinations.
1502 /// The passed-in Prob is the edge probability to EHPadBB.
1503 static void findUnwindDestinations(
1504     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1505     BranchProbability Prob,
1506     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1507         &UnwindDests) {
1508   EHPersonality Personality =
1509     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1510   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1511   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1512   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1513   bool IsSEH = isAsynchronousEHPersonality(Personality);
1514 
1515   if (IsWasmCXX) {
1516     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1517     return;
1518   }
1519 
1520   while (EHPadBB) {
1521     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1522     BasicBlock *NewEHPadBB = nullptr;
1523     if (isa<LandingPadInst>(Pad)) {
1524       // Stop on landingpads. They are not funclets.
1525       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1526       break;
1527     } else if (isa<CleanupPadInst>(Pad)) {
1528       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1529       // personalities.
1530       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1531       UnwindDests.back().first->setIsEHScopeEntry();
1532       UnwindDests.back().first->setIsEHFuncletEntry();
1533       break;
1534     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1535       // Add the catchpad handlers to the possible destinations.
1536       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1537         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1538         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1539         if (IsMSVCCXX || IsCoreCLR)
1540           UnwindDests.back().first->setIsEHFuncletEntry();
1541         if (!IsSEH)
1542           UnwindDests.back().first->setIsEHScopeEntry();
1543       }
1544       NewEHPadBB = CatchSwitch->getUnwindDest();
1545     } else {
1546       continue;
1547     }
1548 
1549     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1550     if (BPI && NewEHPadBB)
1551       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1552     EHPadBB = NewEHPadBB;
1553   }
1554 }
1555 
1556 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1557   // Update successor info.
1558   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1559   auto UnwindDest = I.getUnwindDest();
1560   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1561   BranchProbability UnwindDestProb =
1562       (BPI && UnwindDest)
1563           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1564           : BranchProbability::getZero();
1565   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1566   for (auto &UnwindDest : UnwindDests) {
1567     UnwindDest.first->setIsEHPad();
1568     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1569   }
1570   FuncInfo.MBB->normalizeSuccProbs();
1571 
1572   // Create the terminator node.
1573   SDValue Ret =
1574       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1575   DAG.setRoot(Ret);
1576 }
1577 
1578 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1579   report_fatal_error("visitCatchSwitch not yet implemented!");
1580 }
1581 
1582 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1584   auto &DL = DAG.getDataLayout();
1585   SDValue Chain = getControlRoot();
1586   SmallVector<ISD::OutputArg, 8> Outs;
1587   SmallVector<SDValue, 8> OutVals;
1588 
1589   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1590   // lower
1591   //
1592   //   %val = call <ty> @llvm.experimental.deoptimize()
1593   //   ret <ty> %val
1594   //
1595   // differently.
1596   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1597     LowerDeoptimizingReturn();
1598     return;
1599   }
1600 
1601   if (!FuncInfo.CanLowerReturn) {
1602     unsigned DemoteReg = FuncInfo.DemoteRegister;
1603     const Function *F = I.getParent()->getParent();
1604 
1605     // Emit a store of the return value through the virtual register.
1606     // Leave Outs empty so that LowerReturn won't try to load return
1607     // registers the usual way.
1608     SmallVector<EVT, 1> PtrValueVTs;
1609     ComputeValueVTs(TLI, DL,
1610                     F->getReturnType()->getPointerTo(
1611                         DAG.getDataLayout().getAllocaAddrSpace()),
1612                     PtrValueVTs);
1613 
1614     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1615                                         DemoteReg, PtrValueVTs[0]);
1616     SDValue RetOp = getValue(I.getOperand(0));
1617 
1618     SmallVector<EVT, 4> ValueVTs;
1619     SmallVector<uint64_t, 4> Offsets;
1620     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1621     unsigned NumValues = ValueVTs.size();
1622 
1623     SmallVector<SDValue, 4> Chains(NumValues);
1624     for (unsigned i = 0; i != NumValues; ++i) {
1625       // An aggregate return value cannot wrap around the address space, so
1626       // offsets to its parts don't wrap either.
1627       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1628       Chains[i] = DAG.getStore(
1629           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1630           // FIXME: better loc info would be nice.
1631           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1632     }
1633 
1634     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1635                         MVT::Other, Chains);
1636   } else if (I.getNumOperands() != 0) {
1637     SmallVector<EVT, 4> ValueVTs;
1638     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1639     unsigned NumValues = ValueVTs.size();
1640     if (NumValues) {
1641       SDValue RetOp = getValue(I.getOperand(0));
1642 
1643       const Function *F = I.getParent()->getParent();
1644 
1645       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1646       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1647                                           Attribute::SExt))
1648         ExtendKind = ISD::SIGN_EXTEND;
1649       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1650                                                Attribute::ZExt))
1651         ExtendKind = ISD::ZERO_EXTEND;
1652 
1653       LLVMContext &Context = F->getContext();
1654       bool RetInReg = F->getAttributes().hasAttribute(
1655           AttributeList::ReturnIndex, Attribute::InReg);
1656 
1657       for (unsigned j = 0; j != NumValues; ++j) {
1658         EVT VT = ValueVTs[j];
1659 
1660         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1661           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1662 
1663         CallingConv::ID CC = F->getCallingConv();
1664 
1665         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1666         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1667         SmallVector<SDValue, 4> Parts(NumParts);
1668         getCopyToParts(DAG, getCurSDLoc(),
1669                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1670                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1671 
1672         // 'inreg' on function refers to return value
1673         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1674         if (RetInReg)
1675           Flags.setInReg();
1676 
1677         // Propagate extension type if any
1678         if (ExtendKind == ISD::SIGN_EXTEND)
1679           Flags.setSExt();
1680         else if (ExtendKind == ISD::ZERO_EXTEND)
1681           Flags.setZExt();
1682 
1683         for (unsigned i = 0; i < NumParts; ++i) {
1684           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1685                                         VT, /*isfixed=*/true, 0, 0));
1686           OutVals.push_back(Parts[i]);
1687         }
1688       }
1689     }
1690   }
1691 
1692   // Push in swifterror virtual register as the last element of Outs. This makes
1693   // sure swifterror virtual register will be returned in the swifterror
1694   // physical register.
1695   const Function *F = I.getParent()->getParent();
1696   if (TLI.supportSwiftError() &&
1697       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1698     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1699     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1700     Flags.setSwiftError();
1701     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1702                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1703                                   true /*isfixed*/, 1 /*origidx*/,
1704                                   0 /*partOffs*/));
1705     // Create SDNode for the swifterror virtual register.
1706     OutVals.push_back(
1707         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1708                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1709                         EVT(TLI.getPointerTy(DL))));
1710   }
1711 
1712   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1713   CallingConv::ID CallConv =
1714     DAG.getMachineFunction().getFunction().getCallingConv();
1715   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1716       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1717 
1718   // Verify that the target's LowerReturn behaved as expected.
1719   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1720          "LowerReturn didn't return a valid chain!");
1721 
1722   // Update the DAG with the new chain value resulting from return lowering.
1723   DAG.setRoot(Chain);
1724 }
1725 
1726 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1727 /// created for it, emit nodes to copy the value into the virtual
1728 /// registers.
1729 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1730   // Skip empty types
1731   if (V->getType()->isEmptyTy())
1732     return;
1733 
1734   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1735   if (VMI != FuncInfo.ValueMap.end()) {
1736     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1737     CopyValueToVirtualRegister(V, VMI->second);
1738   }
1739 }
1740 
1741 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1742 /// the current basic block, add it to ValueMap now so that we'll get a
1743 /// CopyTo/FromReg.
1744 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1745   // No need to export constants.
1746   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1747 
1748   // Already exported?
1749   if (FuncInfo.isExportedInst(V)) return;
1750 
1751   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1752   CopyValueToVirtualRegister(V, Reg);
1753 }
1754 
1755 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1756                                                      const BasicBlock *FromBB) {
1757   // The operands of the setcc have to be in this block.  We don't know
1758   // how to export them from some other block.
1759   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1760     // Can export from current BB.
1761     if (VI->getParent() == FromBB)
1762       return true;
1763 
1764     // Is already exported, noop.
1765     return FuncInfo.isExportedInst(V);
1766   }
1767 
1768   // If this is an argument, we can export it if the BB is the entry block or
1769   // if it is already exported.
1770   if (isa<Argument>(V)) {
1771     if (FromBB == &FromBB->getParent()->getEntryBlock())
1772       return true;
1773 
1774     // Otherwise, can only export this if it is already exported.
1775     return FuncInfo.isExportedInst(V);
1776   }
1777 
1778   // Otherwise, constants can always be exported.
1779   return true;
1780 }
1781 
1782 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1783 BranchProbability
1784 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1785                                         const MachineBasicBlock *Dst) const {
1786   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1787   const BasicBlock *SrcBB = Src->getBasicBlock();
1788   const BasicBlock *DstBB = Dst->getBasicBlock();
1789   if (!BPI) {
1790     // If BPI is not available, set the default probability as 1 / N, where N is
1791     // the number of successors.
1792     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1793     return BranchProbability(1, SuccSize);
1794   }
1795   return BPI->getEdgeProbability(SrcBB, DstBB);
1796 }
1797 
1798 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1799                                                MachineBasicBlock *Dst,
1800                                                BranchProbability Prob) {
1801   if (!FuncInfo.BPI)
1802     Src->addSuccessorWithoutProb(Dst);
1803   else {
1804     if (Prob.isUnknown())
1805       Prob = getEdgeProbability(Src, Dst);
1806     Src->addSuccessor(Dst, Prob);
1807   }
1808 }
1809 
1810 static bool InBlock(const Value *V, const BasicBlock *BB) {
1811   if (const Instruction *I = dyn_cast<Instruction>(V))
1812     return I->getParent() == BB;
1813   return true;
1814 }
1815 
1816 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1817 /// This function emits a branch and is used at the leaves of an OR or an
1818 /// AND operator tree.
1819 void
1820 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1821                                                   MachineBasicBlock *TBB,
1822                                                   MachineBasicBlock *FBB,
1823                                                   MachineBasicBlock *CurBB,
1824                                                   MachineBasicBlock *SwitchBB,
1825                                                   BranchProbability TProb,
1826                                                   BranchProbability FProb,
1827                                                   bool InvertCond) {
1828   const BasicBlock *BB = CurBB->getBasicBlock();
1829 
1830   // If the leaf of the tree is a comparison, merge the condition into
1831   // the caseblock.
1832   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1833     // The operands of the cmp have to be in this block.  We don't know
1834     // how to export them from some other block.  If this is the first block
1835     // of the sequence, no exporting is needed.
1836     if (CurBB == SwitchBB ||
1837         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1838          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1839       ISD::CondCode Condition;
1840       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1841         ICmpInst::Predicate Pred =
1842             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1843         Condition = getICmpCondCode(Pred);
1844       } else {
1845         const FCmpInst *FC = cast<FCmpInst>(Cond);
1846         FCmpInst::Predicate Pred =
1847             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1848         Condition = getFCmpCondCode(Pred);
1849         if (TM.Options.NoNaNsFPMath)
1850           Condition = getFCmpCodeWithoutNaN(Condition);
1851       }
1852 
1853       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1854                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1855       SwitchCases.push_back(CB);
1856       return;
1857     }
1858   }
1859 
1860   // Create a CaseBlock record representing this branch.
1861   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1862   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1863                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1864   SwitchCases.push_back(CB);
1865 }
1866 
1867 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1868                                                MachineBasicBlock *TBB,
1869                                                MachineBasicBlock *FBB,
1870                                                MachineBasicBlock *CurBB,
1871                                                MachineBasicBlock *SwitchBB,
1872                                                Instruction::BinaryOps Opc,
1873                                                BranchProbability TProb,
1874                                                BranchProbability FProb,
1875                                                bool InvertCond) {
1876   // Skip over not part of the tree and remember to invert op and operands at
1877   // next level.
1878   Value *NotCond;
1879   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1880       InBlock(NotCond, CurBB->getBasicBlock())) {
1881     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1882                          !InvertCond);
1883     return;
1884   }
1885 
1886   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1887   // Compute the effective opcode for Cond, taking into account whether it needs
1888   // to be inverted, e.g.
1889   //   and (not (or A, B)), C
1890   // gets lowered as
1891   //   and (and (not A, not B), C)
1892   unsigned BOpc = 0;
1893   if (BOp) {
1894     BOpc = BOp->getOpcode();
1895     if (InvertCond) {
1896       if (BOpc == Instruction::And)
1897         BOpc = Instruction::Or;
1898       else if (BOpc == Instruction::Or)
1899         BOpc = Instruction::And;
1900     }
1901   }
1902 
1903   // If this node is not part of the or/and tree, emit it as a branch.
1904   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1905       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1906       BOp->getParent() != CurBB->getBasicBlock() ||
1907       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1908       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1909     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1910                                  TProb, FProb, InvertCond);
1911     return;
1912   }
1913 
1914   //  Create TmpBB after CurBB.
1915   MachineFunction::iterator BBI(CurBB);
1916   MachineFunction &MF = DAG.getMachineFunction();
1917   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1918   CurBB->getParent()->insert(++BBI, TmpBB);
1919 
1920   if (Opc == Instruction::Or) {
1921     // Codegen X | Y as:
1922     // BB1:
1923     //   jmp_if_X TBB
1924     //   jmp TmpBB
1925     // TmpBB:
1926     //   jmp_if_Y TBB
1927     //   jmp FBB
1928     //
1929 
1930     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1931     // The requirement is that
1932     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1933     //     = TrueProb for original BB.
1934     // Assuming the original probabilities are A and B, one choice is to set
1935     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1936     // A/(1+B) and 2B/(1+B). This choice assumes that
1937     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1938     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1939     // TmpBB, but the math is more complicated.
1940 
1941     auto NewTrueProb = TProb / 2;
1942     auto NewFalseProb = TProb / 2 + FProb;
1943     // Emit the LHS condition.
1944     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1945                          NewTrueProb, NewFalseProb, InvertCond);
1946 
1947     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1948     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1949     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1950     // Emit the RHS condition into TmpBB.
1951     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1952                          Probs[0], Probs[1], InvertCond);
1953   } else {
1954     assert(Opc == Instruction::And && "Unknown merge op!");
1955     // Codegen X & Y as:
1956     // BB1:
1957     //   jmp_if_X TmpBB
1958     //   jmp FBB
1959     // TmpBB:
1960     //   jmp_if_Y TBB
1961     //   jmp FBB
1962     //
1963     //  This requires creation of TmpBB after CurBB.
1964 
1965     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1966     // The requirement is that
1967     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1968     //     = FalseProb for original BB.
1969     // Assuming the original probabilities are A and B, one choice is to set
1970     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1971     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1972     // TrueProb for BB1 * FalseProb for TmpBB.
1973 
1974     auto NewTrueProb = TProb + FProb / 2;
1975     auto NewFalseProb = FProb / 2;
1976     // Emit the LHS condition.
1977     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1978                          NewTrueProb, NewFalseProb, InvertCond);
1979 
1980     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1981     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1982     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1983     // Emit the RHS condition into TmpBB.
1984     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1985                          Probs[0], Probs[1], InvertCond);
1986   }
1987 }
1988 
1989 /// If the set of cases should be emitted as a series of branches, return true.
1990 /// If we should emit this as a bunch of and/or'd together conditions, return
1991 /// false.
1992 bool
1993 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1994   if (Cases.size() != 2) return true;
1995 
1996   // If this is two comparisons of the same values or'd or and'd together, they
1997   // will get folded into a single comparison, so don't emit two blocks.
1998   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1999        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2000       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2001        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2002     return false;
2003   }
2004 
2005   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2006   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2007   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2008       Cases[0].CC == Cases[1].CC &&
2009       isa<Constant>(Cases[0].CmpRHS) &&
2010       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2011     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2012       return false;
2013     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2014       return false;
2015   }
2016 
2017   return true;
2018 }
2019 
2020 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2021   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2022 
2023   // Update machine-CFG edges.
2024   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2025 
2026   if (I.isUnconditional()) {
2027     // Update machine-CFG edges.
2028     BrMBB->addSuccessor(Succ0MBB);
2029 
2030     // If this is not a fall-through branch or optimizations are switched off,
2031     // emit the branch.
2032     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2033       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2034                               MVT::Other, getControlRoot(),
2035                               DAG.getBasicBlock(Succ0MBB)));
2036 
2037     return;
2038   }
2039 
2040   // If this condition is one of the special cases we handle, do special stuff
2041   // now.
2042   const Value *CondVal = I.getCondition();
2043   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2044 
2045   // If this is a series of conditions that are or'd or and'd together, emit
2046   // this as a sequence of branches instead of setcc's with and/or operations.
2047   // As long as jumps are not expensive, this should improve performance.
2048   // For example, instead of something like:
2049   //     cmp A, B
2050   //     C = seteq
2051   //     cmp D, E
2052   //     F = setle
2053   //     or C, F
2054   //     jnz foo
2055   // Emit:
2056   //     cmp A, B
2057   //     je foo
2058   //     cmp D, E
2059   //     jle foo
2060   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2061     Instruction::BinaryOps Opcode = BOp->getOpcode();
2062     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2063         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2064         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2065       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2066                            Opcode,
2067                            getEdgeProbability(BrMBB, Succ0MBB),
2068                            getEdgeProbability(BrMBB, Succ1MBB),
2069                            /*InvertCond=*/false);
2070       // If the compares in later blocks need to use values not currently
2071       // exported from this block, export them now.  This block should always
2072       // be the first entry.
2073       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2074 
2075       // Allow some cases to be rejected.
2076       if (ShouldEmitAsBranches(SwitchCases)) {
2077         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2078           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2079           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2080         }
2081 
2082         // Emit the branch for this block.
2083         visitSwitchCase(SwitchCases[0], BrMBB);
2084         SwitchCases.erase(SwitchCases.begin());
2085         return;
2086       }
2087 
2088       // Okay, we decided not to do this, remove any inserted MBB's and clear
2089       // SwitchCases.
2090       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2091         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2092 
2093       SwitchCases.clear();
2094     }
2095   }
2096 
2097   // Create a CaseBlock record representing this branch.
2098   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2099                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2100 
2101   // Use visitSwitchCase to actually insert the fast branch sequence for this
2102   // cond branch.
2103   visitSwitchCase(CB, BrMBB);
2104 }
2105 
2106 /// visitSwitchCase - Emits the necessary code to represent a single node in
2107 /// the binary search tree resulting from lowering a switch instruction.
2108 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2109                                           MachineBasicBlock *SwitchBB) {
2110   SDValue Cond;
2111   SDValue CondLHS = getValue(CB.CmpLHS);
2112   SDLoc dl = CB.DL;
2113 
2114   // Build the setcc now.
2115   if (!CB.CmpMHS) {
2116     // Fold "(X == true)" to X and "(X == false)" to !X to
2117     // handle common cases produced by branch lowering.
2118     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2119         CB.CC == ISD::SETEQ)
2120       Cond = CondLHS;
2121     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2122              CB.CC == ISD::SETEQ) {
2123       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2124       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2125     } else
2126       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2127   } else {
2128     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2129 
2130     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2131     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2132 
2133     SDValue CmpOp = getValue(CB.CmpMHS);
2134     EVT VT = CmpOp.getValueType();
2135 
2136     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2137       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2138                           ISD::SETLE);
2139     } else {
2140       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2141                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2142       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2143                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2144     }
2145   }
2146 
2147   // Update successor info
2148   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2149   // TrueBB and FalseBB are always different unless the incoming IR is
2150   // degenerate. This only happens when running llc on weird IR.
2151   if (CB.TrueBB != CB.FalseBB)
2152     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2153   SwitchBB->normalizeSuccProbs();
2154 
2155   // If the lhs block is the next block, invert the condition so that we can
2156   // fall through to the lhs instead of the rhs block.
2157   if (CB.TrueBB == NextBlock(SwitchBB)) {
2158     std::swap(CB.TrueBB, CB.FalseBB);
2159     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2160     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2161   }
2162 
2163   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2164                                MVT::Other, getControlRoot(), Cond,
2165                                DAG.getBasicBlock(CB.TrueBB));
2166 
2167   // Insert the false branch. Do this even if it's a fall through branch,
2168   // this makes it easier to do DAG optimizations which require inverting
2169   // the branch condition.
2170   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2171                        DAG.getBasicBlock(CB.FalseBB));
2172 
2173   DAG.setRoot(BrCond);
2174 }
2175 
2176 /// visitJumpTable - Emit JumpTable node in the current MBB
2177 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2178   // Emit the code for the jump table
2179   assert(JT.Reg != -1U && "Should lower JT Header first!");
2180   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2181   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2182                                      JT.Reg, PTy);
2183   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2184   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2185                                     MVT::Other, Index.getValue(1),
2186                                     Table, Index);
2187   DAG.setRoot(BrJumpTable);
2188 }
2189 
2190 /// visitJumpTableHeader - This function emits necessary code to produce index
2191 /// in the JumpTable from switch case.
2192 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2193                                                JumpTableHeader &JTH,
2194                                                MachineBasicBlock *SwitchBB) {
2195   SDLoc dl = getCurSDLoc();
2196 
2197   // Subtract the lowest switch case value from the value being switched on and
2198   // conditional branch to default mbb if the result is greater than the
2199   // difference between smallest and largest cases.
2200   SDValue SwitchOp = getValue(JTH.SValue);
2201   EVT VT = SwitchOp.getValueType();
2202   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2203                             DAG.getConstant(JTH.First, dl, VT));
2204 
2205   // The SDNode we just created, which holds the value being switched on minus
2206   // the smallest case value, needs to be copied to a virtual register so it
2207   // can be used as an index into the jump table in a subsequent basic block.
2208   // This value may be smaller or larger than the target's pointer type, and
2209   // therefore require extension or truncating.
2210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2211   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2212 
2213   unsigned JumpTableReg =
2214       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2215   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2216                                     JumpTableReg, SwitchOp);
2217   JT.Reg = JumpTableReg;
2218 
2219   // Emit the range check for the jump table, and branch to the default block
2220   // for the switch statement if the value being switched on exceeds the largest
2221   // case in the switch.
2222   SDValue CMP = DAG.getSetCC(
2223       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2224                                  Sub.getValueType()),
2225       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2226 
2227   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2228                                MVT::Other, CopyTo, CMP,
2229                                DAG.getBasicBlock(JT.Default));
2230 
2231   // Avoid emitting unnecessary branches to the next block.
2232   if (JT.MBB != NextBlock(SwitchBB))
2233     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2234                          DAG.getBasicBlock(JT.MBB));
2235 
2236   DAG.setRoot(BrCond);
2237 }
2238 
2239 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2240 /// variable if there exists one.
2241 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2242                                  SDValue &Chain) {
2243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2244   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2245   MachineFunction &MF = DAG.getMachineFunction();
2246   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2247   MachineSDNode *Node =
2248       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2249   if (Global) {
2250     MachinePointerInfo MPInfo(Global);
2251     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2252                  MachineMemOperand::MODereferenceable;
2253     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2254         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2255     DAG.setNodeMemRefs(Node, {MemRef});
2256   }
2257   return SDValue(Node, 0);
2258 }
2259 
2260 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2261 /// tail spliced into a stack protector check success bb.
2262 ///
2263 /// For a high level explanation of how this fits into the stack protector
2264 /// generation see the comment on the declaration of class
2265 /// StackProtectorDescriptor.
2266 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2267                                                   MachineBasicBlock *ParentBB) {
2268 
2269   // First create the loads to the guard/stack slot for the comparison.
2270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2271   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2272 
2273   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2274   int FI = MFI.getStackProtectorIndex();
2275 
2276   SDValue Guard;
2277   SDLoc dl = getCurSDLoc();
2278   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2279   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2280   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2281 
2282   // Generate code to load the content of the guard slot.
2283   SDValue GuardVal = DAG.getLoad(
2284       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2285       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2286       MachineMemOperand::MOVolatile);
2287 
2288   if (TLI.useStackGuardXorFP())
2289     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2290 
2291   // Retrieve guard check function, nullptr if instrumentation is inlined.
2292   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2293     // The target provides a guard check function to validate the guard value.
2294     // Generate a call to that function with the content of the guard slot as
2295     // argument.
2296     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2297     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2298 
2299     TargetLowering::ArgListTy Args;
2300     TargetLowering::ArgListEntry Entry;
2301     Entry.Node = GuardVal;
2302     Entry.Ty = FnTy->getParamType(0);
2303     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2304       Entry.IsInReg = true;
2305     Args.push_back(Entry);
2306 
2307     TargetLowering::CallLoweringInfo CLI(DAG);
2308     CLI.setDebugLoc(getCurSDLoc())
2309         .setChain(DAG.getEntryNode())
2310         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2311                    getValue(GuardCheckFn), std::move(Args));
2312 
2313     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2314     DAG.setRoot(Result.second);
2315     return;
2316   }
2317 
2318   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2319   // Otherwise, emit a volatile load to retrieve the stack guard value.
2320   SDValue Chain = DAG.getEntryNode();
2321   if (TLI.useLoadStackGuardNode()) {
2322     Guard = getLoadStackGuard(DAG, dl, Chain);
2323   } else {
2324     const Value *IRGuard = TLI.getSDagStackGuard(M);
2325     SDValue GuardPtr = getValue(IRGuard);
2326 
2327     Guard =
2328         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2329                     Align, MachineMemOperand::MOVolatile);
2330   }
2331 
2332   // Perform the comparison via a subtract/getsetcc.
2333   EVT VT = Guard.getValueType();
2334   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2335 
2336   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2337                                                         *DAG.getContext(),
2338                                                         Sub.getValueType()),
2339                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2340 
2341   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2342   // branch to failure MBB.
2343   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2344                                MVT::Other, GuardVal.getOperand(0),
2345                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2346   // Otherwise branch to success MBB.
2347   SDValue Br = DAG.getNode(ISD::BR, dl,
2348                            MVT::Other, BrCond,
2349                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2350 
2351   DAG.setRoot(Br);
2352 }
2353 
2354 /// Codegen the failure basic block for a stack protector check.
2355 ///
2356 /// A failure stack protector machine basic block consists simply of a call to
2357 /// __stack_chk_fail().
2358 ///
2359 /// For a high level explanation of how this fits into the stack protector
2360 /// generation see the comment on the declaration of class
2361 /// StackProtectorDescriptor.
2362 void
2363 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2365   SDValue Chain =
2366       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2367                       None, false, getCurSDLoc(), false, false).second;
2368   DAG.setRoot(Chain);
2369 }
2370 
2371 /// visitBitTestHeader - This function emits necessary code to produce value
2372 /// suitable for "bit tests"
2373 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2374                                              MachineBasicBlock *SwitchBB) {
2375   SDLoc dl = getCurSDLoc();
2376 
2377   // Subtract the minimum value
2378   SDValue SwitchOp = getValue(B.SValue);
2379   EVT VT = SwitchOp.getValueType();
2380   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2381                             DAG.getConstant(B.First, dl, VT));
2382 
2383   // Check range
2384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2385   SDValue RangeCmp = DAG.getSetCC(
2386       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2387                                  Sub.getValueType()),
2388       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2389 
2390   // Determine the type of the test operands.
2391   bool UsePtrType = false;
2392   if (!TLI.isTypeLegal(VT))
2393     UsePtrType = true;
2394   else {
2395     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2396       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2397         // Switch table case range are encoded into series of masks.
2398         // Just use pointer type, it's guaranteed to fit.
2399         UsePtrType = true;
2400         break;
2401       }
2402   }
2403   if (UsePtrType) {
2404     VT = TLI.getPointerTy(DAG.getDataLayout());
2405     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2406   }
2407 
2408   B.RegVT = VT.getSimpleVT();
2409   B.Reg = FuncInfo.CreateReg(B.RegVT);
2410   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2411 
2412   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2413 
2414   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2415   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2416   SwitchBB->normalizeSuccProbs();
2417 
2418   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2419                                 MVT::Other, CopyTo, RangeCmp,
2420                                 DAG.getBasicBlock(B.Default));
2421 
2422   // Avoid emitting unnecessary branches to the next block.
2423   if (MBB != NextBlock(SwitchBB))
2424     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2425                           DAG.getBasicBlock(MBB));
2426 
2427   DAG.setRoot(BrRange);
2428 }
2429 
2430 /// visitBitTestCase - this function produces one "bit test"
2431 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2432                                            MachineBasicBlock* NextMBB,
2433                                            BranchProbability BranchProbToNext,
2434                                            unsigned Reg,
2435                                            BitTestCase &B,
2436                                            MachineBasicBlock *SwitchBB) {
2437   SDLoc dl = getCurSDLoc();
2438   MVT VT = BB.RegVT;
2439   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2440   SDValue Cmp;
2441   unsigned PopCount = countPopulation(B.Mask);
2442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2443   if (PopCount == 1) {
2444     // Testing for a single bit; just compare the shift count with what it
2445     // would need to be to shift a 1 bit in that position.
2446     Cmp = DAG.getSetCC(
2447         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2448         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2449         ISD::SETEQ);
2450   } else if (PopCount == BB.Range) {
2451     // There is only one zero bit in the range, test for it directly.
2452     Cmp = DAG.getSetCC(
2453         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2454         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2455         ISD::SETNE);
2456   } else {
2457     // Make desired shift
2458     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2459                                     DAG.getConstant(1, dl, VT), ShiftOp);
2460 
2461     // Emit bit tests and jumps
2462     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2463                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2464     Cmp = DAG.getSetCC(
2465         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2466         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2467   }
2468 
2469   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2470   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2471   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2472   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2473   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2474   // one as they are relative probabilities (and thus work more like weights),
2475   // and hence we need to normalize them to let the sum of them become one.
2476   SwitchBB->normalizeSuccProbs();
2477 
2478   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2479                               MVT::Other, getControlRoot(),
2480                               Cmp, DAG.getBasicBlock(B.TargetBB));
2481 
2482   // Avoid emitting unnecessary branches to the next block.
2483   if (NextMBB != NextBlock(SwitchBB))
2484     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2485                         DAG.getBasicBlock(NextMBB));
2486 
2487   DAG.setRoot(BrAnd);
2488 }
2489 
2490 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2491   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2492 
2493   // Retrieve successors. Look through artificial IR level blocks like
2494   // catchswitch for successors.
2495   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2496   const BasicBlock *EHPadBB = I.getSuccessor(1);
2497 
2498   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2499   // have to do anything here to lower funclet bundles.
2500   assert(!I.hasOperandBundlesOtherThan(
2501              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2502          "Cannot lower invokes with arbitrary operand bundles yet!");
2503 
2504   const Value *Callee(I.getCalledValue());
2505   const Function *Fn = dyn_cast<Function>(Callee);
2506   if (isa<InlineAsm>(Callee))
2507     visitInlineAsm(&I);
2508   else if (Fn && Fn->isIntrinsic()) {
2509     switch (Fn->getIntrinsicID()) {
2510     default:
2511       llvm_unreachable("Cannot invoke this intrinsic");
2512     case Intrinsic::donothing:
2513       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2514       break;
2515     case Intrinsic::experimental_patchpoint_void:
2516     case Intrinsic::experimental_patchpoint_i64:
2517       visitPatchpoint(&I, EHPadBB);
2518       break;
2519     case Intrinsic::experimental_gc_statepoint:
2520       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2521       break;
2522     }
2523   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2524     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2525     // Eventually we will support lowering the @llvm.experimental.deoptimize
2526     // intrinsic, and right now there are no plans to support other intrinsics
2527     // with deopt state.
2528     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2529   } else {
2530     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2531   }
2532 
2533   // If the value of the invoke is used outside of its defining block, make it
2534   // available as a virtual register.
2535   // We already took care of the exported value for the statepoint instruction
2536   // during call to the LowerStatepoint.
2537   if (!isStatepoint(I)) {
2538     CopyToExportRegsIfNeeded(&I);
2539   }
2540 
2541   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2542   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2543   BranchProbability EHPadBBProb =
2544       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2545           : BranchProbability::getZero();
2546   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2547 
2548   // Update successor info.
2549   addSuccessorWithProb(InvokeMBB, Return);
2550   for (auto &UnwindDest : UnwindDests) {
2551     UnwindDest.first->setIsEHPad();
2552     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2553   }
2554   InvokeMBB->normalizeSuccProbs();
2555 
2556   // Drop into normal successor.
2557   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2558                           DAG.getBasicBlock(Return)));
2559 }
2560 
2561 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2562   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2563 
2564   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2565   // have to do anything here to lower funclet bundles.
2566   assert(!I.hasOperandBundlesOtherThan(
2567              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2568          "Cannot lower callbrs with arbitrary operand bundles yet!");
2569 
2570   assert(isa<InlineAsm>(I.getCalledValue()) &&
2571          "Only know how to handle inlineasm callbr");
2572   visitInlineAsm(&I);
2573 
2574   // Retrieve successors.
2575   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2576 
2577   // Update successor info.
2578   addSuccessorWithProb(CallBrMBB, Return);
2579   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2580     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2581     addSuccessorWithProb(CallBrMBB, Target);
2582   }
2583   CallBrMBB->normalizeSuccProbs();
2584 
2585   // Drop into default successor.
2586   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2587                           MVT::Other, getControlRoot(),
2588                           DAG.getBasicBlock(Return)));
2589 }
2590 
2591 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2592   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2593 }
2594 
2595 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2596   assert(FuncInfo.MBB->isEHPad() &&
2597          "Call to landingpad not in landing pad!");
2598 
2599   // If there aren't registers to copy the values into (e.g., during SjLj
2600   // exceptions), then don't bother to create these DAG nodes.
2601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2603   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2604       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2605     return;
2606 
2607   // If landingpad's return type is token type, we don't create DAG nodes
2608   // for its exception pointer and selector value. The extraction of exception
2609   // pointer or selector value from token type landingpads is not currently
2610   // supported.
2611   if (LP.getType()->isTokenTy())
2612     return;
2613 
2614   SmallVector<EVT, 2> ValueVTs;
2615   SDLoc dl = getCurSDLoc();
2616   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2617   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2618 
2619   // Get the two live-in registers as SDValues. The physregs have already been
2620   // copied into virtual registers.
2621   SDValue Ops[2];
2622   if (FuncInfo.ExceptionPointerVirtReg) {
2623     Ops[0] = DAG.getZExtOrTrunc(
2624         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2625                            FuncInfo.ExceptionPointerVirtReg,
2626                            TLI.getPointerTy(DAG.getDataLayout())),
2627         dl, ValueVTs[0]);
2628   } else {
2629     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2630   }
2631   Ops[1] = DAG.getZExtOrTrunc(
2632       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2633                          FuncInfo.ExceptionSelectorVirtReg,
2634                          TLI.getPointerTy(DAG.getDataLayout())),
2635       dl, ValueVTs[1]);
2636 
2637   // Merge into one.
2638   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2639                             DAG.getVTList(ValueVTs), Ops);
2640   setValue(&LP, Res);
2641 }
2642 
2643 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2644 #ifndef NDEBUG
2645   for (const CaseCluster &CC : Clusters)
2646     assert(CC.Low == CC.High && "Input clusters must be single-case");
2647 #endif
2648 
2649   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2650     return a.Low->getValue().slt(b.Low->getValue());
2651   });
2652 
2653   // Merge adjacent clusters with the same destination.
2654   const unsigned N = Clusters.size();
2655   unsigned DstIndex = 0;
2656   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2657     CaseCluster &CC = Clusters[SrcIndex];
2658     const ConstantInt *CaseVal = CC.Low;
2659     MachineBasicBlock *Succ = CC.MBB;
2660 
2661     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2662         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2663       // If this case has the same successor and is a neighbour, merge it into
2664       // the previous cluster.
2665       Clusters[DstIndex - 1].High = CaseVal;
2666       Clusters[DstIndex - 1].Prob += CC.Prob;
2667     } else {
2668       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2669                    sizeof(Clusters[SrcIndex]));
2670     }
2671   }
2672   Clusters.resize(DstIndex);
2673 }
2674 
2675 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2676                                            MachineBasicBlock *Last) {
2677   // Update JTCases.
2678   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2679     if (JTCases[i].first.HeaderBB == First)
2680       JTCases[i].first.HeaderBB = Last;
2681 
2682   // Update BitTestCases.
2683   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2684     if (BitTestCases[i].Parent == First)
2685       BitTestCases[i].Parent = Last;
2686 }
2687 
2688 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2689   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2690 
2691   // Update machine-CFG edges with unique successors.
2692   SmallSet<BasicBlock*, 32> Done;
2693   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2694     BasicBlock *BB = I.getSuccessor(i);
2695     bool Inserted = Done.insert(BB).second;
2696     if (!Inserted)
2697         continue;
2698 
2699     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2700     addSuccessorWithProb(IndirectBrMBB, Succ);
2701   }
2702   IndirectBrMBB->normalizeSuccProbs();
2703 
2704   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2705                           MVT::Other, getControlRoot(),
2706                           getValue(I.getAddress())));
2707 }
2708 
2709 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2710   if (!DAG.getTarget().Options.TrapUnreachable)
2711     return;
2712 
2713   // We may be able to ignore unreachable behind a noreturn call.
2714   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2715     const BasicBlock &BB = *I.getParent();
2716     if (&I != &BB.front()) {
2717       BasicBlock::const_iterator PredI =
2718         std::prev(BasicBlock::const_iterator(&I));
2719       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2720         if (Call->doesNotReturn())
2721           return;
2722       }
2723     }
2724   }
2725 
2726   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2727 }
2728 
2729 void SelectionDAGBuilder::visitFSub(const User &I) {
2730   // -0.0 - X --> fneg
2731   Type *Ty = I.getType();
2732   if (isa<Constant>(I.getOperand(0)) &&
2733       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2734     SDValue Op2 = getValue(I.getOperand(1));
2735     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2736                              Op2.getValueType(), Op2));
2737     return;
2738   }
2739 
2740   visitBinary(I, ISD::FSUB);
2741 }
2742 
2743 /// Checks if the given instruction performs a vector reduction, in which case
2744 /// we have the freedom to alter the elements in the result as long as the
2745 /// reduction of them stays unchanged.
2746 static bool isVectorReductionOp(const User *I) {
2747   const Instruction *Inst = dyn_cast<Instruction>(I);
2748   if (!Inst || !Inst->getType()->isVectorTy())
2749     return false;
2750 
2751   auto OpCode = Inst->getOpcode();
2752   switch (OpCode) {
2753   case Instruction::Add:
2754   case Instruction::Mul:
2755   case Instruction::And:
2756   case Instruction::Or:
2757   case Instruction::Xor:
2758     break;
2759   case Instruction::FAdd:
2760   case Instruction::FMul:
2761     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2762       if (FPOp->getFastMathFlags().isFast())
2763         break;
2764     LLVM_FALLTHROUGH;
2765   default:
2766     return false;
2767   }
2768 
2769   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2770   // Ensure the reduction size is a power of 2.
2771   if (!isPowerOf2_32(ElemNum))
2772     return false;
2773 
2774   unsigned ElemNumToReduce = ElemNum;
2775 
2776   // Do DFS search on the def-use chain from the given instruction. We only
2777   // allow four kinds of operations during the search until we reach the
2778   // instruction that extracts the first element from the vector:
2779   //
2780   //   1. The reduction operation of the same opcode as the given instruction.
2781   //
2782   //   2. PHI node.
2783   //
2784   //   3. ShuffleVector instruction together with a reduction operation that
2785   //      does a partial reduction.
2786   //
2787   //   4. ExtractElement that extracts the first element from the vector, and we
2788   //      stop searching the def-use chain here.
2789   //
2790   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2791   // from 1-3 to the stack to continue the DFS. The given instruction is not
2792   // a reduction operation if we meet any other instructions other than those
2793   // listed above.
2794 
2795   SmallVector<const User *, 16> UsersToVisit{Inst};
2796   SmallPtrSet<const User *, 16> Visited;
2797   bool ReduxExtracted = false;
2798 
2799   while (!UsersToVisit.empty()) {
2800     auto User = UsersToVisit.back();
2801     UsersToVisit.pop_back();
2802     if (!Visited.insert(User).second)
2803       continue;
2804 
2805     for (const auto &U : User->users()) {
2806       auto Inst = dyn_cast<Instruction>(U);
2807       if (!Inst)
2808         return false;
2809 
2810       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2811         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2812           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2813             return false;
2814         UsersToVisit.push_back(U);
2815       } else if (const ShuffleVectorInst *ShufInst =
2816                      dyn_cast<ShuffleVectorInst>(U)) {
2817         // Detect the following pattern: A ShuffleVector instruction together
2818         // with a reduction that do partial reduction on the first and second
2819         // ElemNumToReduce / 2 elements, and store the result in
2820         // ElemNumToReduce / 2 elements in another vector.
2821 
2822         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2823         if (ResultElements < ElemNum)
2824           return false;
2825 
2826         if (ElemNumToReduce == 1)
2827           return false;
2828         if (!isa<UndefValue>(U->getOperand(1)))
2829           return false;
2830         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2831           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2832             return false;
2833         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2834           if (ShufInst->getMaskValue(i) != -1)
2835             return false;
2836 
2837         // There is only one user of this ShuffleVector instruction, which
2838         // must be a reduction operation.
2839         if (!U->hasOneUse())
2840           return false;
2841 
2842         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2843         if (!U2 || U2->getOpcode() != OpCode)
2844           return false;
2845 
2846         // Check operands of the reduction operation.
2847         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2848             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2849           UsersToVisit.push_back(U2);
2850           ElemNumToReduce /= 2;
2851         } else
2852           return false;
2853       } else if (isa<ExtractElementInst>(U)) {
2854         // At this moment we should have reduced all elements in the vector.
2855         if (ElemNumToReduce != 1)
2856           return false;
2857 
2858         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2859         if (!Val || !Val->isZero())
2860           return false;
2861 
2862         ReduxExtracted = true;
2863       } else
2864         return false;
2865     }
2866   }
2867   return ReduxExtracted;
2868 }
2869 
2870 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2871   SDNodeFlags Flags;
2872 
2873   SDValue Op = getValue(I.getOperand(0));
2874   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2875                                     Op, Flags);
2876   setValue(&I, UnNodeValue);
2877 }
2878 
2879 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2880   SDNodeFlags Flags;
2881   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2882     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2883     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2884   }
2885   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2886     Flags.setExact(ExactOp->isExact());
2887   }
2888   if (isVectorReductionOp(&I)) {
2889     Flags.setVectorReduction(true);
2890     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2891   }
2892 
2893   SDValue Op1 = getValue(I.getOperand(0));
2894   SDValue Op2 = getValue(I.getOperand(1));
2895   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2896                                      Op1, Op2, Flags);
2897   setValue(&I, BinNodeValue);
2898 }
2899 
2900 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2901   SDValue Op1 = getValue(I.getOperand(0));
2902   SDValue Op2 = getValue(I.getOperand(1));
2903 
2904   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2905       Op1.getValueType(), DAG.getDataLayout());
2906 
2907   // Coerce the shift amount to the right type if we can.
2908   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2909     unsigned ShiftSize = ShiftTy.getSizeInBits();
2910     unsigned Op2Size = Op2.getValueSizeInBits();
2911     SDLoc DL = getCurSDLoc();
2912 
2913     // If the operand is smaller than the shift count type, promote it.
2914     if (ShiftSize > Op2Size)
2915       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2916 
2917     // If the operand is larger than the shift count type but the shift
2918     // count type has enough bits to represent any shift value, truncate
2919     // it now. This is a common case and it exposes the truncate to
2920     // optimization early.
2921     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2922       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2923     // Otherwise we'll need to temporarily settle for some other convenient
2924     // type.  Type legalization will make adjustments once the shiftee is split.
2925     else
2926       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2927   }
2928 
2929   bool nuw = false;
2930   bool nsw = false;
2931   bool exact = false;
2932 
2933   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2934 
2935     if (const OverflowingBinaryOperator *OFBinOp =
2936             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2937       nuw = OFBinOp->hasNoUnsignedWrap();
2938       nsw = OFBinOp->hasNoSignedWrap();
2939     }
2940     if (const PossiblyExactOperator *ExactOp =
2941             dyn_cast<const PossiblyExactOperator>(&I))
2942       exact = ExactOp->isExact();
2943   }
2944   SDNodeFlags Flags;
2945   Flags.setExact(exact);
2946   Flags.setNoSignedWrap(nsw);
2947   Flags.setNoUnsignedWrap(nuw);
2948   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2949                             Flags);
2950   setValue(&I, Res);
2951 }
2952 
2953 void SelectionDAGBuilder::visitSDiv(const User &I) {
2954   SDValue Op1 = getValue(I.getOperand(0));
2955   SDValue Op2 = getValue(I.getOperand(1));
2956 
2957   SDNodeFlags Flags;
2958   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2959                  cast<PossiblyExactOperator>(&I)->isExact());
2960   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2961                            Op2, Flags));
2962 }
2963 
2964 void SelectionDAGBuilder::visitICmp(const User &I) {
2965   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2966   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2967     predicate = IC->getPredicate();
2968   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2969     predicate = ICmpInst::Predicate(IC->getPredicate());
2970   SDValue Op1 = getValue(I.getOperand(0));
2971   SDValue Op2 = getValue(I.getOperand(1));
2972   ISD::CondCode Opcode = getICmpCondCode(predicate);
2973 
2974   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2975                                                         I.getType());
2976   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2977 }
2978 
2979 void SelectionDAGBuilder::visitFCmp(const User &I) {
2980   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2981   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2982     predicate = FC->getPredicate();
2983   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2984     predicate = FCmpInst::Predicate(FC->getPredicate());
2985   SDValue Op1 = getValue(I.getOperand(0));
2986   SDValue Op2 = getValue(I.getOperand(1));
2987 
2988   ISD::CondCode Condition = getFCmpCondCode(predicate);
2989   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2990   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2991     Condition = getFCmpCodeWithoutNaN(Condition);
2992 
2993   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2994                                                         I.getType());
2995   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2996 }
2997 
2998 // Check if the condition of the select has one use or two users that are both
2999 // selects with the same condition.
3000 static bool hasOnlySelectUsers(const Value *Cond) {
3001   return llvm::all_of(Cond->users(), [](const Value *V) {
3002     return isa<SelectInst>(V);
3003   });
3004 }
3005 
3006 void SelectionDAGBuilder::visitSelect(const User &I) {
3007   SmallVector<EVT, 4> ValueVTs;
3008   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3009                   ValueVTs);
3010   unsigned NumValues = ValueVTs.size();
3011   if (NumValues == 0) return;
3012 
3013   SmallVector<SDValue, 4> Values(NumValues);
3014   SDValue Cond     = getValue(I.getOperand(0));
3015   SDValue LHSVal   = getValue(I.getOperand(1));
3016   SDValue RHSVal   = getValue(I.getOperand(2));
3017   auto BaseOps = {Cond};
3018   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3019     ISD::VSELECT : ISD::SELECT;
3020 
3021   // Min/max matching is only viable if all output VTs are the same.
3022   if (is_splat(ValueVTs)) {
3023     EVT VT = ValueVTs[0];
3024     LLVMContext &Ctx = *DAG.getContext();
3025     auto &TLI = DAG.getTargetLoweringInfo();
3026 
3027     // We care about the legality of the operation after it has been type
3028     // legalized.
3029     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3030            VT != TLI.getTypeToTransformTo(Ctx, VT))
3031       VT = TLI.getTypeToTransformTo(Ctx, VT);
3032 
3033     // If the vselect is legal, assume we want to leave this as a vector setcc +
3034     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3035     // min/max is legal on the scalar type.
3036     bool UseScalarMinMax = VT.isVector() &&
3037       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3038 
3039     Value *LHS, *RHS;
3040     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3041     ISD::NodeType Opc = ISD::DELETED_NODE;
3042     switch (SPR.Flavor) {
3043     case SPF_UMAX:    Opc = ISD::UMAX; break;
3044     case SPF_UMIN:    Opc = ISD::UMIN; break;
3045     case SPF_SMAX:    Opc = ISD::SMAX; break;
3046     case SPF_SMIN:    Opc = ISD::SMIN; break;
3047     case SPF_FMINNUM:
3048       switch (SPR.NaNBehavior) {
3049       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3050       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3051       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3052       case SPNB_RETURNS_ANY: {
3053         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3054           Opc = ISD::FMINNUM;
3055         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3056           Opc = ISD::FMINIMUM;
3057         else if (UseScalarMinMax)
3058           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3059             ISD::FMINNUM : ISD::FMINIMUM;
3060         break;
3061       }
3062       }
3063       break;
3064     case SPF_FMAXNUM:
3065       switch (SPR.NaNBehavior) {
3066       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3067       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3068       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3069       case SPNB_RETURNS_ANY:
3070 
3071         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3072           Opc = ISD::FMAXNUM;
3073         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3074           Opc = ISD::FMAXIMUM;
3075         else if (UseScalarMinMax)
3076           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3077             ISD::FMAXNUM : ISD::FMAXIMUM;
3078         break;
3079       }
3080       break;
3081     default: break;
3082     }
3083 
3084     if (Opc != ISD::DELETED_NODE &&
3085         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3086          (UseScalarMinMax &&
3087           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3088         // If the underlying comparison instruction is used by any other
3089         // instruction, the consumed instructions won't be destroyed, so it is
3090         // not profitable to convert to a min/max.
3091         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3092       OpCode = Opc;
3093       LHSVal = getValue(LHS);
3094       RHSVal = getValue(RHS);
3095       BaseOps = {};
3096     }
3097   }
3098 
3099   for (unsigned i = 0; i != NumValues; ++i) {
3100     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3101     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3102     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3103     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3104                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3105                             Ops);
3106   }
3107 
3108   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3109                            DAG.getVTList(ValueVTs), Values));
3110 }
3111 
3112 void SelectionDAGBuilder::visitTrunc(const User &I) {
3113   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3114   SDValue N = getValue(I.getOperand(0));
3115   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3116                                                         I.getType());
3117   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3118 }
3119 
3120 void SelectionDAGBuilder::visitZExt(const User &I) {
3121   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3122   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3123   SDValue N = getValue(I.getOperand(0));
3124   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3125                                                         I.getType());
3126   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3127 }
3128 
3129 void SelectionDAGBuilder::visitSExt(const User &I) {
3130   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3131   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3132   SDValue N = getValue(I.getOperand(0));
3133   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3134                                                         I.getType());
3135   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3136 }
3137 
3138 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3139   // FPTrunc is never a no-op cast, no need to check
3140   SDValue N = getValue(I.getOperand(0));
3141   SDLoc dl = getCurSDLoc();
3142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3143   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3144   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3145                            DAG.getTargetConstant(
3146                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3147 }
3148 
3149 void SelectionDAGBuilder::visitFPExt(const User &I) {
3150   // FPExt is never a no-op cast, no need to check
3151   SDValue N = getValue(I.getOperand(0));
3152   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3153                                                         I.getType());
3154   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3155 }
3156 
3157 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3158   // FPToUI is never a no-op cast, no need to check
3159   SDValue N = getValue(I.getOperand(0));
3160   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3161                                                         I.getType());
3162   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3163 }
3164 
3165 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3166   // FPToSI is never a no-op cast, no need to check
3167   SDValue N = getValue(I.getOperand(0));
3168   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3169                                                         I.getType());
3170   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3171 }
3172 
3173 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3174   // UIToFP is never a no-op cast, no need to check
3175   SDValue N = getValue(I.getOperand(0));
3176   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3177                                                         I.getType());
3178   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3179 }
3180 
3181 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3182   // SIToFP is never a no-op cast, no need to check
3183   SDValue N = getValue(I.getOperand(0));
3184   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3185                                                         I.getType());
3186   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3187 }
3188 
3189 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3190   // What to do depends on the size of the integer and the size of the pointer.
3191   // We can either truncate, zero extend, or no-op, accordingly.
3192   SDValue N = getValue(I.getOperand(0));
3193   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3194                                                         I.getType());
3195   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3196 }
3197 
3198 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3199   // What to do depends on the size of the integer and the size of the pointer.
3200   // We can either truncate, zero extend, or no-op, accordingly.
3201   SDValue N = getValue(I.getOperand(0));
3202   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3203                                                         I.getType());
3204   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3205 }
3206 
3207 void SelectionDAGBuilder::visitBitCast(const User &I) {
3208   SDValue N = getValue(I.getOperand(0));
3209   SDLoc dl = getCurSDLoc();
3210   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3211                                                         I.getType());
3212 
3213   // BitCast assures us that source and destination are the same size so this is
3214   // either a BITCAST or a no-op.
3215   if (DestVT != N.getValueType())
3216     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3217                              DestVT, N)); // convert types.
3218   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3219   // might fold any kind of constant expression to an integer constant and that
3220   // is not what we are looking for. Only recognize a bitcast of a genuine
3221   // constant integer as an opaque constant.
3222   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3223     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3224                                  /*isOpaque*/true));
3225   else
3226     setValue(&I, N);            // noop cast.
3227 }
3228 
3229 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3231   const Value *SV = I.getOperand(0);
3232   SDValue N = getValue(SV);
3233   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3234 
3235   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3236   unsigned DestAS = I.getType()->getPointerAddressSpace();
3237 
3238   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3239     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3240 
3241   setValue(&I, N);
3242 }
3243 
3244 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3246   SDValue InVec = getValue(I.getOperand(0));
3247   SDValue InVal = getValue(I.getOperand(1));
3248   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3249                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3250   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3251                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3252                            InVec, InVal, InIdx));
3253 }
3254 
3255 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3257   SDValue InVec = getValue(I.getOperand(0));
3258   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3259                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3260   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3261                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3262                            InVec, InIdx));
3263 }
3264 
3265 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3266   SDValue Src1 = getValue(I.getOperand(0));
3267   SDValue Src2 = getValue(I.getOperand(1));
3268   SDLoc DL = getCurSDLoc();
3269 
3270   SmallVector<int, 8> Mask;
3271   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3272   unsigned MaskNumElts = Mask.size();
3273 
3274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3276   EVT SrcVT = Src1.getValueType();
3277   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3278 
3279   if (SrcNumElts == MaskNumElts) {
3280     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3281     return;
3282   }
3283 
3284   // Normalize the shuffle vector since mask and vector length don't match.
3285   if (SrcNumElts < MaskNumElts) {
3286     // Mask is longer than the source vectors. We can use concatenate vector to
3287     // make the mask and vectors lengths match.
3288 
3289     if (MaskNumElts % SrcNumElts == 0) {
3290       // Mask length is a multiple of the source vector length.
3291       // Check if the shuffle is some kind of concatenation of the input
3292       // vectors.
3293       unsigned NumConcat = MaskNumElts / SrcNumElts;
3294       bool IsConcat = true;
3295       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3296       for (unsigned i = 0; i != MaskNumElts; ++i) {
3297         int Idx = Mask[i];
3298         if (Idx < 0)
3299           continue;
3300         // Ensure the indices in each SrcVT sized piece are sequential and that
3301         // the same source is used for the whole piece.
3302         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3303             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3304              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3305           IsConcat = false;
3306           break;
3307         }
3308         // Remember which source this index came from.
3309         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3310       }
3311 
3312       // The shuffle is concatenating multiple vectors together. Just emit
3313       // a CONCAT_VECTORS operation.
3314       if (IsConcat) {
3315         SmallVector<SDValue, 8> ConcatOps;
3316         for (auto Src : ConcatSrcs) {
3317           if (Src < 0)
3318             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3319           else if (Src == 0)
3320             ConcatOps.push_back(Src1);
3321           else
3322             ConcatOps.push_back(Src2);
3323         }
3324         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3325         return;
3326       }
3327     }
3328 
3329     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3330     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3331     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3332                                     PaddedMaskNumElts);
3333 
3334     // Pad both vectors with undefs to make them the same length as the mask.
3335     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3336 
3337     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3338     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3339     MOps1[0] = Src1;
3340     MOps2[0] = Src2;
3341 
3342     Src1 = Src1.isUndef()
3343                ? DAG.getUNDEF(PaddedVT)
3344                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3345     Src2 = Src2.isUndef()
3346                ? DAG.getUNDEF(PaddedVT)
3347                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3348 
3349     // Readjust mask for new input vector length.
3350     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3351     for (unsigned i = 0; i != MaskNumElts; ++i) {
3352       int Idx = Mask[i];
3353       if (Idx >= (int)SrcNumElts)
3354         Idx -= SrcNumElts - PaddedMaskNumElts;
3355       MappedOps[i] = Idx;
3356     }
3357 
3358     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3359 
3360     // If the concatenated vector was padded, extract a subvector with the
3361     // correct number of elements.
3362     if (MaskNumElts != PaddedMaskNumElts)
3363       Result = DAG.getNode(
3364           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3365           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3366 
3367     setValue(&I, Result);
3368     return;
3369   }
3370 
3371   if (SrcNumElts > MaskNumElts) {
3372     // Analyze the access pattern of the vector to see if we can extract
3373     // two subvectors and do the shuffle.
3374     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3375     bool CanExtract = true;
3376     for (int Idx : Mask) {
3377       unsigned Input = 0;
3378       if (Idx < 0)
3379         continue;
3380 
3381       if (Idx >= (int)SrcNumElts) {
3382         Input = 1;
3383         Idx -= SrcNumElts;
3384       }
3385 
3386       // If all the indices come from the same MaskNumElts sized portion of
3387       // the sources we can use extract. Also make sure the extract wouldn't
3388       // extract past the end of the source.
3389       int NewStartIdx = alignDown(Idx, MaskNumElts);
3390       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3391           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3392         CanExtract = false;
3393       // Make sure we always update StartIdx as we use it to track if all
3394       // elements are undef.
3395       StartIdx[Input] = NewStartIdx;
3396     }
3397 
3398     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3399       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3400       return;
3401     }
3402     if (CanExtract) {
3403       // Extract appropriate subvector and generate a vector shuffle
3404       for (unsigned Input = 0; Input < 2; ++Input) {
3405         SDValue &Src = Input == 0 ? Src1 : Src2;
3406         if (StartIdx[Input] < 0)
3407           Src = DAG.getUNDEF(VT);
3408         else {
3409           Src = DAG.getNode(
3410               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3411               DAG.getConstant(StartIdx[Input], DL,
3412                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3413         }
3414       }
3415 
3416       // Calculate new mask.
3417       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3418       for (int &Idx : MappedOps) {
3419         if (Idx >= (int)SrcNumElts)
3420           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3421         else if (Idx >= 0)
3422           Idx -= StartIdx[0];
3423       }
3424 
3425       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3426       return;
3427     }
3428   }
3429 
3430   // We can't use either concat vectors or extract subvectors so fall back to
3431   // replacing the shuffle with extract and build vector.
3432   // to insert and build vector.
3433   EVT EltVT = VT.getVectorElementType();
3434   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3435   SmallVector<SDValue,8> Ops;
3436   for (int Idx : Mask) {
3437     SDValue Res;
3438 
3439     if (Idx < 0) {
3440       Res = DAG.getUNDEF(EltVT);
3441     } else {
3442       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3443       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3444 
3445       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3446                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3447     }
3448 
3449     Ops.push_back(Res);
3450   }
3451 
3452   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3453 }
3454 
3455 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3456   ArrayRef<unsigned> Indices;
3457   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3458     Indices = IV->getIndices();
3459   else
3460     Indices = cast<ConstantExpr>(&I)->getIndices();
3461 
3462   const Value *Op0 = I.getOperand(0);
3463   const Value *Op1 = I.getOperand(1);
3464   Type *AggTy = I.getType();
3465   Type *ValTy = Op1->getType();
3466   bool IntoUndef = isa<UndefValue>(Op0);
3467   bool FromUndef = isa<UndefValue>(Op1);
3468 
3469   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3470 
3471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3472   SmallVector<EVT, 4> AggValueVTs;
3473   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3474   SmallVector<EVT, 4> ValValueVTs;
3475   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3476 
3477   unsigned NumAggValues = AggValueVTs.size();
3478   unsigned NumValValues = ValValueVTs.size();
3479   SmallVector<SDValue, 4> Values(NumAggValues);
3480 
3481   // Ignore an insertvalue that produces an empty object
3482   if (!NumAggValues) {
3483     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3484     return;
3485   }
3486 
3487   SDValue Agg = getValue(Op0);
3488   unsigned i = 0;
3489   // Copy the beginning value(s) from the original aggregate.
3490   for (; i != LinearIndex; ++i)
3491     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3492                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3493   // Copy values from the inserted value(s).
3494   if (NumValValues) {
3495     SDValue Val = getValue(Op1);
3496     for (; i != LinearIndex + NumValValues; ++i)
3497       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3498                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3499   }
3500   // Copy remaining value(s) from the original aggregate.
3501   for (; i != NumAggValues; ++i)
3502     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3503                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3504 
3505   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3506                            DAG.getVTList(AggValueVTs), Values));
3507 }
3508 
3509 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3510   ArrayRef<unsigned> Indices;
3511   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3512     Indices = EV->getIndices();
3513   else
3514     Indices = cast<ConstantExpr>(&I)->getIndices();
3515 
3516   const Value *Op0 = I.getOperand(0);
3517   Type *AggTy = Op0->getType();
3518   Type *ValTy = I.getType();
3519   bool OutOfUndef = isa<UndefValue>(Op0);
3520 
3521   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3522 
3523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3524   SmallVector<EVT, 4> ValValueVTs;
3525   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3526 
3527   unsigned NumValValues = ValValueVTs.size();
3528 
3529   // Ignore a extractvalue that produces an empty object
3530   if (!NumValValues) {
3531     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3532     return;
3533   }
3534 
3535   SmallVector<SDValue, 4> Values(NumValValues);
3536 
3537   SDValue Agg = getValue(Op0);
3538   // Copy out the selected value(s).
3539   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3540     Values[i - LinearIndex] =
3541       OutOfUndef ?
3542         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3543         SDValue(Agg.getNode(), Agg.getResNo() + i);
3544 
3545   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3546                            DAG.getVTList(ValValueVTs), Values));
3547 }
3548 
3549 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3550   Value *Op0 = I.getOperand(0);
3551   // Note that the pointer operand may be a vector of pointers. Take the scalar
3552   // element which holds a pointer.
3553   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3554   SDValue N = getValue(Op0);
3555   SDLoc dl = getCurSDLoc();
3556 
3557   // Normalize Vector GEP - all scalar operands should be converted to the
3558   // splat vector.
3559   unsigned VectorWidth = I.getType()->isVectorTy() ?
3560     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3561 
3562   if (VectorWidth && !N.getValueType().isVector()) {
3563     LLVMContext &Context = *DAG.getContext();
3564     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3565     N = DAG.getSplatBuildVector(VT, dl, N);
3566   }
3567 
3568   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3569        GTI != E; ++GTI) {
3570     const Value *Idx = GTI.getOperand();
3571     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3572       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3573       if (Field) {
3574         // N = N + Offset
3575         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3576 
3577         // In an inbounds GEP with an offset that is nonnegative even when
3578         // interpreted as signed, assume there is no unsigned overflow.
3579         SDNodeFlags Flags;
3580         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3581           Flags.setNoUnsignedWrap(true);
3582 
3583         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3584                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3585       }
3586     } else {
3587       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3588       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3589       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3590 
3591       // If this is a scalar constant or a splat vector of constants,
3592       // handle it quickly.
3593       const auto *CI = dyn_cast<ConstantInt>(Idx);
3594       if (!CI && isa<ConstantDataVector>(Idx) &&
3595           cast<ConstantDataVector>(Idx)->getSplatValue())
3596         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3597 
3598       if (CI) {
3599         if (CI->isZero())
3600           continue;
3601         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3602         LLVMContext &Context = *DAG.getContext();
3603         SDValue OffsVal = VectorWidth ?
3604           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3605           DAG.getConstant(Offs, dl, IdxTy);
3606 
3607         // In an inbouds GEP with an offset that is nonnegative even when
3608         // interpreted as signed, assume there is no unsigned overflow.
3609         SDNodeFlags Flags;
3610         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3611           Flags.setNoUnsignedWrap(true);
3612 
3613         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3614         continue;
3615       }
3616 
3617       // N = N + Idx * ElementSize;
3618       SDValue IdxN = getValue(Idx);
3619 
3620       if (!IdxN.getValueType().isVector() && VectorWidth) {
3621         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3622         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3623       }
3624 
3625       // If the index is smaller or larger than intptr_t, truncate or extend
3626       // it.
3627       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3628 
3629       // If this is a multiply by a power of two, turn it into a shl
3630       // immediately.  This is a very common case.
3631       if (ElementSize != 1) {
3632         if (ElementSize.isPowerOf2()) {
3633           unsigned Amt = ElementSize.logBase2();
3634           IdxN = DAG.getNode(ISD::SHL, dl,
3635                              N.getValueType(), IdxN,
3636                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3637         } else {
3638           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3639           IdxN = DAG.getNode(ISD::MUL, dl,
3640                              N.getValueType(), IdxN, Scale);
3641         }
3642       }
3643 
3644       N = DAG.getNode(ISD::ADD, dl,
3645                       N.getValueType(), N, IdxN);
3646     }
3647   }
3648 
3649   setValue(&I, N);
3650 }
3651 
3652 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3653   // If this is a fixed sized alloca in the entry block of the function,
3654   // allocate it statically on the stack.
3655   if (FuncInfo.StaticAllocaMap.count(&I))
3656     return;   // getValue will auto-populate this.
3657 
3658   SDLoc dl = getCurSDLoc();
3659   Type *Ty = I.getAllocatedType();
3660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3661   auto &DL = DAG.getDataLayout();
3662   uint64_t TySize = DL.getTypeAllocSize(Ty);
3663   unsigned Align =
3664       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3665 
3666   SDValue AllocSize = getValue(I.getArraySize());
3667 
3668   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3669   if (AllocSize.getValueType() != IntPtr)
3670     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3671 
3672   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3673                           AllocSize,
3674                           DAG.getConstant(TySize, dl, IntPtr));
3675 
3676   // Handle alignment.  If the requested alignment is less than or equal to
3677   // the stack alignment, ignore it.  If the size is greater than or equal to
3678   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3679   unsigned StackAlign =
3680       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3681   if (Align <= StackAlign)
3682     Align = 0;
3683 
3684   // Round the size of the allocation up to the stack alignment size
3685   // by add SA-1 to the size. This doesn't overflow because we're computing
3686   // an address inside an alloca.
3687   SDNodeFlags Flags;
3688   Flags.setNoUnsignedWrap(true);
3689   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3690                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3691 
3692   // Mask out the low bits for alignment purposes.
3693   AllocSize =
3694       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3695                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3696 
3697   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3698   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3699   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3700   setValue(&I, DSA);
3701   DAG.setRoot(DSA.getValue(1));
3702 
3703   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3704 }
3705 
3706 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3707   if (I.isAtomic())
3708     return visitAtomicLoad(I);
3709 
3710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3711   const Value *SV = I.getOperand(0);
3712   if (TLI.supportSwiftError()) {
3713     // Swifterror values can come from either a function parameter with
3714     // swifterror attribute or an alloca with swifterror attribute.
3715     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3716       if (Arg->hasSwiftErrorAttr())
3717         return visitLoadFromSwiftError(I);
3718     }
3719 
3720     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3721       if (Alloca->isSwiftError())
3722         return visitLoadFromSwiftError(I);
3723     }
3724   }
3725 
3726   SDValue Ptr = getValue(SV);
3727 
3728   Type *Ty = I.getType();
3729 
3730   bool isVolatile = I.isVolatile();
3731   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3732   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3733   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3734   unsigned Alignment = I.getAlignment();
3735 
3736   AAMDNodes AAInfo;
3737   I.getAAMetadata(AAInfo);
3738   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3739 
3740   SmallVector<EVT, 4> ValueVTs;
3741   SmallVector<uint64_t, 4> Offsets;
3742   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3743   unsigned NumValues = ValueVTs.size();
3744   if (NumValues == 0)
3745     return;
3746 
3747   SDValue Root;
3748   bool ConstantMemory = false;
3749   if (isVolatile || NumValues > MaxParallelChains)
3750     // Serialize volatile loads with other side effects.
3751     Root = getRoot();
3752   else if (AA &&
3753            AA->pointsToConstantMemory(MemoryLocation(
3754                SV,
3755                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3756                AAInfo))) {
3757     // Do not serialize (non-volatile) loads of constant memory with anything.
3758     Root = DAG.getEntryNode();
3759     ConstantMemory = true;
3760   } else {
3761     // Do not serialize non-volatile loads against each other.
3762     Root = DAG.getRoot();
3763   }
3764 
3765   SDLoc dl = getCurSDLoc();
3766 
3767   if (isVolatile)
3768     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3769 
3770   // An aggregate load cannot wrap around the address space, so offsets to its
3771   // parts don't wrap either.
3772   SDNodeFlags Flags;
3773   Flags.setNoUnsignedWrap(true);
3774 
3775   SmallVector<SDValue, 4> Values(NumValues);
3776   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3777   EVT PtrVT = Ptr.getValueType();
3778   unsigned ChainI = 0;
3779   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3780     // Serializing loads here may result in excessive register pressure, and
3781     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3782     // could recover a bit by hoisting nodes upward in the chain by recognizing
3783     // they are side-effect free or do not alias. The optimizer should really
3784     // avoid this case by converting large object/array copies to llvm.memcpy
3785     // (MaxParallelChains should always remain as failsafe).
3786     if (ChainI == MaxParallelChains) {
3787       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3788       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3789                                   makeArrayRef(Chains.data(), ChainI));
3790       Root = Chain;
3791       ChainI = 0;
3792     }
3793     SDValue A = DAG.getNode(ISD::ADD, dl,
3794                             PtrVT, Ptr,
3795                             DAG.getConstant(Offsets[i], dl, PtrVT),
3796                             Flags);
3797     auto MMOFlags = MachineMemOperand::MONone;
3798     if (isVolatile)
3799       MMOFlags |= MachineMemOperand::MOVolatile;
3800     if (isNonTemporal)
3801       MMOFlags |= MachineMemOperand::MONonTemporal;
3802     if (isInvariant)
3803       MMOFlags |= MachineMemOperand::MOInvariant;
3804     if (isDereferenceable)
3805       MMOFlags |= MachineMemOperand::MODereferenceable;
3806     MMOFlags |= TLI.getMMOFlags(I);
3807 
3808     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3809                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3810                             MMOFlags, AAInfo, Ranges);
3811 
3812     Values[i] = L;
3813     Chains[ChainI] = L.getValue(1);
3814   }
3815 
3816   if (!ConstantMemory) {
3817     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3818                                 makeArrayRef(Chains.data(), ChainI));
3819     if (isVolatile)
3820       DAG.setRoot(Chain);
3821     else
3822       PendingLoads.push_back(Chain);
3823   }
3824 
3825   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3826                            DAG.getVTList(ValueVTs), Values));
3827 }
3828 
3829 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3830   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3831          "call visitStoreToSwiftError when backend supports swifterror");
3832 
3833   SmallVector<EVT, 4> ValueVTs;
3834   SmallVector<uint64_t, 4> Offsets;
3835   const Value *SrcV = I.getOperand(0);
3836   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3837                   SrcV->getType(), ValueVTs, &Offsets);
3838   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3839          "expect a single EVT for swifterror");
3840 
3841   SDValue Src = getValue(SrcV);
3842   // Create a virtual register, then update the virtual register.
3843   unsigned VReg; bool CreatedVReg;
3844   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3845   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3846   // Chain can be getRoot or getControlRoot.
3847   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3848                                       SDValue(Src.getNode(), Src.getResNo()));
3849   DAG.setRoot(CopyNode);
3850   if (CreatedVReg)
3851     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3852 }
3853 
3854 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3855   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3856          "call visitLoadFromSwiftError when backend supports swifterror");
3857 
3858   assert(!I.isVolatile() &&
3859          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3860          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3861          "Support volatile, non temporal, invariant for load_from_swift_error");
3862 
3863   const Value *SV = I.getOperand(0);
3864   Type *Ty = I.getType();
3865   AAMDNodes AAInfo;
3866   I.getAAMetadata(AAInfo);
3867   assert(
3868       (!AA ||
3869        !AA->pointsToConstantMemory(MemoryLocation(
3870            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3871            AAInfo))) &&
3872       "load_from_swift_error should not be constant memory");
3873 
3874   SmallVector<EVT, 4> ValueVTs;
3875   SmallVector<uint64_t, 4> Offsets;
3876   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3877                   ValueVTs, &Offsets);
3878   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3879          "expect a single EVT for swifterror");
3880 
3881   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3882   SDValue L = DAG.getCopyFromReg(
3883       getRoot(), getCurSDLoc(),
3884       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3885       ValueVTs[0]);
3886 
3887   setValue(&I, L);
3888 }
3889 
3890 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3891   if (I.isAtomic())
3892     return visitAtomicStore(I);
3893 
3894   const Value *SrcV = I.getOperand(0);
3895   const Value *PtrV = I.getOperand(1);
3896 
3897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3898   if (TLI.supportSwiftError()) {
3899     // Swifterror values can come from either a function parameter with
3900     // swifterror attribute or an alloca with swifterror attribute.
3901     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3902       if (Arg->hasSwiftErrorAttr())
3903         return visitStoreToSwiftError(I);
3904     }
3905 
3906     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3907       if (Alloca->isSwiftError())
3908         return visitStoreToSwiftError(I);
3909     }
3910   }
3911 
3912   SmallVector<EVT, 4> ValueVTs;
3913   SmallVector<uint64_t, 4> Offsets;
3914   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3915                   SrcV->getType(), ValueVTs, &Offsets);
3916   unsigned NumValues = ValueVTs.size();
3917   if (NumValues == 0)
3918     return;
3919 
3920   // Get the lowered operands. Note that we do this after
3921   // checking if NumResults is zero, because with zero results
3922   // the operands won't have values in the map.
3923   SDValue Src = getValue(SrcV);
3924   SDValue Ptr = getValue(PtrV);
3925 
3926   SDValue Root = getRoot();
3927   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3928   SDLoc dl = getCurSDLoc();
3929   EVT PtrVT = Ptr.getValueType();
3930   unsigned Alignment = I.getAlignment();
3931   AAMDNodes AAInfo;
3932   I.getAAMetadata(AAInfo);
3933 
3934   auto MMOFlags = MachineMemOperand::MONone;
3935   if (I.isVolatile())
3936     MMOFlags |= MachineMemOperand::MOVolatile;
3937   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3938     MMOFlags |= MachineMemOperand::MONonTemporal;
3939   MMOFlags |= TLI.getMMOFlags(I);
3940 
3941   // An aggregate load cannot wrap around the address space, so offsets to its
3942   // parts don't wrap either.
3943   SDNodeFlags Flags;
3944   Flags.setNoUnsignedWrap(true);
3945 
3946   unsigned ChainI = 0;
3947   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3948     // See visitLoad comments.
3949     if (ChainI == MaxParallelChains) {
3950       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3951                                   makeArrayRef(Chains.data(), ChainI));
3952       Root = Chain;
3953       ChainI = 0;
3954     }
3955     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3956                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3957     SDValue St = DAG.getStore(
3958         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3959         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3960     Chains[ChainI] = St;
3961   }
3962 
3963   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3964                                   makeArrayRef(Chains.data(), ChainI));
3965   DAG.setRoot(StoreNode);
3966 }
3967 
3968 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3969                                            bool IsCompressing) {
3970   SDLoc sdl = getCurSDLoc();
3971 
3972   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3973                            unsigned& Alignment) {
3974     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3975     Src0 = I.getArgOperand(0);
3976     Ptr = I.getArgOperand(1);
3977     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3978     Mask = I.getArgOperand(3);
3979   };
3980   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3981                            unsigned& Alignment) {
3982     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3983     Src0 = I.getArgOperand(0);
3984     Ptr = I.getArgOperand(1);
3985     Mask = I.getArgOperand(2);
3986     Alignment = 0;
3987   };
3988 
3989   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3990   unsigned Alignment;
3991   if (IsCompressing)
3992     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3993   else
3994     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3995 
3996   SDValue Ptr = getValue(PtrOperand);
3997   SDValue Src0 = getValue(Src0Operand);
3998   SDValue Mask = getValue(MaskOperand);
3999 
4000   EVT VT = Src0.getValueType();
4001   if (!Alignment)
4002     Alignment = DAG.getEVTAlignment(VT);
4003 
4004   AAMDNodes AAInfo;
4005   I.getAAMetadata(AAInfo);
4006 
4007   MachineMemOperand *MMO =
4008     DAG.getMachineFunction().
4009     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4010                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4011                           Alignment, AAInfo);
4012   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4013                                          MMO, false /* Truncating */,
4014                                          IsCompressing);
4015   DAG.setRoot(StoreNode);
4016   setValue(&I, StoreNode);
4017 }
4018 
4019 // Get a uniform base for the Gather/Scatter intrinsic.
4020 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4021 // We try to represent it as a base pointer + vector of indices.
4022 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4023 // The first operand of the GEP may be a single pointer or a vector of pointers
4024 // Example:
4025 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4026 //  or
4027 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4028 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4029 //
4030 // When the first GEP operand is a single pointer - it is the uniform base we
4031 // are looking for. If first operand of the GEP is a splat vector - we
4032 // extract the splat value and use it as a uniform base.
4033 // In all other cases the function returns 'false'.
4034 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4035                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4036   SelectionDAG& DAG = SDB->DAG;
4037   LLVMContext &Context = *DAG.getContext();
4038 
4039   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4040   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4041   if (!GEP)
4042     return false;
4043 
4044   const Value *GEPPtr = GEP->getPointerOperand();
4045   if (!GEPPtr->getType()->isVectorTy())
4046     Ptr = GEPPtr;
4047   else if (!(Ptr = getSplatValue(GEPPtr)))
4048     return false;
4049 
4050   unsigned FinalIndex = GEP->getNumOperands() - 1;
4051   Value *IndexVal = GEP->getOperand(FinalIndex);
4052 
4053   // Ensure all the other indices are 0.
4054   for (unsigned i = 1; i < FinalIndex; ++i) {
4055     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4056     if (!C || !C->isZero())
4057       return false;
4058   }
4059 
4060   // The operands of the GEP may be defined in another basic block.
4061   // In this case we'll not find nodes for the operands.
4062   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4063     return false;
4064 
4065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4066   const DataLayout &DL = DAG.getDataLayout();
4067   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4068                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4069   Base = SDB->getValue(Ptr);
4070   Index = SDB->getValue(IndexVal);
4071 
4072   if (!Index.getValueType().isVector()) {
4073     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4074     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4075     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4076   }
4077   return true;
4078 }
4079 
4080 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4081   SDLoc sdl = getCurSDLoc();
4082 
4083   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4084   const Value *Ptr = I.getArgOperand(1);
4085   SDValue Src0 = getValue(I.getArgOperand(0));
4086   SDValue Mask = getValue(I.getArgOperand(3));
4087   EVT VT = Src0.getValueType();
4088   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4089   if (!Alignment)
4090     Alignment = DAG.getEVTAlignment(VT);
4091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4092 
4093   AAMDNodes AAInfo;
4094   I.getAAMetadata(AAInfo);
4095 
4096   SDValue Base;
4097   SDValue Index;
4098   SDValue Scale;
4099   const Value *BasePtr = Ptr;
4100   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4101 
4102   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4103   MachineMemOperand *MMO = DAG.getMachineFunction().
4104     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4105                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4106                          Alignment, AAInfo);
4107   if (!UniformBase) {
4108     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4109     Index = getValue(Ptr);
4110     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4111   }
4112   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4113   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4114                                          Ops, MMO);
4115   DAG.setRoot(Scatter);
4116   setValue(&I, Scatter);
4117 }
4118 
4119 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4120   SDLoc sdl = getCurSDLoc();
4121 
4122   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4123                            unsigned& Alignment) {
4124     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4125     Ptr = I.getArgOperand(0);
4126     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4127     Mask = I.getArgOperand(2);
4128     Src0 = I.getArgOperand(3);
4129   };
4130   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4131                            unsigned& Alignment) {
4132     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4133     Ptr = I.getArgOperand(0);
4134     Alignment = 0;
4135     Mask = I.getArgOperand(1);
4136     Src0 = I.getArgOperand(2);
4137   };
4138 
4139   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4140   unsigned Alignment;
4141   if (IsExpanding)
4142     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4143   else
4144     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4145 
4146   SDValue Ptr = getValue(PtrOperand);
4147   SDValue Src0 = getValue(Src0Operand);
4148   SDValue Mask = getValue(MaskOperand);
4149 
4150   EVT VT = Src0.getValueType();
4151   if (!Alignment)
4152     Alignment = DAG.getEVTAlignment(VT);
4153 
4154   AAMDNodes AAInfo;
4155   I.getAAMetadata(AAInfo);
4156   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4157 
4158   // Do not serialize masked loads of constant memory with anything.
4159   bool AddToChain =
4160       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4161                  PtrOperand,
4162                  LocationSize::precise(
4163                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4164                  AAInfo));
4165   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4166 
4167   MachineMemOperand *MMO =
4168     DAG.getMachineFunction().
4169     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4170                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4171                           Alignment, AAInfo, Ranges);
4172 
4173   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4174                                    ISD::NON_EXTLOAD, IsExpanding);
4175   if (AddToChain)
4176     PendingLoads.push_back(Load.getValue(1));
4177   setValue(&I, Load);
4178 }
4179 
4180 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4181   SDLoc sdl = getCurSDLoc();
4182 
4183   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4184   const Value *Ptr = I.getArgOperand(0);
4185   SDValue Src0 = getValue(I.getArgOperand(3));
4186   SDValue Mask = getValue(I.getArgOperand(2));
4187 
4188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4189   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4190   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4191   if (!Alignment)
4192     Alignment = DAG.getEVTAlignment(VT);
4193 
4194   AAMDNodes AAInfo;
4195   I.getAAMetadata(AAInfo);
4196   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4197 
4198   SDValue Root = DAG.getRoot();
4199   SDValue Base;
4200   SDValue Index;
4201   SDValue Scale;
4202   const Value *BasePtr = Ptr;
4203   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4204   bool ConstantMemory = false;
4205   if (UniformBase && AA &&
4206       AA->pointsToConstantMemory(
4207           MemoryLocation(BasePtr,
4208                          LocationSize::precise(
4209                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4210                          AAInfo))) {
4211     // Do not serialize (non-volatile) loads of constant memory with anything.
4212     Root = DAG.getEntryNode();
4213     ConstantMemory = true;
4214   }
4215 
4216   MachineMemOperand *MMO =
4217     DAG.getMachineFunction().
4218     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4219                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4220                          Alignment, AAInfo, Ranges);
4221 
4222   if (!UniformBase) {
4223     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4224     Index = getValue(Ptr);
4225     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4226   }
4227   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4228   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4229                                        Ops, MMO);
4230 
4231   SDValue OutChain = Gather.getValue(1);
4232   if (!ConstantMemory)
4233     PendingLoads.push_back(OutChain);
4234   setValue(&I, Gather);
4235 }
4236 
4237 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4238   SDLoc dl = getCurSDLoc();
4239   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4240   AtomicOrdering FailureOrder = I.getFailureOrdering();
4241   SyncScope::ID SSID = I.getSyncScopeID();
4242 
4243   SDValue InChain = getRoot();
4244 
4245   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4246   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4247   SDValue L = DAG.getAtomicCmpSwap(
4248       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4249       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4250       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4251       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4252 
4253   SDValue OutChain = L.getValue(2);
4254 
4255   setValue(&I, L);
4256   DAG.setRoot(OutChain);
4257 }
4258 
4259 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4260   SDLoc dl = getCurSDLoc();
4261   ISD::NodeType NT;
4262   switch (I.getOperation()) {
4263   default: llvm_unreachable("Unknown atomicrmw operation");
4264   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4265   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4266   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4267   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4268   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4269   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4270   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4271   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4272   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4273   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4274   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4275   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4276   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4277   }
4278   AtomicOrdering Order = I.getOrdering();
4279   SyncScope::ID SSID = I.getSyncScopeID();
4280 
4281   SDValue InChain = getRoot();
4282 
4283   SDValue L =
4284     DAG.getAtomic(NT, dl,
4285                   getValue(I.getValOperand()).getSimpleValueType(),
4286                   InChain,
4287                   getValue(I.getPointerOperand()),
4288                   getValue(I.getValOperand()),
4289                   I.getPointerOperand(),
4290                   /* Alignment=*/ 0, Order, SSID);
4291 
4292   SDValue OutChain = L.getValue(1);
4293 
4294   setValue(&I, L);
4295   DAG.setRoot(OutChain);
4296 }
4297 
4298 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4299   SDLoc dl = getCurSDLoc();
4300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4301   SDValue Ops[3];
4302   Ops[0] = getRoot();
4303   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4304                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4305   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4306                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4307   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4308 }
4309 
4310 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4311   SDLoc dl = getCurSDLoc();
4312   AtomicOrdering Order = I.getOrdering();
4313   SyncScope::ID SSID = I.getSyncScopeID();
4314 
4315   SDValue InChain = getRoot();
4316 
4317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4318   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4319 
4320   if (!TLI.supportsUnalignedAtomics() &&
4321       I.getAlignment() < VT.getStoreSize())
4322     report_fatal_error("Cannot generate unaligned atomic load");
4323 
4324   MachineMemOperand *MMO =
4325       DAG.getMachineFunction().
4326       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4327                            MachineMemOperand::MOVolatile |
4328                            MachineMemOperand::MOLoad,
4329                            VT.getStoreSize(),
4330                            I.getAlignment() ? I.getAlignment() :
4331                                               DAG.getEVTAlignment(VT),
4332                            AAMDNodes(), nullptr, SSID, Order);
4333 
4334   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4335   SDValue L =
4336       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4337                     getValue(I.getPointerOperand()), MMO);
4338 
4339   SDValue OutChain = L.getValue(1);
4340 
4341   setValue(&I, L);
4342   DAG.setRoot(OutChain);
4343 }
4344 
4345 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4346   SDLoc dl = getCurSDLoc();
4347 
4348   AtomicOrdering Order = I.getOrdering();
4349   SyncScope::ID SSID = I.getSyncScopeID();
4350 
4351   SDValue InChain = getRoot();
4352 
4353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4354   EVT VT =
4355       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4356 
4357   if (I.getAlignment() < VT.getStoreSize())
4358     report_fatal_error("Cannot generate unaligned atomic store");
4359 
4360   SDValue OutChain =
4361     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4362                   InChain,
4363                   getValue(I.getPointerOperand()),
4364                   getValue(I.getValueOperand()),
4365                   I.getPointerOperand(), I.getAlignment(),
4366                   Order, SSID);
4367 
4368   DAG.setRoot(OutChain);
4369 }
4370 
4371 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4372 /// node.
4373 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4374                                                unsigned Intrinsic) {
4375   // Ignore the callsite's attributes. A specific call site may be marked with
4376   // readnone, but the lowering code will expect the chain based on the
4377   // definition.
4378   const Function *F = I.getCalledFunction();
4379   bool HasChain = !F->doesNotAccessMemory();
4380   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4381 
4382   // Build the operand list.
4383   SmallVector<SDValue, 8> Ops;
4384   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4385     if (OnlyLoad) {
4386       // We don't need to serialize loads against other loads.
4387       Ops.push_back(DAG.getRoot());
4388     } else {
4389       Ops.push_back(getRoot());
4390     }
4391   }
4392 
4393   // Info is set by getTgtMemInstrinsic
4394   TargetLowering::IntrinsicInfo Info;
4395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4396   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4397                                                DAG.getMachineFunction(),
4398                                                Intrinsic);
4399 
4400   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4401   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4402       Info.opc == ISD::INTRINSIC_W_CHAIN)
4403     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4404                                         TLI.getPointerTy(DAG.getDataLayout())));
4405 
4406   // Add all operands of the call to the operand list.
4407   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4408     SDValue Op = getValue(I.getArgOperand(i));
4409     Ops.push_back(Op);
4410   }
4411 
4412   SmallVector<EVT, 4> ValueVTs;
4413   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4414 
4415   if (HasChain)
4416     ValueVTs.push_back(MVT::Other);
4417 
4418   SDVTList VTs = DAG.getVTList(ValueVTs);
4419 
4420   // Create the node.
4421   SDValue Result;
4422   if (IsTgtIntrinsic) {
4423     // This is target intrinsic that touches memory
4424     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4425       Ops, Info.memVT,
4426       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4427       Info.flags, Info.size);
4428   } else if (!HasChain) {
4429     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4430   } else if (!I.getType()->isVoidTy()) {
4431     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4432   } else {
4433     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4434   }
4435 
4436   if (HasChain) {
4437     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4438     if (OnlyLoad)
4439       PendingLoads.push_back(Chain);
4440     else
4441       DAG.setRoot(Chain);
4442   }
4443 
4444   if (!I.getType()->isVoidTy()) {
4445     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4446       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4447       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4448     } else
4449       Result = lowerRangeToAssertZExt(DAG, I, Result);
4450 
4451     setValue(&I, Result);
4452   }
4453 }
4454 
4455 /// GetSignificand - Get the significand and build it into a floating-point
4456 /// number with exponent of 1:
4457 ///
4458 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4459 ///
4460 /// where Op is the hexadecimal representation of floating point value.
4461 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4462   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4463                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4464   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4465                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4466   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4467 }
4468 
4469 /// GetExponent - Get the exponent:
4470 ///
4471 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4472 ///
4473 /// where Op is the hexadecimal representation of floating point value.
4474 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4475                            const TargetLowering &TLI, const SDLoc &dl) {
4476   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4477                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4478   SDValue t1 = DAG.getNode(
4479       ISD::SRL, dl, MVT::i32, t0,
4480       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4481   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4482                            DAG.getConstant(127, dl, MVT::i32));
4483   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4484 }
4485 
4486 /// getF32Constant - Get 32-bit floating point constant.
4487 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4488                               const SDLoc &dl) {
4489   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4490                            MVT::f32);
4491 }
4492 
4493 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4494                                        SelectionDAG &DAG) {
4495   // TODO: What fast-math-flags should be set on the floating-point nodes?
4496 
4497   //   IntegerPartOfX = ((int32_t)(t0);
4498   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4499 
4500   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4501   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4502   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4503 
4504   //   IntegerPartOfX <<= 23;
4505   IntegerPartOfX = DAG.getNode(
4506       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4507       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4508                                   DAG.getDataLayout())));
4509 
4510   SDValue TwoToFractionalPartOfX;
4511   if (LimitFloatPrecision <= 6) {
4512     // For floating-point precision of 6:
4513     //
4514     //   TwoToFractionalPartOfX =
4515     //     0.997535578f +
4516     //       (0.735607626f + 0.252464424f * x) * x;
4517     //
4518     // error 0.0144103317, which is 6 bits
4519     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4520                              getF32Constant(DAG, 0x3e814304, dl));
4521     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4522                              getF32Constant(DAG, 0x3f3c50c8, dl));
4523     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4524     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4525                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4526   } else if (LimitFloatPrecision <= 12) {
4527     // For floating-point precision of 12:
4528     //
4529     //   TwoToFractionalPartOfX =
4530     //     0.999892986f +
4531     //       (0.696457318f +
4532     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4533     //
4534     // error 0.000107046256, which is 13 to 14 bits
4535     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4536                              getF32Constant(DAG, 0x3da235e3, dl));
4537     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4538                              getF32Constant(DAG, 0x3e65b8f3, dl));
4539     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4540     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4541                              getF32Constant(DAG, 0x3f324b07, dl));
4542     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4543     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4544                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4545   } else { // LimitFloatPrecision <= 18
4546     // For floating-point precision of 18:
4547     //
4548     //   TwoToFractionalPartOfX =
4549     //     0.999999982f +
4550     //       (0.693148872f +
4551     //         (0.240227044f +
4552     //           (0.554906021e-1f +
4553     //             (0.961591928e-2f +
4554     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4555     // error 2.47208000*10^(-7), which is better than 18 bits
4556     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4557                              getF32Constant(DAG, 0x3924b03e, dl));
4558     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4559                              getF32Constant(DAG, 0x3ab24b87, dl));
4560     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4561     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4562                              getF32Constant(DAG, 0x3c1d8c17, dl));
4563     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4564     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4565                              getF32Constant(DAG, 0x3d634a1d, dl));
4566     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4567     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4568                              getF32Constant(DAG, 0x3e75fe14, dl));
4569     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4570     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4571                               getF32Constant(DAG, 0x3f317234, dl));
4572     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4573     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4574                                          getF32Constant(DAG, 0x3f800000, dl));
4575   }
4576 
4577   // Add the exponent into the result in integer domain.
4578   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4579   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4580                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4581 }
4582 
4583 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4584 /// limited-precision mode.
4585 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4586                          const TargetLowering &TLI) {
4587   if (Op.getValueType() == MVT::f32 &&
4588       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4589 
4590     // Put the exponent in the right bit position for later addition to the
4591     // final result:
4592     //
4593     //   #define LOG2OFe 1.4426950f
4594     //   t0 = Op * LOG2OFe
4595 
4596     // TODO: What fast-math-flags should be set here?
4597     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4598                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4599     return getLimitedPrecisionExp2(t0, dl, DAG);
4600   }
4601 
4602   // No special expansion.
4603   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4604 }
4605 
4606 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4607 /// limited-precision mode.
4608 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4609                          const TargetLowering &TLI) {
4610   // TODO: What fast-math-flags should be set on the floating-point nodes?
4611 
4612   if (Op.getValueType() == MVT::f32 &&
4613       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4614     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4615 
4616     // Scale the exponent by log(2) [0.69314718f].
4617     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4618     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4619                                         getF32Constant(DAG, 0x3f317218, dl));
4620 
4621     // Get the significand and build it into a floating-point number with
4622     // exponent of 1.
4623     SDValue X = GetSignificand(DAG, Op1, dl);
4624 
4625     SDValue LogOfMantissa;
4626     if (LimitFloatPrecision <= 6) {
4627       // For floating-point precision of 6:
4628       //
4629       //   LogofMantissa =
4630       //     -1.1609546f +
4631       //       (1.4034025f - 0.23903021f * x) * x;
4632       //
4633       // error 0.0034276066, which is better than 8 bits
4634       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4635                                getF32Constant(DAG, 0xbe74c456, dl));
4636       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4637                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4638       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4639       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4640                                   getF32Constant(DAG, 0x3f949a29, dl));
4641     } else if (LimitFloatPrecision <= 12) {
4642       // For floating-point precision of 12:
4643       //
4644       //   LogOfMantissa =
4645       //     -1.7417939f +
4646       //       (2.8212026f +
4647       //         (-1.4699568f +
4648       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4649       //
4650       // error 0.000061011436, which is 14 bits
4651       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4652                                getF32Constant(DAG, 0xbd67b6d6, dl));
4653       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4654                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4655       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4656       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4657                                getF32Constant(DAG, 0x3fbc278b, dl));
4658       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4659       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4660                                getF32Constant(DAG, 0x40348e95, dl));
4661       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4662       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4663                                   getF32Constant(DAG, 0x3fdef31a, dl));
4664     } else { // LimitFloatPrecision <= 18
4665       // For floating-point precision of 18:
4666       //
4667       //   LogOfMantissa =
4668       //     -2.1072184f +
4669       //       (4.2372794f +
4670       //         (-3.7029485f +
4671       //           (2.2781945f +
4672       //             (-0.87823314f +
4673       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4674       //
4675       // error 0.0000023660568, which is better than 18 bits
4676       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4677                                getF32Constant(DAG, 0xbc91e5ac, dl));
4678       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4679                                getF32Constant(DAG, 0x3e4350aa, dl));
4680       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4681       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4682                                getF32Constant(DAG, 0x3f60d3e3, dl));
4683       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4684       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4685                                getF32Constant(DAG, 0x4011cdf0, dl));
4686       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4687       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4688                                getF32Constant(DAG, 0x406cfd1c, dl));
4689       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4690       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4691                                getF32Constant(DAG, 0x408797cb, dl));
4692       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4693       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4694                                   getF32Constant(DAG, 0x4006dcab, dl));
4695     }
4696 
4697     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4698   }
4699 
4700   // No special expansion.
4701   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4702 }
4703 
4704 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4705 /// limited-precision mode.
4706 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4707                           const TargetLowering &TLI) {
4708   // TODO: What fast-math-flags should be set on the floating-point nodes?
4709 
4710   if (Op.getValueType() == MVT::f32 &&
4711       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4712     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4713 
4714     // Get the exponent.
4715     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4716 
4717     // Get the significand and build it into a floating-point number with
4718     // exponent of 1.
4719     SDValue X = GetSignificand(DAG, Op1, dl);
4720 
4721     // Different possible minimax approximations of significand in
4722     // floating-point for various degrees of accuracy over [1,2].
4723     SDValue Log2ofMantissa;
4724     if (LimitFloatPrecision <= 6) {
4725       // For floating-point precision of 6:
4726       //
4727       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4728       //
4729       // error 0.0049451742, which is more than 7 bits
4730       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4731                                getF32Constant(DAG, 0xbeb08fe0, dl));
4732       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4733                                getF32Constant(DAG, 0x40019463, dl));
4734       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4735       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4736                                    getF32Constant(DAG, 0x3fd6633d, dl));
4737     } else if (LimitFloatPrecision <= 12) {
4738       // For floating-point precision of 12:
4739       //
4740       //   Log2ofMantissa =
4741       //     -2.51285454f +
4742       //       (4.07009056f +
4743       //         (-2.12067489f +
4744       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4745       //
4746       // error 0.0000876136000, which is better than 13 bits
4747       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4748                                getF32Constant(DAG, 0xbda7262e, dl));
4749       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4750                                getF32Constant(DAG, 0x3f25280b, dl));
4751       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4752       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4753                                getF32Constant(DAG, 0x4007b923, dl));
4754       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4755       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4756                                getF32Constant(DAG, 0x40823e2f, dl));
4757       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4758       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4759                                    getF32Constant(DAG, 0x4020d29c, dl));
4760     } else { // LimitFloatPrecision <= 18
4761       // For floating-point precision of 18:
4762       //
4763       //   Log2ofMantissa =
4764       //     -3.0400495f +
4765       //       (6.1129976f +
4766       //         (-5.3420409f +
4767       //           (3.2865683f +
4768       //             (-1.2669343f +
4769       //               (0.27515199f -
4770       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4771       //
4772       // error 0.0000018516, which is better than 18 bits
4773       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4774                                getF32Constant(DAG, 0xbcd2769e, dl));
4775       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4776                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4777       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4778       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4779                                getF32Constant(DAG, 0x3fa22ae7, dl));
4780       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4781       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4782                                getF32Constant(DAG, 0x40525723, dl));
4783       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4784       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4785                                getF32Constant(DAG, 0x40aaf200, dl));
4786       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4787       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4788                                getF32Constant(DAG, 0x40c39dad, dl));
4789       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4790       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4791                                    getF32Constant(DAG, 0x4042902c, dl));
4792     }
4793 
4794     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4795   }
4796 
4797   // No special expansion.
4798   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4799 }
4800 
4801 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4802 /// limited-precision mode.
4803 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4804                            const TargetLowering &TLI) {
4805   // TODO: What fast-math-flags should be set on the floating-point nodes?
4806 
4807   if (Op.getValueType() == MVT::f32 &&
4808       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4809     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4810 
4811     // Scale the exponent by log10(2) [0.30102999f].
4812     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4813     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4814                                         getF32Constant(DAG, 0x3e9a209a, dl));
4815 
4816     // Get the significand and build it into a floating-point number with
4817     // exponent of 1.
4818     SDValue X = GetSignificand(DAG, Op1, dl);
4819 
4820     SDValue Log10ofMantissa;
4821     if (LimitFloatPrecision <= 6) {
4822       // For floating-point precision of 6:
4823       //
4824       //   Log10ofMantissa =
4825       //     -0.50419619f +
4826       //       (0.60948995f - 0.10380950f * x) * x;
4827       //
4828       // error 0.0014886165, which is 6 bits
4829       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4830                                getF32Constant(DAG, 0xbdd49a13, dl));
4831       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4832                                getF32Constant(DAG, 0x3f1c0789, dl));
4833       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4834       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4835                                     getF32Constant(DAG, 0x3f011300, dl));
4836     } else if (LimitFloatPrecision <= 12) {
4837       // For floating-point precision of 12:
4838       //
4839       //   Log10ofMantissa =
4840       //     -0.64831180f +
4841       //       (0.91751397f +
4842       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4843       //
4844       // error 0.00019228036, which is better than 12 bits
4845       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4846                                getF32Constant(DAG, 0x3d431f31, dl));
4847       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4848                                getF32Constant(DAG, 0x3ea21fb2, dl));
4849       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4850       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4851                                getF32Constant(DAG, 0x3f6ae232, dl));
4852       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4853       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4854                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4855     } else { // LimitFloatPrecision <= 18
4856       // For floating-point precision of 18:
4857       //
4858       //   Log10ofMantissa =
4859       //     -0.84299375f +
4860       //       (1.5327582f +
4861       //         (-1.0688956f +
4862       //           (0.49102474f +
4863       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4864       //
4865       // error 0.0000037995730, which is better than 18 bits
4866       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4867                                getF32Constant(DAG, 0x3c5d51ce, dl));
4868       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4869                                getF32Constant(DAG, 0x3e00685a, dl));
4870       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4871       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4872                                getF32Constant(DAG, 0x3efb6798, dl));
4873       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4874       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4875                                getF32Constant(DAG, 0x3f88d192, dl));
4876       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4877       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4878                                getF32Constant(DAG, 0x3fc4316c, dl));
4879       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4880       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4881                                     getF32Constant(DAG, 0x3f57ce70, dl));
4882     }
4883 
4884     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4885   }
4886 
4887   // No special expansion.
4888   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4889 }
4890 
4891 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4892 /// limited-precision mode.
4893 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4894                           const TargetLowering &TLI) {
4895   if (Op.getValueType() == MVT::f32 &&
4896       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4897     return getLimitedPrecisionExp2(Op, dl, DAG);
4898 
4899   // No special expansion.
4900   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4901 }
4902 
4903 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4904 /// limited-precision mode with x == 10.0f.
4905 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4906                          SelectionDAG &DAG, const TargetLowering &TLI) {
4907   bool IsExp10 = false;
4908   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4909       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4910     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4911       APFloat Ten(10.0f);
4912       IsExp10 = LHSC->isExactlyValue(Ten);
4913     }
4914   }
4915 
4916   // TODO: What fast-math-flags should be set on the FMUL node?
4917   if (IsExp10) {
4918     // Put the exponent in the right bit position for later addition to the
4919     // final result:
4920     //
4921     //   #define LOG2OF10 3.3219281f
4922     //   t0 = Op * LOG2OF10;
4923     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4924                              getF32Constant(DAG, 0x40549a78, dl));
4925     return getLimitedPrecisionExp2(t0, dl, DAG);
4926   }
4927 
4928   // No special expansion.
4929   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4930 }
4931 
4932 /// ExpandPowI - Expand a llvm.powi intrinsic.
4933 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4934                           SelectionDAG &DAG) {
4935   // If RHS is a constant, we can expand this out to a multiplication tree,
4936   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4937   // optimizing for size, we only want to do this if the expansion would produce
4938   // a small number of multiplies, otherwise we do the full expansion.
4939   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4940     // Get the exponent as a positive value.
4941     unsigned Val = RHSC->getSExtValue();
4942     if ((int)Val < 0) Val = -Val;
4943 
4944     // powi(x, 0) -> 1.0
4945     if (Val == 0)
4946       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4947 
4948     const Function &F = DAG.getMachineFunction().getFunction();
4949     if (!F.optForSize() ||
4950         // If optimizing for size, don't insert too many multiplies.
4951         // This inserts up to 5 multiplies.
4952         countPopulation(Val) + Log2_32(Val) < 7) {
4953       // We use the simple binary decomposition method to generate the multiply
4954       // sequence.  There are more optimal ways to do this (for example,
4955       // powi(x,15) generates one more multiply than it should), but this has
4956       // the benefit of being both really simple and much better than a libcall.
4957       SDValue Res;  // Logically starts equal to 1.0
4958       SDValue CurSquare = LHS;
4959       // TODO: Intrinsics should have fast-math-flags that propagate to these
4960       // nodes.
4961       while (Val) {
4962         if (Val & 1) {
4963           if (Res.getNode())
4964             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4965           else
4966             Res = CurSquare;  // 1.0*CurSquare.
4967         }
4968 
4969         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4970                                 CurSquare, CurSquare);
4971         Val >>= 1;
4972       }
4973 
4974       // If the original was negative, invert the result, producing 1/(x*x*x).
4975       if (RHSC->getSExtValue() < 0)
4976         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4977                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4978       return Res;
4979     }
4980   }
4981 
4982   // Otherwise, expand to a libcall.
4983   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4984 }
4985 
4986 // getUnderlyingArgReg - Find underlying register used for a truncated or
4987 // bitcasted argument.
4988 static unsigned getUnderlyingArgReg(const SDValue &N) {
4989   switch (N.getOpcode()) {
4990   case ISD::CopyFromReg:
4991     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4992   case ISD::BITCAST:
4993   case ISD::AssertZext:
4994   case ISD::AssertSext:
4995   case ISD::TRUNCATE:
4996     return getUnderlyingArgReg(N.getOperand(0));
4997   default:
4998     return 0;
4999   }
5000 }
5001 
5002 /// If the DbgValueInst is a dbg_value of a function argument, create the
5003 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5004 /// instruction selection, they will be inserted to the entry BB.
5005 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5006     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5007     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5008   const Argument *Arg = dyn_cast<Argument>(V);
5009   if (!Arg)
5010     return false;
5011 
5012   if (!IsDbgDeclare) {
5013     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5014     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5015     // the entry block.
5016     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5017     if (!IsInEntryBlock)
5018       return false;
5019 
5020     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5021     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5022     // variable that also is a param.
5023     //
5024     // Although, if we are at the top of the entry block already, we can still
5025     // emit using ArgDbgValue. This might catch some situations when the
5026     // dbg.value refers to an argument that isn't used in the entry block, so
5027     // any CopyToReg node would be optimized out and the only way to express
5028     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5029     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5030     // we should only emit as ArgDbgValue if the Variable is an argument to the
5031     // current function, and the dbg.value intrinsic is found in the entry
5032     // block.
5033     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5034         !DL->getInlinedAt();
5035     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5036     if (!IsInPrologue && !VariableIsFunctionInputArg)
5037       return false;
5038 
5039     // Here we assume that a function argument on IR level only can be used to
5040     // describe one input parameter on source level. If we for example have
5041     // source code like this
5042     //
5043     //    struct A { long x, y; };
5044     //    void foo(struct A a, long b) {
5045     //      ...
5046     //      b = a.x;
5047     //      ...
5048     //    }
5049     //
5050     // and IR like this
5051     //
5052     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5053     //  entry:
5054     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5055     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5056     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5057     //    ...
5058     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5059     //    ...
5060     //
5061     // then the last dbg.value is describing a parameter "b" using a value that
5062     // is an argument. But since we already has used %a1 to describe a parameter
5063     // we should not handle that last dbg.value here (that would result in an
5064     // incorrect hoisting of the DBG_VALUE to the function entry).
5065     // Notice that we allow one dbg.value per IR level argument, to accomodate
5066     // for the situation with fragments above.
5067     if (VariableIsFunctionInputArg) {
5068       unsigned ArgNo = Arg->getArgNo();
5069       if (ArgNo >= FuncInfo.DescribedArgs.size())
5070         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5071       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5072         return false;
5073       FuncInfo.DescribedArgs.set(ArgNo);
5074     }
5075   }
5076 
5077   MachineFunction &MF = DAG.getMachineFunction();
5078   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5079 
5080   bool IsIndirect = false;
5081   Optional<MachineOperand> Op;
5082   // Some arguments' frame index is recorded during argument lowering.
5083   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5084   if (FI != std::numeric_limits<int>::max())
5085     Op = MachineOperand::CreateFI(FI);
5086 
5087   if (!Op && N.getNode()) {
5088     unsigned Reg = getUnderlyingArgReg(N);
5089     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5090       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5091       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5092       if (PR)
5093         Reg = PR;
5094     }
5095     if (Reg) {
5096       Op = MachineOperand::CreateReg(Reg, false);
5097       IsIndirect = IsDbgDeclare;
5098     }
5099   }
5100 
5101   if (!Op && N.getNode())
5102     // Check if frame index is available.
5103     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
5104       if (FrameIndexSDNode *FINode =
5105           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5106         Op = MachineOperand::CreateFI(FINode->getIndex());
5107 
5108   if (!Op) {
5109     // Check if ValueMap has reg number.
5110     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5111     if (VMI != FuncInfo.ValueMap.end()) {
5112       const auto &TLI = DAG.getTargetLoweringInfo();
5113       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5114                        V->getType(), getABIRegCopyCC(V));
5115       if (RFV.occupiesMultipleRegs()) {
5116         unsigned Offset = 0;
5117         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5118           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5119           auto FragmentExpr = DIExpression::createFragmentExpression(
5120               Expr, Offset, RegAndSize.second);
5121           if (!FragmentExpr)
5122             continue;
5123           FuncInfo.ArgDbgValues.push_back(
5124               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5125                       Op->getReg(), Variable, *FragmentExpr));
5126           Offset += RegAndSize.second;
5127         }
5128         return true;
5129       }
5130       Op = MachineOperand::CreateReg(VMI->second, false);
5131       IsIndirect = IsDbgDeclare;
5132     }
5133   }
5134 
5135   if (!Op)
5136     return false;
5137 
5138   assert(Variable->isValidLocationForIntrinsic(DL) &&
5139          "Expected inlined-at fields to agree");
5140   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5141   FuncInfo.ArgDbgValues.push_back(
5142       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5143               *Op, Variable, Expr));
5144 
5145   return true;
5146 }
5147 
5148 /// Return the appropriate SDDbgValue based on N.
5149 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5150                                              DILocalVariable *Variable,
5151                                              DIExpression *Expr,
5152                                              const DebugLoc &dl,
5153                                              unsigned DbgSDNodeOrder) {
5154   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5155     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5156     // stack slot locations.
5157     //
5158     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5159     // debug values here after optimization:
5160     //
5161     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5162     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5163     //
5164     // Both describe the direct values of their associated variables.
5165     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5166                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5167   }
5168   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5169                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5170 }
5171 
5172 // VisualStudio defines setjmp as _setjmp
5173 #if defined(_MSC_VER) && defined(setjmp) && \
5174                          !defined(setjmp_undefined_for_msvc)
5175 #  pragma push_macro("setjmp")
5176 #  undef setjmp
5177 #  define setjmp_undefined_for_msvc
5178 #endif
5179 
5180 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5181   switch (Intrinsic) {
5182   case Intrinsic::smul_fix:
5183     return ISD::SMULFIX;
5184   case Intrinsic::umul_fix:
5185     return ISD::UMULFIX;
5186   default:
5187     llvm_unreachable("Unhandled fixed point intrinsic");
5188   }
5189 }
5190 
5191 /// Lower the call to the specified intrinsic function. If we want to emit this
5192 /// as a call to a named external function, return the name. Otherwise, lower it
5193 /// and return null.
5194 const char *
5195 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5197   SDLoc sdl = getCurSDLoc();
5198   DebugLoc dl = getCurDebugLoc();
5199   SDValue Res;
5200 
5201   switch (Intrinsic) {
5202   default:
5203     // By default, turn this into a target intrinsic node.
5204     visitTargetIntrinsic(I, Intrinsic);
5205     return nullptr;
5206   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5207   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5208   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5209   case Intrinsic::returnaddress:
5210     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5211                              TLI.getPointerTy(DAG.getDataLayout()),
5212                              getValue(I.getArgOperand(0))));
5213     return nullptr;
5214   case Intrinsic::addressofreturnaddress:
5215     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5216                              TLI.getPointerTy(DAG.getDataLayout())));
5217     return nullptr;
5218   case Intrinsic::sponentry:
5219     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5220                              TLI.getPointerTy(DAG.getDataLayout())));
5221     return nullptr;
5222   case Intrinsic::frameaddress:
5223     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5224                              TLI.getPointerTy(DAG.getDataLayout()),
5225                              getValue(I.getArgOperand(0))));
5226     return nullptr;
5227   case Intrinsic::read_register: {
5228     Value *Reg = I.getArgOperand(0);
5229     SDValue Chain = getRoot();
5230     SDValue RegName =
5231         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5232     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5233     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5234       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5235     setValue(&I, Res);
5236     DAG.setRoot(Res.getValue(1));
5237     return nullptr;
5238   }
5239   case Intrinsic::write_register: {
5240     Value *Reg = I.getArgOperand(0);
5241     Value *RegValue = I.getArgOperand(1);
5242     SDValue Chain = getRoot();
5243     SDValue RegName =
5244         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5245     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5246                             RegName, getValue(RegValue)));
5247     return nullptr;
5248   }
5249   case Intrinsic::setjmp:
5250     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5251   case Intrinsic::longjmp:
5252     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5253   case Intrinsic::memcpy: {
5254     const auto &MCI = cast<MemCpyInst>(I);
5255     SDValue Op1 = getValue(I.getArgOperand(0));
5256     SDValue Op2 = getValue(I.getArgOperand(1));
5257     SDValue Op3 = getValue(I.getArgOperand(2));
5258     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5259     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5260     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5261     unsigned Align = MinAlign(DstAlign, SrcAlign);
5262     bool isVol = MCI.isVolatile();
5263     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5264     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5265     // node.
5266     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5267                                false, isTC,
5268                                MachinePointerInfo(I.getArgOperand(0)),
5269                                MachinePointerInfo(I.getArgOperand(1)));
5270     updateDAGForMaybeTailCall(MC);
5271     return nullptr;
5272   }
5273   case Intrinsic::memset: {
5274     const auto &MSI = cast<MemSetInst>(I);
5275     SDValue Op1 = getValue(I.getArgOperand(0));
5276     SDValue Op2 = getValue(I.getArgOperand(1));
5277     SDValue Op3 = getValue(I.getArgOperand(2));
5278     // @llvm.memset defines 0 and 1 to both mean no alignment.
5279     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5280     bool isVol = MSI.isVolatile();
5281     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5282     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5283                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5284     updateDAGForMaybeTailCall(MS);
5285     return nullptr;
5286   }
5287   case Intrinsic::memmove: {
5288     const auto &MMI = cast<MemMoveInst>(I);
5289     SDValue Op1 = getValue(I.getArgOperand(0));
5290     SDValue Op2 = getValue(I.getArgOperand(1));
5291     SDValue Op3 = getValue(I.getArgOperand(2));
5292     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5293     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5294     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5295     unsigned Align = MinAlign(DstAlign, SrcAlign);
5296     bool isVol = MMI.isVolatile();
5297     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5298     // FIXME: Support passing different dest/src alignments to the memmove DAG
5299     // node.
5300     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5301                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5302                                 MachinePointerInfo(I.getArgOperand(1)));
5303     updateDAGForMaybeTailCall(MM);
5304     return nullptr;
5305   }
5306   case Intrinsic::memcpy_element_unordered_atomic: {
5307     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5308     SDValue Dst = getValue(MI.getRawDest());
5309     SDValue Src = getValue(MI.getRawSource());
5310     SDValue Length = getValue(MI.getLength());
5311 
5312     unsigned DstAlign = MI.getDestAlignment();
5313     unsigned SrcAlign = MI.getSourceAlignment();
5314     Type *LengthTy = MI.getLength()->getType();
5315     unsigned ElemSz = MI.getElementSizeInBytes();
5316     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5317     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5318                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5319                                      MachinePointerInfo(MI.getRawDest()),
5320                                      MachinePointerInfo(MI.getRawSource()));
5321     updateDAGForMaybeTailCall(MC);
5322     return nullptr;
5323   }
5324   case Intrinsic::memmove_element_unordered_atomic: {
5325     auto &MI = cast<AtomicMemMoveInst>(I);
5326     SDValue Dst = getValue(MI.getRawDest());
5327     SDValue Src = getValue(MI.getRawSource());
5328     SDValue Length = getValue(MI.getLength());
5329 
5330     unsigned DstAlign = MI.getDestAlignment();
5331     unsigned SrcAlign = MI.getSourceAlignment();
5332     Type *LengthTy = MI.getLength()->getType();
5333     unsigned ElemSz = MI.getElementSizeInBytes();
5334     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5335     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5336                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5337                                       MachinePointerInfo(MI.getRawDest()),
5338                                       MachinePointerInfo(MI.getRawSource()));
5339     updateDAGForMaybeTailCall(MC);
5340     return nullptr;
5341   }
5342   case Intrinsic::memset_element_unordered_atomic: {
5343     auto &MI = cast<AtomicMemSetInst>(I);
5344     SDValue Dst = getValue(MI.getRawDest());
5345     SDValue Val = getValue(MI.getValue());
5346     SDValue Length = getValue(MI.getLength());
5347 
5348     unsigned DstAlign = MI.getDestAlignment();
5349     Type *LengthTy = MI.getLength()->getType();
5350     unsigned ElemSz = MI.getElementSizeInBytes();
5351     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5352     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5353                                      LengthTy, ElemSz, isTC,
5354                                      MachinePointerInfo(MI.getRawDest()));
5355     updateDAGForMaybeTailCall(MC);
5356     return nullptr;
5357   }
5358   case Intrinsic::dbg_addr:
5359   case Intrinsic::dbg_declare: {
5360     const auto &DI = cast<DbgVariableIntrinsic>(I);
5361     DILocalVariable *Variable = DI.getVariable();
5362     DIExpression *Expression = DI.getExpression();
5363     dropDanglingDebugInfo(Variable, Expression);
5364     assert(Variable && "Missing variable");
5365 
5366     // Check if address has undef value.
5367     const Value *Address = DI.getVariableLocation();
5368     if (!Address || isa<UndefValue>(Address) ||
5369         (Address->use_empty() && !isa<Argument>(Address))) {
5370       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5371       return nullptr;
5372     }
5373 
5374     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5375 
5376     // Check if this variable can be described by a frame index, typically
5377     // either as a static alloca or a byval parameter.
5378     int FI = std::numeric_limits<int>::max();
5379     if (const auto *AI =
5380             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5381       if (AI->isStaticAlloca()) {
5382         auto I = FuncInfo.StaticAllocaMap.find(AI);
5383         if (I != FuncInfo.StaticAllocaMap.end())
5384           FI = I->second;
5385       }
5386     } else if (const auto *Arg = dyn_cast<Argument>(
5387                    Address->stripInBoundsConstantOffsets())) {
5388       FI = FuncInfo.getArgumentFrameIndex(Arg);
5389     }
5390 
5391     // llvm.dbg.addr is control dependent and always generates indirect
5392     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5393     // the MachineFunction variable table.
5394     if (FI != std::numeric_limits<int>::max()) {
5395       if (Intrinsic == Intrinsic::dbg_addr) {
5396         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5397             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5398         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5399       }
5400       return nullptr;
5401     }
5402 
5403     SDValue &N = NodeMap[Address];
5404     if (!N.getNode() && isa<Argument>(Address))
5405       // Check unused arguments map.
5406       N = UnusedArgNodeMap[Address];
5407     SDDbgValue *SDV;
5408     if (N.getNode()) {
5409       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5410         Address = BCI->getOperand(0);
5411       // Parameters are handled specially.
5412       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5413       if (isParameter && FINode) {
5414         // Byval parameter. We have a frame index at this point.
5415         SDV =
5416             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5417                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5418       } else if (isa<Argument>(Address)) {
5419         // Address is an argument, so try to emit its dbg value using
5420         // virtual register info from the FuncInfo.ValueMap.
5421         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5422         return nullptr;
5423       } else {
5424         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5425                               true, dl, SDNodeOrder);
5426       }
5427       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5428     } else {
5429       // If Address is an argument then try to emit its dbg value using
5430       // virtual register info from the FuncInfo.ValueMap.
5431       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5432                                     N)) {
5433         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5434       }
5435     }
5436     return nullptr;
5437   }
5438   case Intrinsic::dbg_label: {
5439     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5440     DILabel *Label = DI.getLabel();
5441     assert(Label && "Missing label");
5442 
5443     SDDbgLabel *SDV;
5444     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5445     DAG.AddDbgLabel(SDV);
5446     return nullptr;
5447   }
5448   case Intrinsic::dbg_value: {
5449     const DbgValueInst &DI = cast<DbgValueInst>(I);
5450     assert(DI.getVariable() && "Missing variable");
5451 
5452     DILocalVariable *Variable = DI.getVariable();
5453     DIExpression *Expression = DI.getExpression();
5454     dropDanglingDebugInfo(Variable, Expression);
5455     const Value *V = DI.getValue();
5456     if (!V)
5457       return nullptr;
5458 
5459     SDDbgValue *SDV;
5460     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
5461         isa<ConstantPointerNull>(V)) {
5462       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5463       DAG.AddDbgValue(SDV, nullptr, false);
5464       return nullptr;
5465     }
5466 
5467     // If the Value is a frame index, we can create a FrameIndex debug value
5468     // without relying on the DAG at all.
5469     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5470       auto SI = FuncInfo.StaticAllocaMap.find(AI);
5471       if (SI != FuncInfo.StaticAllocaMap.end()) {
5472         auto SDV =
5473             DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
5474                                       /*IsIndirect*/ false, dl, SDNodeOrder);
5475         // Do not attach the SDNodeDbgValue to an SDNode: this variable location
5476         // is still available even if the SDNode gets optimized out.
5477         DAG.AddDbgValue(SDV, nullptr, false);
5478         return nullptr;
5479       }
5480     }
5481 
5482     // Do not use getValue() in here; we don't want to generate code at
5483     // this point if it hasn't been done yet.
5484     SDValue N = NodeMap[V];
5485     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5486       N = UnusedArgNodeMap[V];
5487     if (N.getNode()) {
5488       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5489         return nullptr;
5490       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5491       DAG.AddDbgValue(SDV, N.getNode(), false);
5492       return nullptr;
5493     }
5494 
5495     // Special rules apply for the first dbg.values of parameter variables in a
5496     // function. Identify them by the fact they reference Argument Values, that
5497     // they're parameters, and they are parameters of the current function. We
5498     // need to let them dangle until they get an SDNode.
5499     bool IsParamOfFunc = isa<Argument>(V) && Variable->isParameter() &&
5500                          !DI.getDebugLoc()->getInlinedAt();
5501     if (!IsParamOfFunc) {
5502       // The value is not used in this block yet (or it would have an SDNode).
5503       // We still want the value to appear for the user if possible -- if it has
5504       // an associated VReg, we can refer to that instead.
5505       auto VMI = FuncInfo.ValueMap.find(V);
5506       if (VMI != FuncInfo.ValueMap.end()) {
5507         unsigned Reg = VMI->second;
5508         // If this is a PHI node, it may be split up into several MI PHI nodes
5509         // (in FunctionLoweringInfo::set).
5510         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5511                          V->getType(), None);
5512         if (RFV.occupiesMultipleRegs()) {
5513           unsigned Offset = 0;
5514           unsigned BitsToDescribe = 0;
5515           if (auto VarSize = Variable->getSizeInBits())
5516             BitsToDescribe = *VarSize;
5517           if (auto Fragment = Expression->getFragmentInfo())
5518             BitsToDescribe = Fragment->SizeInBits;
5519           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5520             unsigned RegisterSize = RegAndSize.second;
5521             // Bail out if all bits are described already.
5522             if (Offset >= BitsToDescribe)
5523               break;
5524             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5525                 ? BitsToDescribe - Offset
5526                 : RegisterSize;
5527             auto FragmentExpr = DIExpression::createFragmentExpression(
5528                 Expression, Offset, FragmentSize);
5529             if (!FragmentExpr)
5530                 continue;
5531             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5532                                       false, dl, SDNodeOrder);
5533             DAG.AddDbgValue(SDV, nullptr, false);
5534             Offset += RegisterSize;
5535           }
5536         } else {
5537           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5538                                     SDNodeOrder);
5539           DAG.AddDbgValue(SDV, nullptr, false);
5540         }
5541         return nullptr;
5542       }
5543     }
5544 
5545     // TODO: When we get here we will either drop the dbg.value completely, or
5546     // we try to move it forward by letting it dangle for awhile. So we should
5547     // probably add an extra DbgValue to the DAG here, with a reference to
5548     // "noreg", to indicate that we have lost the debug location for the
5549     // variable.
5550 
5551     if (!V->use_empty() ) {
5552       // Do not call getValue(V) yet, as we don't want to generate code.
5553       // Remember it for later.
5554       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5555       return nullptr;
5556     }
5557 
5558     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5559     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5560     return nullptr;
5561   }
5562 
5563   case Intrinsic::eh_typeid_for: {
5564     // Find the type id for the given typeinfo.
5565     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5566     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5567     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5568     setValue(&I, Res);
5569     return nullptr;
5570   }
5571 
5572   case Intrinsic::eh_return_i32:
5573   case Intrinsic::eh_return_i64:
5574     DAG.getMachineFunction().setCallsEHReturn(true);
5575     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5576                             MVT::Other,
5577                             getControlRoot(),
5578                             getValue(I.getArgOperand(0)),
5579                             getValue(I.getArgOperand(1))));
5580     return nullptr;
5581   case Intrinsic::eh_unwind_init:
5582     DAG.getMachineFunction().setCallsUnwindInit(true);
5583     return nullptr;
5584   case Intrinsic::eh_dwarf_cfa:
5585     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5586                              TLI.getPointerTy(DAG.getDataLayout()),
5587                              getValue(I.getArgOperand(0))));
5588     return nullptr;
5589   case Intrinsic::eh_sjlj_callsite: {
5590     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5591     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5592     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5593     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5594 
5595     MMI.setCurrentCallSite(CI->getZExtValue());
5596     return nullptr;
5597   }
5598   case Intrinsic::eh_sjlj_functioncontext: {
5599     // Get and store the index of the function context.
5600     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5601     AllocaInst *FnCtx =
5602       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5603     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5604     MFI.setFunctionContextIndex(FI);
5605     return nullptr;
5606   }
5607   case Intrinsic::eh_sjlj_setjmp: {
5608     SDValue Ops[2];
5609     Ops[0] = getRoot();
5610     Ops[1] = getValue(I.getArgOperand(0));
5611     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5612                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5613     setValue(&I, Op.getValue(0));
5614     DAG.setRoot(Op.getValue(1));
5615     return nullptr;
5616   }
5617   case Intrinsic::eh_sjlj_longjmp:
5618     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5619                             getRoot(), getValue(I.getArgOperand(0))));
5620     return nullptr;
5621   case Intrinsic::eh_sjlj_setup_dispatch:
5622     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5623                             getRoot()));
5624     return nullptr;
5625   case Intrinsic::masked_gather:
5626     visitMaskedGather(I);
5627     return nullptr;
5628   case Intrinsic::masked_load:
5629     visitMaskedLoad(I);
5630     return nullptr;
5631   case Intrinsic::masked_scatter:
5632     visitMaskedScatter(I);
5633     return nullptr;
5634   case Intrinsic::masked_store:
5635     visitMaskedStore(I);
5636     return nullptr;
5637   case Intrinsic::masked_expandload:
5638     visitMaskedLoad(I, true /* IsExpanding */);
5639     return nullptr;
5640   case Intrinsic::masked_compressstore:
5641     visitMaskedStore(I, true /* IsCompressing */);
5642     return nullptr;
5643   case Intrinsic::x86_mmx_pslli_w:
5644   case Intrinsic::x86_mmx_pslli_d:
5645   case Intrinsic::x86_mmx_pslli_q:
5646   case Intrinsic::x86_mmx_psrli_w:
5647   case Intrinsic::x86_mmx_psrli_d:
5648   case Intrinsic::x86_mmx_psrli_q:
5649   case Intrinsic::x86_mmx_psrai_w:
5650   case Intrinsic::x86_mmx_psrai_d: {
5651     SDValue ShAmt = getValue(I.getArgOperand(1));
5652     if (isa<ConstantSDNode>(ShAmt)) {
5653       visitTargetIntrinsic(I, Intrinsic);
5654       return nullptr;
5655     }
5656     unsigned NewIntrinsic = 0;
5657     EVT ShAmtVT = MVT::v2i32;
5658     switch (Intrinsic) {
5659     case Intrinsic::x86_mmx_pslli_w:
5660       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5661       break;
5662     case Intrinsic::x86_mmx_pslli_d:
5663       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5664       break;
5665     case Intrinsic::x86_mmx_pslli_q:
5666       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5667       break;
5668     case Intrinsic::x86_mmx_psrli_w:
5669       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5670       break;
5671     case Intrinsic::x86_mmx_psrli_d:
5672       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5673       break;
5674     case Intrinsic::x86_mmx_psrli_q:
5675       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5676       break;
5677     case Intrinsic::x86_mmx_psrai_w:
5678       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5679       break;
5680     case Intrinsic::x86_mmx_psrai_d:
5681       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5682       break;
5683     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5684     }
5685 
5686     // The vector shift intrinsics with scalars uses 32b shift amounts but
5687     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5688     // to be zero.
5689     // We must do this early because v2i32 is not a legal type.
5690     SDValue ShOps[2];
5691     ShOps[0] = ShAmt;
5692     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5693     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5694     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5695     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5696     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5697                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5698                        getValue(I.getArgOperand(0)), ShAmt);
5699     setValue(&I, Res);
5700     return nullptr;
5701   }
5702   case Intrinsic::powi:
5703     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5704                             getValue(I.getArgOperand(1)), DAG));
5705     return nullptr;
5706   case Intrinsic::log:
5707     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5708     return nullptr;
5709   case Intrinsic::log2:
5710     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5711     return nullptr;
5712   case Intrinsic::log10:
5713     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5714     return nullptr;
5715   case Intrinsic::exp:
5716     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5717     return nullptr;
5718   case Intrinsic::exp2:
5719     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5720     return nullptr;
5721   case Intrinsic::pow:
5722     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5723                            getValue(I.getArgOperand(1)), DAG, TLI));
5724     return nullptr;
5725   case Intrinsic::sqrt:
5726   case Intrinsic::fabs:
5727   case Intrinsic::sin:
5728   case Intrinsic::cos:
5729   case Intrinsic::floor:
5730   case Intrinsic::ceil:
5731   case Intrinsic::trunc:
5732   case Intrinsic::rint:
5733   case Intrinsic::nearbyint:
5734   case Intrinsic::round:
5735   case Intrinsic::canonicalize: {
5736     unsigned Opcode;
5737     switch (Intrinsic) {
5738     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5739     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5740     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5741     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5742     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5743     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5744     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5745     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5746     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5747     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5748     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5749     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5750     }
5751 
5752     setValue(&I, DAG.getNode(Opcode, sdl,
5753                              getValue(I.getArgOperand(0)).getValueType(),
5754                              getValue(I.getArgOperand(0))));
5755     return nullptr;
5756   }
5757   case Intrinsic::minnum: {
5758     auto VT = getValue(I.getArgOperand(0)).getValueType();
5759     unsigned Opc =
5760         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5761             ? ISD::FMINIMUM
5762             : ISD::FMINNUM;
5763     setValue(&I, DAG.getNode(Opc, sdl, VT,
5764                              getValue(I.getArgOperand(0)),
5765                              getValue(I.getArgOperand(1))));
5766     return nullptr;
5767   }
5768   case Intrinsic::maxnum: {
5769     auto VT = getValue(I.getArgOperand(0)).getValueType();
5770     unsigned Opc =
5771         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5772             ? ISD::FMAXIMUM
5773             : ISD::FMAXNUM;
5774     setValue(&I, DAG.getNode(Opc, sdl, VT,
5775                              getValue(I.getArgOperand(0)),
5776                              getValue(I.getArgOperand(1))));
5777     return nullptr;
5778   }
5779   case Intrinsic::minimum:
5780     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5781                              getValue(I.getArgOperand(0)).getValueType(),
5782                              getValue(I.getArgOperand(0)),
5783                              getValue(I.getArgOperand(1))));
5784     return nullptr;
5785   case Intrinsic::maximum:
5786     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5787                              getValue(I.getArgOperand(0)).getValueType(),
5788                              getValue(I.getArgOperand(0)),
5789                              getValue(I.getArgOperand(1))));
5790     return nullptr;
5791   case Intrinsic::copysign:
5792     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5793                              getValue(I.getArgOperand(0)).getValueType(),
5794                              getValue(I.getArgOperand(0)),
5795                              getValue(I.getArgOperand(1))));
5796     return nullptr;
5797   case Intrinsic::fma:
5798     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5799                              getValue(I.getArgOperand(0)).getValueType(),
5800                              getValue(I.getArgOperand(0)),
5801                              getValue(I.getArgOperand(1)),
5802                              getValue(I.getArgOperand(2))));
5803     return nullptr;
5804   case Intrinsic::experimental_constrained_fadd:
5805   case Intrinsic::experimental_constrained_fsub:
5806   case Intrinsic::experimental_constrained_fmul:
5807   case Intrinsic::experimental_constrained_fdiv:
5808   case Intrinsic::experimental_constrained_frem:
5809   case Intrinsic::experimental_constrained_fma:
5810   case Intrinsic::experimental_constrained_sqrt:
5811   case Intrinsic::experimental_constrained_pow:
5812   case Intrinsic::experimental_constrained_powi:
5813   case Intrinsic::experimental_constrained_sin:
5814   case Intrinsic::experimental_constrained_cos:
5815   case Intrinsic::experimental_constrained_exp:
5816   case Intrinsic::experimental_constrained_exp2:
5817   case Intrinsic::experimental_constrained_log:
5818   case Intrinsic::experimental_constrained_log10:
5819   case Intrinsic::experimental_constrained_log2:
5820   case Intrinsic::experimental_constrained_rint:
5821   case Intrinsic::experimental_constrained_nearbyint:
5822   case Intrinsic::experimental_constrained_maxnum:
5823   case Intrinsic::experimental_constrained_minnum:
5824   case Intrinsic::experimental_constrained_ceil:
5825   case Intrinsic::experimental_constrained_floor:
5826   case Intrinsic::experimental_constrained_round:
5827   case Intrinsic::experimental_constrained_trunc:
5828     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5829     return nullptr;
5830   case Intrinsic::fmuladd: {
5831     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5832     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5833         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5834       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5835                                getValue(I.getArgOperand(0)).getValueType(),
5836                                getValue(I.getArgOperand(0)),
5837                                getValue(I.getArgOperand(1)),
5838                                getValue(I.getArgOperand(2))));
5839     } else {
5840       // TODO: Intrinsic calls should have fast-math-flags.
5841       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5842                                 getValue(I.getArgOperand(0)).getValueType(),
5843                                 getValue(I.getArgOperand(0)),
5844                                 getValue(I.getArgOperand(1)));
5845       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5846                                 getValue(I.getArgOperand(0)).getValueType(),
5847                                 Mul,
5848                                 getValue(I.getArgOperand(2)));
5849       setValue(&I, Add);
5850     }
5851     return nullptr;
5852   }
5853   case Intrinsic::convert_to_fp16:
5854     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5855                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5856                                          getValue(I.getArgOperand(0)),
5857                                          DAG.getTargetConstant(0, sdl,
5858                                                                MVT::i32))));
5859     return nullptr;
5860   case Intrinsic::convert_from_fp16:
5861     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5862                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5863                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5864                                          getValue(I.getArgOperand(0)))));
5865     return nullptr;
5866   case Intrinsic::pcmarker: {
5867     SDValue Tmp = getValue(I.getArgOperand(0));
5868     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5869     return nullptr;
5870   }
5871   case Intrinsic::readcyclecounter: {
5872     SDValue Op = getRoot();
5873     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5874                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5875     setValue(&I, Res);
5876     DAG.setRoot(Res.getValue(1));
5877     return nullptr;
5878   }
5879   case Intrinsic::bitreverse:
5880     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5881                              getValue(I.getArgOperand(0)).getValueType(),
5882                              getValue(I.getArgOperand(0))));
5883     return nullptr;
5884   case Intrinsic::bswap:
5885     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5886                              getValue(I.getArgOperand(0)).getValueType(),
5887                              getValue(I.getArgOperand(0))));
5888     return nullptr;
5889   case Intrinsic::cttz: {
5890     SDValue Arg = getValue(I.getArgOperand(0));
5891     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5892     EVT Ty = Arg.getValueType();
5893     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5894                              sdl, Ty, Arg));
5895     return nullptr;
5896   }
5897   case Intrinsic::ctlz: {
5898     SDValue Arg = getValue(I.getArgOperand(0));
5899     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5900     EVT Ty = Arg.getValueType();
5901     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5902                              sdl, Ty, Arg));
5903     return nullptr;
5904   }
5905   case Intrinsic::ctpop: {
5906     SDValue Arg = getValue(I.getArgOperand(0));
5907     EVT Ty = Arg.getValueType();
5908     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5909     return nullptr;
5910   }
5911   case Intrinsic::fshl:
5912   case Intrinsic::fshr: {
5913     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5914     SDValue X = getValue(I.getArgOperand(0));
5915     SDValue Y = getValue(I.getArgOperand(1));
5916     SDValue Z = getValue(I.getArgOperand(2));
5917     EVT VT = X.getValueType();
5918     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5919     SDValue Zero = DAG.getConstant(0, sdl, VT);
5920     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5921 
5922     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
5923     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
5924       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
5925       return nullptr;
5926     }
5927 
5928     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5929     // avoid the select that is necessary in the general case to filter out
5930     // the 0-shift possibility that leads to UB.
5931     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5932       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5933       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5934         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5935         return nullptr;
5936       }
5937 
5938       // Some targets only rotate one way. Try the opposite direction.
5939       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5940       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5941         // Negate the shift amount because it is safe to ignore the high bits.
5942         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5943         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5944         return nullptr;
5945       }
5946 
5947       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5948       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5949       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5950       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5951       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5952       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5953       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5954       return nullptr;
5955     }
5956 
5957     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5958     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5959     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5960     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5961     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5962     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5963 
5964     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5965     // and that is undefined. We must compare and select to avoid UB.
5966     EVT CCVT = MVT::i1;
5967     if (VT.isVector())
5968       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5969 
5970     // For fshl, 0-shift returns the 1st arg (X).
5971     // For fshr, 0-shift returns the 2nd arg (Y).
5972     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5973     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5974     return nullptr;
5975   }
5976   case Intrinsic::sadd_sat: {
5977     SDValue Op1 = getValue(I.getArgOperand(0));
5978     SDValue Op2 = getValue(I.getArgOperand(1));
5979     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5980     return nullptr;
5981   }
5982   case Intrinsic::uadd_sat: {
5983     SDValue Op1 = getValue(I.getArgOperand(0));
5984     SDValue Op2 = getValue(I.getArgOperand(1));
5985     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5986     return nullptr;
5987   }
5988   case Intrinsic::ssub_sat: {
5989     SDValue Op1 = getValue(I.getArgOperand(0));
5990     SDValue Op2 = getValue(I.getArgOperand(1));
5991     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5992     return nullptr;
5993   }
5994   case Intrinsic::usub_sat: {
5995     SDValue Op1 = getValue(I.getArgOperand(0));
5996     SDValue Op2 = getValue(I.getArgOperand(1));
5997     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5998     return nullptr;
5999   }
6000   case Intrinsic::smul_fix:
6001   case Intrinsic::umul_fix: {
6002     SDValue Op1 = getValue(I.getArgOperand(0));
6003     SDValue Op2 = getValue(I.getArgOperand(1));
6004     SDValue Op3 = getValue(I.getArgOperand(2));
6005     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6006                              Op1.getValueType(), Op1, Op2, Op3));
6007     return nullptr;
6008   }
6009   case Intrinsic::stacksave: {
6010     SDValue Op = getRoot();
6011     Res = DAG.getNode(
6012         ISD::STACKSAVE, sdl,
6013         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6014     setValue(&I, Res);
6015     DAG.setRoot(Res.getValue(1));
6016     return nullptr;
6017   }
6018   case Intrinsic::stackrestore:
6019     Res = getValue(I.getArgOperand(0));
6020     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6021     return nullptr;
6022   case Intrinsic::get_dynamic_area_offset: {
6023     SDValue Op = getRoot();
6024     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6025     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6026     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6027     // target.
6028     if (PtrTy != ResTy)
6029       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6030                          " intrinsic!");
6031     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6032                       Op);
6033     DAG.setRoot(Op);
6034     setValue(&I, Res);
6035     return nullptr;
6036   }
6037   case Intrinsic::stackguard: {
6038     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6039     MachineFunction &MF = DAG.getMachineFunction();
6040     const Module &M = *MF.getFunction().getParent();
6041     SDValue Chain = getRoot();
6042     if (TLI.useLoadStackGuardNode()) {
6043       Res = getLoadStackGuard(DAG, sdl, Chain);
6044     } else {
6045       const Value *Global = TLI.getSDagStackGuard(M);
6046       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6047       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6048                         MachinePointerInfo(Global, 0), Align,
6049                         MachineMemOperand::MOVolatile);
6050     }
6051     if (TLI.useStackGuardXorFP())
6052       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6053     DAG.setRoot(Chain);
6054     setValue(&I, Res);
6055     return nullptr;
6056   }
6057   case Intrinsic::stackprotector: {
6058     // Emit code into the DAG to store the stack guard onto the stack.
6059     MachineFunction &MF = DAG.getMachineFunction();
6060     MachineFrameInfo &MFI = MF.getFrameInfo();
6061     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6062     SDValue Src, Chain = getRoot();
6063 
6064     if (TLI.useLoadStackGuardNode())
6065       Src = getLoadStackGuard(DAG, sdl, Chain);
6066     else
6067       Src = getValue(I.getArgOperand(0));   // The guard's value.
6068 
6069     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6070 
6071     int FI = FuncInfo.StaticAllocaMap[Slot];
6072     MFI.setStackProtectorIndex(FI);
6073 
6074     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6075 
6076     // Store the stack protector onto the stack.
6077     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6078                                                  DAG.getMachineFunction(), FI),
6079                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6080     setValue(&I, Res);
6081     DAG.setRoot(Res);
6082     return nullptr;
6083   }
6084   case Intrinsic::objectsize: {
6085     // If we don't know by now, we're never going to know.
6086     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6087 
6088     assert(CI && "Non-constant type in __builtin_object_size?");
6089 
6090     SDValue Arg = getValue(I.getCalledValue());
6091     EVT Ty = Arg.getValueType();
6092 
6093     if (CI->isZero())
6094       Res = DAG.getConstant(-1ULL, sdl, Ty);
6095     else
6096       Res = DAG.getConstant(0, sdl, Ty);
6097 
6098     setValue(&I, Res);
6099     return nullptr;
6100   }
6101 
6102   case Intrinsic::is_constant:
6103     // If this wasn't constant-folded away by now, then it's not a
6104     // constant.
6105     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6106     return nullptr;
6107 
6108   case Intrinsic::annotation:
6109   case Intrinsic::ptr_annotation:
6110   case Intrinsic::launder_invariant_group:
6111   case Intrinsic::strip_invariant_group:
6112     // Drop the intrinsic, but forward the value
6113     setValue(&I, getValue(I.getOperand(0)));
6114     return nullptr;
6115   case Intrinsic::assume:
6116   case Intrinsic::var_annotation:
6117   case Intrinsic::sideeffect:
6118     // Discard annotate attributes, assumptions, and artificial side-effects.
6119     return nullptr;
6120 
6121   case Intrinsic::codeview_annotation: {
6122     // Emit a label associated with this metadata.
6123     MachineFunction &MF = DAG.getMachineFunction();
6124     MCSymbol *Label =
6125         MF.getMMI().getContext().createTempSymbol("annotation", true);
6126     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6127     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6128     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6129     DAG.setRoot(Res);
6130     return nullptr;
6131   }
6132 
6133   case Intrinsic::init_trampoline: {
6134     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6135 
6136     SDValue Ops[6];
6137     Ops[0] = getRoot();
6138     Ops[1] = getValue(I.getArgOperand(0));
6139     Ops[2] = getValue(I.getArgOperand(1));
6140     Ops[3] = getValue(I.getArgOperand(2));
6141     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6142     Ops[5] = DAG.getSrcValue(F);
6143 
6144     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6145 
6146     DAG.setRoot(Res);
6147     return nullptr;
6148   }
6149   case Intrinsic::adjust_trampoline:
6150     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6151                              TLI.getPointerTy(DAG.getDataLayout()),
6152                              getValue(I.getArgOperand(0))));
6153     return nullptr;
6154   case Intrinsic::gcroot: {
6155     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6156            "only valid in functions with gc specified, enforced by Verifier");
6157     assert(GFI && "implied by previous");
6158     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6159     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6160 
6161     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6162     GFI->addStackRoot(FI->getIndex(), TypeMap);
6163     return nullptr;
6164   }
6165   case Intrinsic::gcread:
6166   case Intrinsic::gcwrite:
6167     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6168   case Intrinsic::flt_rounds:
6169     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6170     return nullptr;
6171 
6172   case Intrinsic::expect:
6173     // Just replace __builtin_expect(exp, c) with EXP.
6174     setValue(&I, getValue(I.getArgOperand(0)));
6175     return nullptr;
6176 
6177   case Intrinsic::debugtrap:
6178   case Intrinsic::trap: {
6179     StringRef TrapFuncName =
6180         I.getAttributes()
6181             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6182             .getValueAsString();
6183     if (TrapFuncName.empty()) {
6184       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6185         ISD::TRAP : ISD::DEBUGTRAP;
6186       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6187       return nullptr;
6188     }
6189     TargetLowering::ArgListTy Args;
6190 
6191     TargetLowering::CallLoweringInfo CLI(DAG);
6192     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6193         CallingConv::C, I.getType(),
6194         DAG.getExternalSymbol(TrapFuncName.data(),
6195                               TLI.getPointerTy(DAG.getDataLayout())),
6196         std::move(Args));
6197 
6198     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6199     DAG.setRoot(Result.second);
6200     return nullptr;
6201   }
6202 
6203   case Intrinsic::uadd_with_overflow:
6204   case Intrinsic::sadd_with_overflow:
6205   case Intrinsic::usub_with_overflow:
6206   case Intrinsic::ssub_with_overflow:
6207   case Intrinsic::umul_with_overflow:
6208   case Intrinsic::smul_with_overflow: {
6209     ISD::NodeType Op;
6210     switch (Intrinsic) {
6211     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6212     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6213     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6214     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6215     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6216     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6217     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6218     }
6219     SDValue Op1 = getValue(I.getArgOperand(0));
6220     SDValue Op2 = getValue(I.getArgOperand(1));
6221 
6222     EVT ResultVT = Op1.getValueType();
6223     EVT OverflowVT = MVT::i1;
6224     if (ResultVT.isVector())
6225       OverflowVT = EVT::getVectorVT(
6226           *Context, OverflowVT, ResultVT.getVectorNumElements());
6227 
6228     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6229     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6230     return nullptr;
6231   }
6232   case Intrinsic::prefetch: {
6233     SDValue Ops[5];
6234     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6235     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6236     Ops[0] = DAG.getRoot();
6237     Ops[1] = getValue(I.getArgOperand(0));
6238     Ops[2] = getValue(I.getArgOperand(1));
6239     Ops[3] = getValue(I.getArgOperand(2));
6240     Ops[4] = getValue(I.getArgOperand(3));
6241     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6242                                              DAG.getVTList(MVT::Other), Ops,
6243                                              EVT::getIntegerVT(*Context, 8),
6244                                              MachinePointerInfo(I.getArgOperand(0)),
6245                                              0, /* align */
6246                                              Flags);
6247 
6248     // Chain the prefetch in parallell with any pending loads, to stay out of
6249     // the way of later optimizations.
6250     PendingLoads.push_back(Result);
6251     Result = getRoot();
6252     DAG.setRoot(Result);
6253     return nullptr;
6254   }
6255   case Intrinsic::lifetime_start:
6256   case Intrinsic::lifetime_end: {
6257     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6258     // Stack coloring is not enabled in O0, discard region information.
6259     if (TM.getOptLevel() == CodeGenOpt::None)
6260       return nullptr;
6261 
6262     SmallVector<Value *, 4> Allocas;
6263     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6264 
6265     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6266            E = Allocas.end(); Object != E; ++Object) {
6267       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6268 
6269       // Could not find an Alloca.
6270       if (!LifetimeObject)
6271         continue;
6272 
6273       // First check that the Alloca is static, otherwise it won't have a
6274       // valid frame index.
6275       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6276       if (SI == FuncInfo.StaticAllocaMap.end())
6277         return nullptr;
6278 
6279       int FI = SI->second;
6280 
6281       SDValue Ops[2];
6282       Ops[0] = getRoot();
6283       Ops[1] =
6284           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6285       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6286 
6287       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6288       DAG.setRoot(Res);
6289     }
6290     return nullptr;
6291   }
6292   case Intrinsic::invariant_start:
6293     // Discard region information.
6294     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6295     return nullptr;
6296   case Intrinsic::invariant_end:
6297     // Discard region information.
6298     return nullptr;
6299   case Intrinsic::clear_cache:
6300     return TLI.getClearCacheBuiltinName();
6301   case Intrinsic::donothing:
6302     // ignore
6303     return nullptr;
6304   case Intrinsic::experimental_stackmap:
6305     visitStackmap(I);
6306     return nullptr;
6307   case Intrinsic::experimental_patchpoint_void:
6308   case Intrinsic::experimental_patchpoint_i64:
6309     visitPatchpoint(&I);
6310     return nullptr;
6311   case Intrinsic::experimental_gc_statepoint:
6312     LowerStatepoint(ImmutableStatepoint(&I));
6313     return nullptr;
6314   case Intrinsic::experimental_gc_result:
6315     visitGCResult(cast<GCResultInst>(I));
6316     return nullptr;
6317   case Intrinsic::experimental_gc_relocate:
6318     visitGCRelocate(cast<GCRelocateInst>(I));
6319     return nullptr;
6320   case Intrinsic::instrprof_increment:
6321     llvm_unreachable("instrprof failed to lower an increment");
6322   case Intrinsic::instrprof_value_profile:
6323     llvm_unreachable("instrprof failed to lower a value profiling call");
6324   case Intrinsic::localescape: {
6325     MachineFunction &MF = DAG.getMachineFunction();
6326     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6327 
6328     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6329     // is the same on all targets.
6330     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6331       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6332       if (isa<ConstantPointerNull>(Arg))
6333         continue; // Skip null pointers. They represent a hole in index space.
6334       AllocaInst *Slot = cast<AllocaInst>(Arg);
6335       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6336              "can only escape static allocas");
6337       int FI = FuncInfo.StaticAllocaMap[Slot];
6338       MCSymbol *FrameAllocSym =
6339           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6340               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6341       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6342               TII->get(TargetOpcode::LOCAL_ESCAPE))
6343           .addSym(FrameAllocSym)
6344           .addFrameIndex(FI);
6345     }
6346 
6347     return nullptr;
6348   }
6349 
6350   case Intrinsic::localrecover: {
6351     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6352     MachineFunction &MF = DAG.getMachineFunction();
6353     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6354 
6355     // Get the symbol that defines the frame offset.
6356     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6357     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6358     unsigned IdxVal =
6359         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6360     MCSymbol *FrameAllocSym =
6361         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6362             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6363 
6364     // Create a MCSymbol for the label to avoid any target lowering
6365     // that would make this PC relative.
6366     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6367     SDValue OffsetVal =
6368         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6369 
6370     // Add the offset to the FP.
6371     Value *FP = I.getArgOperand(1);
6372     SDValue FPVal = getValue(FP);
6373     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6374     setValue(&I, Add);
6375 
6376     return nullptr;
6377   }
6378 
6379   case Intrinsic::eh_exceptionpointer:
6380   case Intrinsic::eh_exceptioncode: {
6381     // Get the exception pointer vreg, copy from it, and resize it to fit.
6382     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6383     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6384     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6385     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6386     SDValue N =
6387         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6388     if (Intrinsic == Intrinsic::eh_exceptioncode)
6389       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6390     setValue(&I, N);
6391     return nullptr;
6392   }
6393   case Intrinsic::xray_customevent: {
6394     // Here we want to make sure that the intrinsic behaves as if it has a
6395     // specific calling convention, and only for x86_64.
6396     // FIXME: Support other platforms later.
6397     const auto &Triple = DAG.getTarget().getTargetTriple();
6398     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6399       return nullptr;
6400 
6401     SDLoc DL = getCurSDLoc();
6402     SmallVector<SDValue, 8> Ops;
6403 
6404     // We want to say that we always want the arguments in registers.
6405     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6406     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6407     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6408     SDValue Chain = getRoot();
6409     Ops.push_back(LogEntryVal);
6410     Ops.push_back(StrSizeVal);
6411     Ops.push_back(Chain);
6412 
6413     // We need to enforce the calling convention for the callsite, so that
6414     // argument ordering is enforced correctly, and that register allocation can
6415     // see that some registers may be assumed clobbered and have to preserve
6416     // them across calls to the intrinsic.
6417     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6418                                            DL, NodeTys, Ops);
6419     SDValue patchableNode = SDValue(MN, 0);
6420     DAG.setRoot(patchableNode);
6421     setValue(&I, patchableNode);
6422     return nullptr;
6423   }
6424   case Intrinsic::xray_typedevent: {
6425     // Here we want to make sure that the intrinsic behaves as if it has a
6426     // specific calling convention, and only for x86_64.
6427     // FIXME: Support other platforms later.
6428     const auto &Triple = DAG.getTarget().getTargetTriple();
6429     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6430       return nullptr;
6431 
6432     SDLoc DL = getCurSDLoc();
6433     SmallVector<SDValue, 8> Ops;
6434 
6435     // We want to say that we always want the arguments in registers.
6436     // It's unclear to me how manipulating the selection DAG here forces callers
6437     // to provide arguments in registers instead of on the stack.
6438     SDValue LogTypeId = getValue(I.getArgOperand(0));
6439     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6440     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6441     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6442     SDValue Chain = getRoot();
6443     Ops.push_back(LogTypeId);
6444     Ops.push_back(LogEntryVal);
6445     Ops.push_back(StrSizeVal);
6446     Ops.push_back(Chain);
6447 
6448     // We need to enforce the calling convention for the callsite, so that
6449     // argument ordering is enforced correctly, and that register allocation can
6450     // see that some registers may be assumed clobbered and have to preserve
6451     // them across calls to the intrinsic.
6452     MachineSDNode *MN = DAG.getMachineNode(
6453         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6454     SDValue patchableNode = SDValue(MN, 0);
6455     DAG.setRoot(patchableNode);
6456     setValue(&I, patchableNode);
6457     return nullptr;
6458   }
6459   case Intrinsic::experimental_deoptimize:
6460     LowerDeoptimizeCall(&I);
6461     return nullptr;
6462 
6463   case Intrinsic::experimental_vector_reduce_fadd:
6464   case Intrinsic::experimental_vector_reduce_fmul:
6465   case Intrinsic::experimental_vector_reduce_add:
6466   case Intrinsic::experimental_vector_reduce_mul:
6467   case Intrinsic::experimental_vector_reduce_and:
6468   case Intrinsic::experimental_vector_reduce_or:
6469   case Intrinsic::experimental_vector_reduce_xor:
6470   case Intrinsic::experimental_vector_reduce_smax:
6471   case Intrinsic::experimental_vector_reduce_smin:
6472   case Intrinsic::experimental_vector_reduce_umax:
6473   case Intrinsic::experimental_vector_reduce_umin:
6474   case Intrinsic::experimental_vector_reduce_fmax:
6475   case Intrinsic::experimental_vector_reduce_fmin:
6476     visitVectorReduce(I, Intrinsic);
6477     return nullptr;
6478 
6479   case Intrinsic::icall_branch_funnel: {
6480     SmallVector<SDValue, 16> Ops;
6481     Ops.push_back(DAG.getRoot());
6482     Ops.push_back(getValue(I.getArgOperand(0)));
6483 
6484     int64_t Offset;
6485     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6486         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6487     if (!Base)
6488       report_fatal_error(
6489           "llvm.icall.branch.funnel operand must be a GlobalValue");
6490     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6491 
6492     struct BranchFunnelTarget {
6493       int64_t Offset;
6494       SDValue Target;
6495     };
6496     SmallVector<BranchFunnelTarget, 8> Targets;
6497 
6498     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6499       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6500           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6501       if (ElemBase != Base)
6502         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6503                            "to the same GlobalValue");
6504 
6505       SDValue Val = getValue(I.getArgOperand(Op + 1));
6506       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6507       if (!GA)
6508         report_fatal_error(
6509             "llvm.icall.branch.funnel operand must be a GlobalValue");
6510       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6511                                      GA->getGlobal(), getCurSDLoc(),
6512                                      Val.getValueType(), GA->getOffset())});
6513     }
6514     llvm::sort(Targets,
6515                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6516                  return T1.Offset < T2.Offset;
6517                });
6518 
6519     for (auto &T : Targets) {
6520       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6521       Ops.push_back(T.Target);
6522     }
6523 
6524     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6525                                  getCurSDLoc(), MVT::Other, Ops),
6526               0);
6527     DAG.setRoot(N);
6528     setValue(&I, N);
6529     HasTailCall = true;
6530     return nullptr;
6531   }
6532 
6533   case Intrinsic::wasm_landingpad_index:
6534     // Information this intrinsic contained has been transferred to
6535     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6536     // delete it now.
6537     return nullptr;
6538   }
6539 }
6540 
6541 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6542     const ConstrainedFPIntrinsic &FPI) {
6543   SDLoc sdl = getCurSDLoc();
6544   unsigned Opcode;
6545   switch (FPI.getIntrinsicID()) {
6546   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6547   case Intrinsic::experimental_constrained_fadd:
6548     Opcode = ISD::STRICT_FADD;
6549     break;
6550   case Intrinsic::experimental_constrained_fsub:
6551     Opcode = ISD::STRICT_FSUB;
6552     break;
6553   case Intrinsic::experimental_constrained_fmul:
6554     Opcode = ISD::STRICT_FMUL;
6555     break;
6556   case Intrinsic::experimental_constrained_fdiv:
6557     Opcode = ISD::STRICT_FDIV;
6558     break;
6559   case Intrinsic::experimental_constrained_frem:
6560     Opcode = ISD::STRICT_FREM;
6561     break;
6562   case Intrinsic::experimental_constrained_fma:
6563     Opcode = ISD::STRICT_FMA;
6564     break;
6565   case Intrinsic::experimental_constrained_sqrt:
6566     Opcode = ISD::STRICT_FSQRT;
6567     break;
6568   case Intrinsic::experimental_constrained_pow:
6569     Opcode = ISD::STRICT_FPOW;
6570     break;
6571   case Intrinsic::experimental_constrained_powi:
6572     Opcode = ISD::STRICT_FPOWI;
6573     break;
6574   case Intrinsic::experimental_constrained_sin:
6575     Opcode = ISD::STRICT_FSIN;
6576     break;
6577   case Intrinsic::experimental_constrained_cos:
6578     Opcode = ISD::STRICT_FCOS;
6579     break;
6580   case Intrinsic::experimental_constrained_exp:
6581     Opcode = ISD::STRICT_FEXP;
6582     break;
6583   case Intrinsic::experimental_constrained_exp2:
6584     Opcode = ISD::STRICT_FEXP2;
6585     break;
6586   case Intrinsic::experimental_constrained_log:
6587     Opcode = ISD::STRICT_FLOG;
6588     break;
6589   case Intrinsic::experimental_constrained_log10:
6590     Opcode = ISD::STRICT_FLOG10;
6591     break;
6592   case Intrinsic::experimental_constrained_log2:
6593     Opcode = ISD::STRICT_FLOG2;
6594     break;
6595   case Intrinsic::experimental_constrained_rint:
6596     Opcode = ISD::STRICT_FRINT;
6597     break;
6598   case Intrinsic::experimental_constrained_nearbyint:
6599     Opcode = ISD::STRICT_FNEARBYINT;
6600     break;
6601   case Intrinsic::experimental_constrained_maxnum:
6602     Opcode = ISD::STRICT_FMAXNUM;
6603     break;
6604   case Intrinsic::experimental_constrained_minnum:
6605     Opcode = ISD::STRICT_FMINNUM;
6606     break;
6607   case Intrinsic::experimental_constrained_ceil:
6608     Opcode = ISD::STRICT_FCEIL;
6609     break;
6610   case Intrinsic::experimental_constrained_floor:
6611     Opcode = ISD::STRICT_FFLOOR;
6612     break;
6613   case Intrinsic::experimental_constrained_round:
6614     Opcode = ISD::STRICT_FROUND;
6615     break;
6616   case Intrinsic::experimental_constrained_trunc:
6617     Opcode = ISD::STRICT_FTRUNC;
6618     break;
6619   }
6620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6621   SDValue Chain = getRoot();
6622   SmallVector<EVT, 4> ValueVTs;
6623   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6624   ValueVTs.push_back(MVT::Other); // Out chain
6625 
6626   SDVTList VTs = DAG.getVTList(ValueVTs);
6627   SDValue Result;
6628   if (FPI.isUnaryOp())
6629     Result = DAG.getNode(Opcode, sdl, VTs,
6630                          { Chain, getValue(FPI.getArgOperand(0)) });
6631   else if (FPI.isTernaryOp())
6632     Result = DAG.getNode(Opcode, sdl, VTs,
6633                          { Chain, getValue(FPI.getArgOperand(0)),
6634                                   getValue(FPI.getArgOperand(1)),
6635                                   getValue(FPI.getArgOperand(2)) });
6636   else
6637     Result = DAG.getNode(Opcode, sdl, VTs,
6638                          { Chain, getValue(FPI.getArgOperand(0)),
6639                            getValue(FPI.getArgOperand(1))  });
6640 
6641   assert(Result.getNode()->getNumValues() == 2);
6642   SDValue OutChain = Result.getValue(1);
6643   DAG.setRoot(OutChain);
6644   SDValue FPResult = Result.getValue(0);
6645   setValue(&FPI, FPResult);
6646 }
6647 
6648 std::pair<SDValue, SDValue>
6649 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6650                                     const BasicBlock *EHPadBB) {
6651   MachineFunction &MF = DAG.getMachineFunction();
6652   MachineModuleInfo &MMI = MF.getMMI();
6653   MCSymbol *BeginLabel = nullptr;
6654 
6655   if (EHPadBB) {
6656     // Insert a label before the invoke call to mark the try range.  This can be
6657     // used to detect deletion of the invoke via the MachineModuleInfo.
6658     BeginLabel = MMI.getContext().createTempSymbol();
6659 
6660     // For SjLj, keep track of which landing pads go with which invokes
6661     // so as to maintain the ordering of pads in the LSDA.
6662     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6663     if (CallSiteIndex) {
6664       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6665       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6666 
6667       // Now that the call site is handled, stop tracking it.
6668       MMI.setCurrentCallSite(0);
6669     }
6670 
6671     // Both PendingLoads and PendingExports must be flushed here;
6672     // this call might not return.
6673     (void)getRoot();
6674     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6675 
6676     CLI.setChain(getRoot());
6677   }
6678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6679   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6680 
6681   assert((CLI.IsTailCall || Result.second.getNode()) &&
6682          "Non-null chain expected with non-tail call!");
6683   assert((Result.second.getNode() || !Result.first.getNode()) &&
6684          "Null value expected with tail call!");
6685 
6686   if (!Result.second.getNode()) {
6687     // As a special case, a null chain means that a tail call has been emitted
6688     // and the DAG root is already updated.
6689     HasTailCall = true;
6690 
6691     // Since there's no actual continuation from this block, nothing can be
6692     // relying on us setting vregs for them.
6693     PendingExports.clear();
6694   } else {
6695     DAG.setRoot(Result.second);
6696   }
6697 
6698   if (EHPadBB) {
6699     // Insert a label at the end of the invoke call to mark the try range.  This
6700     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6701     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6702     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6703 
6704     // Inform MachineModuleInfo of range.
6705     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6706     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6707     // actually use outlined funclets and their LSDA info style.
6708     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6709       assert(CLI.CS);
6710       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6711       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6712                                 BeginLabel, EndLabel);
6713     } else if (!isScopedEHPersonality(Pers)) {
6714       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6715     }
6716   }
6717 
6718   return Result;
6719 }
6720 
6721 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6722                                       bool isTailCall,
6723                                       const BasicBlock *EHPadBB) {
6724   auto &DL = DAG.getDataLayout();
6725   FunctionType *FTy = CS.getFunctionType();
6726   Type *RetTy = CS.getType();
6727 
6728   TargetLowering::ArgListTy Args;
6729   Args.reserve(CS.arg_size());
6730 
6731   const Value *SwiftErrorVal = nullptr;
6732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6733 
6734   // We can't tail call inside a function with a swifterror argument. Lowering
6735   // does not support this yet. It would have to move into the swifterror
6736   // register before the call.
6737   auto *Caller = CS.getInstruction()->getParent()->getParent();
6738   if (TLI.supportSwiftError() &&
6739       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6740     isTailCall = false;
6741 
6742   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6743        i != e; ++i) {
6744     TargetLowering::ArgListEntry Entry;
6745     const Value *V = *i;
6746 
6747     // Skip empty types
6748     if (V->getType()->isEmptyTy())
6749       continue;
6750 
6751     SDValue ArgNode = getValue(V);
6752     Entry.Node = ArgNode; Entry.Ty = V->getType();
6753 
6754     Entry.setAttributes(&CS, i - CS.arg_begin());
6755 
6756     // Use swifterror virtual register as input to the call.
6757     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6758       SwiftErrorVal = V;
6759       // We find the virtual register for the actual swifterror argument.
6760       // Instead of using the Value, we use the virtual register instead.
6761       Entry.Node = DAG.getRegister(FuncInfo
6762                                        .getOrCreateSwiftErrorVRegUseAt(
6763                                            CS.getInstruction(), FuncInfo.MBB, V)
6764                                        .first,
6765                                    EVT(TLI.getPointerTy(DL)));
6766     }
6767 
6768     Args.push_back(Entry);
6769 
6770     // If we have an explicit sret argument that is an Instruction, (i.e., it
6771     // might point to function-local memory), we can't meaningfully tail-call.
6772     if (Entry.IsSRet && isa<Instruction>(V))
6773       isTailCall = false;
6774   }
6775 
6776   // Check if target-independent constraints permit a tail call here.
6777   // Target-dependent constraints are checked within TLI->LowerCallTo.
6778   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6779     isTailCall = false;
6780 
6781   // Disable tail calls if there is an swifterror argument. Targets have not
6782   // been updated to support tail calls.
6783   if (TLI.supportSwiftError() && SwiftErrorVal)
6784     isTailCall = false;
6785 
6786   TargetLowering::CallLoweringInfo CLI(DAG);
6787   CLI.setDebugLoc(getCurSDLoc())
6788       .setChain(getRoot())
6789       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6790       .setTailCall(isTailCall)
6791       .setConvergent(CS.isConvergent());
6792   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6793 
6794   if (Result.first.getNode()) {
6795     const Instruction *Inst = CS.getInstruction();
6796     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6797     setValue(Inst, Result.first);
6798   }
6799 
6800   // The last element of CLI.InVals has the SDValue for swifterror return.
6801   // Here we copy it to a virtual register and update SwiftErrorMap for
6802   // book-keeping.
6803   if (SwiftErrorVal && TLI.supportSwiftError()) {
6804     // Get the last element of InVals.
6805     SDValue Src = CLI.InVals.back();
6806     unsigned VReg; bool CreatedVReg;
6807     std::tie(VReg, CreatedVReg) =
6808         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6809     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6810     // We update the virtual register for the actual swifterror argument.
6811     if (CreatedVReg)
6812       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6813     DAG.setRoot(CopyNode);
6814   }
6815 }
6816 
6817 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6818                              SelectionDAGBuilder &Builder) {
6819   // Check to see if this load can be trivially constant folded, e.g. if the
6820   // input is from a string literal.
6821   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6822     // Cast pointer to the type we really want to load.
6823     Type *LoadTy =
6824         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6825     if (LoadVT.isVector())
6826       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6827 
6828     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6829                                          PointerType::getUnqual(LoadTy));
6830 
6831     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6832             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6833       return Builder.getValue(LoadCst);
6834   }
6835 
6836   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6837   // still constant memory, the input chain can be the entry node.
6838   SDValue Root;
6839   bool ConstantMemory = false;
6840 
6841   // Do not serialize (non-volatile) loads of constant memory with anything.
6842   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6843     Root = Builder.DAG.getEntryNode();
6844     ConstantMemory = true;
6845   } else {
6846     // Do not serialize non-volatile loads against each other.
6847     Root = Builder.DAG.getRoot();
6848   }
6849 
6850   SDValue Ptr = Builder.getValue(PtrVal);
6851   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6852                                         Ptr, MachinePointerInfo(PtrVal),
6853                                         /* Alignment = */ 1);
6854 
6855   if (!ConstantMemory)
6856     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6857   return LoadVal;
6858 }
6859 
6860 /// Record the value for an instruction that produces an integer result,
6861 /// converting the type where necessary.
6862 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6863                                                   SDValue Value,
6864                                                   bool IsSigned) {
6865   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6866                                                     I.getType(), true);
6867   if (IsSigned)
6868     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6869   else
6870     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6871   setValue(&I, Value);
6872 }
6873 
6874 /// See if we can lower a memcmp call into an optimized form. If so, return
6875 /// true and lower it. Otherwise return false, and it will be lowered like a
6876 /// normal call.
6877 /// The caller already checked that \p I calls the appropriate LibFunc with a
6878 /// correct prototype.
6879 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6880   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6881   const Value *Size = I.getArgOperand(2);
6882   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6883   if (CSize && CSize->getZExtValue() == 0) {
6884     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6885                                                           I.getType(), true);
6886     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6887     return true;
6888   }
6889 
6890   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6891   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6892       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6893       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6894   if (Res.first.getNode()) {
6895     processIntegerCallValue(I, Res.first, true);
6896     PendingLoads.push_back(Res.second);
6897     return true;
6898   }
6899 
6900   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6901   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6902   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6903     return false;
6904 
6905   // If the target has a fast compare for the given size, it will return a
6906   // preferred load type for that size. Require that the load VT is legal and
6907   // that the target supports unaligned loads of that type. Otherwise, return
6908   // INVALID.
6909   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6910     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6911     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6912     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6913       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6914       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6915       // TODO: Check alignment of src and dest ptrs.
6916       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6917       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6918       if (!TLI.isTypeLegal(LVT) ||
6919           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6920           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6921         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6922     }
6923 
6924     return LVT;
6925   };
6926 
6927   // This turns into unaligned loads. We only do this if the target natively
6928   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6929   // we'll only produce a small number of byte loads.
6930   MVT LoadVT;
6931   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6932   switch (NumBitsToCompare) {
6933   default:
6934     return false;
6935   case 16:
6936     LoadVT = MVT::i16;
6937     break;
6938   case 32:
6939     LoadVT = MVT::i32;
6940     break;
6941   case 64:
6942   case 128:
6943   case 256:
6944     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6945     break;
6946   }
6947 
6948   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6949     return false;
6950 
6951   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6952   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6953 
6954   // Bitcast to a wide integer type if the loads are vectors.
6955   if (LoadVT.isVector()) {
6956     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6957     LoadL = DAG.getBitcast(CmpVT, LoadL);
6958     LoadR = DAG.getBitcast(CmpVT, LoadR);
6959   }
6960 
6961   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6962   processIntegerCallValue(I, Cmp, false);
6963   return true;
6964 }
6965 
6966 /// See if we can lower a memchr call into an optimized form. If so, return
6967 /// true and lower it. Otherwise return false, and it will be lowered like a
6968 /// normal call.
6969 /// The caller already checked that \p I calls the appropriate LibFunc with a
6970 /// correct prototype.
6971 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6972   const Value *Src = I.getArgOperand(0);
6973   const Value *Char = I.getArgOperand(1);
6974   const Value *Length = I.getArgOperand(2);
6975 
6976   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6977   std::pair<SDValue, SDValue> Res =
6978     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6979                                 getValue(Src), getValue(Char), getValue(Length),
6980                                 MachinePointerInfo(Src));
6981   if (Res.first.getNode()) {
6982     setValue(&I, Res.first);
6983     PendingLoads.push_back(Res.second);
6984     return true;
6985   }
6986 
6987   return false;
6988 }
6989 
6990 /// See if we can lower a mempcpy call into an optimized form. If so, return
6991 /// true and lower it. Otherwise return false, and it will be lowered like a
6992 /// normal call.
6993 /// The caller already checked that \p I calls the appropriate LibFunc with a
6994 /// correct prototype.
6995 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6996   SDValue Dst = getValue(I.getArgOperand(0));
6997   SDValue Src = getValue(I.getArgOperand(1));
6998   SDValue Size = getValue(I.getArgOperand(2));
6999 
7000   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7001   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7002   unsigned Align = std::min(DstAlign, SrcAlign);
7003   if (Align == 0) // Alignment of one or both could not be inferred.
7004     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7005 
7006   bool isVol = false;
7007   SDLoc sdl = getCurSDLoc();
7008 
7009   // In the mempcpy context we need to pass in a false value for isTailCall
7010   // because the return pointer needs to be adjusted by the size of
7011   // the copied memory.
7012   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7013                              false, /*isTailCall=*/false,
7014                              MachinePointerInfo(I.getArgOperand(0)),
7015                              MachinePointerInfo(I.getArgOperand(1)));
7016   assert(MC.getNode() != nullptr &&
7017          "** memcpy should not be lowered as TailCall in mempcpy context **");
7018   DAG.setRoot(MC);
7019 
7020   // Check if Size needs to be truncated or extended.
7021   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7022 
7023   // Adjust return pointer to point just past the last dst byte.
7024   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7025                                     Dst, Size);
7026   setValue(&I, DstPlusSize);
7027   return true;
7028 }
7029 
7030 /// See if we can lower a strcpy call into an optimized form.  If so, return
7031 /// true and lower it, otherwise return false and it will be lowered like a
7032 /// normal call.
7033 /// The caller already checked that \p I calls the appropriate LibFunc with a
7034 /// correct prototype.
7035 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7036   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7037 
7038   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7039   std::pair<SDValue, SDValue> Res =
7040     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7041                                 getValue(Arg0), getValue(Arg1),
7042                                 MachinePointerInfo(Arg0),
7043                                 MachinePointerInfo(Arg1), isStpcpy);
7044   if (Res.first.getNode()) {
7045     setValue(&I, Res.first);
7046     DAG.setRoot(Res.second);
7047     return true;
7048   }
7049 
7050   return false;
7051 }
7052 
7053 /// See if we can lower a strcmp call into an optimized form.  If so, return
7054 /// true and lower it, otherwise return false and it will be lowered like a
7055 /// normal call.
7056 /// The caller already checked that \p I calls the appropriate LibFunc with a
7057 /// correct prototype.
7058 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7059   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7060 
7061   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7062   std::pair<SDValue, SDValue> Res =
7063     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7064                                 getValue(Arg0), getValue(Arg1),
7065                                 MachinePointerInfo(Arg0),
7066                                 MachinePointerInfo(Arg1));
7067   if (Res.first.getNode()) {
7068     processIntegerCallValue(I, Res.first, true);
7069     PendingLoads.push_back(Res.second);
7070     return true;
7071   }
7072 
7073   return false;
7074 }
7075 
7076 /// See if we can lower a strlen call into an optimized form.  If so, return
7077 /// true and lower it, otherwise return false and it will be lowered like a
7078 /// normal call.
7079 /// The caller already checked that \p I calls the appropriate LibFunc with a
7080 /// correct prototype.
7081 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7082   const Value *Arg0 = I.getArgOperand(0);
7083 
7084   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7085   std::pair<SDValue, SDValue> Res =
7086     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7087                                 getValue(Arg0), MachinePointerInfo(Arg0));
7088   if (Res.first.getNode()) {
7089     processIntegerCallValue(I, Res.first, false);
7090     PendingLoads.push_back(Res.second);
7091     return true;
7092   }
7093 
7094   return false;
7095 }
7096 
7097 /// See if we can lower a strnlen call into an optimized form.  If so, return
7098 /// true and lower it, otherwise return false and it will be lowered like a
7099 /// normal call.
7100 /// The caller already checked that \p I calls the appropriate LibFunc with a
7101 /// correct prototype.
7102 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7103   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7104 
7105   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7106   std::pair<SDValue, SDValue> Res =
7107     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7108                                  getValue(Arg0), getValue(Arg1),
7109                                  MachinePointerInfo(Arg0));
7110   if (Res.first.getNode()) {
7111     processIntegerCallValue(I, Res.first, false);
7112     PendingLoads.push_back(Res.second);
7113     return true;
7114   }
7115 
7116   return false;
7117 }
7118 
7119 /// See if we can lower a unary floating-point operation into an SDNode with
7120 /// the specified Opcode.  If so, return true and lower it, otherwise return
7121 /// false and it will be lowered like a normal call.
7122 /// The caller already checked that \p I calls the appropriate LibFunc with a
7123 /// correct prototype.
7124 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7125                                               unsigned Opcode) {
7126   // We already checked this call's prototype; verify it doesn't modify errno.
7127   if (!I.onlyReadsMemory())
7128     return false;
7129 
7130   SDValue Tmp = getValue(I.getArgOperand(0));
7131   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7132   return true;
7133 }
7134 
7135 /// See if we can lower a binary floating-point operation into an SDNode with
7136 /// the specified Opcode. If so, return true and lower it. Otherwise return
7137 /// false, and it will be lowered like a normal call.
7138 /// The caller already checked that \p I calls the appropriate LibFunc with a
7139 /// correct prototype.
7140 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7141                                                unsigned Opcode) {
7142   // We already checked this call's prototype; verify it doesn't modify errno.
7143   if (!I.onlyReadsMemory())
7144     return false;
7145 
7146   SDValue Tmp0 = getValue(I.getArgOperand(0));
7147   SDValue Tmp1 = getValue(I.getArgOperand(1));
7148   EVT VT = Tmp0.getValueType();
7149   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7150   return true;
7151 }
7152 
7153 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7154   // Handle inline assembly differently.
7155   if (isa<InlineAsm>(I.getCalledValue())) {
7156     visitInlineAsm(&I);
7157     return;
7158   }
7159 
7160   const char *RenameFn = nullptr;
7161   if (Function *F = I.getCalledFunction()) {
7162     if (F->isDeclaration()) {
7163       // Is this an LLVM intrinsic or a target-specific intrinsic?
7164       unsigned IID = F->getIntrinsicID();
7165       if (!IID)
7166         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7167           IID = II->getIntrinsicID(F);
7168 
7169       if (IID) {
7170         RenameFn = visitIntrinsicCall(I, IID);
7171         if (!RenameFn)
7172           return;
7173       }
7174     }
7175 
7176     // Check for well-known libc/libm calls.  If the function is internal, it
7177     // can't be a library call.  Don't do the check if marked as nobuiltin for
7178     // some reason or the call site requires strict floating point semantics.
7179     LibFunc Func;
7180     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7181         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7182         LibInfo->hasOptimizedCodeGen(Func)) {
7183       switch (Func) {
7184       default: break;
7185       case LibFunc_copysign:
7186       case LibFunc_copysignf:
7187       case LibFunc_copysignl:
7188         // We already checked this call's prototype; verify it doesn't modify
7189         // errno.
7190         if (I.onlyReadsMemory()) {
7191           SDValue LHS = getValue(I.getArgOperand(0));
7192           SDValue RHS = getValue(I.getArgOperand(1));
7193           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7194                                    LHS.getValueType(), LHS, RHS));
7195           return;
7196         }
7197         break;
7198       case LibFunc_fabs:
7199       case LibFunc_fabsf:
7200       case LibFunc_fabsl:
7201         if (visitUnaryFloatCall(I, ISD::FABS))
7202           return;
7203         break;
7204       case LibFunc_fmin:
7205       case LibFunc_fminf:
7206       case LibFunc_fminl:
7207         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7208           return;
7209         break;
7210       case LibFunc_fmax:
7211       case LibFunc_fmaxf:
7212       case LibFunc_fmaxl:
7213         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7214           return;
7215         break;
7216       case LibFunc_sin:
7217       case LibFunc_sinf:
7218       case LibFunc_sinl:
7219         if (visitUnaryFloatCall(I, ISD::FSIN))
7220           return;
7221         break;
7222       case LibFunc_cos:
7223       case LibFunc_cosf:
7224       case LibFunc_cosl:
7225         if (visitUnaryFloatCall(I, ISD::FCOS))
7226           return;
7227         break;
7228       case LibFunc_sqrt:
7229       case LibFunc_sqrtf:
7230       case LibFunc_sqrtl:
7231       case LibFunc_sqrt_finite:
7232       case LibFunc_sqrtf_finite:
7233       case LibFunc_sqrtl_finite:
7234         if (visitUnaryFloatCall(I, ISD::FSQRT))
7235           return;
7236         break;
7237       case LibFunc_floor:
7238       case LibFunc_floorf:
7239       case LibFunc_floorl:
7240         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7241           return;
7242         break;
7243       case LibFunc_nearbyint:
7244       case LibFunc_nearbyintf:
7245       case LibFunc_nearbyintl:
7246         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7247           return;
7248         break;
7249       case LibFunc_ceil:
7250       case LibFunc_ceilf:
7251       case LibFunc_ceill:
7252         if (visitUnaryFloatCall(I, ISD::FCEIL))
7253           return;
7254         break;
7255       case LibFunc_rint:
7256       case LibFunc_rintf:
7257       case LibFunc_rintl:
7258         if (visitUnaryFloatCall(I, ISD::FRINT))
7259           return;
7260         break;
7261       case LibFunc_round:
7262       case LibFunc_roundf:
7263       case LibFunc_roundl:
7264         if (visitUnaryFloatCall(I, ISD::FROUND))
7265           return;
7266         break;
7267       case LibFunc_trunc:
7268       case LibFunc_truncf:
7269       case LibFunc_truncl:
7270         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7271           return;
7272         break;
7273       case LibFunc_log2:
7274       case LibFunc_log2f:
7275       case LibFunc_log2l:
7276         if (visitUnaryFloatCall(I, ISD::FLOG2))
7277           return;
7278         break;
7279       case LibFunc_exp2:
7280       case LibFunc_exp2f:
7281       case LibFunc_exp2l:
7282         if (visitUnaryFloatCall(I, ISD::FEXP2))
7283           return;
7284         break;
7285       case LibFunc_memcmp:
7286         if (visitMemCmpCall(I))
7287           return;
7288         break;
7289       case LibFunc_mempcpy:
7290         if (visitMemPCpyCall(I))
7291           return;
7292         break;
7293       case LibFunc_memchr:
7294         if (visitMemChrCall(I))
7295           return;
7296         break;
7297       case LibFunc_strcpy:
7298         if (visitStrCpyCall(I, false))
7299           return;
7300         break;
7301       case LibFunc_stpcpy:
7302         if (visitStrCpyCall(I, true))
7303           return;
7304         break;
7305       case LibFunc_strcmp:
7306         if (visitStrCmpCall(I))
7307           return;
7308         break;
7309       case LibFunc_strlen:
7310         if (visitStrLenCall(I))
7311           return;
7312         break;
7313       case LibFunc_strnlen:
7314         if (visitStrNLenCall(I))
7315           return;
7316         break;
7317       }
7318     }
7319   }
7320 
7321   SDValue Callee;
7322   if (!RenameFn)
7323     Callee = getValue(I.getCalledValue());
7324   else
7325     Callee = DAG.getExternalSymbol(
7326         RenameFn,
7327         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7328 
7329   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7330   // have to do anything here to lower funclet bundles.
7331   assert(!I.hasOperandBundlesOtherThan(
7332              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7333          "Cannot lower calls with arbitrary operand bundles!");
7334 
7335   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7336     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7337   else
7338     // Check if we can potentially perform a tail call. More detailed checking
7339     // is be done within LowerCallTo, after more information about the call is
7340     // known.
7341     LowerCallTo(&I, Callee, I.isTailCall());
7342 }
7343 
7344 namespace {
7345 
7346 /// AsmOperandInfo - This contains information for each constraint that we are
7347 /// lowering.
7348 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7349 public:
7350   /// CallOperand - If this is the result output operand or a clobber
7351   /// this is null, otherwise it is the incoming operand to the CallInst.
7352   /// This gets modified as the asm is processed.
7353   SDValue CallOperand;
7354 
7355   /// AssignedRegs - If this is a register or register class operand, this
7356   /// contains the set of register corresponding to the operand.
7357   RegsForValue AssignedRegs;
7358 
7359   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7360     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7361   }
7362 
7363   /// Whether or not this operand accesses memory
7364   bool hasMemory(const TargetLowering &TLI) const {
7365     // Indirect operand accesses access memory.
7366     if (isIndirect)
7367       return true;
7368 
7369     for (const auto &Code : Codes)
7370       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7371         return true;
7372 
7373     return false;
7374   }
7375 
7376   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7377   /// corresponds to.  If there is no Value* for this operand, it returns
7378   /// MVT::Other.
7379   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7380                            const DataLayout &DL) const {
7381     if (!CallOperandVal) return MVT::Other;
7382 
7383     if (isa<BasicBlock>(CallOperandVal))
7384       return TLI.getPointerTy(DL);
7385 
7386     llvm::Type *OpTy = CallOperandVal->getType();
7387 
7388     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7389     // If this is an indirect operand, the operand is a pointer to the
7390     // accessed type.
7391     if (isIndirect) {
7392       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7393       if (!PtrTy)
7394         report_fatal_error("Indirect operand for inline asm not a pointer!");
7395       OpTy = PtrTy->getElementType();
7396     }
7397 
7398     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7399     if (StructType *STy = dyn_cast<StructType>(OpTy))
7400       if (STy->getNumElements() == 1)
7401         OpTy = STy->getElementType(0);
7402 
7403     // If OpTy is not a single value, it may be a struct/union that we
7404     // can tile with integers.
7405     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7406       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7407       switch (BitSize) {
7408       default: break;
7409       case 1:
7410       case 8:
7411       case 16:
7412       case 32:
7413       case 64:
7414       case 128:
7415         OpTy = IntegerType::get(Context, BitSize);
7416         break;
7417       }
7418     }
7419 
7420     return TLI.getValueType(DL, OpTy, true);
7421   }
7422 };
7423 
7424 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7425 
7426 } // end anonymous namespace
7427 
7428 /// Make sure that the output operand \p OpInfo and its corresponding input
7429 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7430 /// out).
7431 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7432                                SDISelAsmOperandInfo &MatchingOpInfo,
7433                                SelectionDAG &DAG) {
7434   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7435     return;
7436 
7437   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7438   const auto &TLI = DAG.getTargetLoweringInfo();
7439 
7440   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7441       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7442                                        OpInfo.ConstraintVT);
7443   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7444       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7445                                        MatchingOpInfo.ConstraintVT);
7446   if ((OpInfo.ConstraintVT.isInteger() !=
7447        MatchingOpInfo.ConstraintVT.isInteger()) ||
7448       (MatchRC.second != InputRC.second)) {
7449     // FIXME: error out in a more elegant fashion
7450     report_fatal_error("Unsupported asm: input constraint"
7451                        " with a matching output constraint of"
7452                        " incompatible type!");
7453   }
7454   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7455 }
7456 
7457 /// Get a direct memory input to behave well as an indirect operand.
7458 /// This may introduce stores, hence the need for a \p Chain.
7459 /// \return The (possibly updated) chain.
7460 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7461                                         SDISelAsmOperandInfo &OpInfo,
7462                                         SelectionDAG &DAG) {
7463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7464 
7465   // If we don't have an indirect input, put it in the constpool if we can,
7466   // otherwise spill it to a stack slot.
7467   // TODO: This isn't quite right. We need to handle these according to
7468   // the addressing mode that the constraint wants. Also, this may take
7469   // an additional register for the computation and we don't want that
7470   // either.
7471 
7472   // If the operand is a float, integer, or vector constant, spill to a
7473   // constant pool entry to get its address.
7474   const Value *OpVal = OpInfo.CallOperandVal;
7475   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7476       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7477     OpInfo.CallOperand = DAG.getConstantPool(
7478         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7479     return Chain;
7480   }
7481 
7482   // Otherwise, create a stack slot and emit a store to it before the asm.
7483   Type *Ty = OpVal->getType();
7484   auto &DL = DAG.getDataLayout();
7485   uint64_t TySize = DL.getTypeAllocSize(Ty);
7486   unsigned Align = DL.getPrefTypeAlignment(Ty);
7487   MachineFunction &MF = DAG.getMachineFunction();
7488   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7489   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7490   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7491                        MachinePointerInfo::getFixedStack(MF, SSFI));
7492   OpInfo.CallOperand = StackSlot;
7493 
7494   return Chain;
7495 }
7496 
7497 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7498 /// specified operand.  We prefer to assign virtual registers, to allow the
7499 /// register allocator to handle the assignment process.  However, if the asm
7500 /// uses features that we can't model on machineinstrs, we have SDISel do the
7501 /// allocation.  This produces generally horrible, but correct, code.
7502 ///
7503 ///   OpInfo describes the operand
7504 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7505 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7506                                  SDISelAsmOperandInfo &OpInfo,
7507                                  SDISelAsmOperandInfo &RefOpInfo) {
7508   LLVMContext &Context = *DAG.getContext();
7509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7510 
7511   MachineFunction &MF = DAG.getMachineFunction();
7512   SmallVector<unsigned, 4> Regs;
7513   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7514 
7515   // No work to do for memory operations.
7516   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7517     return;
7518 
7519   // If this is a constraint for a single physreg, or a constraint for a
7520   // register class, find it.
7521   unsigned AssignedReg;
7522   const TargetRegisterClass *RC;
7523   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7524       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7525   // RC is unset only on failure. Return immediately.
7526   if (!RC)
7527     return;
7528 
7529   // Get the actual register value type.  This is important, because the user
7530   // may have asked for (e.g.) the AX register in i32 type.  We need to
7531   // remember that AX is actually i16 to get the right extension.
7532   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7533 
7534   if (OpInfo.ConstraintVT != MVT::Other) {
7535     // If this is an FP operand in an integer register (or visa versa), or more
7536     // generally if the operand value disagrees with the register class we plan
7537     // to stick it in, fix the operand type.
7538     //
7539     // If this is an input value, the bitcast to the new type is done now.
7540     // Bitcast for output value is done at the end of visitInlineAsm().
7541     if ((OpInfo.Type == InlineAsm::isOutput ||
7542          OpInfo.Type == InlineAsm::isInput) &&
7543         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7544       // Try to convert to the first EVT that the reg class contains.  If the
7545       // types are identical size, use a bitcast to convert (e.g. two differing
7546       // vector types).  Note: output bitcast is done at the end of
7547       // visitInlineAsm().
7548       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7549         // Exclude indirect inputs while they are unsupported because the code
7550         // to perform the load is missing and thus OpInfo.CallOperand still
7551         // refers to the input address rather than the pointed-to value.
7552         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7553           OpInfo.CallOperand =
7554               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7555         OpInfo.ConstraintVT = RegVT;
7556         // If the operand is an FP value and we want it in integer registers,
7557         // use the corresponding integer type. This turns an f64 value into
7558         // i64, which can be passed with two i32 values on a 32-bit machine.
7559       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7560         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7561         if (OpInfo.Type == InlineAsm::isInput)
7562           OpInfo.CallOperand =
7563               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7564         OpInfo.ConstraintVT = VT;
7565       }
7566     }
7567   }
7568 
7569   // No need to allocate a matching input constraint since the constraint it's
7570   // matching to has already been allocated.
7571   if (OpInfo.isMatchingInputConstraint())
7572     return;
7573 
7574   EVT ValueVT = OpInfo.ConstraintVT;
7575   if (OpInfo.ConstraintVT == MVT::Other)
7576     ValueVT = RegVT;
7577 
7578   // Initialize NumRegs.
7579   unsigned NumRegs = 1;
7580   if (OpInfo.ConstraintVT != MVT::Other)
7581     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7582 
7583   // If this is a constraint for a specific physical register, like {r17},
7584   // assign it now.
7585 
7586   // If this associated to a specific register, initialize iterator to correct
7587   // place. If virtual, make sure we have enough registers
7588 
7589   // Initialize iterator if necessary
7590   TargetRegisterClass::iterator I = RC->begin();
7591   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7592 
7593   // Do not check for single registers.
7594   if (AssignedReg) {
7595       for (; *I != AssignedReg; ++I)
7596         assert(I != RC->end() && "AssignedReg should be member of RC");
7597   }
7598 
7599   for (; NumRegs; --NumRegs, ++I) {
7600     assert(I != RC->end() && "Ran out of registers to allocate!");
7601     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7602     Regs.push_back(R);
7603   }
7604 
7605   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7606 }
7607 
7608 static unsigned
7609 findMatchingInlineAsmOperand(unsigned OperandNo,
7610                              const std::vector<SDValue> &AsmNodeOperands) {
7611   // Scan until we find the definition we already emitted of this operand.
7612   unsigned CurOp = InlineAsm::Op_FirstOperand;
7613   for (; OperandNo; --OperandNo) {
7614     // Advance to the next operand.
7615     unsigned OpFlag =
7616         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7617     assert((InlineAsm::isRegDefKind(OpFlag) ||
7618             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7619             InlineAsm::isMemKind(OpFlag)) &&
7620            "Skipped past definitions?");
7621     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7622   }
7623   return CurOp;
7624 }
7625 
7626 namespace {
7627 
7628 class ExtraFlags {
7629   unsigned Flags = 0;
7630 
7631 public:
7632   explicit ExtraFlags(ImmutableCallSite CS) {
7633     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7634     if (IA->hasSideEffects())
7635       Flags |= InlineAsm::Extra_HasSideEffects;
7636     if (IA->isAlignStack())
7637       Flags |= InlineAsm::Extra_IsAlignStack;
7638     if (CS.isConvergent())
7639       Flags |= InlineAsm::Extra_IsConvergent;
7640     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7641   }
7642 
7643   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7644     // Ideally, we would only check against memory constraints.  However, the
7645     // meaning of an Other constraint can be target-specific and we can't easily
7646     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7647     // for Other constraints as well.
7648     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7649         OpInfo.ConstraintType == TargetLowering::C_Other) {
7650       if (OpInfo.Type == InlineAsm::isInput)
7651         Flags |= InlineAsm::Extra_MayLoad;
7652       else if (OpInfo.Type == InlineAsm::isOutput)
7653         Flags |= InlineAsm::Extra_MayStore;
7654       else if (OpInfo.Type == InlineAsm::isClobber)
7655         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7656     }
7657   }
7658 
7659   unsigned get() const { return Flags; }
7660 };
7661 
7662 } // end anonymous namespace
7663 
7664 /// visitInlineAsm - Handle a call to an InlineAsm object.
7665 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7666   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7667 
7668   /// ConstraintOperands - Information about all of the constraints.
7669   SDISelAsmOperandInfoVector ConstraintOperands;
7670 
7671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7672   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7673       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7674 
7675   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7676   // AsmDialect, MayLoad, MayStore).
7677   bool HasSideEffect = IA->hasSideEffects();
7678   ExtraFlags ExtraInfo(CS);
7679 
7680   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7681   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7682   for (auto &T : TargetConstraints) {
7683     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7684     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7685 
7686     // Compute the value type for each operand.
7687     if (OpInfo.Type == InlineAsm::isInput ||
7688         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7689       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7690 
7691       // Process the call argument. BasicBlocks are labels, currently appearing
7692       // only in asm's.
7693       const Instruction *I = CS.getInstruction();
7694       if (isa<CallBrInst>(I) &&
7695           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7696                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7697         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7698         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7699         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7700       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7701         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7702       } else {
7703         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7704       }
7705 
7706       OpInfo.ConstraintVT =
7707           OpInfo
7708               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7709               .getSimpleVT();
7710     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7711       // The return value of the call is this value.  As such, there is no
7712       // corresponding argument.
7713       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7714       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7715         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7716             DAG.getDataLayout(), STy->getElementType(ResNo));
7717       } else {
7718         assert(ResNo == 0 && "Asm only has one result!");
7719         OpInfo.ConstraintVT =
7720             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7721       }
7722       ++ResNo;
7723     } else {
7724       OpInfo.ConstraintVT = MVT::Other;
7725     }
7726 
7727     if (!HasSideEffect)
7728       HasSideEffect = OpInfo.hasMemory(TLI);
7729 
7730     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7731     // FIXME: Could we compute this on OpInfo rather than T?
7732 
7733     // Compute the constraint code and ConstraintType to use.
7734     TLI.ComputeConstraintToUse(T, SDValue());
7735 
7736     ExtraInfo.update(T);
7737   }
7738 
7739   // We won't need to flush pending loads if this asm doesn't touch
7740   // memory and is nonvolatile.
7741   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7742 
7743   // Second pass over the constraints: compute which constraint option to use.
7744   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7745     // If this is an output operand with a matching input operand, look up the
7746     // matching input. If their types mismatch, e.g. one is an integer, the
7747     // other is floating point, or their sizes are different, flag it as an
7748     // error.
7749     if (OpInfo.hasMatchingInput()) {
7750       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7751       patchMatchingInput(OpInfo, Input, DAG);
7752     }
7753 
7754     // Compute the constraint code and ConstraintType to use.
7755     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7756 
7757     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7758         OpInfo.Type == InlineAsm::isClobber)
7759       continue;
7760 
7761     // If this is a memory input, and if the operand is not indirect, do what we
7762     // need to provide an address for the memory input.
7763     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7764         !OpInfo.isIndirect) {
7765       assert((OpInfo.isMultipleAlternative ||
7766               (OpInfo.Type == InlineAsm::isInput)) &&
7767              "Can only indirectify direct input operands!");
7768 
7769       // Memory operands really want the address of the value.
7770       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7771 
7772       // There is no longer a Value* corresponding to this operand.
7773       OpInfo.CallOperandVal = nullptr;
7774 
7775       // It is now an indirect operand.
7776       OpInfo.isIndirect = true;
7777     }
7778 
7779   }
7780 
7781   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7782   std::vector<SDValue> AsmNodeOperands;
7783   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7784   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7785       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7786 
7787   // If we have a !srcloc metadata node associated with it, we want to attach
7788   // this to the ultimately generated inline asm machineinstr.  To do this, we
7789   // pass in the third operand as this (potentially null) inline asm MDNode.
7790   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7791   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7792 
7793   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7794   // bits as operand 3.
7795   AsmNodeOperands.push_back(DAG.getTargetConstant(
7796       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7797 
7798   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7799   // this, assign virtual and physical registers for inputs and otput.
7800   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7801     // Assign Registers.
7802     SDISelAsmOperandInfo &RefOpInfo =
7803         OpInfo.isMatchingInputConstraint()
7804             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7805             : OpInfo;
7806     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7807 
7808     switch (OpInfo.Type) {
7809     case InlineAsm::isOutput:
7810       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7811           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7812            OpInfo.isIndirect)) {
7813         unsigned ConstraintID =
7814             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7815         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7816                "Failed to convert memory constraint code to constraint id.");
7817 
7818         // Add information to the INLINEASM node to know about this output.
7819         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7820         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7821         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7822                                                         MVT::i32));
7823         AsmNodeOperands.push_back(OpInfo.CallOperand);
7824         break;
7825       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7826                   !OpInfo.isIndirect) ||
7827                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7828                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7829         // Otherwise, this outputs to a register (directly for C_Register /
7830         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7831         // register that we can use.
7832         if (OpInfo.AssignedRegs.Regs.empty()) {
7833           emitInlineAsmError(
7834               CS, "couldn't allocate output register for constraint '" +
7835                       Twine(OpInfo.ConstraintCode) + "'");
7836           return;
7837         }
7838 
7839         // Add information to the INLINEASM node to know that this register is
7840         // set.
7841         OpInfo.AssignedRegs.AddInlineAsmOperands(
7842             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7843                                   : InlineAsm::Kind_RegDef,
7844             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7845       }
7846       break;
7847 
7848     case InlineAsm::isInput: {
7849       SDValue InOperandVal = OpInfo.CallOperand;
7850 
7851       if (OpInfo.isMatchingInputConstraint()) {
7852         // If this is required to match an output register we have already set,
7853         // just use its register.
7854         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7855                                                   AsmNodeOperands);
7856         unsigned OpFlag =
7857           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7858         if (InlineAsm::isRegDefKind(OpFlag) ||
7859             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7860           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7861           if (OpInfo.isIndirect) {
7862             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7863             emitInlineAsmError(CS, "inline asm not supported yet:"
7864                                    " don't know how to handle tied "
7865                                    "indirect register inputs");
7866             return;
7867           }
7868 
7869           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7870           SmallVector<unsigned, 4> Regs;
7871 
7872           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7873             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7874             MachineRegisterInfo &RegInfo =
7875                 DAG.getMachineFunction().getRegInfo();
7876             for (unsigned i = 0; i != NumRegs; ++i)
7877               Regs.push_back(RegInfo.createVirtualRegister(RC));
7878           } else {
7879             emitInlineAsmError(CS, "inline asm error: This value type register "
7880                                    "class is not natively supported!");
7881             return;
7882           }
7883 
7884           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7885 
7886           SDLoc dl = getCurSDLoc();
7887           // Use the produced MatchedRegs object to
7888           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7889                                     CS.getInstruction());
7890           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7891                                            true, OpInfo.getMatchedOperand(), dl,
7892                                            DAG, AsmNodeOperands);
7893           break;
7894         }
7895 
7896         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7897         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7898                "Unexpected number of operands");
7899         // Add information to the INLINEASM node to know about this input.
7900         // See InlineAsm.h isUseOperandTiedToDef.
7901         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7902         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7903                                                     OpInfo.getMatchedOperand());
7904         AsmNodeOperands.push_back(DAG.getTargetConstant(
7905             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7906         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7907         break;
7908       }
7909 
7910       // Treat indirect 'X' constraint as memory.
7911       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7912           OpInfo.isIndirect)
7913         OpInfo.ConstraintType = TargetLowering::C_Memory;
7914 
7915       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7916         std::vector<SDValue> Ops;
7917         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7918                                           Ops, DAG);
7919         if (Ops.empty()) {
7920           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7921                                      Twine(OpInfo.ConstraintCode) + "'");
7922           return;
7923         }
7924 
7925         // Add information to the INLINEASM node to know about this input.
7926         unsigned ResOpType =
7927           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7928         AsmNodeOperands.push_back(DAG.getTargetConstant(
7929             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7930         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7931         break;
7932       }
7933 
7934       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7935         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7936         assert(InOperandVal.getValueType() ==
7937                    TLI.getPointerTy(DAG.getDataLayout()) &&
7938                "Memory operands expect pointer values");
7939 
7940         unsigned ConstraintID =
7941             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7942         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7943                "Failed to convert memory constraint code to constraint id.");
7944 
7945         // Add information to the INLINEASM node to know about this input.
7946         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7947         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7948         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7949                                                         getCurSDLoc(),
7950                                                         MVT::i32));
7951         AsmNodeOperands.push_back(InOperandVal);
7952         break;
7953       }
7954 
7955       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7956               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7957              "Unknown constraint type!");
7958 
7959       // TODO: Support this.
7960       if (OpInfo.isIndirect) {
7961         emitInlineAsmError(
7962             CS, "Don't know how to handle indirect register inputs yet "
7963                 "for constraint '" +
7964                     Twine(OpInfo.ConstraintCode) + "'");
7965         return;
7966       }
7967 
7968       // Copy the input into the appropriate registers.
7969       if (OpInfo.AssignedRegs.Regs.empty()) {
7970         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7971                                    Twine(OpInfo.ConstraintCode) + "'");
7972         return;
7973       }
7974 
7975       SDLoc dl = getCurSDLoc();
7976 
7977       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7978                                         Chain, &Flag, CS.getInstruction());
7979 
7980       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7981                                                dl, DAG, AsmNodeOperands);
7982       break;
7983     }
7984     case InlineAsm::isClobber:
7985       // Add the clobbered value to the operand list, so that the register
7986       // allocator is aware that the physreg got clobbered.
7987       if (!OpInfo.AssignedRegs.Regs.empty())
7988         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7989                                                  false, 0, getCurSDLoc(), DAG,
7990                                                  AsmNodeOperands);
7991       break;
7992     }
7993   }
7994 
7995   // Finish up input operands.  Set the input chain and add the flag last.
7996   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7997   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7998 
7999   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM;
8000   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8001                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8002   Flag = Chain.getValue(1);
8003 
8004   // Do additional work to generate outputs.
8005 
8006   SmallVector<EVT, 1> ResultVTs;
8007   SmallVector<SDValue, 1> ResultValues;
8008   SmallVector<SDValue, 8> OutChains;
8009 
8010   llvm::Type *CSResultType = CS.getType();
8011   ArrayRef<Type *> ResultTypes;
8012   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8013     ResultTypes = StructResult->elements();
8014   else if (!CSResultType->isVoidTy())
8015     ResultTypes = makeArrayRef(CSResultType);
8016 
8017   auto CurResultType = ResultTypes.begin();
8018   auto handleRegAssign = [&](SDValue V) {
8019     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8020     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8021     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8022     ++CurResultType;
8023     // If the type of the inline asm call site return value is different but has
8024     // same size as the type of the asm output bitcast it.  One example of this
8025     // is for vectors with different width / number of elements.  This can
8026     // happen for register classes that can contain multiple different value
8027     // types.  The preg or vreg allocated may not have the same VT as was
8028     // expected.
8029     //
8030     // This can also happen for a return value that disagrees with the register
8031     // class it is put in, eg. a double in a general-purpose register on a
8032     // 32-bit machine.
8033     if (ResultVT != V.getValueType() &&
8034         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8035       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8036     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8037              V.getValueType().isInteger()) {
8038       // If a result value was tied to an input value, the computed result
8039       // may have a wider width than the expected result.  Extract the
8040       // relevant portion.
8041       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8042     }
8043     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8044     ResultVTs.push_back(ResultVT);
8045     ResultValues.push_back(V);
8046   };
8047 
8048   // Deal with output operands.
8049   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8050     if (OpInfo.Type == InlineAsm::isOutput) {
8051       SDValue Val;
8052       // Skip trivial output operands.
8053       if (OpInfo.AssignedRegs.Regs.empty())
8054         continue;
8055 
8056       switch (OpInfo.ConstraintType) {
8057       case TargetLowering::C_Register:
8058       case TargetLowering::C_RegisterClass:
8059         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8060             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8061         break;
8062       case TargetLowering::C_Other:
8063         Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(),
8064                                               OpInfo, DAG);
8065         break;
8066       case TargetLowering::C_Memory:
8067         break; // Already handled.
8068       case TargetLowering::C_Unknown:
8069         assert(false && "Unexpected unknown constraint");
8070       }
8071 
8072       // Indirect output manifest as stores. Record output chains.
8073       if (OpInfo.isIndirect) {
8074 
8075         const Value *Ptr = OpInfo.CallOperandVal;
8076         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8077         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8078                                      MachinePointerInfo(Ptr));
8079         OutChains.push_back(Store);
8080       } else {
8081         // generate CopyFromRegs to associated registers.
8082         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8083         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8084           for (const SDValue &V : Val->op_values())
8085             handleRegAssign(V);
8086         } else
8087           handleRegAssign(Val);
8088       }
8089     }
8090   }
8091 
8092   // Set results.
8093   if (!ResultValues.empty()) {
8094     assert(CurResultType == ResultTypes.end() &&
8095            "Mismatch in number of ResultTypes");
8096     assert(ResultValues.size() == ResultTypes.size() &&
8097            "Mismatch in number of output operands in asm result");
8098 
8099     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8100                             DAG.getVTList(ResultVTs), ResultValues);
8101     setValue(CS.getInstruction(), V);
8102   }
8103 
8104   // Collect store chains.
8105   if (!OutChains.empty())
8106     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8107 
8108   // Only Update Root if inline assembly has a memory effect.
8109   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8110     DAG.setRoot(Chain);
8111 }
8112 
8113 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8114                                              const Twine &Message) {
8115   LLVMContext &Ctx = *DAG.getContext();
8116   Ctx.emitError(CS.getInstruction(), Message);
8117 
8118   // Make sure we leave the DAG in a valid state
8119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8120   SmallVector<EVT, 1> ValueVTs;
8121   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8122 
8123   if (ValueVTs.empty())
8124     return;
8125 
8126   SmallVector<SDValue, 1> Ops;
8127   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8128     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8129 
8130   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8131 }
8132 
8133 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8134   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8135                           MVT::Other, getRoot(),
8136                           getValue(I.getArgOperand(0)),
8137                           DAG.getSrcValue(I.getArgOperand(0))));
8138 }
8139 
8140 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8142   const DataLayout &DL = DAG.getDataLayout();
8143   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8144                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8145                            DAG.getSrcValue(I.getOperand(0)),
8146                            DL.getABITypeAlignment(I.getType()));
8147   setValue(&I, V);
8148   DAG.setRoot(V.getValue(1));
8149 }
8150 
8151 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8152   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8153                           MVT::Other, getRoot(),
8154                           getValue(I.getArgOperand(0)),
8155                           DAG.getSrcValue(I.getArgOperand(0))));
8156 }
8157 
8158 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8159   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8160                           MVT::Other, getRoot(),
8161                           getValue(I.getArgOperand(0)),
8162                           getValue(I.getArgOperand(1)),
8163                           DAG.getSrcValue(I.getArgOperand(0)),
8164                           DAG.getSrcValue(I.getArgOperand(1))));
8165 }
8166 
8167 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8168                                                     const Instruction &I,
8169                                                     SDValue Op) {
8170   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8171   if (!Range)
8172     return Op;
8173 
8174   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8175   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8176     return Op;
8177 
8178   APInt Lo = CR.getUnsignedMin();
8179   if (!Lo.isMinValue())
8180     return Op;
8181 
8182   APInt Hi = CR.getUnsignedMax();
8183   unsigned Bits = std::max(Hi.getActiveBits(),
8184                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8185 
8186   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8187 
8188   SDLoc SL = getCurSDLoc();
8189 
8190   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8191                              DAG.getValueType(SmallVT));
8192   unsigned NumVals = Op.getNode()->getNumValues();
8193   if (NumVals == 1)
8194     return ZExt;
8195 
8196   SmallVector<SDValue, 4> Ops;
8197 
8198   Ops.push_back(ZExt);
8199   for (unsigned I = 1; I != NumVals; ++I)
8200     Ops.push_back(Op.getValue(I));
8201 
8202   return DAG.getMergeValues(Ops, SL);
8203 }
8204 
8205 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8206 /// the call being lowered.
8207 ///
8208 /// This is a helper for lowering intrinsics that follow a target calling
8209 /// convention or require stack pointer adjustment. Only a subset of the
8210 /// intrinsic's operands need to participate in the calling convention.
8211 void SelectionDAGBuilder::populateCallLoweringInfo(
8212     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8213     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8214     bool IsPatchPoint) {
8215   TargetLowering::ArgListTy Args;
8216   Args.reserve(NumArgs);
8217 
8218   // Populate the argument list.
8219   // Attributes for args start at offset 1, after the return attribute.
8220   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8221        ArgI != ArgE; ++ArgI) {
8222     const Value *V = Call->getOperand(ArgI);
8223 
8224     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8225 
8226     TargetLowering::ArgListEntry Entry;
8227     Entry.Node = getValue(V);
8228     Entry.Ty = V->getType();
8229     Entry.setAttributes(Call, ArgI);
8230     Args.push_back(Entry);
8231   }
8232 
8233   CLI.setDebugLoc(getCurSDLoc())
8234       .setChain(getRoot())
8235       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8236       .setDiscardResult(Call->use_empty())
8237       .setIsPatchPoint(IsPatchPoint);
8238 }
8239 
8240 /// Add a stack map intrinsic call's live variable operands to a stackmap
8241 /// or patchpoint target node's operand list.
8242 ///
8243 /// Constants are converted to TargetConstants purely as an optimization to
8244 /// avoid constant materialization and register allocation.
8245 ///
8246 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8247 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8248 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8249 /// address materialization and register allocation, but may also be required
8250 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8251 /// alloca in the entry block, then the runtime may assume that the alloca's
8252 /// StackMap location can be read immediately after compilation and that the
8253 /// location is valid at any point during execution (this is similar to the
8254 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8255 /// only available in a register, then the runtime would need to trap when
8256 /// execution reaches the StackMap in order to read the alloca's location.
8257 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8258                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8259                                 SelectionDAGBuilder &Builder) {
8260   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8261     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8263       Ops.push_back(
8264         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8265       Ops.push_back(
8266         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8267     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8268       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8269       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8270           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8271     } else
8272       Ops.push_back(OpVal);
8273   }
8274 }
8275 
8276 /// Lower llvm.experimental.stackmap directly to its target opcode.
8277 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8278   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8279   //                                  [live variables...])
8280 
8281   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8282 
8283   SDValue Chain, InFlag, Callee, NullPtr;
8284   SmallVector<SDValue, 32> Ops;
8285 
8286   SDLoc DL = getCurSDLoc();
8287   Callee = getValue(CI.getCalledValue());
8288   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8289 
8290   // The stackmap intrinsic only records the live variables (the arguemnts
8291   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8292   // intrinsic, this won't be lowered to a function call. This means we don't
8293   // have to worry about calling conventions and target specific lowering code.
8294   // Instead we perform the call lowering right here.
8295   //
8296   // chain, flag = CALLSEQ_START(chain, 0, 0)
8297   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8298   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8299   //
8300   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8301   InFlag = Chain.getValue(1);
8302 
8303   // Add the <id> and <numBytes> constants.
8304   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8305   Ops.push_back(DAG.getTargetConstant(
8306                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8307   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8308   Ops.push_back(DAG.getTargetConstant(
8309                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8310                   MVT::i32));
8311 
8312   // Push live variables for the stack map.
8313   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8314 
8315   // We are not pushing any register mask info here on the operands list,
8316   // because the stackmap doesn't clobber anything.
8317 
8318   // Push the chain and the glue flag.
8319   Ops.push_back(Chain);
8320   Ops.push_back(InFlag);
8321 
8322   // Create the STACKMAP node.
8323   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8324   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8325   Chain = SDValue(SM, 0);
8326   InFlag = Chain.getValue(1);
8327 
8328   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8329 
8330   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8331 
8332   // Set the root to the target-lowered call chain.
8333   DAG.setRoot(Chain);
8334 
8335   // Inform the Frame Information that we have a stackmap in this function.
8336   FuncInfo.MF->getFrameInfo().setHasStackMap();
8337 }
8338 
8339 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8340 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8341                                           const BasicBlock *EHPadBB) {
8342   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8343   //                                                 i32 <numBytes>,
8344   //                                                 i8* <target>,
8345   //                                                 i32 <numArgs>,
8346   //                                                 [Args...],
8347   //                                                 [live variables...])
8348 
8349   CallingConv::ID CC = CS.getCallingConv();
8350   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8351   bool HasDef = !CS->getType()->isVoidTy();
8352   SDLoc dl = getCurSDLoc();
8353   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8354 
8355   // Handle immediate and symbolic callees.
8356   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8357     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8358                                    /*isTarget=*/true);
8359   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8360     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8361                                          SDLoc(SymbolicCallee),
8362                                          SymbolicCallee->getValueType(0));
8363 
8364   // Get the real number of arguments participating in the call <numArgs>
8365   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8366   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8367 
8368   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8369   // Intrinsics include all meta-operands up to but not including CC.
8370   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8371   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8372          "Not enough arguments provided to the patchpoint intrinsic");
8373 
8374   // For AnyRegCC the arguments are lowered later on manually.
8375   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8376   Type *ReturnTy =
8377     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8378 
8379   TargetLowering::CallLoweringInfo CLI(DAG);
8380   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8381                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8382   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8383 
8384   SDNode *CallEnd = Result.second.getNode();
8385   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8386     CallEnd = CallEnd->getOperand(0).getNode();
8387 
8388   /// Get a call instruction from the call sequence chain.
8389   /// Tail calls are not allowed.
8390   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8391          "Expected a callseq node.");
8392   SDNode *Call = CallEnd->getOperand(0).getNode();
8393   bool HasGlue = Call->getGluedNode();
8394 
8395   // Replace the target specific call node with the patchable intrinsic.
8396   SmallVector<SDValue, 8> Ops;
8397 
8398   // Add the <id> and <numBytes> constants.
8399   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8400   Ops.push_back(DAG.getTargetConstant(
8401                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8402   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8403   Ops.push_back(DAG.getTargetConstant(
8404                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8405                   MVT::i32));
8406 
8407   // Add the callee.
8408   Ops.push_back(Callee);
8409 
8410   // Adjust <numArgs> to account for any arguments that have been passed on the
8411   // stack instead.
8412   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8413   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8414   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8415   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8416 
8417   // Add the calling convention
8418   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8419 
8420   // Add the arguments we omitted previously. The register allocator should
8421   // place these in any free register.
8422   if (IsAnyRegCC)
8423     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8424       Ops.push_back(getValue(CS.getArgument(i)));
8425 
8426   // Push the arguments from the call instruction up to the register mask.
8427   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8428   Ops.append(Call->op_begin() + 2, e);
8429 
8430   // Push live variables for the stack map.
8431   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8432 
8433   // Push the register mask info.
8434   if (HasGlue)
8435     Ops.push_back(*(Call->op_end()-2));
8436   else
8437     Ops.push_back(*(Call->op_end()-1));
8438 
8439   // Push the chain (this is originally the first operand of the call, but
8440   // becomes now the last or second to last operand).
8441   Ops.push_back(*(Call->op_begin()));
8442 
8443   // Push the glue flag (last operand).
8444   if (HasGlue)
8445     Ops.push_back(*(Call->op_end()-1));
8446 
8447   SDVTList NodeTys;
8448   if (IsAnyRegCC && HasDef) {
8449     // Create the return types based on the intrinsic definition
8450     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8451     SmallVector<EVT, 3> ValueVTs;
8452     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8453     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8454 
8455     // There is always a chain and a glue type at the end
8456     ValueVTs.push_back(MVT::Other);
8457     ValueVTs.push_back(MVT::Glue);
8458     NodeTys = DAG.getVTList(ValueVTs);
8459   } else
8460     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8461 
8462   // Replace the target specific call node with a PATCHPOINT node.
8463   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8464                                          dl, NodeTys, Ops);
8465 
8466   // Update the NodeMap.
8467   if (HasDef) {
8468     if (IsAnyRegCC)
8469       setValue(CS.getInstruction(), SDValue(MN, 0));
8470     else
8471       setValue(CS.getInstruction(), Result.first);
8472   }
8473 
8474   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8475   // call sequence. Furthermore the location of the chain and glue can change
8476   // when the AnyReg calling convention is used and the intrinsic returns a
8477   // value.
8478   if (IsAnyRegCC && HasDef) {
8479     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8480     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8481     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8482   } else
8483     DAG.ReplaceAllUsesWith(Call, MN);
8484   DAG.DeleteNode(Call);
8485 
8486   // Inform the Frame Information that we have a patchpoint in this function.
8487   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8488 }
8489 
8490 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8491                                             unsigned Intrinsic) {
8492   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8493   SDValue Op1 = getValue(I.getArgOperand(0));
8494   SDValue Op2;
8495   if (I.getNumArgOperands() > 1)
8496     Op2 = getValue(I.getArgOperand(1));
8497   SDLoc dl = getCurSDLoc();
8498   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8499   SDValue Res;
8500   FastMathFlags FMF;
8501   if (isa<FPMathOperator>(I))
8502     FMF = I.getFastMathFlags();
8503 
8504   switch (Intrinsic) {
8505   case Intrinsic::experimental_vector_reduce_fadd:
8506     if (FMF.isFast())
8507       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8508     else
8509       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8510     break;
8511   case Intrinsic::experimental_vector_reduce_fmul:
8512     if (FMF.isFast())
8513       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8514     else
8515       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8516     break;
8517   case Intrinsic::experimental_vector_reduce_add:
8518     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8519     break;
8520   case Intrinsic::experimental_vector_reduce_mul:
8521     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8522     break;
8523   case Intrinsic::experimental_vector_reduce_and:
8524     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8525     break;
8526   case Intrinsic::experimental_vector_reduce_or:
8527     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8528     break;
8529   case Intrinsic::experimental_vector_reduce_xor:
8530     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8531     break;
8532   case Intrinsic::experimental_vector_reduce_smax:
8533     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8534     break;
8535   case Intrinsic::experimental_vector_reduce_smin:
8536     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8537     break;
8538   case Intrinsic::experimental_vector_reduce_umax:
8539     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8540     break;
8541   case Intrinsic::experimental_vector_reduce_umin:
8542     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8543     break;
8544   case Intrinsic::experimental_vector_reduce_fmax:
8545     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8546     break;
8547   case Intrinsic::experimental_vector_reduce_fmin:
8548     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8549     break;
8550   default:
8551     llvm_unreachable("Unhandled vector reduce intrinsic");
8552   }
8553   setValue(&I, Res);
8554 }
8555 
8556 /// Returns an AttributeList representing the attributes applied to the return
8557 /// value of the given call.
8558 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8559   SmallVector<Attribute::AttrKind, 2> Attrs;
8560   if (CLI.RetSExt)
8561     Attrs.push_back(Attribute::SExt);
8562   if (CLI.RetZExt)
8563     Attrs.push_back(Attribute::ZExt);
8564   if (CLI.IsInReg)
8565     Attrs.push_back(Attribute::InReg);
8566 
8567   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8568                             Attrs);
8569 }
8570 
8571 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8572 /// implementation, which just calls LowerCall.
8573 /// FIXME: When all targets are
8574 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8575 std::pair<SDValue, SDValue>
8576 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8577   // Handle the incoming return values from the call.
8578   CLI.Ins.clear();
8579   Type *OrigRetTy = CLI.RetTy;
8580   SmallVector<EVT, 4> RetTys;
8581   SmallVector<uint64_t, 4> Offsets;
8582   auto &DL = CLI.DAG.getDataLayout();
8583   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8584 
8585   if (CLI.IsPostTypeLegalization) {
8586     // If we are lowering a libcall after legalization, split the return type.
8587     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8588     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8589     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8590       EVT RetVT = OldRetTys[i];
8591       uint64_t Offset = OldOffsets[i];
8592       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8593       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8594       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8595       RetTys.append(NumRegs, RegisterVT);
8596       for (unsigned j = 0; j != NumRegs; ++j)
8597         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8598     }
8599   }
8600 
8601   SmallVector<ISD::OutputArg, 4> Outs;
8602   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8603 
8604   bool CanLowerReturn =
8605       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8606                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8607 
8608   SDValue DemoteStackSlot;
8609   int DemoteStackIdx = -100;
8610   if (!CanLowerReturn) {
8611     // FIXME: equivalent assert?
8612     // assert(!CS.hasInAllocaArgument() &&
8613     //        "sret demotion is incompatible with inalloca");
8614     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8615     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8616     MachineFunction &MF = CLI.DAG.getMachineFunction();
8617     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8618     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8619                                               DL.getAllocaAddrSpace());
8620 
8621     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8622     ArgListEntry Entry;
8623     Entry.Node = DemoteStackSlot;
8624     Entry.Ty = StackSlotPtrType;
8625     Entry.IsSExt = false;
8626     Entry.IsZExt = false;
8627     Entry.IsInReg = false;
8628     Entry.IsSRet = true;
8629     Entry.IsNest = false;
8630     Entry.IsByVal = false;
8631     Entry.IsReturned = false;
8632     Entry.IsSwiftSelf = false;
8633     Entry.IsSwiftError = false;
8634     Entry.Alignment = Align;
8635     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8636     CLI.NumFixedArgs += 1;
8637     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8638 
8639     // sret demotion isn't compatible with tail-calls, since the sret argument
8640     // points into the callers stack frame.
8641     CLI.IsTailCall = false;
8642   } else {
8643     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8644       EVT VT = RetTys[I];
8645       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8646                                                      CLI.CallConv, VT);
8647       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8648                                                        CLI.CallConv, VT);
8649       for (unsigned i = 0; i != NumRegs; ++i) {
8650         ISD::InputArg MyFlags;
8651         MyFlags.VT = RegisterVT;
8652         MyFlags.ArgVT = VT;
8653         MyFlags.Used = CLI.IsReturnValueUsed;
8654         if (CLI.RetSExt)
8655           MyFlags.Flags.setSExt();
8656         if (CLI.RetZExt)
8657           MyFlags.Flags.setZExt();
8658         if (CLI.IsInReg)
8659           MyFlags.Flags.setInReg();
8660         CLI.Ins.push_back(MyFlags);
8661       }
8662     }
8663   }
8664 
8665   // We push in swifterror return as the last element of CLI.Ins.
8666   ArgListTy &Args = CLI.getArgs();
8667   if (supportSwiftError()) {
8668     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8669       if (Args[i].IsSwiftError) {
8670         ISD::InputArg MyFlags;
8671         MyFlags.VT = getPointerTy(DL);
8672         MyFlags.ArgVT = EVT(getPointerTy(DL));
8673         MyFlags.Flags.setSwiftError();
8674         CLI.Ins.push_back(MyFlags);
8675       }
8676     }
8677   }
8678 
8679   // Handle all of the outgoing arguments.
8680   CLI.Outs.clear();
8681   CLI.OutVals.clear();
8682   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8683     SmallVector<EVT, 4> ValueVTs;
8684     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8685     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8686     Type *FinalType = Args[i].Ty;
8687     if (Args[i].IsByVal)
8688       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8689     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8690         FinalType, CLI.CallConv, CLI.IsVarArg);
8691     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8692          ++Value) {
8693       EVT VT = ValueVTs[Value];
8694       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8695       SDValue Op = SDValue(Args[i].Node.getNode(),
8696                            Args[i].Node.getResNo() + Value);
8697       ISD::ArgFlagsTy Flags;
8698 
8699       // Certain targets (such as MIPS), may have a different ABI alignment
8700       // for a type depending on the context. Give the target a chance to
8701       // specify the alignment it wants.
8702       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8703 
8704       if (Args[i].IsZExt)
8705         Flags.setZExt();
8706       if (Args[i].IsSExt)
8707         Flags.setSExt();
8708       if (Args[i].IsInReg) {
8709         // If we are using vectorcall calling convention, a structure that is
8710         // passed InReg - is surely an HVA
8711         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8712             isa<StructType>(FinalType)) {
8713           // The first value of a structure is marked
8714           if (0 == Value)
8715             Flags.setHvaStart();
8716           Flags.setHva();
8717         }
8718         // Set InReg Flag
8719         Flags.setInReg();
8720       }
8721       if (Args[i].IsSRet)
8722         Flags.setSRet();
8723       if (Args[i].IsSwiftSelf)
8724         Flags.setSwiftSelf();
8725       if (Args[i].IsSwiftError)
8726         Flags.setSwiftError();
8727       if (Args[i].IsByVal)
8728         Flags.setByVal();
8729       if (Args[i].IsInAlloca) {
8730         Flags.setInAlloca();
8731         // Set the byval flag for CCAssignFn callbacks that don't know about
8732         // inalloca.  This way we can know how many bytes we should've allocated
8733         // and how many bytes a callee cleanup function will pop.  If we port
8734         // inalloca to more targets, we'll have to add custom inalloca handling
8735         // in the various CC lowering callbacks.
8736         Flags.setByVal();
8737       }
8738       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8739         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8740         Type *ElementTy = Ty->getElementType();
8741         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8742         // For ByVal, alignment should come from FE.  BE will guess if this
8743         // info is not there but there are cases it cannot get right.
8744         unsigned FrameAlign;
8745         if (Args[i].Alignment)
8746           FrameAlign = Args[i].Alignment;
8747         else
8748           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8749         Flags.setByValAlign(FrameAlign);
8750       }
8751       if (Args[i].IsNest)
8752         Flags.setNest();
8753       if (NeedsRegBlock)
8754         Flags.setInConsecutiveRegs();
8755       Flags.setOrigAlign(OriginalAlignment);
8756 
8757       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8758                                                  CLI.CallConv, VT);
8759       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8760                                                         CLI.CallConv, VT);
8761       SmallVector<SDValue, 4> Parts(NumParts);
8762       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8763 
8764       if (Args[i].IsSExt)
8765         ExtendKind = ISD::SIGN_EXTEND;
8766       else if (Args[i].IsZExt)
8767         ExtendKind = ISD::ZERO_EXTEND;
8768 
8769       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8770       // for now.
8771       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8772           CanLowerReturn) {
8773         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8774                "unexpected use of 'returned'");
8775         // Before passing 'returned' to the target lowering code, ensure that
8776         // either the register MVT and the actual EVT are the same size or that
8777         // the return value and argument are extended in the same way; in these
8778         // cases it's safe to pass the argument register value unchanged as the
8779         // return register value (although it's at the target's option whether
8780         // to do so)
8781         // TODO: allow code generation to take advantage of partially preserved
8782         // registers rather than clobbering the entire register when the
8783         // parameter extension method is not compatible with the return
8784         // extension method
8785         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8786             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8787              CLI.RetZExt == Args[i].IsZExt))
8788           Flags.setReturned();
8789       }
8790 
8791       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8792                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8793 
8794       for (unsigned j = 0; j != NumParts; ++j) {
8795         // if it isn't first piece, alignment must be 1
8796         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8797                                i < CLI.NumFixedArgs,
8798                                i, j*Parts[j].getValueType().getStoreSize());
8799         if (NumParts > 1 && j == 0)
8800           MyFlags.Flags.setSplit();
8801         else if (j != 0) {
8802           MyFlags.Flags.setOrigAlign(1);
8803           if (j == NumParts - 1)
8804             MyFlags.Flags.setSplitEnd();
8805         }
8806 
8807         CLI.Outs.push_back(MyFlags);
8808         CLI.OutVals.push_back(Parts[j]);
8809       }
8810 
8811       if (NeedsRegBlock && Value == NumValues - 1)
8812         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8813     }
8814   }
8815 
8816   SmallVector<SDValue, 4> InVals;
8817   CLI.Chain = LowerCall(CLI, InVals);
8818 
8819   // Update CLI.InVals to use outside of this function.
8820   CLI.InVals = InVals;
8821 
8822   // Verify that the target's LowerCall behaved as expected.
8823   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8824          "LowerCall didn't return a valid chain!");
8825   assert((!CLI.IsTailCall || InVals.empty()) &&
8826          "LowerCall emitted a return value for a tail call!");
8827   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8828          "LowerCall didn't emit the correct number of values!");
8829 
8830   // For a tail call, the return value is merely live-out and there aren't
8831   // any nodes in the DAG representing it. Return a special value to
8832   // indicate that a tail call has been emitted and no more Instructions
8833   // should be processed in the current block.
8834   if (CLI.IsTailCall) {
8835     CLI.DAG.setRoot(CLI.Chain);
8836     return std::make_pair(SDValue(), SDValue());
8837   }
8838 
8839 #ifndef NDEBUG
8840   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8841     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8842     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8843            "LowerCall emitted a value with the wrong type!");
8844   }
8845 #endif
8846 
8847   SmallVector<SDValue, 4> ReturnValues;
8848   if (!CanLowerReturn) {
8849     // The instruction result is the result of loading from the
8850     // hidden sret parameter.
8851     SmallVector<EVT, 1> PVTs;
8852     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8853 
8854     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8855     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8856     EVT PtrVT = PVTs[0];
8857 
8858     unsigned NumValues = RetTys.size();
8859     ReturnValues.resize(NumValues);
8860     SmallVector<SDValue, 4> Chains(NumValues);
8861 
8862     // An aggregate return value cannot wrap around the address space, so
8863     // offsets to its parts don't wrap either.
8864     SDNodeFlags Flags;
8865     Flags.setNoUnsignedWrap(true);
8866 
8867     for (unsigned i = 0; i < NumValues; ++i) {
8868       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8869                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8870                                                         PtrVT), Flags);
8871       SDValue L = CLI.DAG.getLoad(
8872           RetTys[i], CLI.DL, CLI.Chain, Add,
8873           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8874                                             DemoteStackIdx, Offsets[i]),
8875           /* Alignment = */ 1);
8876       ReturnValues[i] = L;
8877       Chains[i] = L.getValue(1);
8878     }
8879 
8880     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8881   } else {
8882     // Collect the legal value parts into potentially illegal values
8883     // that correspond to the original function's return values.
8884     Optional<ISD::NodeType> AssertOp;
8885     if (CLI.RetSExt)
8886       AssertOp = ISD::AssertSext;
8887     else if (CLI.RetZExt)
8888       AssertOp = ISD::AssertZext;
8889     unsigned CurReg = 0;
8890     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8891       EVT VT = RetTys[I];
8892       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8893                                                      CLI.CallConv, VT);
8894       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8895                                                        CLI.CallConv, VT);
8896 
8897       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8898                                               NumRegs, RegisterVT, VT, nullptr,
8899                                               CLI.CallConv, AssertOp));
8900       CurReg += NumRegs;
8901     }
8902 
8903     // For a function returning void, there is no return value. We can't create
8904     // such a node, so we just return a null return value in that case. In
8905     // that case, nothing will actually look at the value.
8906     if (ReturnValues.empty())
8907       return std::make_pair(SDValue(), CLI.Chain);
8908   }
8909 
8910   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8911                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8912   return std::make_pair(Res, CLI.Chain);
8913 }
8914 
8915 void TargetLowering::LowerOperationWrapper(SDNode *N,
8916                                            SmallVectorImpl<SDValue> &Results,
8917                                            SelectionDAG &DAG) const {
8918   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8919     Results.push_back(Res);
8920 }
8921 
8922 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8923   llvm_unreachable("LowerOperation not implemented for this target!");
8924 }
8925 
8926 void
8927 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8928   SDValue Op = getNonRegisterValue(V);
8929   assert((Op.getOpcode() != ISD::CopyFromReg ||
8930           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8931          "Copy from a reg to the same reg!");
8932   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8933 
8934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8935   // If this is an InlineAsm we have to match the registers required, not the
8936   // notional registers required by the type.
8937 
8938   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8939                    None); // This is not an ABI copy.
8940   SDValue Chain = DAG.getEntryNode();
8941 
8942   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8943                               FuncInfo.PreferredExtendType.end())
8944                                  ? ISD::ANY_EXTEND
8945                                  : FuncInfo.PreferredExtendType[V];
8946   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8947   PendingExports.push_back(Chain);
8948 }
8949 
8950 #include "llvm/CodeGen/SelectionDAGISel.h"
8951 
8952 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8953 /// entry block, return true.  This includes arguments used by switches, since
8954 /// the switch may expand into multiple basic blocks.
8955 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8956   // With FastISel active, we may be splitting blocks, so force creation
8957   // of virtual registers for all non-dead arguments.
8958   if (FastISel)
8959     return A->use_empty();
8960 
8961   const BasicBlock &Entry = A->getParent()->front();
8962   for (const User *U : A->users())
8963     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8964       return false;  // Use not in entry block.
8965 
8966   return true;
8967 }
8968 
8969 using ArgCopyElisionMapTy =
8970     DenseMap<const Argument *,
8971              std::pair<const AllocaInst *, const StoreInst *>>;
8972 
8973 /// Scan the entry block of the function in FuncInfo for arguments that look
8974 /// like copies into a local alloca. Record any copied arguments in
8975 /// ArgCopyElisionCandidates.
8976 static void
8977 findArgumentCopyElisionCandidates(const DataLayout &DL,
8978                                   FunctionLoweringInfo *FuncInfo,
8979                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8980   // Record the state of every static alloca used in the entry block. Argument
8981   // allocas are all used in the entry block, so we need approximately as many
8982   // entries as we have arguments.
8983   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8984   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8985   unsigned NumArgs = FuncInfo->Fn->arg_size();
8986   StaticAllocas.reserve(NumArgs * 2);
8987 
8988   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8989     if (!V)
8990       return nullptr;
8991     V = V->stripPointerCasts();
8992     const auto *AI = dyn_cast<AllocaInst>(V);
8993     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8994       return nullptr;
8995     auto Iter = StaticAllocas.insert({AI, Unknown});
8996     return &Iter.first->second;
8997   };
8998 
8999   // Look for stores of arguments to static allocas. Look through bitcasts and
9000   // GEPs to handle type coercions, as long as the alloca is fully initialized
9001   // by the store. Any non-store use of an alloca escapes it and any subsequent
9002   // unanalyzed store might write it.
9003   // FIXME: Handle structs initialized with multiple stores.
9004   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9005     // Look for stores, and handle non-store uses conservatively.
9006     const auto *SI = dyn_cast<StoreInst>(&I);
9007     if (!SI) {
9008       // We will look through cast uses, so ignore them completely.
9009       if (I.isCast())
9010         continue;
9011       // Ignore debug info intrinsics, they don't escape or store to allocas.
9012       if (isa<DbgInfoIntrinsic>(I))
9013         continue;
9014       // This is an unknown instruction. Assume it escapes or writes to all
9015       // static alloca operands.
9016       for (const Use &U : I.operands()) {
9017         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9018           *Info = StaticAllocaInfo::Clobbered;
9019       }
9020       continue;
9021     }
9022 
9023     // If the stored value is a static alloca, mark it as escaped.
9024     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9025       *Info = StaticAllocaInfo::Clobbered;
9026 
9027     // Check if the destination is a static alloca.
9028     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9029     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9030     if (!Info)
9031       continue;
9032     const AllocaInst *AI = cast<AllocaInst>(Dst);
9033 
9034     // Skip allocas that have been initialized or clobbered.
9035     if (*Info != StaticAllocaInfo::Unknown)
9036       continue;
9037 
9038     // Check if the stored value is an argument, and that this store fully
9039     // initializes the alloca. Don't elide copies from the same argument twice.
9040     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9041     const auto *Arg = dyn_cast<Argument>(Val);
9042     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9043         Arg->getType()->isEmptyTy() ||
9044         DL.getTypeStoreSize(Arg->getType()) !=
9045             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9046         ArgCopyElisionCandidates.count(Arg)) {
9047       *Info = StaticAllocaInfo::Clobbered;
9048       continue;
9049     }
9050 
9051     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9052                       << '\n');
9053 
9054     // Mark this alloca and store for argument copy elision.
9055     *Info = StaticAllocaInfo::Elidable;
9056     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9057 
9058     // Stop scanning if we've seen all arguments. This will happen early in -O0
9059     // builds, which is useful, because -O0 builds have large entry blocks and
9060     // many allocas.
9061     if (ArgCopyElisionCandidates.size() == NumArgs)
9062       break;
9063   }
9064 }
9065 
9066 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9067 /// ArgVal is a load from a suitable fixed stack object.
9068 static void tryToElideArgumentCopy(
9069     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9070     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9071     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9072     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9073     SDValue ArgVal, bool &ArgHasUses) {
9074   // Check if this is a load from a fixed stack object.
9075   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9076   if (!LNode)
9077     return;
9078   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9079   if (!FINode)
9080     return;
9081 
9082   // Check that the fixed stack object is the right size and alignment.
9083   // Look at the alignment that the user wrote on the alloca instead of looking
9084   // at the stack object.
9085   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9086   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9087   const AllocaInst *AI = ArgCopyIter->second.first;
9088   int FixedIndex = FINode->getIndex();
9089   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9090   int OldIndex = AllocaIndex;
9091   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9092   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9093     LLVM_DEBUG(
9094         dbgs() << "  argument copy elision failed due to bad fixed stack "
9095                   "object size\n");
9096     return;
9097   }
9098   unsigned RequiredAlignment = AI->getAlignment();
9099   if (!RequiredAlignment) {
9100     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9101         AI->getAllocatedType());
9102   }
9103   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9104     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9105                          "greater than stack argument alignment ("
9106                       << RequiredAlignment << " vs "
9107                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9108     return;
9109   }
9110 
9111   // Perform the elision. Delete the old stack object and replace its only use
9112   // in the variable info map. Mark the stack object as mutable.
9113   LLVM_DEBUG({
9114     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9115            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9116            << '\n';
9117   });
9118   MFI.RemoveStackObject(OldIndex);
9119   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9120   AllocaIndex = FixedIndex;
9121   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9122   Chains.push_back(ArgVal.getValue(1));
9123 
9124   // Avoid emitting code for the store implementing the copy.
9125   const StoreInst *SI = ArgCopyIter->second.second;
9126   ElidedArgCopyInstrs.insert(SI);
9127 
9128   // Check for uses of the argument again so that we can avoid exporting ArgVal
9129   // if it is't used by anything other than the store.
9130   for (const Value *U : Arg.users()) {
9131     if (U != SI) {
9132       ArgHasUses = true;
9133       break;
9134     }
9135   }
9136 }
9137 
9138 void SelectionDAGISel::LowerArguments(const Function &F) {
9139   SelectionDAG &DAG = SDB->DAG;
9140   SDLoc dl = SDB->getCurSDLoc();
9141   const DataLayout &DL = DAG.getDataLayout();
9142   SmallVector<ISD::InputArg, 16> Ins;
9143 
9144   if (!FuncInfo->CanLowerReturn) {
9145     // Put in an sret pointer parameter before all the other parameters.
9146     SmallVector<EVT, 1> ValueVTs;
9147     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9148                     F.getReturnType()->getPointerTo(
9149                         DAG.getDataLayout().getAllocaAddrSpace()),
9150                     ValueVTs);
9151 
9152     // NOTE: Assuming that a pointer will never break down to more than one VT
9153     // or one register.
9154     ISD::ArgFlagsTy Flags;
9155     Flags.setSRet();
9156     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9157     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9158                          ISD::InputArg::NoArgIndex, 0);
9159     Ins.push_back(RetArg);
9160   }
9161 
9162   // Look for stores of arguments to static allocas. Mark such arguments with a
9163   // flag to ask the target to give us the memory location of that argument if
9164   // available.
9165   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9166   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9167 
9168   // Set up the incoming argument description vector.
9169   for (const Argument &Arg : F.args()) {
9170     unsigned ArgNo = Arg.getArgNo();
9171     SmallVector<EVT, 4> ValueVTs;
9172     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9173     bool isArgValueUsed = !Arg.use_empty();
9174     unsigned PartBase = 0;
9175     Type *FinalType = Arg.getType();
9176     if (Arg.hasAttribute(Attribute::ByVal))
9177       FinalType = cast<PointerType>(FinalType)->getElementType();
9178     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9179         FinalType, F.getCallingConv(), F.isVarArg());
9180     for (unsigned Value = 0, NumValues = ValueVTs.size();
9181          Value != NumValues; ++Value) {
9182       EVT VT = ValueVTs[Value];
9183       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9184       ISD::ArgFlagsTy Flags;
9185 
9186       // Certain targets (such as MIPS), may have a different ABI alignment
9187       // for a type depending on the context. Give the target a chance to
9188       // specify the alignment it wants.
9189       unsigned OriginalAlignment =
9190           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9191 
9192       if (Arg.hasAttribute(Attribute::ZExt))
9193         Flags.setZExt();
9194       if (Arg.hasAttribute(Attribute::SExt))
9195         Flags.setSExt();
9196       if (Arg.hasAttribute(Attribute::InReg)) {
9197         // If we are using vectorcall calling convention, a structure that is
9198         // passed InReg - is surely an HVA
9199         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9200             isa<StructType>(Arg.getType())) {
9201           // The first value of a structure is marked
9202           if (0 == Value)
9203             Flags.setHvaStart();
9204           Flags.setHva();
9205         }
9206         // Set InReg Flag
9207         Flags.setInReg();
9208       }
9209       if (Arg.hasAttribute(Attribute::StructRet))
9210         Flags.setSRet();
9211       if (Arg.hasAttribute(Attribute::SwiftSelf))
9212         Flags.setSwiftSelf();
9213       if (Arg.hasAttribute(Attribute::SwiftError))
9214         Flags.setSwiftError();
9215       if (Arg.hasAttribute(Attribute::ByVal))
9216         Flags.setByVal();
9217       if (Arg.hasAttribute(Attribute::InAlloca)) {
9218         Flags.setInAlloca();
9219         // Set the byval flag for CCAssignFn callbacks that don't know about
9220         // inalloca.  This way we can know how many bytes we should've allocated
9221         // and how many bytes a callee cleanup function will pop.  If we port
9222         // inalloca to more targets, we'll have to add custom inalloca handling
9223         // in the various CC lowering callbacks.
9224         Flags.setByVal();
9225       }
9226       if (F.getCallingConv() == CallingConv::X86_INTR) {
9227         // IA Interrupt passes frame (1st parameter) by value in the stack.
9228         if (ArgNo == 0)
9229           Flags.setByVal();
9230       }
9231       if (Flags.isByVal() || Flags.isInAlloca()) {
9232         PointerType *Ty = cast<PointerType>(Arg.getType());
9233         Type *ElementTy = Ty->getElementType();
9234         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9235         // For ByVal, alignment should be passed from FE.  BE will guess if
9236         // this info is not there but there are cases it cannot get right.
9237         unsigned FrameAlign;
9238         if (Arg.getParamAlignment())
9239           FrameAlign = Arg.getParamAlignment();
9240         else
9241           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9242         Flags.setByValAlign(FrameAlign);
9243       }
9244       if (Arg.hasAttribute(Attribute::Nest))
9245         Flags.setNest();
9246       if (NeedsRegBlock)
9247         Flags.setInConsecutiveRegs();
9248       Flags.setOrigAlign(OriginalAlignment);
9249       if (ArgCopyElisionCandidates.count(&Arg))
9250         Flags.setCopyElisionCandidate();
9251 
9252       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9253           *CurDAG->getContext(), F.getCallingConv(), VT);
9254       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9255           *CurDAG->getContext(), F.getCallingConv(), VT);
9256       for (unsigned i = 0; i != NumRegs; ++i) {
9257         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9258                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9259         if (NumRegs > 1 && i == 0)
9260           MyFlags.Flags.setSplit();
9261         // if it isn't first piece, alignment must be 1
9262         else if (i > 0) {
9263           MyFlags.Flags.setOrigAlign(1);
9264           if (i == NumRegs - 1)
9265             MyFlags.Flags.setSplitEnd();
9266         }
9267         Ins.push_back(MyFlags);
9268       }
9269       if (NeedsRegBlock && Value == NumValues - 1)
9270         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9271       PartBase += VT.getStoreSize();
9272     }
9273   }
9274 
9275   // Call the target to set up the argument values.
9276   SmallVector<SDValue, 8> InVals;
9277   SDValue NewRoot = TLI->LowerFormalArguments(
9278       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9279 
9280   // Verify that the target's LowerFormalArguments behaved as expected.
9281   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9282          "LowerFormalArguments didn't return a valid chain!");
9283   assert(InVals.size() == Ins.size() &&
9284          "LowerFormalArguments didn't emit the correct number of values!");
9285   LLVM_DEBUG({
9286     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9287       assert(InVals[i].getNode() &&
9288              "LowerFormalArguments emitted a null value!");
9289       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9290              "LowerFormalArguments emitted a value with the wrong type!");
9291     }
9292   });
9293 
9294   // Update the DAG with the new chain value resulting from argument lowering.
9295   DAG.setRoot(NewRoot);
9296 
9297   // Set up the argument values.
9298   unsigned i = 0;
9299   if (!FuncInfo->CanLowerReturn) {
9300     // Create a virtual register for the sret pointer, and put in a copy
9301     // from the sret argument into it.
9302     SmallVector<EVT, 1> ValueVTs;
9303     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9304                     F.getReturnType()->getPointerTo(
9305                         DAG.getDataLayout().getAllocaAddrSpace()),
9306                     ValueVTs);
9307     MVT VT = ValueVTs[0].getSimpleVT();
9308     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9309     Optional<ISD::NodeType> AssertOp = None;
9310     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9311                                         nullptr, F.getCallingConv(), AssertOp);
9312 
9313     MachineFunction& MF = SDB->DAG.getMachineFunction();
9314     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9315     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9316     FuncInfo->DemoteRegister = SRetReg;
9317     NewRoot =
9318         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9319     DAG.setRoot(NewRoot);
9320 
9321     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9322     ++i;
9323   }
9324 
9325   SmallVector<SDValue, 4> Chains;
9326   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9327   for (const Argument &Arg : F.args()) {
9328     SmallVector<SDValue, 4> ArgValues;
9329     SmallVector<EVT, 4> ValueVTs;
9330     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9331     unsigned NumValues = ValueVTs.size();
9332     if (NumValues == 0)
9333       continue;
9334 
9335     bool ArgHasUses = !Arg.use_empty();
9336 
9337     // Elide the copying store if the target loaded this argument from a
9338     // suitable fixed stack object.
9339     if (Ins[i].Flags.isCopyElisionCandidate()) {
9340       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9341                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9342                              InVals[i], ArgHasUses);
9343     }
9344 
9345     // If this argument is unused then remember its value. It is used to generate
9346     // debugging information.
9347     bool isSwiftErrorArg =
9348         TLI->supportSwiftError() &&
9349         Arg.hasAttribute(Attribute::SwiftError);
9350     if (!ArgHasUses && !isSwiftErrorArg) {
9351       SDB->setUnusedArgValue(&Arg, InVals[i]);
9352 
9353       // Also remember any frame index for use in FastISel.
9354       if (FrameIndexSDNode *FI =
9355           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9356         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9357     }
9358 
9359     for (unsigned Val = 0; Val != NumValues; ++Val) {
9360       EVT VT = ValueVTs[Val];
9361       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9362                                                       F.getCallingConv(), VT);
9363       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9364           *CurDAG->getContext(), F.getCallingConv(), VT);
9365 
9366       // Even an apparant 'unused' swifterror argument needs to be returned. So
9367       // we do generate a copy for it that can be used on return from the
9368       // function.
9369       if (ArgHasUses || isSwiftErrorArg) {
9370         Optional<ISD::NodeType> AssertOp;
9371         if (Arg.hasAttribute(Attribute::SExt))
9372           AssertOp = ISD::AssertSext;
9373         else if (Arg.hasAttribute(Attribute::ZExt))
9374           AssertOp = ISD::AssertZext;
9375 
9376         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9377                                              PartVT, VT, nullptr,
9378                                              F.getCallingConv(), AssertOp));
9379       }
9380 
9381       i += NumParts;
9382     }
9383 
9384     // We don't need to do anything else for unused arguments.
9385     if (ArgValues.empty())
9386       continue;
9387 
9388     // Note down frame index.
9389     if (FrameIndexSDNode *FI =
9390         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9391       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9392 
9393     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9394                                      SDB->getCurSDLoc());
9395 
9396     SDB->setValue(&Arg, Res);
9397     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9398       // We want to associate the argument with the frame index, among
9399       // involved operands, that correspond to the lowest address. The
9400       // getCopyFromParts function, called earlier, is swapping the order of
9401       // the operands to BUILD_PAIR depending on endianness. The result of
9402       // that swapping is that the least significant bits of the argument will
9403       // be in the first operand of the BUILD_PAIR node, and the most
9404       // significant bits will be in the second operand.
9405       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9406       if (LoadSDNode *LNode =
9407           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9408         if (FrameIndexSDNode *FI =
9409             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9410           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9411     }
9412 
9413     // Update the SwiftErrorVRegDefMap.
9414     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9415       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9416       if (TargetRegisterInfo::isVirtualRegister(Reg))
9417         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9418                                            FuncInfo->SwiftErrorArg, Reg);
9419     }
9420 
9421     // If this argument is live outside of the entry block, insert a copy from
9422     // wherever we got it to the vreg that other BB's will reference it as.
9423     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9424       // If we can, though, try to skip creating an unnecessary vreg.
9425       // FIXME: This isn't very clean... it would be nice to make this more
9426       // general.  It's also subtly incompatible with the hacks FastISel
9427       // uses with vregs.
9428       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9429       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9430         FuncInfo->ValueMap[&Arg] = Reg;
9431         continue;
9432       }
9433     }
9434     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9435       FuncInfo->InitializeRegForValue(&Arg);
9436       SDB->CopyToExportRegsIfNeeded(&Arg);
9437     }
9438   }
9439 
9440   if (!Chains.empty()) {
9441     Chains.push_back(NewRoot);
9442     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9443   }
9444 
9445   DAG.setRoot(NewRoot);
9446 
9447   assert(i == InVals.size() && "Argument register count mismatch!");
9448 
9449   // If any argument copy elisions occurred and we have debug info, update the
9450   // stale frame indices used in the dbg.declare variable info table.
9451   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9452   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9453     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9454       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9455       if (I != ArgCopyElisionFrameIndexMap.end())
9456         VI.Slot = I->second;
9457     }
9458   }
9459 
9460   // Finally, if the target has anything special to do, allow it to do so.
9461   EmitFunctionEntryCode();
9462 }
9463 
9464 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9465 /// ensure constants are generated when needed.  Remember the virtual registers
9466 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9467 /// directly add them, because expansion might result in multiple MBB's for one
9468 /// BB.  As such, the start of the BB might correspond to a different MBB than
9469 /// the end.
9470 void
9471 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9472   const Instruction *TI = LLVMBB->getTerminator();
9473 
9474   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9475 
9476   // Check PHI nodes in successors that expect a value to be available from this
9477   // block.
9478   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9479     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9480     if (!isa<PHINode>(SuccBB->begin())) continue;
9481     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9482 
9483     // If this terminator has multiple identical successors (common for
9484     // switches), only handle each succ once.
9485     if (!SuccsHandled.insert(SuccMBB).second)
9486       continue;
9487 
9488     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9489 
9490     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9491     // nodes and Machine PHI nodes, but the incoming operands have not been
9492     // emitted yet.
9493     for (const PHINode &PN : SuccBB->phis()) {
9494       // Ignore dead phi's.
9495       if (PN.use_empty())
9496         continue;
9497 
9498       // Skip empty types
9499       if (PN.getType()->isEmptyTy())
9500         continue;
9501 
9502       unsigned Reg;
9503       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9504 
9505       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9506         unsigned &RegOut = ConstantsOut[C];
9507         if (RegOut == 0) {
9508           RegOut = FuncInfo.CreateRegs(C->getType());
9509           CopyValueToVirtualRegister(C, RegOut);
9510         }
9511         Reg = RegOut;
9512       } else {
9513         DenseMap<const Value *, unsigned>::iterator I =
9514           FuncInfo.ValueMap.find(PHIOp);
9515         if (I != FuncInfo.ValueMap.end())
9516           Reg = I->second;
9517         else {
9518           assert(isa<AllocaInst>(PHIOp) &&
9519                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9520                  "Didn't codegen value into a register!??");
9521           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9522           CopyValueToVirtualRegister(PHIOp, Reg);
9523         }
9524       }
9525 
9526       // Remember that this register needs to added to the machine PHI node as
9527       // the input for this MBB.
9528       SmallVector<EVT, 4> ValueVTs;
9529       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9530       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9531       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9532         EVT VT = ValueVTs[vti];
9533         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9534         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9535           FuncInfo.PHINodesToUpdate.push_back(
9536               std::make_pair(&*MBBI++, Reg + i));
9537         Reg += NumRegisters;
9538       }
9539     }
9540   }
9541 
9542   ConstantsOut.clear();
9543 }
9544 
9545 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9546 /// is 0.
9547 MachineBasicBlock *
9548 SelectionDAGBuilder::StackProtectorDescriptor::
9549 AddSuccessorMBB(const BasicBlock *BB,
9550                 MachineBasicBlock *ParentMBB,
9551                 bool IsLikely,
9552                 MachineBasicBlock *SuccMBB) {
9553   // If SuccBB has not been created yet, create it.
9554   if (!SuccMBB) {
9555     MachineFunction *MF = ParentMBB->getParent();
9556     MachineFunction::iterator BBI(ParentMBB);
9557     SuccMBB = MF->CreateMachineBasicBlock(BB);
9558     MF->insert(++BBI, SuccMBB);
9559   }
9560   // Add it as a successor of ParentMBB.
9561   ParentMBB->addSuccessor(
9562       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9563   return SuccMBB;
9564 }
9565 
9566 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9567   MachineFunction::iterator I(MBB);
9568   if (++I == FuncInfo.MF->end())
9569     return nullptr;
9570   return &*I;
9571 }
9572 
9573 /// During lowering new call nodes can be created (such as memset, etc.).
9574 /// Those will become new roots of the current DAG, but complications arise
9575 /// when they are tail calls. In such cases, the call lowering will update
9576 /// the root, but the builder still needs to know that a tail call has been
9577 /// lowered in order to avoid generating an additional return.
9578 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9579   // If the node is null, we do have a tail call.
9580   if (MaybeTC.getNode() != nullptr)
9581     DAG.setRoot(MaybeTC);
9582   else
9583     HasTailCall = true;
9584 }
9585 
9586 uint64_t
9587 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9588                                        unsigned First, unsigned Last) const {
9589   assert(Last >= First);
9590   const APInt &LowCase = Clusters[First].Low->getValue();
9591   const APInt &HighCase = Clusters[Last].High->getValue();
9592   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9593 
9594   // FIXME: A range of consecutive cases has 100% density, but only requires one
9595   // comparison to lower. We should discriminate against such consecutive ranges
9596   // in jump tables.
9597 
9598   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9599 }
9600 
9601 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9602     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9603     unsigned Last) const {
9604   assert(Last >= First);
9605   assert(TotalCases[Last] >= TotalCases[First]);
9606   uint64_t NumCases =
9607       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9608   return NumCases;
9609 }
9610 
9611 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9612                                          unsigned First, unsigned Last,
9613                                          const SwitchInst *SI,
9614                                          MachineBasicBlock *DefaultMBB,
9615                                          CaseCluster &JTCluster) {
9616   assert(First <= Last);
9617 
9618   auto Prob = BranchProbability::getZero();
9619   unsigned NumCmps = 0;
9620   std::vector<MachineBasicBlock*> Table;
9621   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9622 
9623   // Initialize probabilities in JTProbs.
9624   for (unsigned I = First; I <= Last; ++I)
9625     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9626 
9627   for (unsigned I = First; I <= Last; ++I) {
9628     assert(Clusters[I].Kind == CC_Range);
9629     Prob += Clusters[I].Prob;
9630     const APInt &Low = Clusters[I].Low->getValue();
9631     const APInt &High = Clusters[I].High->getValue();
9632     NumCmps += (Low == High) ? 1 : 2;
9633     if (I != First) {
9634       // Fill the gap between this and the previous cluster.
9635       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9636       assert(PreviousHigh.slt(Low));
9637       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9638       for (uint64_t J = 0; J < Gap; J++)
9639         Table.push_back(DefaultMBB);
9640     }
9641     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9642     for (uint64_t J = 0; J < ClusterSize; ++J)
9643       Table.push_back(Clusters[I].MBB);
9644     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9645   }
9646 
9647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9648   unsigned NumDests = JTProbs.size();
9649   if (TLI.isSuitableForBitTests(
9650           NumDests, NumCmps, Clusters[First].Low->getValue(),
9651           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9652     // Clusters[First..Last] should be lowered as bit tests instead.
9653     return false;
9654   }
9655 
9656   // Create the MBB that will load from and jump through the table.
9657   // Note: We create it here, but it's not inserted into the function yet.
9658   MachineFunction *CurMF = FuncInfo.MF;
9659   MachineBasicBlock *JumpTableMBB =
9660       CurMF->CreateMachineBasicBlock(SI->getParent());
9661 
9662   // Add successors. Note: use table order for determinism.
9663   SmallPtrSet<MachineBasicBlock *, 8> Done;
9664   for (MachineBasicBlock *Succ : Table) {
9665     if (Done.count(Succ))
9666       continue;
9667     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9668     Done.insert(Succ);
9669   }
9670   JumpTableMBB->normalizeSuccProbs();
9671 
9672   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9673                      ->createJumpTableIndex(Table);
9674 
9675   // Set up the jump table info.
9676   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9677   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9678                       Clusters[Last].High->getValue(), SI->getCondition(),
9679                       nullptr, false);
9680   JTCases.emplace_back(std::move(JTH), std::move(JT));
9681 
9682   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9683                                      JTCases.size() - 1, Prob);
9684   return true;
9685 }
9686 
9687 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9688                                          const SwitchInst *SI,
9689                                          MachineBasicBlock *DefaultMBB) {
9690 #ifndef NDEBUG
9691   // Clusters must be non-empty, sorted, and only contain Range clusters.
9692   assert(!Clusters.empty());
9693   for (CaseCluster &C : Clusters)
9694     assert(C.Kind == CC_Range);
9695   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9696     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9697 #endif
9698 
9699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9700   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9701     return;
9702 
9703   const int64_t N = Clusters.size();
9704   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9705   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9706 
9707   if (N < 2 || N < MinJumpTableEntries)
9708     return;
9709 
9710   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9711   SmallVector<unsigned, 8> TotalCases(N);
9712   for (unsigned i = 0; i < N; ++i) {
9713     const APInt &Hi = Clusters[i].High->getValue();
9714     const APInt &Lo = Clusters[i].Low->getValue();
9715     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9716     if (i != 0)
9717       TotalCases[i] += TotalCases[i - 1];
9718   }
9719 
9720   // Cheap case: the whole range may be suitable for jump table.
9721   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9722   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9723   assert(NumCases < UINT64_MAX / 100);
9724   assert(Range >= NumCases);
9725   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9726     CaseCluster JTCluster;
9727     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9728       Clusters[0] = JTCluster;
9729       Clusters.resize(1);
9730       return;
9731     }
9732   }
9733 
9734   // The algorithm below is not suitable for -O0.
9735   if (TM.getOptLevel() == CodeGenOpt::None)
9736     return;
9737 
9738   // Split Clusters into minimum number of dense partitions. The algorithm uses
9739   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9740   // for the Case Statement'" (1994), but builds the MinPartitions array in
9741   // reverse order to make it easier to reconstruct the partitions in ascending
9742   // order. In the choice between two optimal partitionings, it picks the one
9743   // which yields more jump tables.
9744 
9745   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9746   SmallVector<unsigned, 8> MinPartitions(N);
9747   // LastElement[i] is the last element of the partition starting at i.
9748   SmallVector<unsigned, 8> LastElement(N);
9749   // PartitionsScore[i] is used to break ties when choosing between two
9750   // partitionings resulting in the same number of partitions.
9751   SmallVector<unsigned, 8> PartitionsScore(N);
9752   // For PartitionsScore, a small number of comparisons is considered as good as
9753   // a jump table and a single comparison is considered better than a jump
9754   // table.
9755   enum PartitionScores : unsigned {
9756     NoTable = 0,
9757     Table = 1,
9758     FewCases = 1,
9759     SingleCase = 2
9760   };
9761 
9762   // Base case: There is only one way to partition Clusters[N-1].
9763   MinPartitions[N - 1] = 1;
9764   LastElement[N - 1] = N - 1;
9765   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9766 
9767   // Note: loop indexes are signed to avoid underflow.
9768   for (int64_t i = N - 2; i >= 0; i--) {
9769     // Find optimal partitioning of Clusters[i..N-1].
9770     // Baseline: Put Clusters[i] into a partition on its own.
9771     MinPartitions[i] = MinPartitions[i + 1] + 1;
9772     LastElement[i] = i;
9773     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9774 
9775     // Search for a solution that results in fewer partitions.
9776     for (int64_t j = N - 1; j > i; j--) {
9777       // Try building a partition from Clusters[i..j].
9778       uint64_t Range = getJumpTableRange(Clusters, i, j);
9779       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9780       assert(NumCases < UINT64_MAX / 100);
9781       assert(Range >= NumCases);
9782       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9783         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9784         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9785         int64_t NumEntries = j - i + 1;
9786 
9787         if (NumEntries == 1)
9788           Score += PartitionScores::SingleCase;
9789         else if (NumEntries <= SmallNumberOfEntries)
9790           Score += PartitionScores::FewCases;
9791         else if (NumEntries >= MinJumpTableEntries)
9792           Score += PartitionScores::Table;
9793 
9794         // If this leads to fewer partitions, or to the same number of
9795         // partitions with better score, it is a better partitioning.
9796         if (NumPartitions < MinPartitions[i] ||
9797             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9798           MinPartitions[i] = NumPartitions;
9799           LastElement[i] = j;
9800           PartitionsScore[i] = Score;
9801         }
9802       }
9803     }
9804   }
9805 
9806   // Iterate over the partitions, replacing some with jump tables in-place.
9807   unsigned DstIndex = 0;
9808   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9809     Last = LastElement[First];
9810     assert(Last >= First);
9811     assert(DstIndex <= First);
9812     unsigned NumClusters = Last - First + 1;
9813 
9814     CaseCluster JTCluster;
9815     if (NumClusters >= MinJumpTableEntries &&
9816         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9817       Clusters[DstIndex++] = JTCluster;
9818     } else {
9819       for (unsigned I = First; I <= Last; ++I)
9820         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9821     }
9822   }
9823   Clusters.resize(DstIndex);
9824 }
9825 
9826 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9827                                         unsigned First, unsigned Last,
9828                                         const SwitchInst *SI,
9829                                         CaseCluster &BTCluster) {
9830   assert(First <= Last);
9831   if (First == Last)
9832     return false;
9833 
9834   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9835   unsigned NumCmps = 0;
9836   for (int64_t I = First; I <= Last; ++I) {
9837     assert(Clusters[I].Kind == CC_Range);
9838     Dests.set(Clusters[I].MBB->getNumber());
9839     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9840   }
9841   unsigned NumDests = Dests.count();
9842 
9843   APInt Low = Clusters[First].Low->getValue();
9844   APInt High = Clusters[Last].High->getValue();
9845   assert(Low.slt(High));
9846 
9847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9848   const DataLayout &DL = DAG.getDataLayout();
9849   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9850     return false;
9851 
9852   APInt LowBound;
9853   APInt CmpRange;
9854 
9855   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9856   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9857          "Case range must fit in bit mask!");
9858 
9859   // Check if the clusters cover a contiguous range such that no value in the
9860   // range will jump to the default statement.
9861   bool ContiguousRange = true;
9862   for (int64_t I = First + 1; I <= Last; ++I) {
9863     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9864       ContiguousRange = false;
9865       break;
9866     }
9867   }
9868 
9869   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9870     // Optimize the case where all the case values fit in a word without having
9871     // to subtract minValue. In this case, we can optimize away the subtraction.
9872     LowBound = APInt::getNullValue(Low.getBitWidth());
9873     CmpRange = High;
9874     ContiguousRange = false;
9875   } else {
9876     LowBound = Low;
9877     CmpRange = High - Low;
9878   }
9879 
9880   CaseBitsVector CBV;
9881   auto TotalProb = BranchProbability::getZero();
9882   for (unsigned i = First; i <= Last; ++i) {
9883     // Find the CaseBits for this destination.
9884     unsigned j;
9885     for (j = 0; j < CBV.size(); ++j)
9886       if (CBV[j].BB == Clusters[i].MBB)
9887         break;
9888     if (j == CBV.size())
9889       CBV.push_back(
9890           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9891     CaseBits *CB = &CBV[j];
9892 
9893     // Update Mask, Bits and ExtraProb.
9894     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9895     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9896     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9897     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9898     CB->Bits += Hi - Lo + 1;
9899     CB->ExtraProb += Clusters[i].Prob;
9900     TotalProb += Clusters[i].Prob;
9901   }
9902 
9903   BitTestInfo BTI;
9904   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9905     // Sort by probability first, number of bits second, bit mask third.
9906     if (a.ExtraProb != b.ExtraProb)
9907       return a.ExtraProb > b.ExtraProb;
9908     if (a.Bits != b.Bits)
9909       return a.Bits > b.Bits;
9910     return a.Mask < b.Mask;
9911   });
9912 
9913   for (auto &CB : CBV) {
9914     MachineBasicBlock *BitTestBB =
9915         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9916     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9917   }
9918   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9919                             SI->getCondition(), -1U, MVT::Other, false,
9920                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9921                             TotalProb);
9922 
9923   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9924                                     BitTestCases.size() - 1, TotalProb);
9925   return true;
9926 }
9927 
9928 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9929                                               const SwitchInst *SI) {
9930 // Partition Clusters into as few subsets as possible, where each subset has a
9931 // range that fits in a machine word and has <= 3 unique destinations.
9932 
9933 #ifndef NDEBUG
9934   // Clusters must be sorted and contain Range or JumpTable clusters.
9935   assert(!Clusters.empty());
9936   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9937   for (const CaseCluster &C : Clusters)
9938     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9939   for (unsigned i = 1; i < Clusters.size(); ++i)
9940     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9941 #endif
9942 
9943   // The algorithm below is not suitable for -O0.
9944   if (TM.getOptLevel() == CodeGenOpt::None)
9945     return;
9946 
9947   // If target does not have legal shift left, do not emit bit tests at all.
9948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9949   const DataLayout &DL = DAG.getDataLayout();
9950 
9951   EVT PTy = TLI.getPointerTy(DL);
9952   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9953     return;
9954 
9955   int BitWidth = PTy.getSizeInBits();
9956   const int64_t N = Clusters.size();
9957 
9958   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9959   SmallVector<unsigned, 8> MinPartitions(N);
9960   // LastElement[i] is the last element of the partition starting at i.
9961   SmallVector<unsigned, 8> LastElement(N);
9962 
9963   // FIXME: This might not be the best algorithm for finding bit test clusters.
9964 
9965   // Base case: There is only one way to partition Clusters[N-1].
9966   MinPartitions[N - 1] = 1;
9967   LastElement[N - 1] = N - 1;
9968 
9969   // Note: loop indexes are signed to avoid underflow.
9970   for (int64_t i = N - 2; i >= 0; --i) {
9971     // Find optimal partitioning of Clusters[i..N-1].
9972     // Baseline: Put Clusters[i] into a partition on its own.
9973     MinPartitions[i] = MinPartitions[i + 1] + 1;
9974     LastElement[i] = i;
9975 
9976     // Search for a solution that results in fewer partitions.
9977     // Note: the search is limited by BitWidth, reducing time complexity.
9978     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9979       // Try building a partition from Clusters[i..j].
9980 
9981       // Check the range.
9982       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9983                                Clusters[j].High->getValue(), DL))
9984         continue;
9985 
9986       // Check nbr of destinations and cluster types.
9987       // FIXME: This works, but doesn't seem very efficient.
9988       bool RangesOnly = true;
9989       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9990       for (int64_t k = i; k <= j; k++) {
9991         if (Clusters[k].Kind != CC_Range) {
9992           RangesOnly = false;
9993           break;
9994         }
9995         Dests.set(Clusters[k].MBB->getNumber());
9996       }
9997       if (!RangesOnly || Dests.count() > 3)
9998         break;
9999 
10000       // Check if it's a better partition.
10001       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10002       if (NumPartitions < MinPartitions[i]) {
10003         // Found a better partition.
10004         MinPartitions[i] = NumPartitions;
10005         LastElement[i] = j;
10006       }
10007     }
10008   }
10009 
10010   // Iterate over the partitions, replacing with bit-test clusters in-place.
10011   unsigned DstIndex = 0;
10012   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10013     Last = LastElement[First];
10014     assert(First <= Last);
10015     assert(DstIndex <= First);
10016 
10017     CaseCluster BitTestCluster;
10018     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10019       Clusters[DstIndex++] = BitTestCluster;
10020     } else {
10021       size_t NumClusters = Last - First + 1;
10022       std::memmove(&Clusters[DstIndex], &Clusters[First],
10023                    sizeof(Clusters[0]) * NumClusters);
10024       DstIndex += NumClusters;
10025     }
10026   }
10027   Clusters.resize(DstIndex);
10028 }
10029 
10030 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10031                                         MachineBasicBlock *SwitchMBB,
10032                                         MachineBasicBlock *DefaultMBB) {
10033   MachineFunction *CurMF = FuncInfo.MF;
10034   MachineBasicBlock *NextMBB = nullptr;
10035   MachineFunction::iterator BBI(W.MBB);
10036   if (++BBI != FuncInfo.MF->end())
10037     NextMBB = &*BBI;
10038 
10039   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10040 
10041   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10042 
10043   if (Size == 2 && W.MBB == SwitchMBB) {
10044     // If any two of the cases has the same destination, and if one value
10045     // is the same as the other, but has one bit unset that the other has set,
10046     // use bit manipulation to do two compares at once.  For example:
10047     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10048     // TODO: This could be extended to merge any 2 cases in switches with 3
10049     // cases.
10050     // TODO: Handle cases where W.CaseBB != SwitchBB.
10051     CaseCluster &Small = *W.FirstCluster;
10052     CaseCluster &Big = *W.LastCluster;
10053 
10054     if (Small.Low == Small.High && Big.Low == Big.High &&
10055         Small.MBB == Big.MBB) {
10056       const APInt &SmallValue = Small.Low->getValue();
10057       const APInt &BigValue = Big.Low->getValue();
10058 
10059       // Check that there is only one bit different.
10060       APInt CommonBit = BigValue ^ SmallValue;
10061       if (CommonBit.isPowerOf2()) {
10062         SDValue CondLHS = getValue(Cond);
10063         EVT VT = CondLHS.getValueType();
10064         SDLoc DL = getCurSDLoc();
10065 
10066         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10067                                  DAG.getConstant(CommonBit, DL, VT));
10068         SDValue Cond = DAG.getSetCC(
10069             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10070             ISD::SETEQ);
10071 
10072         // Update successor info.
10073         // Both Small and Big will jump to Small.BB, so we sum up the
10074         // probabilities.
10075         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10076         if (BPI)
10077           addSuccessorWithProb(
10078               SwitchMBB, DefaultMBB,
10079               // The default destination is the first successor in IR.
10080               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10081         else
10082           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10083 
10084         // Insert the true branch.
10085         SDValue BrCond =
10086             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10087                         DAG.getBasicBlock(Small.MBB));
10088         // Insert the false branch.
10089         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10090                              DAG.getBasicBlock(DefaultMBB));
10091 
10092         DAG.setRoot(BrCond);
10093         return;
10094       }
10095     }
10096   }
10097 
10098   if (TM.getOptLevel() != CodeGenOpt::None) {
10099     // Here, we order cases by probability so the most likely case will be
10100     // checked first. However, two clusters can have the same probability in
10101     // which case their relative ordering is non-deterministic. So we use Low
10102     // as a tie-breaker as clusters are guaranteed to never overlap.
10103     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10104                [](const CaseCluster &a, const CaseCluster &b) {
10105       return a.Prob != b.Prob ?
10106              a.Prob > b.Prob :
10107              a.Low->getValue().slt(b.Low->getValue());
10108     });
10109 
10110     // Rearrange the case blocks so that the last one falls through if possible
10111     // without changing the order of probabilities.
10112     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10113       --I;
10114       if (I->Prob > W.LastCluster->Prob)
10115         break;
10116       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10117         std::swap(*I, *W.LastCluster);
10118         break;
10119       }
10120     }
10121   }
10122 
10123   // Compute total probability.
10124   BranchProbability DefaultProb = W.DefaultProb;
10125   BranchProbability UnhandledProbs = DefaultProb;
10126   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10127     UnhandledProbs += I->Prob;
10128 
10129   MachineBasicBlock *CurMBB = W.MBB;
10130   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10131     MachineBasicBlock *Fallthrough;
10132     if (I == W.LastCluster) {
10133       // For the last cluster, fall through to the default destination.
10134       Fallthrough = DefaultMBB;
10135     } else {
10136       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10137       CurMF->insert(BBI, Fallthrough);
10138       // Put Cond in a virtual register to make it available from the new blocks.
10139       ExportFromCurrentBlock(Cond);
10140     }
10141     UnhandledProbs -= I->Prob;
10142 
10143     switch (I->Kind) {
10144       case CC_JumpTable: {
10145         // FIXME: Optimize away range check based on pivot comparisons.
10146         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10147         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10148 
10149         // The jump block hasn't been inserted yet; insert it here.
10150         MachineBasicBlock *JumpMBB = JT->MBB;
10151         CurMF->insert(BBI, JumpMBB);
10152 
10153         auto JumpProb = I->Prob;
10154         auto FallthroughProb = UnhandledProbs;
10155 
10156         // If the default statement is a target of the jump table, we evenly
10157         // distribute the default probability to successors of CurMBB. Also
10158         // update the probability on the edge from JumpMBB to Fallthrough.
10159         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10160                                               SE = JumpMBB->succ_end();
10161              SI != SE; ++SI) {
10162           if (*SI == DefaultMBB) {
10163             JumpProb += DefaultProb / 2;
10164             FallthroughProb -= DefaultProb / 2;
10165             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10166             JumpMBB->normalizeSuccProbs();
10167             break;
10168           }
10169         }
10170 
10171         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10172         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10173         CurMBB->normalizeSuccProbs();
10174 
10175         // The jump table header will be inserted in our current block, do the
10176         // range check, and fall through to our fallthrough block.
10177         JTH->HeaderBB = CurMBB;
10178         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10179 
10180         // If we're in the right place, emit the jump table header right now.
10181         if (CurMBB == SwitchMBB) {
10182           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10183           JTH->Emitted = true;
10184         }
10185         break;
10186       }
10187       case CC_BitTests: {
10188         // FIXME: Optimize away range check based on pivot comparisons.
10189         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10190 
10191         // The bit test blocks haven't been inserted yet; insert them here.
10192         for (BitTestCase &BTC : BTB->Cases)
10193           CurMF->insert(BBI, BTC.ThisBB);
10194 
10195         // Fill in fields of the BitTestBlock.
10196         BTB->Parent = CurMBB;
10197         BTB->Default = Fallthrough;
10198 
10199         BTB->DefaultProb = UnhandledProbs;
10200         // If the cases in bit test don't form a contiguous range, we evenly
10201         // distribute the probability on the edge to Fallthrough to two
10202         // successors of CurMBB.
10203         if (!BTB->ContiguousRange) {
10204           BTB->Prob += DefaultProb / 2;
10205           BTB->DefaultProb -= DefaultProb / 2;
10206         }
10207 
10208         // If we're in the right place, emit the bit test header right now.
10209         if (CurMBB == SwitchMBB) {
10210           visitBitTestHeader(*BTB, SwitchMBB);
10211           BTB->Emitted = true;
10212         }
10213         break;
10214       }
10215       case CC_Range: {
10216         const Value *RHS, *LHS, *MHS;
10217         ISD::CondCode CC;
10218         if (I->Low == I->High) {
10219           // Check Cond == I->Low.
10220           CC = ISD::SETEQ;
10221           LHS = Cond;
10222           RHS=I->Low;
10223           MHS = nullptr;
10224         } else {
10225           // Check I->Low <= Cond <= I->High.
10226           CC = ISD::SETLE;
10227           LHS = I->Low;
10228           MHS = Cond;
10229           RHS = I->High;
10230         }
10231 
10232         // The false probability is the sum of all unhandled cases.
10233         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10234                      getCurSDLoc(), I->Prob, UnhandledProbs);
10235 
10236         if (CurMBB == SwitchMBB)
10237           visitSwitchCase(CB, SwitchMBB);
10238         else
10239           SwitchCases.push_back(CB);
10240 
10241         break;
10242       }
10243     }
10244     CurMBB = Fallthrough;
10245   }
10246 }
10247 
10248 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10249                                               CaseClusterIt First,
10250                                               CaseClusterIt Last) {
10251   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10252     if (X.Prob != CC.Prob)
10253       return X.Prob > CC.Prob;
10254 
10255     // Ties are broken by comparing the case value.
10256     return X.Low->getValue().slt(CC.Low->getValue());
10257   });
10258 }
10259 
10260 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10261                                         const SwitchWorkListItem &W,
10262                                         Value *Cond,
10263                                         MachineBasicBlock *SwitchMBB) {
10264   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10265          "Clusters not sorted?");
10266 
10267   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10268 
10269   // Balance the tree based on branch probabilities to create a near-optimal (in
10270   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10271   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10272   CaseClusterIt LastLeft = W.FirstCluster;
10273   CaseClusterIt FirstRight = W.LastCluster;
10274   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10275   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10276 
10277   // Move LastLeft and FirstRight towards each other from opposite directions to
10278   // find a partitioning of the clusters which balances the probability on both
10279   // sides. If LeftProb and RightProb are equal, alternate which side is
10280   // taken to ensure 0-probability nodes are distributed evenly.
10281   unsigned I = 0;
10282   while (LastLeft + 1 < FirstRight) {
10283     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10284       LeftProb += (++LastLeft)->Prob;
10285     else
10286       RightProb += (--FirstRight)->Prob;
10287     I++;
10288   }
10289 
10290   while (true) {
10291     // Our binary search tree differs from a typical BST in that ours can have up
10292     // to three values in each leaf. The pivot selection above doesn't take that
10293     // into account, which means the tree might require more nodes and be less
10294     // efficient. We compensate for this here.
10295 
10296     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10297     unsigned NumRight = W.LastCluster - FirstRight + 1;
10298 
10299     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10300       // If one side has less than 3 clusters, and the other has more than 3,
10301       // consider taking a cluster from the other side.
10302 
10303       if (NumLeft < NumRight) {
10304         // Consider moving the first cluster on the right to the left side.
10305         CaseCluster &CC = *FirstRight;
10306         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10307         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10308         if (LeftSideRank <= RightSideRank) {
10309           // Moving the cluster to the left does not demote it.
10310           ++LastLeft;
10311           ++FirstRight;
10312           continue;
10313         }
10314       } else {
10315         assert(NumRight < NumLeft);
10316         // Consider moving the last element on the left to the right side.
10317         CaseCluster &CC = *LastLeft;
10318         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10319         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10320         if (RightSideRank <= LeftSideRank) {
10321           // Moving the cluster to the right does not demot it.
10322           --LastLeft;
10323           --FirstRight;
10324           continue;
10325         }
10326       }
10327     }
10328     break;
10329   }
10330 
10331   assert(LastLeft + 1 == FirstRight);
10332   assert(LastLeft >= W.FirstCluster);
10333   assert(FirstRight <= W.LastCluster);
10334 
10335   // Use the first element on the right as pivot since we will make less-than
10336   // comparisons against it.
10337   CaseClusterIt PivotCluster = FirstRight;
10338   assert(PivotCluster > W.FirstCluster);
10339   assert(PivotCluster <= W.LastCluster);
10340 
10341   CaseClusterIt FirstLeft = W.FirstCluster;
10342   CaseClusterIt LastRight = W.LastCluster;
10343 
10344   const ConstantInt *Pivot = PivotCluster->Low;
10345 
10346   // New blocks will be inserted immediately after the current one.
10347   MachineFunction::iterator BBI(W.MBB);
10348   ++BBI;
10349 
10350   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10351   // we can branch to its destination directly if it's squeezed exactly in
10352   // between the known lower bound and Pivot - 1.
10353   MachineBasicBlock *LeftMBB;
10354   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10355       FirstLeft->Low == W.GE &&
10356       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10357     LeftMBB = FirstLeft->MBB;
10358   } else {
10359     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10360     FuncInfo.MF->insert(BBI, LeftMBB);
10361     WorkList.push_back(
10362         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10363     // Put Cond in a virtual register to make it available from the new blocks.
10364     ExportFromCurrentBlock(Cond);
10365   }
10366 
10367   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10368   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10369   // directly if RHS.High equals the current upper bound.
10370   MachineBasicBlock *RightMBB;
10371   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10372       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10373     RightMBB = FirstRight->MBB;
10374   } else {
10375     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10376     FuncInfo.MF->insert(BBI, RightMBB);
10377     WorkList.push_back(
10378         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10379     // Put Cond in a virtual register to make it available from the new blocks.
10380     ExportFromCurrentBlock(Cond);
10381   }
10382 
10383   // Create the CaseBlock record that will be used to lower the branch.
10384   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10385                getCurSDLoc(), LeftProb, RightProb);
10386 
10387   if (W.MBB == SwitchMBB)
10388     visitSwitchCase(CB, SwitchMBB);
10389   else
10390     SwitchCases.push_back(CB);
10391 }
10392 
10393 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10394 // from the swith statement.
10395 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10396                                             BranchProbability PeeledCaseProb) {
10397   if (PeeledCaseProb == BranchProbability::getOne())
10398     return BranchProbability::getZero();
10399   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10400 
10401   uint32_t Numerator = CaseProb.getNumerator();
10402   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10403   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10404 }
10405 
10406 // Try to peel the top probability case if it exceeds the threshold.
10407 // Return current MachineBasicBlock for the switch statement if the peeling
10408 // does not occur.
10409 // If the peeling is performed, return the newly created MachineBasicBlock
10410 // for the peeled switch statement. Also update Clusters to remove the peeled
10411 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10412 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10413     const SwitchInst &SI, CaseClusterVector &Clusters,
10414     BranchProbability &PeeledCaseProb) {
10415   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10416   // Don't perform if there is only one cluster or optimizing for size.
10417   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10418       TM.getOptLevel() == CodeGenOpt::None ||
10419       SwitchMBB->getParent()->getFunction().optForMinSize())
10420     return SwitchMBB;
10421 
10422   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10423   unsigned PeeledCaseIndex = 0;
10424   bool SwitchPeeled = false;
10425   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10426     CaseCluster &CC = Clusters[Index];
10427     if (CC.Prob < TopCaseProb)
10428       continue;
10429     TopCaseProb = CC.Prob;
10430     PeeledCaseIndex = Index;
10431     SwitchPeeled = true;
10432   }
10433   if (!SwitchPeeled)
10434     return SwitchMBB;
10435 
10436   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10437                     << TopCaseProb << "\n");
10438 
10439   // Record the MBB for the peeled switch statement.
10440   MachineFunction::iterator BBI(SwitchMBB);
10441   ++BBI;
10442   MachineBasicBlock *PeeledSwitchMBB =
10443       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10444   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10445 
10446   ExportFromCurrentBlock(SI.getCondition());
10447   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10448   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10449                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10450   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10451 
10452   Clusters.erase(PeeledCaseIt);
10453   for (CaseCluster &CC : Clusters) {
10454     LLVM_DEBUG(
10455         dbgs() << "Scale the probablity for one cluster, before scaling: "
10456                << CC.Prob << "\n");
10457     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10458     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10459   }
10460   PeeledCaseProb = TopCaseProb;
10461   return PeeledSwitchMBB;
10462 }
10463 
10464 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10465   // Extract cases from the switch.
10466   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10467   CaseClusterVector Clusters;
10468   Clusters.reserve(SI.getNumCases());
10469   for (auto I : SI.cases()) {
10470     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10471     const ConstantInt *CaseVal = I.getCaseValue();
10472     BranchProbability Prob =
10473         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10474             : BranchProbability(1, SI.getNumCases() + 1);
10475     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10476   }
10477 
10478   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10479 
10480   // Cluster adjacent cases with the same destination. We do this at all
10481   // optimization levels because it's cheap to do and will make codegen faster
10482   // if there are many clusters.
10483   sortAndRangeify(Clusters);
10484 
10485   if (TM.getOptLevel() != CodeGenOpt::None) {
10486     // Replace an unreachable default with the most popular destination.
10487     // FIXME: Exploit unreachable default more aggressively.
10488     bool UnreachableDefault =
10489         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10490     if (UnreachableDefault && !Clusters.empty()) {
10491       DenseMap<const BasicBlock *, unsigned> Popularity;
10492       unsigned MaxPop = 0;
10493       const BasicBlock *MaxBB = nullptr;
10494       for (auto I : SI.cases()) {
10495         const BasicBlock *BB = I.getCaseSuccessor();
10496         if (++Popularity[BB] > MaxPop) {
10497           MaxPop = Popularity[BB];
10498           MaxBB = BB;
10499         }
10500       }
10501       // Set new default.
10502       assert(MaxPop > 0 && MaxBB);
10503       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10504 
10505       // Remove cases that were pointing to the destination that is now the
10506       // default.
10507       CaseClusterVector New;
10508       New.reserve(Clusters.size());
10509       for (CaseCluster &CC : Clusters) {
10510         if (CC.MBB != DefaultMBB)
10511           New.push_back(CC);
10512       }
10513       Clusters = std::move(New);
10514     }
10515   }
10516 
10517   // The branch probablity of the peeled case.
10518   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10519   MachineBasicBlock *PeeledSwitchMBB =
10520       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10521 
10522   // If there is only the default destination, jump there directly.
10523   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10524   if (Clusters.empty()) {
10525     assert(PeeledSwitchMBB == SwitchMBB);
10526     SwitchMBB->addSuccessor(DefaultMBB);
10527     if (DefaultMBB != NextBlock(SwitchMBB)) {
10528       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10529                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10530     }
10531     return;
10532   }
10533 
10534   findJumpTables(Clusters, &SI, DefaultMBB);
10535   findBitTestClusters(Clusters, &SI);
10536 
10537   LLVM_DEBUG({
10538     dbgs() << "Case clusters: ";
10539     for (const CaseCluster &C : Clusters) {
10540       if (C.Kind == CC_JumpTable)
10541         dbgs() << "JT:";
10542       if (C.Kind == CC_BitTests)
10543         dbgs() << "BT:";
10544 
10545       C.Low->getValue().print(dbgs(), true);
10546       if (C.Low != C.High) {
10547         dbgs() << '-';
10548         C.High->getValue().print(dbgs(), true);
10549       }
10550       dbgs() << ' ';
10551     }
10552     dbgs() << '\n';
10553   });
10554 
10555   assert(!Clusters.empty());
10556   SwitchWorkList WorkList;
10557   CaseClusterIt First = Clusters.begin();
10558   CaseClusterIt Last = Clusters.end() - 1;
10559   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10560   // Scale the branchprobability for DefaultMBB if the peel occurs and
10561   // DefaultMBB is not replaced.
10562   if (PeeledCaseProb != BranchProbability::getZero() &&
10563       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10564     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10565   WorkList.push_back(
10566       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10567 
10568   while (!WorkList.empty()) {
10569     SwitchWorkListItem W = WorkList.back();
10570     WorkList.pop_back();
10571     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10572 
10573     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10574         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10575       // For optimized builds, lower large range as a balanced binary tree.
10576       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10577       continue;
10578     }
10579 
10580     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10581   }
10582 }
10583