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