xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4892f06e06cc5c987dfb77bfe13a91e1b1b00524)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 using namespace PatternMatch;
125 
126 #define DEBUG_TYPE "isel"
127 
128 /// LimitFloatPrecision - Generate low-precision inline sequences for
129 /// some float libcalls (6, 8 or 12 bits).
130 static unsigned LimitFloatPrecision;
131 
132 static cl::opt<unsigned, true>
133     LimitFPPrecision("limit-float-precision",
134                      cl::desc("Generate low-precision inline sequences "
135                               "for some float libcalls"),
136                      cl::location(LimitFloatPrecision), cl::Hidden,
137                      cl::init(0));
138 
139 static cl::opt<unsigned> SwitchPeelThreshold(
140     "switch-peel-threshold", cl::Hidden, cl::init(66),
141     cl::desc("Set the case probability threshold for peeling the case from a "
142              "switch statement. A value greater than 100 will void this "
143              "optimization"));
144 
145 // Limit the width of DAG chains. This is important in general to prevent
146 // DAG-based analysis from blowing up. For example, alias analysis and
147 // load clustering may not complete in reasonable time. It is difficult to
148 // recognize and avoid this situation within each individual analysis, and
149 // future analyses are likely to have the same behavior. Limiting DAG width is
150 // the safe approach and will be especially important with global DAGs.
151 //
152 // MaxParallelChains default is arbitrarily high to avoid affecting
153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
154 // sequence over this should have been converted to llvm.memcpy by the
155 // frontend. It is easy to induce this behavior with .ll code such as:
156 // %buffer = alloca [4096 x i8]
157 // %data = load [4096 x i8]* %argPtr
158 // store [4096 x i8] %data, [4096 x i8]* %buffer
159 static const unsigned MaxParallelChains = 64;
160 
161 // Return the calling convention if the Value passed requires ABI mangling as it
162 // is a parameter to a function or a return value from a function which is not
163 // an intrinsic.
164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
165   if (auto *R = dyn_cast<ReturnInst>(V))
166     return R->getParent()->getParent()->getCallingConv();
167 
168   if (auto *CI = dyn_cast<CallInst>(V)) {
169     const bool IsInlineAsm = CI->isInlineAsm();
170     const bool IsIndirectFunctionCall =
171         !IsInlineAsm && !CI->getCalledFunction();
172 
173     // It is possible that the call instruction is an inline asm statement or an
174     // indirect function call in which case the return value of
175     // getCalledFunction() would be nullptr.
176     const bool IsInstrinsicCall =
177         !IsInlineAsm && !IsIndirectFunctionCall &&
178         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
179 
180     if (!IsInlineAsm && !IsInstrinsicCall)
181       return CI->getCallingConv();
182   }
183 
184   return None;
185 }
186 
187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
188                                       const SDValue *Parts, unsigned NumParts,
189                                       MVT PartVT, EVT ValueVT, const Value *V,
190                                       Optional<CallingConv::ID> CC);
191 
192 /// getCopyFromParts - Create a value that contains the specified legal parts
193 /// combined into the value they represent.  If the parts combine to a type
194 /// larger than ValueVT then AssertOp can be used to specify whether the extra
195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
196 /// (ISD::AssertSext).
197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
198                                 const SDValue *Parts, unsigned NumParts,
199                                 MVT PartVT, EVT ValueVT, const Value *V,
200                                 Optional<CallingConv::ID> CC = None,
201                                 Optional<ISD::NodeType> AssertOp = None) {
202   if (ValueVT.isVector())
203     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
204                                   CC);
205 
206   assert(NumParts > 0 && "No parts to assemble!");
207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
208   SDValue Val = Parts[0];
209 
210   if (NumParts > 1) {
211     // Assemble the value from multiple parts.
212     if (ValueVT.isInteger()) {
213       unsigned PartBits = PartVT.getSizeInBits();
214       unsigned ValueBits = ValueVT.getSizeInBits();
215 
216       // Assemble the power of 2 part.
217       unsigned RoundParts = NumParts & (NumParts - 1) ?
218         1 << Log2_32(NumParts) : NumParts;
219       unsigned RoundBits = PartBits * RoundParts;
220       EVT RoundVT = RoundBits == ValueBits ?
221         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
222       SDValue Lo, Hi;
223 
224       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
225 
226       if (RoundParts > 2) {
227         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
228                               PartVT, HalfVT, V);
229         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
230                               RoundParts / 2, PartVT, HalfVT, V);
231       } else {
232         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
233         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
234       }
235 
236       if (DAG.getDataLayout().isBigEndian())
237         std::swap(Lo, Hi);
238 
239       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
240 
241       if (RoundParts < NumParts) {
242         // Assemble the trailing non-power-of-2 part.
243         unsigned OddParts = NumParts - RoundParts;
244         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
246                               OddVT, V, CC);
247 
248         // Combine the round and odd parts.
249         Lo = Val;
250         if (DAG.getDataLayout().isBigEndian())
251           std::swap(Lo, Hi);
252         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
253         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
254         Hi =
255             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
256                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
257                                         TLI.getPointerTy(DAG.getDataLayout())));
258         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
259         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
260       }
261     } else if (PartVT.isFloatingPoint()) {
262       // FP split into multiple FP parts (for ppcf128)
263       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
264              "Unexpected split");
265       SDValue Lo, Hi;
266       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
267       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
268       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
269         std::swap(Lo, Hi);
270       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
271     } else {
272       // FP split into integer parts (soft fp)
273       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
274              !PartVT.isVector() && "Unexpected split");
275       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
276       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
277     }
278   }
279 
280   // There is now one part, held in Val.  Correct it to match ValueVT.
281   // PartEVT is the type of the register class that holds the value.
282   // ValueVT is the type of the inline asm operation.
283   EVT PartEVT = Val.getValueType();
284 
285   if (PartEVT == ValueVT)
286     return Val;
287 
288   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
289       ValueVT.bitsLT(PartEVT)) {
290     // For an FP value in an integer part, we need to truncate to the right
291     // width first.
292     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
293     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
294   }
295 
296   // Handle types that have the same size.
297   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
298     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
299 
300   // Handle types with different sizes.
301   if (PartEVT.isInteger() && ValueVT.isInteger()) {
302     if (ValueVT.bitsLT(PartEVT)) {
303       // For a truncate, see if we have any information to
304       // indicate whether the truncated bits will always be
305       // zero or sign-extension.
306       if (AssertOp.hasValue())
307         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
308                           DAG.getValueType(ValueVT));
309       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
310     }
311     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
312   }
313 
314   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
315     // FP_ROUND's are always exact here.
316     if (ValueVT.bitsLT(Val.getValueType()))
317       return DAG.getNode(
318           ISD::FP_ROUND, DL, ValueVT, Val,
319           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
320 
321     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
322   }
323 
324   llvm_unreachable("Unknown mismatch!");
325 }
326 
327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
328                                               const Twine &ErrMsg) {
329   const Instruction *I = dyn_cast_or_null<Instruction>(V);
330   if (!V)
331     return Ctx.emitError(ErrMsg);
332 
333   const char *AsmError = ", possible invalid constraint for vector type";
334   if (const CallInst *CI = dyn_cast<CallInst>(I))
335     if (isa<InlineAsm>(CI->getCalledValue()))
336       return Ctx.emitError(I, ErrMsg + AsmError);
337 
338   return Ctx.emitError(I, ErrMsg);
339 }
340 
341 /// getCopyFromPartsVector - Create a value that contains the specified legal
342 /// parts combined into the value they represent.  If the parts combine to a
343 /// type larger than ValueVT then AssertOp can be used to specify whether the
344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
345 /// ValueVT (ISD::AssertSext).
346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
347                                       const SDValue *Parts, unsigned NumParts,
348                                       MVT PartVT, EVT ValueVT, const Value *V,
349                                       Optional<CallingConv::ID> CallConv) {
350   assert(ValueVT.isVector() && "Not a vector value");
351   assert(NumParts > 0 && "No parts to assemble!");
352   const bool IsABIRegCopy = CallConv.hasValue();
353 
354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
355   SDValue Val = Parts[0];
356 
357   // Handle a multi-element vector.
358   if (NumParts > 1) {
359     EVT IntermediateVT;
360     MVT RegisterVT;
361     unsigned NumIntermediates;
362     unsigned NumRegs;
363 
364     if (IsABIRegCopy) {
365       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
366           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
367           NumIntermediates, RegisterVT);
368     } else {
369       NumRegs =
370           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
371                                      NumIntermediates, RegisterVT);
372     }
373 
374     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
375     NumParts = NumRegs; // Silence a compiler warning.
376     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
377     assert(RegisterVT.getSizeInBits() ==
378            Parts[0].getSimpleValueType().getSizeInBits() &&
379            "Part type sizes don't match!");
380 
381     // Assemble the parts into intermediate operands.
382     SmallVector<SDValue, 8> Ops(NumIntermediates);
383     if (NumIntermediates == NumParts) {
384       // If the register was not expanded, truncate or copy the value,
385       // as appropriate.
386       for (unsigned i = 0; i != NumParts; ++i)
387         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
388                                   PartVT, IntermediateVT, V);
389     } else if (NumParts > 0) {
390       // If the intermediate type was expanded, build the intermediate
391       // operands from the parts.
392       assert(NumParts % NumIntermediates == 0 &&
393              "Must expand into a divisible number of parts!");
394       unsigned Factor = NumParts / NumIntermediates;
395       for (unsigned i = 0; i != NumIntermediates; ++i)
396         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
397                                   PartVT, IntermediateVT, V);
398     }
399 
400     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
401     // intermediate operands.
402     EVT BuiltVectorTy =
403         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
404                          (IntermediateVT.isVector()
405                               ? IntermediateVT.getVectorNumElements() * NumParts
406                               : NumIntermediates));
407     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
408                                                 : ISD::BUILD_VECTOR,
409                       DL, BuiltVectorTy, Ops);
410   }
411 
412   // There is now one part, held in Val.  Correct it to match ValueVT.
413   EVT PartEVT = Val.getValueType();
414 
415   if (PartEVT == ValueVT)
416     return Val;
417 
418   if (PartEVT.isVector()) {
419     // If the element type of the source/dest vectors are the same, but the
420     // parts vector has more elements than the value vector, then we have a
421     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
422     // elements we want.
423     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
424       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
425              "Cannot narrow, it would be a lossy transformation");
426       return DAG.getNode(
427           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
428           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
429     }
430 
431     // Vector/Vector bitcast.
432     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
433       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434 
435     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
436       "Cannot handle this kind of promotion");
437     // Promoted vector extract
438     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
439 
440   }
441 
442   // Trivial bitcast if the types are the same size and the destination
443   // vector type is legal.
444   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
445       TLI.isTypeLegal(ValueVT))
446     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
447 
448   if (ValueVT.getVectorNumElements() != 1) {
449      // Certain ABIs require that vectors are passed as integers. For vectors
450      // are the same size, this is an obvious bitcast.
451      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
452        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
454        // Bitcast Val back the original type and extract the corresponding
455        // vector we want.
456        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
457        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
458                                            ValueVT.getVectorElementType(), Elts);
459        Val = DAG.getBitcast(WiderVecType, Val);
460        return DAG.getNode(
461            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
462            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
463      }
464 
465      diagnosePossiblyInvalidConstraint(
466          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
467      return DAG.getUNDEF(ValueVT);
468   }
469 
470   // Handle cases such as i8 -> <1 x i1>
471   EVT ValueSVT = ValueVT.getVectorElementType();
472   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
473     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
474                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
475 
476   return DAG.getBuildVector(ValueVT, DL, Val);
477 }
478 
479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
480                                  SDValue Val, SDValue *Parts, unsigned NumParts,
481                                  MVT PartVT, const Value *V,
482                                  Optional<CallingConv::ID> CallConv);
483 
484 /// getCopyToParts - Create a series of nodes that contain the specified value
485 /// split into legal parts.  If the parts contain more bits than Val, then, for
486 /// integers, ExtendKind can be used to specify how to generate the extra bits.
487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
488                            SDValue *Parts, unsigned NumParts, MVT PartVT,
489                            const Value *V,
490                            Optional<CallingConv::ID> CallConv = None,
491                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned PartBits = PartVT.getSizeInBits();
500   unsigned OrigNumParts = NumParts;
501   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
502          "Copying to an illegal type!");
503 
504   if (NumParts == 0)
505     return;
506 
507   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
508   EVT PartEVT = PartVT;
509   if (PartEVT == ValueVT) {
510     assert(NumParts == 1 && "No-op copy with multiple parts!");
511     Parts[0] = Val;
512     return;
513   }
514 
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = 1 << Log2_32(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575                                  DAG.getIntPtrConstant(RoundBits, DL));
576     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577                    CallConv);
578 
579     if (DAG.getDataLayout().isBigEndian())
580       // The odd parts were reversed by getCopyToParts - unreverse them.
581       std::reverse(Parts + RoundParts, Parts + NumParts);
582 
583     NumParts = RoundParts;
584     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586   }
587 
588   // The number of parts is a power of 2.  Repeatedly bisect the value using
589   // EXTRACT_ELEMENT.
590   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591                          EVT::getIntegerVT(*DAG.getContext(),
592                                            ValueVT.getSizeInBits()),
593                          Val);
594 
595   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596     for (unsigned i = 0; i < NumParts; i += StepSize) {
597       unsigned ThisBits = StepSize * PartBits / 2;
598       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599       SDValue &Part0 = Parts[i];
600       SDValue &Part1 = Parts[i+StepSize/2];
601 
602       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606 
607       if (ThisBits == PartBits && ThisVT != PartVT) {
608         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610       }
611     }
612   }
613 
614   if (DAG.getDataLayout().isBigEndian())
615     std::reverse(Parts, Parts + OrigNumParts);
616 }
617 
618 static SDValue widenVectorToPartType(SelectionDAG &DAG,
619                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
620   if (!PartVT.isVector())
621     return SDValue();
622 
623   EVT ValueVT = Val.getValueType();
624   unsigned PartNumElts = PartVT.getVectorNumElements();
625   unsigned ValueNumElts = ValueVT.getVectorNumElements();
626   if (PartNumElts > ValueNumElts &&
627       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
628     EVT ElementVT = PartVT.getVectorElementType();
629     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630     // undef elements.
631     SmallVector<SDValue, 16> Ops;
632     DAG.ExtractVectorElements(Val, Ops);
633     SDValue EltUndef = DAG.getUNDEF(ElementVT);
634     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
635       Ops.push_back(EltUndef);
636 
637     // FIXME: Use CONCAT for 2x -> 4x.
638     return DAG.getBuildVector(PartVT, DL, Ops);
639   }
640 
641   return SDValue();
642 }
643 
644 /// getCopyToPartsVector - Create a series of nodes that contain the specified
645 /// value split into legal parts.
646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
647                                  SDValue Val, SDValue *Parts, unsigned NumParts,
648                                  MVT PartVT, const Value *V,
649                                  Optional<CallingConv::ID> CallConv) {
650   EVT ValueVT = Val.getValueType();
651   assert(ValueVT.isVector() && "Not a vector");
652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
653   const bool IsABIRegCopy = CallConv.hasValue();
654 
655   if (NumParts == 1) {
656     EVT PartEVT = PartVT;
657     if (PartEVT == ValueVT) {
658       // Nothing to do.
659     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
660       // Bitconvert vector->vector case.
661       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
662     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
663       Val = Widened;
664     } else if (PartVT.isVector() &&
665                PartEVT.getVectorElementType().bitsGE(
666                  ValueVT.getVectorElementType()) &&
667                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
668 
669       // Promoted vector extract
670       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
671     } else {
672       if (ValueVT.getVectorNumElements() == 1) {
673         Val = DAG.getNode(
674             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
675             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
676       } else {
677         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
678                "lossy conversion of vector to scalar type");
679         EVT IntermediateType =
680             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
681         Val = DAG.getBitcast(IntermediateType, Val);
682         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683       }
684     }
685 
686     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
687     Parts[0] = Val;
688     return;
689   }
690 
691   // Handle a multi-element vector.
692   EVT IntermediateVT;
693   MVT RegisterVT;
694   unsigned NumIntermediates;
695   unsigned NumRegs;
696   if (IsABIRegCopy) {
697     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
698         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
699         NumIntermediates, RegisterVT);
700   } else {
701     NumRegs =
702         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
703                                    NumIntermediates, RegisterVT);
704   }
705 
706   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
707   NumParts = NumRegs; // Silence a compiler warning.
708   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
709 
710   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
711     IntermediateVT.getVectorNumElements() : 1;
712 
713   // Convert the vector to the appropiate type if necessary.
714   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
715 
716   EVT BuiltVectorTy = EVT::getVectorVT(
717       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
718   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
719   if (ValueVT != BuiltVectorTy) {
720     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
721       Val = Widened;
722 
723     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
724   }
725 
726   // Split the vector into intermediate operands.
727   SmallVector<SDValue, 8> Ops(NumIntermediates);
728   for (unsigned i = 0; i != NumIntermediates; ++i) {
729     if (IntermediateVT.isVector()) {
730       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
731                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
732     } else {
733       Ops[i] = DAG.getNode(
734           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
735           DAG.getConstant(i, DL, IdxVT));
736     }
737   }
738 
739   // Split the intermediate operands into legal parts.
740   if (NumParts == NumIntermediates) {
741     // If the register was not expanded, promote or copy the value,
742     // as appropriate.
743     for (unsigned i = 0; i != NumParts; ++i)
744       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
745   } else if (NumParts > 0) {
746     // If the intermediate type was expanded, split each the value into
747     // legal parts.
748     assert(NumIntermediates != 0 && "division by zero");
749     assert(NumParts % NumIntermediates == 0 &&
750            "Must expand into a divisible number of parts!");
751     unsigned Factor = NumParts / NumIntermediates;
752     for (unsigned i = 0; i != NumIntermediates; ++i)
753       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
754                      CallConv);
755   }
756 }
757 
758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
759                            EVT valuevt, Optional<CallingConv::ID> CC)
760     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
761       RegCount(1, regs.size()), CallConv(CC) {}
762 
763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
764                            const DataLayout &DL, unsigned Reg, Type *Ty,
765                            Optional<CallingConv::ID> CC) {
766   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
767 
768   CallConv = CC;
769 
770   for (EVT ValueVT : ValueVTs) {
771     unsigned NumRegs =
772         isABIMangled()
773             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
774             : TLI.getNumRegisters(Context, ValueVT);
775     MVT RegisterVT =
776         isABIMangled()
777             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
778             : TLI.getRegisterType(Context, ValueVT);
779     for (unsigned i = 0; i != NumRegs; ++i)
780       Regs.push_back(Reg + i);
781     RegVTs.push_back(RegisterVT);
782     RegCount.push_back(NumRegs);
783     Reg += NumRegs;
784   }
785 }
786 
787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
788                                       FunctionLoweringInfo &FuncInfo,
789                                       const SDLoc &dl, SDValue &Chain,
790                                       SDValue *Flag, const Value *V) const {
791   // A Value with type {} or [0 x %t] needs no registers.
792   if (ValueVTs.empty())
793     return SDValue();
794 
795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
796 
797   // Assemble the legal parts into the final values.
798   SmallVector<SDValue, 4> Values(ValueVTs.size());
799   SmallVector<SDValue, 8> Parts;
800   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
801     // Copy the legal parts from the registers.
802     EVT ValueVT = ValueVTs[Value];
803     unsigned NumRegs = RegCount[Value];
804     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
805                                           *DAG.getContext(),
806                                           CallConv.getValue(), RegVTs[Value])
807                                     : RegVTs[Value];
808 
809     Parts.resize(NumRegs);
810     for (unsigned i = 0; i != NumRegs; ++i) {
811       SDValue P;
812       if (!Flag) {
813         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
814       } else {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
816         *Flag = P.getValue(2);
817       }
818 
819       Chain = P.getValue(1);
820       Parts[i] = P;
821 
822       // If the source register was virtual and if we know something about it,
823       // add an assert node.
824       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
825           !RegisterVT.isInteger())
826         continue;
827 
828       const FunctionLoweringInfo::LiveOutInfo *LOI =
829         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
830       if (!LOI)
831         continue;
832 
833       unsigned RegSize = RegisterVT.getScalarSizeInBits();
834       unsigned NumSignBits = LOI->NumSignBits;
835       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
836 
837       if (NumZeroBits == RegSize) {
838         // The current value is a zero.
839         // Explicitly express that as it would be easier for
840         // optimizations to kick in.
841         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
842         continue;
843       }
844 
845       // FIXME: We capture more information than the dag can represent.  For
846       // now, just use the tightest assertzext/assertsext possible.
847       bool isSExt;
848       EVT FromVT(MVT::Other);
849       if (NumZeroBits) {
850         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
851         isSExt = false;
852       } else if (NumSignBits > 1) {
853         FromVT =
854             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
855         isSExt = true;
856       } else {
857         continue;
858       }
859       // Add an assertion node.
860       assert(FromVT != MVT::Other);
861       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
862                              RegisterVT, P, DAG.getValueType(FromVT));
863     }
864 
865     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
866                                      RegisterVT, ValueVT, V, CallConv);
867     Part += NumRegs;
868     Parts.clear();
869   }
870 
871   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
872 }
873 
874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
875                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
876                                  const Value *V,
877                                  ISD::NodeType PreferredExtendType) const {
878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
879   ISD::NodeType ExtendKind = PreferredExtendType;
880 
881   // Get the list of the values's legal parts.
882   unsigned NumRegs = Regs.size();
883   SmallVector<SDValue, 8> Parts(NumRegs);
884   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
885     unsigned NumParts = RegCount[Value];
886 
887     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
888                                           *DAG.getContext(),
889                                           CallConv.getValue(), RegVTs[Value])
890                                     : RegVTs[Value];
891 
892     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
893       ExtendKind = ISD::ZERO_EXTEND;
894 
895     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
896                    NumParts, RegisterVT, V, CallConv, ExtendKind);
897     Part += NumParts;
898   }
899 
900   // Copy the parts into the registers.
901   SmallVector<SDValue, 8> Chains(NumRegs);
902   for (unsigned i = 0; i != NumRegs; ++i) {
903     SDValue Part;
904     if (!Flag) {
905       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
906     } else {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
908       *Flag = Part.getValue(1);
909     }
910 
911     Chains[i] = Part.getValue(0);
912   }
913 
914   if (NumRegs == 1 || Flag)
915     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
916     // flagged to it. That is the CopyToReg nodes and the user are considered
917     // a single scheduling unit. If we create a TokenFactor and return it as
918     // chain, then the TokenFactor is both a predecessor (operand) of the
919     // user as well as a successor (the TF operands are flagged to the user).
920     // c1, f1 = CopyToReg
921     // c2, f2 = CopyToReg
922     // c3     = TokenFactor c1, c2
923     // ...
924     //        = op c3, ..., f2
925     Chain = Chains[NumRegs-1];
926   else
927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
928 }
929 
930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
931                                         unsigned MatchingIdx, const SDLoc &dl,
932                                         SelectionDAG &DAG,
933                                         std::vector<SDValue> &Ops) const {
934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
935 
936   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
937   if (HasMatching)
938     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
939   else if (!Regs.empty() &&
940            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, unsigned>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     unsigned RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005 }
1006 
1007 void SelectionDAGBuilder::clear() {
1008   NodeMap.clear();
1009   UnusedArgNodeMap.clear();
1010   PendingLoads.clear();
1011   PendingExports.clear();
1012   CurInst = nullptr;
1013   HasTailCall = false;
1014   SDNodeOrder = LowestSDNodeOrder;
1015   StatepointLowering.clear();
1016 }
1017 
1018 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1019   DanglingDebugInfoMap.clear();
1020 }
1021 
1022 SDValue SelectionDAGBuilder::getRoot() {
1023   if (PendingLoads.empty())
1024     return DAG.getRoot();
1025 
1026   if (PendingLoads.size() == 1) {
1027     SDValue Root = PendingLoads[0];
1028     DAG.setRoot(Root);
1029     PendingLoads.clear();
1030     return Root;
1031   }
1032 
1033   // Otherwise, we have to make a token factor node.
1034   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1035   PendingLoads.clear();
1036   DAG.setRoot(Root);
1037   return Root;
1038 }
1039 
1040 SDValue SelectionDAGBuilder::getControlRoot() {
1041   SDValue Root = DAG.getRoot();
1042 
1043   if (PendingExports.empty())
1044     return Root;
1045 
1046   // Turn all of the CopyToReg chains into one factored node.
1047   if (Root.getOpcode() != ISD::EntryToken) {
1048     unsigned i = 0, e = PendingExports.size();
1049     for (; i != e; ++i) {
1050       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1051       if (PendingExports[i].getNode()->getOperand(0) == Root)
1052         break;  // Don't add the root if we already indirectly depend on it.
1053     }
1054 
1055     if (i == e)
1056       PendingExports.push_back(Root);
1057   }
1058 
1059   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1060                      PendingExports);
1061   PendingExports.clear();
1062   DAG.setRoot(Root);
1063   return Root;
1064 }
1065 
1066 void SelectionDAGBuilder::visit(const Instruction &I) {
1067   // Set up outgoing PHI node register values before emitting the terminator.
1068   if (I.isTerminator()) {
1069     HandlePHINodesInSuccessorBlocks(I.getParent());
1070   }
1071 
1072   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1073   if (!isa<DbgInfoIntrinsic>(I))
1074     ++SDNodeOrder;
1075 
1076   CurInst = &I;
1077 
1078   visit(I.getOpcode(), I);
1079 
1080   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1081     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1082     // maps to this instruction.
1083     // TODO: We could handle all flags (nsw, etc) here.
1084     // TODO: If an IR instruction maps to >1 node, only the final node will have
1085     //       flags set.
1086     if (SDNode *Node = getNodeForIRValue(&I)) {
1087       SDNodeFlags IncomingFlags;
1088       IncomingFlags.copyFMF(*FPMO);
1089       if (!Node->getFlags().isDefined())
1090         Node->setFlags(IncomingFlags);
1091       else
1092         Node->intersectFlagsWith(IncomingFlags);
1093     }
1094   }
1095 
1096   if (!I.isTerminator() && !HasTailCall &&
1097       !isStatepoint(&I)) // statepoints handle their exports internally
1098     CopyToExportRegsIfNeeded(&I);
1099 
1100   CurInst = nullptr;
1101 }
1102 
1103 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1104   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1105 }
1106 
1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1108   // Note: this doesn't use InstVisitor, because it has to work with
1109   // ConstantExpr's in addition to instructions.
1110   switch (Opcode) {
1111   default: llvm_unreachable("Unknown instruction type encountered!");
1112     // Build the switch statement using the Instruction.def file.
1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1114     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1115 #include "llvm/IR/Instruction.def"
1116   }
1117 }
1118 
1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1120                                                 const DIExpression *Expr) {
1121   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1122     const DbgValueInst *DI = DDI.getDI();
1123     DIVariable *DanglingVariable = DI->getVariable();
1124     DIExpression *DanglingExpr = DI->getExpression();
1125     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1126       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1127       return true;
1128     }
1129     return false;
1130   };
1131 
1132   for (auto &DDIMI : DanglingDebugInfoMap) {
1133     DanglingDebugInfoVector &DDIV = DDIMI.second;
1134     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1135   }
1136 }
1137 
1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1139 // generate the debug data structures now that we've seen its definition.
1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1141                                                    SDValue Val) {
1142   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1143   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1144     return;
1145 
1146   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1147   for (auto &DDI : DDIV) {
1148     const DbgValueInst *DI = DDI.getDI();
1149     assert(DI && "Ill-formed DanglingDebugInfo");
1150     DebugLoc dl = DDI.getdl();
1151     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1152     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1153     DILocalVariable *Variable = DI->getVariable();
1154     DIExpression *Expr = DI->getExpression();
1155     assert(Variable->isValidLocationForIntrinsic(dl) &&
1156            "Expected inlined-at fields to agree");
1157     SDDbgValue *SDV;
1158     if (Val.getNode()) {
1159       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1160       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1161       // we couldn't resolve it directly when examining the DbgValue intrinsic
1162       // in the first place we should not be more successful here). Unless we
1163       // have some test case that prove this to be correct we should avoid
1164       // calling EmitFuncArgumentDbgValue here.
1165       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1166         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1167                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1168         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1169         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1170         // inserted after the definition of Val when emitting the instructions
1171         // after ISel. An alternative could be to teach
1172         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1173         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1174                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1175                    << ValSDNodeOrder << "\n");
1176         SDV = getDbgValue(Val, Variable, Expr, dl,
1177                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1178         DAG.AddDbgValue(SDV, Val.getNode(), false);
1179       } else
1180         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1181                           << "in EmitFuncArgumentDbgValue\n");
1182     } else
1183       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1184   }
1185   DDIV.clear();
1186 }
1187 
1188 /// getCopyFromRegs - If there was virtual register allocated for the value V
1189 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1190 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1191   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1192   SDValue Result;
1193 
1194   if (It != FuncInfo.ValueMap.end()) {
1195     unsigned InReg = It->second;
1196 
1197     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1198                      DAG.getDataLayout(), InReg, Ty,
1199                      None); // This is not an ABI copy.
1200     SDValue Chain = DAG.getEntryNode();
1201     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1202                                  V);
1203     resolveDanglingDebugInfo(V, Result);
1204   }
1205 
1206   return Result;
1207 }
1208 
1209 /// getValue - Return an SDValue for the given Value.
1210 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1211   // If we already have an SDValue for this value, use it. It's important
1212   // to do this first, so that we don't create a CopyFromReg if we already
1213   // have a regular SDValue.
1214   SDValue &N = NodeMap[V];
1215   if (N.getNode()) return N;
1216 
1217   // If there's a virtual register allocated and initialized for this
1218   // value, use it.
1219   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1220     return copyFromReg;
1221 
1222   // Otherwise create a new SDValue and remember it.
1223   SDValue Val = getValueImpl(V);
1224   NodeMap[V] = Val;
1225   resolveDanglingDebugInfo(V, Val);
1226   return Val;
1227 }
1228 
1229 // Return true if SDValue exists for the given Value
1230 bool SelectionDAGBuilder::findValue(const Value *V) const {
1231   return (NodeMap.find(V) != NodeMap.end()) ||
1232     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1233 }
1234 
1235 /// getNonRegisterValue - Return an SDValue for the given Value, but
1236 /// don't look in FuncInfo.ValueMap for a virtual register.
1237 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1238   // If we already have an SDValue for this value, use it.
1239   SDValue &N = NodeMap[V];
1240   if (N.getNode()) {
1241     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1242       // Remove the debug location from the node as the node is about to be used
1243       // in a location which may differ from the original debug location.  This
1244       // is relevant to Constant and ConstantFP nodes because they can appear
1245       // as constant expressions inside PHI nodes.
1246       N->setDebugLoc(DebugLoc());
1247     }
1248     return N;
1249   }
1250 
1251   // Otherwise create a new SDValue and remember it.
1252   SDValue Val = getValueImpl(V);
1253   NodeMap[V] = Val;
1254   resolveDanglingDebugInfo(V, Val);
1255   return Val;
1256 }
1257 
1258 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1259 /// Create an SDValue for the given value.
1260 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1262 
1263   if (const Constant *C = dyn_cast<Constant>(V)) {
1264     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1265 
1266     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1267       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1268 
1269     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1270       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1271 
1272     if (isa<ConstantPointerNull>(C)) {
1273       unsigned AS = V->getType()->getPointerAddressSpace();
1274       return DAG.getConstant(0, getCurSDLoc(),
1275                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1276     }
1277 
1278     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1279       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1280 
1281     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1282       return DAG.getUNDEF(VT);
1283 
1284     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1285       visit(CE->getOpcode(), *CE);
1286       SDValue N1 = NodeMap[V];
1287       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1288       return N1;
1289     }
1290 
1291     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1292       SmallVector<SDValue, 4> Constants;
1293       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1294            OI != OE; ++OI) {
1295         SDNode *Val = getValue(*OI).getNode();
1296         // If the operand is an empty aggregate, there are no values.
1297         if (!Val) continue;
1298         // Add each leaf value from the operand to the Constants list
1299         // to form a flattened list of all the values.
1300         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1301           Constants.push_back(SDValue(Val, i));
1302       }
1303 
1304       return DAG.getMergeValues(Constants, getCurSDLoc());
1305     }
1306 
1307     if (const ConstantDataSequential *CDS =
1308           dyn_cast<ConstantDataSequential>(C)) {
1309       SmallVector<SDValue, 4> Ops;
1310       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1311         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1312         // Add each leaf value from the operand to the Constants list
1313         // to form a flattened list of all the values.
1314         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1315           Ops.push_back(SDValue(Val, i));
1316       }
1317 
1318       if (isa<ArrayType>(CDS->getType()))
1319         return DAG.getMergeValues(Ops, getCurSDLoc());
1320       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1321     }
1322 
1323     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1324       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1325              "Unknown struct or array constant!");
1326 
1327       SmallVector<EVT, 4> ValueVTs;
1328       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1329       unsigned NumElts = ValueVTs.size();
1330       if (NumElts == 0)
1331         return SDValue(); // empty struct
1332       SmallVector<SDValue, 4> Constants(NumElts);
1333       for (unsigned i = 0; i != NumElts; ++i) {
1334         EVT EltVT = ValueVTs[i];
1335         if (isa<UndefValue>(C))
1336           Constants[i] = DAG.getUNDEF(EltVT);
1337         else if (EltVT.isFloatingPoint())
1338           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1339         else
1340           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1341       }
1342 
1343       return DAG.getMergeValues(Constants, getCurSDLoc());
1344     }
1345 
1346     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1347       return DAG.getBlockAddress(BA, VT);
1348 
1349     VectorType *VecTy = cast<VectorType>(V->getType());
1350     unsigned NumElements = VecTy->getNumElements();
1351 
1352     // Now that we know the number and type of the elements, get that number of
1353     // elements into the Ops array based on what kind of constant it is.
1354     SmallVector<SDValue, 16> Ops;
1355     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1356       for (unsigned i = 0; i != NumElements; ++i)
1357         Ops.push_back(getValue(CV->getOperand(i)));
1358     } else {
1359       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1360       EVT EltVT =
1361           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1362 
1363       SDValue Op;
1364       if (EltVT.isFloatingPoint())
1365         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1366       else
1367         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1368       Ops.assign(NumElements, Op);
1369     }
1370 
1371     // Create a BUILD_VECTOR node.
1372     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1373   }
1374 
1375   // If this is a static alloca, generate it as the frameindex instead of
1376   // computation.
1377   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1378     DenseMap<const AllocaInst*, int>::iterator SI =
1379       FuncInfo.StaticAllocaMap.find(AI);
1380     if (SI != FuncInfo.StaticAllocaMap.end())
1381       return DAG.getFrameIndex(SI->second,
1382                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1383   }
1384 
1385   // If this is an instruction which fast-isel has deferred, select it now.
1386   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1387     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1388 
1389     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1390                      Inst->getType(), getABIRegCopyCC(V));
1391     SDValue Chain = DAG.getEntryNode();
1392     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1393   }
1394 
1395   llvm_unreachable("Can't get register for value!");
1396 }
1397 
1398 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1399   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1400   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1401   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1402   bool IsSEH = isAsynchronousEHPersonality(Pers);
1403   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1404   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1405   if (!IsSEH)
1406     CatchPadMBB->setIsEHScopeEntry();
1407   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1408   if (IsMSVCCXX || IsCoreCLR)
1409     CatchPadMBB->setIsEHFuncletEntry();
1410   // Wasm does not need catchpads anymore
1411   if (!IsWasmCXX)
1412     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1413                             getControlRoot()));
1414 }
1415 
1416 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1417   // Update machine-CFG edge.
1418   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1419   FuncInfo.MBB->addSuccessor(TargetMBB);
1420 
1421   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1422   bool IsSEH = isAsynchronousEHPersonality(Pers);
1423   if (IsSEH) {
1424     // If this is not a fall-through branch or optimizations are switched off,
1425     // emit the branch.
1426     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1427         TM.getOptLevel() == CodeGenOpt::None)
1428       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1429                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1430     return;
1431   }
1432 
1433   // Figure out the funclet membership for the catchret's successor.
1434   // This will be used by the FuncletLayout pass to determine how to order the
1435   // BB's.
1436   // A 'catchret' returns to the outer scope's color.
1437   Value *ParentPad = I.getCatchSwitchParentPad();
1438   const BasicBlock *SuccessorColor;
1439   if (isa<ConstantTokenNone>(ParentPad))
1440     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1441   else
1442     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1443   assert(SuccessorColor && "No parent funclet for catchret!");
1444   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1445   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1446 
1447   // Create the terminator node.
1448   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1449                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1450                             DAG.getBasicBlock(SuccessorColorMBB));
1451   DAG.setRoot(Ret);
1452 }
1453 
1454 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1455   // Don't emit any special code for the cleanuppad instruction. It just marks
1456   // the start of an EH scope/funclet.
1457   FuncInfo.MBB->setIsEHScopeEntry();
1458   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1459   if (Pers != EHPersonality::Wasm_CXX) {
1460     FuncInfo.MBB->setIsEHFuncletEntry();
1461     FuncInfo.MBB->setIsCleanupFuncletEntry();
1462   }
1463 }
1464 
1465 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1466 // the control flow always stops at the single catch pad, as it does for a
1467 // cleanup pad. In case the exception caught is not of the types the catch pad
1468 // catches, it will be rethrown by a rethrow.
1469 static void findWasmUnwindDestinations(
1470     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1471     BranchProbability Prob,
1472     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1473         &UnwindDests) {
1474   while (EHPadBB) {
1475     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1476     if (isa<CleanupPadInst>(Pad)) {
1477       // Stop on cleanup pads.
1478       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1479       UnwindDests.back().first->setIsEHScopeEntry();
1480       break;
1481     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1482       // Add the catchpad handlers to the possible destinations. We don't
1483       // continue to the unwind destination of the catchswitch for wasm.
1484       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1485         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1486         UnwindDests.back().first->setIsEHScopeEntry();
1487       }
1488       break;
1489     } else {
1490       continue;
1491     }
1492   }
1493 }
1494 
1495 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1496 /// many places it could ultimately go. In the IR, we have a single unwind
1497 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1498 /// This function skips over imaginary basic blocks that hold catchswitch
1499 /// instructions, and finds all the "real" machine
1500 /// basic block destinations. As those destinations may not be successors of
1501 /// EHPadBB, here we also calculate the edge probability to those destinations.
1502 /// The passed-in Prob is the edge probability to EHPadBB.
1503 static void findUnwindDestinations(
1504     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1505     BranchProbability Prob,
1506     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1507         &UnwindDests) {
1508   EHPersonality Personality =
1509     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1510   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1511   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1512   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1513   bool IsSEH = isAsynchronousEHPersonality(Personality);
1514 
1515   if (IsWasmCXX) {
1516     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1517     return;
1518   }
1519 
1520   while (EHPadBB) {
1521     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1522     BasicBlock *NewEHPadBB = nullptr;
1523     if (isa<LandingPadInst>(Pad)) {
1524       // Stop on landingpads. They are not funclets.
1525       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1526       break;
1527     } else if (isa<CleanupPadInst>(Pad)) {
1528       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1529       // personalities.
1530       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1531       UnwindDests.back().first->setIsEHScopeEntry();
1532       UnwindDests.back().first->setIsEHFuncletEntry();
1533       break;
1534     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1535       // Add the catchpad handlers to the possible destinations.
1536       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1537         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1538         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1539         if (IsMSVCCXX || IsCoreCLR)
1540           UnwindDests.back().first->setIsEHFuncletEntry();
1541         if (!IsSEH)
1542           UnwindDests.back().first->setIsEHScopeEntry();
1543       }
1544       NewEHPadBB = CatchSwitch->getUnwindDest();
1545     } else {
1546       continue;
1547     }
1548 
1549     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1550     if (BPI && NewEHPadBB)
1551       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1552     EHPadBB = NewEHPadBB;
1553   }
1554 }
1555 
1556 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1557   // Update successor info.
1558   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1559   auto UnwindDest = I.getUnwindDest();
1560   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1561   BranchProbability UnwindDestProb =
1562       (BPI && UnwindDest)
1563           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1564           : BranchProbability::getZero();
1565   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1566   for (auto &UnwindDest : UnwindDests) {
1567     UnwindDest.first->setIsEHPad();
1568     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1569   }
1570   FuncInfo.MBB->normalizeSuccProbs();
1571 
1572   // Create the terminator node.
1573   SDValue Ret =
1574       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1575   DAG.setRoot(Ret);
1576 }
1577 
1578 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1579   report_fatal_error("visitCatchSwitch not yet implemented!");
1580 }
1581 
1582 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1584   auto &DL = DAG.getDataLayout();
1585   SDValue Chain = getControlRoot();
1586   SmallVector<ISD::OutputArg, 8> Outs;
1587   SmallVector<SDValue, 8> OutVals;
1588 
1589   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1590   // lower
1591   //
1592   //   %val = call <ty> @llvm.experimental.deoptimize()
1593   //   ret <ty> %val
1594   //
1595   // differently.
1596   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1597     LowerDeoptimizingReturn();
1598     return;
1599   }
1600 
1601   if (!FuncInfo.CanLowerReturn) {
1602     unsigned DemoteReg = FuncInfo.DemoteRegister;
1603     const Function *F = I.getParent()->getParent();
1604 
1605     // Emit a store of the return value through the virtual register.
1606     // Leave Outs empty so that LowerReturn won't try to load return
1607     // registers the usual way.
1608     SmallVector<EVT, 1> PtrValueVTs;
1609     ComputeValueVTs(TLI, DL,
1610                     F->getReturnType()->getPointerTo(
1611                         DAG.getDataLayout().getAllocaAddrSpace()),
1612                     PtrValueVTs);
1613 
1614     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1615                                         DemoteReg, PtrValueVTs[0]);
1616     SDValue RetOp = getValue(I.getOperand(0));
1617 
1618     SmallVector<EVT, 4> ValueVTs;
1619     SmallVector<uint64_t, 4> Offsets;
1620     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1621     unsigned NumValues = ValueVTs.size();
1622 
1623     SmallVector<SDValue, 4> Chains(NumValues);
1624     for (unsigned i = 0; i != NumValues; ++i) {
1625       // An aggregate return value cannot wrap around the address space, so
1626       // offsets to its parts don't wrap either.
1627       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1628       Chains[i] = DAG.getStore(
1629           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1630           // FIXME: better loc info would be nice.
1631           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1632     }
1633 
1634     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1635                         MVT::Other, Chains);
1636   } else if (I.getNumOperands() != 0) {
1637     SmallVector<EVT, 4> ValueVTs;
1638     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1639     unsigned NumValues = ValueVTs.size();
1640     if (NumValues) {
1641       SDValue RetOp = getValue(I.getOperand(0));
1642 
1643       const Function *F = I.getParent()->getParent();
1644 
1645       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1646       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1647                                           Attribute::SExt))
1648         ExtendKind = ISD::SIGN_EXTEND;
1649       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1650                                                Attribute::ZExt))
1651         ExtendKind = ISD::ZERO_EXTEND;
1652 
1653       LLVMContext &Context = F->getContext();
1654       bool RetInReg = F->getAttributes().hasAttribute(
1655           AttributeList::ReturnIndex, Attribute::InReg);
1656 
1657       for (unsigned j = 0; j != NumValues; ++j) {
1658         EVT VT = ValueVTs[j];
1659 
1660         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1661           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1662 
1663         CallingConv::ID CC = F->getCallingConv();
1664 
1665         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1666         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1667         SmallVector<SDValue, 4> Parts(NumParts);
1668         getCopyToParts(DAG, getCurSDLoc(),
1669                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1670                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1671 
1672         // 'inreg' on function refers to return value
1673         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1674         if (RetInReg)
1675           Flags.setInReg();
1676 
1677         // Propagate extension type if any
1678         if (ExtendKind == ISD::SIGN_EXTEND)
1679           Flags.setSExt();
1680         else if (ExtendKind == ISD::ZERO_EXTEND)
1681           Flags.setZExt();
1682 
1683         for (unsigned i = 0; i < NumParts; ++i) {
1684           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1685                                         VT, /*isfixed=*/true, 0, 0));
1686           OutVals.push_back(Parts[i]);
1687         }
1688       }
1689     }
1690   }
1691 
1692   // Push in swifterror virtual register as the last element of Outs. This makes
1693   // sure swifterror virtual register will be returned in the swifterror
1694   // physical register.
1695   const Function *F = I.getParent()->getParent();
1696   if (TLI.supportSwiftError() &&
1697       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1698     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1699     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1700     Flags.setSwiftError();
1701     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1702                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1703                                   true /*isfixed*/, 1 /*origidx*/,
1704                                   0 /*partOffs*/));
1705     // Create SDNode for the swifterror virtual register.
1706     OutVals.push_back(
1707         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1708                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1709                         EVT(TLI.getPointerTy(DL))));
1710   }
1711 
1712   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1713   CallingConv::ID CallConv =
1714     DAG.getMachineFunction().getFunction().getCallingConv();
1715   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1716       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1717 
1718   // Verify that the target's LowerReturn behaved as expected.
1719   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1720          "LowerReturn didn't return a valid chain!");
1721 
1722   // Update the DAG with the new chain value resulting from return lowering.
1723   DAG.setRoot(Chain);
1724 }
1725 
1726 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1727 /// created for it, emit nodes to copy the value into the virtual
1728 /// registers.
1729 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1730   // Skip empty types
1731   if (V->getType()->isEmptyTy())
1732     return;
1733 
1734   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1735   if (VMI != FuncInfo.ValueMap.end()) {
1736     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1737     CopyValueToVirtualRegister(V, VMI->second);
1738   }
1739 }
1740 
1741 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1742 /// the current basic block, add it to ValueMap now so that we'll get a
1743 /// CopyTo/FromReg.
1744 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1745   // No need to export constants.
1746   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1747 
1748   // Already exported?
1749   if (FuncInfo.isExportedInst(V)) return;
1750 
1751   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1752   CopyValueToVirtualRegister(V, Reg);
1753 }
1754 
1755 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1756                                                      const BasicBlock *FromBB) {
1757   // The operands of the setcc have to be in this block.  We don't know
1758   // how to export them from some other block.
1759   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1760     // Can export from current BB.
1761     if (VI->getParent() == FromBB)
1762       return true;
1763 
1764     // Is already exported, noop.
1765     return FuncInfo.isExportedInst(V);
1766   }
1767 
1768   // If this is an argument, we can export it if the BB is the entry block or
1769   // if it is already exported.
1770   if (isa<Argument>(V)) {
1771     if (FromBB == &FromBB->getParent()->getEntryBlock())
1772       return true;
1773 
1774     // Otherwise, can only export this if it is already exported.
1775     return FuncInfo.isExportedInst(V);
1776   }
1777 
1778   // Otherwise, constants can always be exported.
1779   return true;
1780 }
1781 
1782 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1783 BranchProbability
1784 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1785                                         const MachineBasicBlock *Dst) const {
1786   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1787   const BasicBlock *SrcBB = Src->getBasicBlock();
1788   const BasicBlock *DstBB = Dst->getBasicBlock();
1789   if (!BPI) {
1790     // If BPI is not available, set the default probability as 1 / N, where N is
1791     // the number of successors.
1792     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1793     return BranchProbability(1, SuccSize);
1794   }
1795   return BPI->getEdgeProbability(SrcBB, DstBB);
1796 }
1797 
1798 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1799                                                MachineBasicBlock *Dst,
1800                                                BranchProbability Prob) {
1801   if (!FuncInfo.BPI)
1802     Src->addSuccessorWithoutProb(Dst);
1803   else {
1804     if (Prob.isUnknown())
1805       Prob = getEdgeProbability(Src, Dst);
1806     Src->addSuccessor(Dst, Prob);
1807   }
1808 }
1809 
1810 static bool InBlock(const Value *V, const BasicBlock *BB) {
1811   if (const Instruction *I = dyn_cast<Instruction>(V))
1812     return I->getParent() == BB;
1813   return true;
1814 }
1815 
1816 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1817 /// This function emits a branch and is used at the leaves of an OR or an
1818 /// AND operator tree.
1819 void
1820 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1821                                                   MachineBasicBlock *TBB,
1822                                                   MachineBasicBlock *FBB,
1823                                                   MachineBasicBlock *CurBB,
1824                                                   MachineBasicBlock *SwitchBB,
1825                                                   BranchProbability TProb,
1826                                                   BranchProbability FProb,
1827                                                   bool InvertCond) {
1828   const BasicBlock *BB = CurBB->getBasicBlock();
1829 
1830   // If the leaf of the tree is a comparison, merge the condition into
1831   // the caseblock.
1832   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1833     // The operands of the cmp have to be in this block.  We don't know
1834     // how to export them from some other block.  If this is the first block
1835     // of the sequence, no exporting is needed.
1836     if (CurBB == SwitchBB ||
1837         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1838          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1839       ISD::CondCode Condition;
1840       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1841         ICmpInst::Predicate Pred =
1842             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1843         Condition = getICmpCondCode(Pred);
1844       } else {
1845         const FCmpInst *FC = cast<FCmpInst>(Cond);
1846         FCmpInst::Predicate Pred =
1847             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1848         Condition = getFCmpCondCode(Pred);
1849         if (TM.Options.NoNaNsFPMath)
1850           Condition = getFCmpCodeWithoutNaN(Condition);
1851       }
1852 
1853       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1854                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1855       SwitchCases.push_back(CB);
1856       return;
1857     }
1858   }
1859 
1860   // Create a CaseBlock record representing this branch.
1861   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1862   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1863                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1864   SwitchCases.push_back(CB);
1865 }
1866 
1867 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1868                                                MachineBasicBlock *TBB,
1869                                                MachineBasicBlock *FBB,
1870                                                MachineBasicBlock *CurBB,
1871                                                MachineBasicBlock *SwitchBB,
1872                                                Instruction::BinaryOps Opc,
1873                                                BranchProbability TProb,
1874                                                BranchProbability FProb,
1875                                                bool InvertCond) {
1876   // Skip over not part of the tree and remember to invert op and operands at
1877   // next level.
1878   Value *NotCond;
1879   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1880       InBlock(NotCond, CurBB->getBasicBlock())) {
1881     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1882                          !InvertCond);
1883     return;
1884   }
1885 
1886   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1887   // Compute the effective opcode for Cond, taking into account whether it needs
1888   // to be inverted, e.g.
1889   //   and (not (or A, B)), C
1890   // gets lowered as
1891   //   and (and (not A, not B), C)
1892   unsigned BOpc = 0;
1893   if (BOp) {
1894     BOpc = BOp->getOpcode();
1895     if (InvertCond) {
1896       if (BOpc == Instruction::And)
1897         BOpc = Instruction::Or;
1898       else if (BOpc == Instruction::Or)
1899         BOpc = Instruction::And;
1900     }
1901   }
1902 
1903   // If this node is not part of the or/and tree, emit it as a branch.
1904   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1905       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1906       BOp->getParent() != CurBB->getBasicBlock() ||
1907       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1908       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1909     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1910                                  TProb, FProb, InvertCond);
1911     return;
1912   }
1913 
1914   //  Create TmpBB after CurBB.
1915   MachineFunction::iterator BBI(CurBB);
1916   MachineFunction &MF = DAG.getMachineFunction();
1917   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1918   CurBB->getParent()->insert(++BBI, TmpBB);
1919 
1920   if (Opc == Instruction::Or) {
1921     // Codegen X | Y as:
1922     // BB1:
1923     //   jmp_if_X TBB
1924     //   jmp TmpBB
1925     // TmpBB:
1926     //   jmp_if_Y TBB
1927     //   jmp FBB
1928     //
1929 
1930     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1931     // The requirement is that
1932     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1933     //     = TrueProb for original BB.
1934     // Assuming the original probabilities are A and B, one choice is to set
1935     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1936     // A/(1+B) and 2B/(1+B). This choice assumes that
1937     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1938     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1939     // TmpBB, but the math is more complicated.
1940 
1941     auto NewTrueProb = TProb / 2;
1942     auto NewFalseProb = TProb / 2 + FProb;
1943     // Emit the LHS condition.
1944     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1945                          NewTrueProb, NewFalseProb, InvertCond);
1946 
1947     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1948     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1949     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1950     // Emit the RHS condition into TmpBB.
1951     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1952                          Probs[0], Probs[1], InvertCond);
1953   } else {
1954     assert(Opc == Instruction::And && "Unknown merge op!");
1955     // Codegen X & Y as:
1956     // BB1:
1957     //   jmp_if_X TmpBB
1958     //   jmp FBB
1959     // TmpBB:
1960     //   jmp_if_Y TBB
1961     //   jmp FBB
1962     //
1963     //  This requires creation of TmpBB after CurBB.
1964 
1965     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1966     // The requirement is that
1967     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1968     //     = FalseProb for original BB.
1969     // Assuming the original probabilities are A and B, one choice is to set
1970     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1971     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1972     // TrueProb for BB1 * FalseProb for TmpBB.
1973 
1974     auto NewTrueProb = TProb + FProb / 2;
1975     auto NewFalseProb = FProb / 2;
1976     // Emit the LHS condition.
1977     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1978                          NewTrueProb, NewFalseProb, InvertCond);
1979 
1980     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1981     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1982     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1983     // Emit the RHS condition into TmpBB.
1984     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1985                          Probs[0], Probs[1], InvertCond);
1986   }
1987 }
1988 
1989 /// If the set of cases should be emitted as a series of branches, return true.
1990 /// If we should emit this as a bunch of and/or'd together conditions, return
1991 /// false.
1992 bool
1993 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1994   if (Cases.size() != 2) return true;
1995 
1996   // If this is two comparisons of the same values or'd or and'd together, they
1997   // will get folded into a single comparison, so don't emit two blocks.
1998   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1999        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2000       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2001        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2002     return false;
2003   }
2004 
2005   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2006   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2007   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2008       Cases[0].CC == Cases[1].CC &&
2009       isa<Constant>(Cases[0].CmpRHS) &&
2010       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2011     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2012       return false;
2013     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2014       return false;
2015   }
2016 
2017   return true;
2018 }
2019 
2020 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2021   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2022 
2023   // Update machine-CFG edges.
2024   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2025 
2026   if (I.isUnconditional()) {
2027     // Update machine-CFG edges.
2028     BrMBB->addSuccessor(Succ0MBB);
2029 
2030     // If this is not a fall-through branch or optimizations are switched off,
2031     // emit the branch.
2032     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2033       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2034                               MVT::Other, getControlRoot(),
2035                               DAG.getBasicBlock(Succ0MBB)));
2036 
2037     return;
2038   }
2039 
2040   // If this condition is one of the special cases we handle, do special stuff
2041   // now.
2042   const Value *CondVal = I.getCondition();
2043   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2044 
2045   // If this is a series of conditions that are or'd or and'd together, emit
2046   // this as a sequence of branches instead of setcc's with and/or operations.
2047   // As long as jumps are not expensive, this should improve performance.
2048   // For example, instead of something like:
2049   //     cmp A, B
2050   //     C = seteq
2051   //     cmp D, E
2052   //     F = setle
2053   //     or C, F
2054   //     jnz foo
2055   // Emit:
2056   //     cmp A, B
2057   //     je foo
2058   //     cmp D, E
2059   //     jle foo
2060   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2061     Instruction::BinaryOps Opcode = BOp->getOpcode();
2062     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2063         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2064         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2065       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2066                            Opcode,
2067                            getEdgeProbability(BrMBB, Succ0MBB),
2068                            getEdgeProbability(BrMBB, Succ1MBB),
2069                            /*InvertCond=*/false);
2070       // If the compares in later blocks need to use values not currently
2071       // exported from this block, export them now.  This block should always
2072       // be the first entry.
2073       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2074 
2075       // Allow some cases to be rejected.
2076       if (ShouldEmitAsBranches(SwitchCases)) {
2077         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2078           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2079           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2080         }
2081 
2082         // Emit the branch for this block.
2083         visitSwitchCase(SwitchCases[0], BrMBB);
2084         SwitchCases.erase(SwitchCases.begin());
2085         return;
2086       }
2087 
2088       // Okay, we decided not to do this, remove any inserted MBB's and clear
2089       // SwitchCases.
2090       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2091         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2092 
2093       SwitchCases.clear();
2094     }
2095   }
2096 
2097   // Create a CaseBlock record representing this branch.
2098   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2099                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2100 
2101   // Use visitSwitchCase to actually insert the fast branch sequence for this
2102   // cond branch.
2103   visitSwitchCase(CB, BrMBB);
2104 }
2105 
2106 /// visitSwitchCase - Emits the necessary code to represent a single node in
2107 /// the binary search tree resulting from lowering a switch instruction.
2108 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2109                                           MachineBasicBlock *SwitchBB) {
2110   SDValue Cond;
2111   SDValue CondLHS = getValue(CB.CmpLHS);
2112   SDLoc dl = CB.DL;
2113 
2114   // Build the setcc now.
2115   if (!CB.CmpMHS) {
2116     // Fold "(X == true)" to X and "(X == false)" to !X to
2117     // handle common cases produced by branch lowering.
2118     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2119         CB.CC == ISD::SETEQ)
2120       Cond = CondLHS;
2121     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2122              CB.CC == ISD::SETEQ) {
2123       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2124       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2125     } else
2126       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2127   } else {
2128     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2129 
2130     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2131     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2132 
2133     SDValue CmpOp = getValue(CB.CmpMHS);
2134     EVT VT = CmpOp.getValueType();
2135 
2136     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2137       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2138                           ISD::SETLE);
2139     } else {
2140       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2141                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2142       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2143                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2144     }
2145   }
2146 
2147   // Update successor info
2148   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2149   // TrueBB and FalseBB are always different unless the incoming IR is
2150   // degenerate. This only happens when running llc on weird IR.
2151   if (CB.TrueBB != CB.FalseBB)
2152     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2153   SwitchBB->normalizeSuccProbs();
2154 
2155   // If the lhs block is the next block, invert the condition so that we can
2156   // fall through to the lhs instead of the rhs block.
2157   if (CB.TrueBB == NextBlock(SwitchBB)) {
2158     std::swap(CB.TrueBB, CB.FalseBB);
2159     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2160     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2161   }
2162 
2163   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2164                                MVT::Other, getControlRoot(), Cond,
2165                                DAG.getBasicBlock(CB.TrueBB));
2166 
2167   // Insert the false branch. Do this even if it's a fall through branch,
2168   // this makes it easier to do DAG optimizations which require inverting
2169   // the branch condition.
2170   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2171                        DAG.getBasicBlock(CB.FalseBB));
2172 
2173   DAG.setRoot(BrCond);
2174 }
2175 
2176 /// visitJumpTable - Emit JumpTable node in the current MBB
2177 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2178   // Emit the code for the jump table
2179   assert(JT.Reg != -1U && "Should lower JT Header first!");
2180   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2181   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2182                                      JT.Reg, PTy);
2183   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2184   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2185                                     MVT::Other, Index.getValue(1),
2186                                     Table, Index);
2187   DAG.setRoot(BrJumpTable);
2188 }
2189 
2190 /// visitJumpTableHeader - This function emits necessary code to produce index
2191 /// in the JumpTable from switch case.
2192 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2193                                                JumpTableHeader &JTH,
2194                                                MachineBasicBlock *SwitchBB) {
2195   SDLoc dl = getCurSDLoc();
2196 
2197   // Subtract the lowest switch case value from the value being switched on and
2198   // conditional branch to default mbb if the result is greater than the
2199   // difference between smallest and largest cases.
2200   SDValue SwitchOp = getValue(JTH.SValue);
2201   EVT VT = SwitchOp.getValueType();
2202   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2203                             DAG.getConstant(JTH.First, dl, VT));
2204 
2205   // The SDNode we just created, which holds the value being switched on minus
2206   // the smallest case value, needs to be copied to a virtual register so it
2207   // can be used as an index into the jump table in a subsequent basic block.
2208   // This value may be smaller or larger than the target's pointer type, and
2209   // therefore require extension or truncating.
2210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2211   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2212 
2213   unsigned JumpTableReg =
2214       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2215   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2216                                     JumpTableReg, SwitchOp);
2217   JT.Reg = JumpTableReg;
2218 
2219   // Emit the range check for the jump table, and branch to the default block
2220   // for the switch statement if the value being switched on exceeds the largest
2221   // case in the switch.
2222   SDValue CMP = DAG.getSetCC(
2223       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2224                                  Sub.getValueType()),
2225       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2226 
2227   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2228                                MVT::Other, CopyTo, CMP,
2229                                DAG.getBasicBlock(JT.Default));
2230 
2231   // Avoid emitting unnecessary branches to the next block.
2232   if (JT.MBB != NextBlock(SwitchBB))
2233     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2234                          DAG.getBasicBlock(JT.MBB));
2235 
2236   DAG.setRoot(BrCond);
2237 }
2238 
2239 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2240 /// variable if there exists one.
2241 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2242                                  SDValue &Chain) {
2243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2244   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2245   MachineFunction &MF = DAG.getMachineFunction();
2246   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2247   MachineSDNode *Node =
2248       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2249   if (Global) {
2250     MachinePointerInfo MPInfo(Global);
2251     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2252                  MachineMemOperand::MODereferenceable;
2253     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2254         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2255     DAG.setNodeMemRefs(Node, {MemRef});
2256   }
2257   return SDValue(Node, 0);
2258 }
2259 
2260 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2261 /// tail spliced into a stack protector check success bb.
2262 ///
2263 /// For a high level explanation of how this fits into the stack protector
2264 /// generation see the comment on the declaration of class
2265 /// StackProtectorDescriptor.
2266 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2267                                                   MachineBasicBlock *ParentBB) {
2268 
2269   // First create the loads to the guard/stack slot for the comparison.
2270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2271   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2272 
2273   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2274   int FI = MFI.getStackProtectorIndex();
2275 
2276   SDValue Guard;
2277   SDLoc dl = getCurSDLoc();
2278   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2279   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2280   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2281 
2282   // Generate code to load the content of the guard slot.
2283   SDValue GuardVal = DAG.getLoad(
2284       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2285       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2286       MachineMemOperand::MOVolatile);
2287 
2288   if (TLI.useStackGuardXorFP())
2289     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2290 
2291   // Retrieve guard check function, nullptr if instrumentation is inlined.
2292   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2293     // The target provides a guard check function to validate the guard value.
2294     // Generate a call to that function with the content of the guard slot as
2295     // argument.
2296     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2297     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2298 
2299     TargetLowering::ArgListTy Args;
2300     TargetLowering::ArgListEntry Entry;
2301     Entry.Node = GuardVal;
2302     Entry.Ty = FnTy->getParamType(0);
2303     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2304       Entry.IsInReg = true;
2305     Args.push_back(Entry);
2306 
2307     TargetLowering::CallLoweringInfo CLI(DAG);
2308     CLI.setDebugLoc(getCurSDLoc())
2309         .setChain(DAG.getEntryNode())
2310         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2311                    getValue(GuardCheckFn), std::move(Args));
2312 
2313     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2314     DAG.setRoot(Result.second);
2315     return;
2316   }
2317 
2318   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2319   // Otherwise, emit a volatile load to retrieve the stack guard value.
2320   SDValue Chain = DAG.getEntryNode();
2321   if (TLI.useLoadStackGuardNode()) {
2322     Guard = getLoadStackGuard(DAG, dl, Chain);
2323   } else {
2324     const Value *IRGuard = TLI.getSDagStackGuard(M);
2325     SDValue GuardPtr = getValue(IRGuard);
2326 
2327     Guard =
2328         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2329                     Align, MachineMemOperand::MOVolatile);
2330   }
2331 
2332   // Perform the comparison via a subtract/getsetcc.
2333   EVT VT = Guard.getValueType();
2334   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2335 
2336   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2337                                                         *DAG.getContext(),
2338                                                         Sub.getValueType()),
2339                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2340 
2341   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2342   // branch to failure MBB.
2343   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2344                                MVT::Other, GuardVal.getOperand(0),
2345                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2346   // Otherwise branch to success MBB.
2347   SDValue Br = DAG.getNode(ISD::BR, dl,
2348                            MVT::Other, BrCond,
2349                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2350 
2351   DAG.setRoot(Br);
2352 }
2353 
2354 /// Codegen the failure basic block for a stack protector check.
2355 ///
2356 /// A failure stack protector machine basic block consists simply of a call to
2357 /// __stack_chk_fail().
2358 ///
2359 /// For a high level explanation of how this fits into the stack protector
2360 /// generation see the comment on the declaration of class
2361 /// StackProtectorDescriptor.
2362 void
2363 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2365   SDValue Chain =
2366       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2367                       None, false, getCurSDLoc(), false, false).second;
2368   DAG.setRoot(Chain);
2369 }
2370 
2371 /// visitBitTestHeader - This function emits necessary code to produce value
2372 /// suitable for "bit tests"
2373 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2374                                              MachineBasicBlock *SwitchBB) {
2375   SDLoc dl = getCurSDLoc();
2376 
2377   // Subtract the minimum value
2378   SDValue SwitchOp = getValue(B.SValue);
2379   EVT VT = SwitchOp.getValueType();
2380   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2381                             DAG.getConstant(B.First, dl, VT));
2382 
2383   // Check range
2384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2385   SDValue RangeCmp = DAG.getSetCC(
2386       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2387                                  Sub.getValueType()),
2388       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2389 
2390   // Determine the type of the test operands.
2391   bool UsePtrType = false;
2392   if (!TLI.isTypeLegal(VT))
2393     UsePtrType = true;
2394   else {
2395     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2396       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2397         // Switch table case range are encoded into series of masks.
2398         // Just use pointer type, it's guaranteed to fit.
2399         UsePtrType = true;
2400         break;
2401       }
2402   }
2403   if (UsePtrType) {
2404     VT = TLI.getPointerTy(DAG.getDataLayout());
2405     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2406   }
2407 
2408   B.RegVT = VT.getSimpleVT();
2409   B.Reg = FuncInfo.CreateReg(B.RegVT);
2410   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2411 
2412   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2413 
2414   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2415   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2416   SwitchBB->normalizeSuccProbs();
2417 
2418   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2419                                 MVT::Other, CopyTo, RangeCmp,
2420                                 DAG.getBasicBlock(B.Default));
2421 
2422   // Avoid emitting unnecessary branches to the next block.
2423   if (MBB != NextBlock(SwitchBB))
2424     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2425                           DAG.getBasicBlock(MBB));
2426 
2427   DAG.setRoot(BrRange);
2428 }
2429 
2430 /// visitBitTestCase - this function produces one "bit test"
2431 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2432                                            MachineBasicBlock* NextMBB,
2433                                            BranchProbability BranchProbToNext,
2434                                            unsigned Reg,
2435                                            BitTestCase &B,
2436                                            MachineBasicBlock *SwitchBB) {
2437   SDLoc dl = getCurSDLoc();
2438   MVT VT = BB.RegVT;
2439   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2440   SDValue Cmp;
2441   unsigned PopCount = countPopulation(B.Mask);
2442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2443   if (PopCount == 1) {
2444     // Testing for a single bit; just compare the shift count with what it
2445     // would need to be to shift a 1 bit in that position.
2446     Cmp = DAG.getSetCC(
2447         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2448         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2449         ISD::SETEQ);
2450   } else if (PopCount == BB.Range) {
2451     // There is only one zero bit in the range, test for it directly.
2452     Cmp = DAG.getSetCC(
2453         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2454         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2455         ISD::SETNE);
2456   } else {
2457     // Make desired shift
2458     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2459                                     DAG.getConstant(1, dl, VT), ShiftOp);
2460 
2461     // Emit bit tests and jumps
2462     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2463                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2464     Cmp = DAG.getSetCC(
2465         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2466         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2467   }
2468 
2469   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2470   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2471   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2472   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2473   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2474   // one as they are relative probabilities (and thus work more like weights),
2475   // and hence we need to normalize them to let the sum of them become one.
2476   SwitchBB->normalizeSuccProbs();
2477 
2478   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2479                               MVT::Other, getControlRoot(),
2480                               Cmp, DAG.getBasicBlock(B.TargetBB));
2481 
2482   // Avoid emitting unnecessary branches to the next block.
2483   if (NextMBB != NextBlock(SwitchBB))
2484     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2485                         DAG.getBasicBlock(NextMBB));
2486 
2487   DAG.setRoot(BrAnd);
2488 }
2489 
2490 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2491   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2492 
2493   // Retrieve successors. Look through artificial IR level blocks like
2494   // catchswitch for successors.
2495   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2496   const BasicBlock *EHPadBB = I.getSuccessor(1);
2497 
2498   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2499   // have to do anything here to lower funclet bundles.
2500   assert(!I.hasOperandBundlesOtherThan(
2501              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2502          "Cannot lower invokes with arbitrary operand bundles yet!");
2503 
2504   const Value *Callee(I.getCalledValue());
2505   const Function *Fn = dyn_cast<Function>(Callee);
2506   if (isa<InlineAsm>(Callee))
2507     visitInlineAsm(&I);
2508   else if (Fn && Fn->isIntrinsic()) {
2509     switch (Fn->getIntrinsicID()) {
2510     default:
2511       llvm_unreachable("Cannot invoke this intrinsic");
2512     case Intrinsic::donothing:
2513       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2514       break;
2515     case Intrinsic::experimental_patchpoint_void:
2516     case Intrinsic::experimental_patchpoint_i64:
2517       visitPatchpoint(&I, EHPadBB);
2518       break;
2519     case Intrinsic::experimental_gc_statepoint:
2520       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2521       break;
2522     }
2523   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2524     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2525     // Eventually we will support lowering the @llvm.experimental.deoptimize
2526     // intrinsic, and right now there are no plans to support other intrinsics
2527     // with deopt state.
2528     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2529   } else {
2530     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2531   }
2532 
2533   // If the value of the invoke is used outside of its defining block, make it
2534   // available as a virtual register.
2535   // We already took care of the exported value for the statepoint instruction
2536   // during call to the LowerStatepoint.
2537   if (!isStatepoint(I)) {
2538     CopyToExportRegsIfNeeded(&I);
2539   }
2540 
2541   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2542   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2543   BranchProbability EHPadBBProb =
2544       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2545           : BranchProbability::getZero();
2546   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2547 
2548   // Update successor info.
2549   addSuccessorWithProb(InvokeMBB, Return);
2550   for (auto &UnwindDest : UnwindDests) {
2551     UnwindDest.first->setIsEHPad();
2552     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2553   }
2554   InvokeMBB->normalizeSuccProbs();
2555 
2556   // Drop into normal successor.
2557   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2558                           DAG.getBasicBlock(Return)));
2559 }
2560 
2561 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2562   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2563 
2564   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2565   // have to do anything here to lower funclet bundles.
2566   assert(!I.hasOperandBundlesOtherThan(
2567              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2568          "Cannot lower callbrs with arbitrary operand bundles yet!");
2569 
2570   assert(isa<InlineAsm>(I.getCalledValue()) &&
2571          "Only know how to handle inlineasm callbr");
2572   visitInlineAsm(&I);
2573 
2574   // Retrieve successors.
2575   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2576 
2577   // Update successor info.
2578   addSuccessorWithProb(CallBrMBB, Return);
2579   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2580     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2581     addSuccessorWithProb(CallBrMBB, Target);
2582   }
2583   CallBrMBB->normalizeSuccProbs();
2584 
2585   // Drop into default successor.
2586   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2587                           MVT::Other, getControlRoot(),
2588                           DAG.getBasicBlock(Return)));
2589 }
2590 
2591 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2592   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2593 }
2594 
2595 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2596   assert(FuncInfo.MBB->isEHPad() &&
2597          "Call to landingpad not in landing pad!");
2598 
2599   // If there aren't registers to copy the values into (e.g., during SjLj
2600   // exceptions), then don't bother to create these DAG nodes.
2601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2603   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2604       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2605     return;
2606 
2607   // If landingpad's return type is token type, we don't create DAG nodes
2608   // for its exception pointer and selector value. The extraction of exception
2609   // pointer or selector value from token type landingpads is not currently
2610   // supported.
2611   if (LP.getType()->isTokenTy())
2612     return;
2613 
2614   SmallVector<EVT, 2> ValueVTs;
2615   SDLoc dl = getCurSDLoc();
2616   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2617   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2618 
2619   // Get the two live-in registers as SDValues. The physregs have already been
2620   // copied into virtual registers.
2621   SDValue Ops[2];
2622   if (FuncInfo.ExceptionPointerVirtReg) {
2623     Ops[0] = DAG.getZExtOrTrunc(
2624         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2625                            FuncInfo.ExceptionPointerVirtReg,
2626                            TLI.getPointerTy(DAG.getDataLayout())),
2627         dl, ValueVTs[0]);
2628   } else {
2629     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2630   }
2631   Ops[1] = DAG.getZExtOrTrunc(
2632       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2633                          FuncInfo.ExceptionSelectorVirtReg,
2634                          TLI.getPointerTy(DAG.getDataLayout())),
2635       dl, ValueVTs[1]);
2636 
2637   // Merge into one.
2638   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2639                             DAG.getVTList(ValueVTs), Ops);
2640   setValue(&LP, Res);
2641 }
2642 
2643 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2644 #ifndef NDEBUG
2645   for (const CaseCluster &CC : Clusters)
2646     assert(CC.Low == CC.High && "Input clusters must be single-case");
2647 #endif
2648 
2649   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2650     return a.Low->getValue().slt(b.Low->getValue());
2651   });
2652 
2653   // Merge adjacent clusters with the same destination.
2654   const unsigned N = Clusters.size();
2655   unsigned DstIndex = 0;
2656   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2657     CaseCluster &CC = Clusters[SrcIndex];
2658     const ConstantInt *CaseVal = CC.Low;
2659     MachineBasicBlock *Succ = CC.MBB;
2660 
2661     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2662         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2663       // If this case has the same successor and is a neighbour, merge it into
2664       // the previous cluster.
2665       Clusters[DstIndex - 1].High = CaseVal;
2666       Clusters[DstIndex - 1].Prob += CC.Prob;
2667     } else {
2668       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2669                    sizeof(Clusters[SrcIndex]));
2670     }
2671   }
2672   Clusters.resize(DstIndex);
2673 }
2674 
2675 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2676                                            MachineBasicBlock *Last) {
2677   // Update JTCases.
2678   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2679     if (JTCases[i].first.HeaderBB == First)
2680       JTCases[i].first.HeaderBB = Last;
2681 
2682   // Update BitTestCases.
2683   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2684     if (BitTestCases[i].Parent == First)
2685       BitTestCases[i].Parent = Last;
2686 }
2687 
2688 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2689   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2690 
2691   // Update machine-CFG edges with unique successors.
2692   SmallSet<BasicBlock*, 32> Done;
2693   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2694     BasicBlock *BB = I.getSuccessor(i);
2695     bool Inserted = Done.insert(BB).second;
2696     if (!Inserted)
2697         continue;
2698 
2699     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2700     addSuccessorWithProb(IndirectBrMBB, Succ);
2701   }
2702   IndirectBrMBB->normalizeSuccProbs();
2703 
2704   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2705                           MVT::Other, getControlRoot(),
2706                           getValue(I.getAddress())));
2707 }
2708 
2709 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2710   if (!DAG.getTarget().Options.TrapUnreachable)
2711     return;
2712 
2713   // We may be able to ignore unreachable behind a noreturn call.
2714   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2715     const BasicBlock &BB = *I.getParent();
2716     if (&I != &BB.front()) {
2717       BasicBlock::const_iterator PredI =
2718         std::prev(BasicBlock::const_iterator(&I));
2719       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2720         if (Call->doesNotReturn())
2721           return;
2722       }
2723     }
2724   }
2725 
2726   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2727 }
2728 
2729 void SelectionDAGBuilder::visitFSub(const User &I) {
2730   // -0.0 - X --> fneg
2731   Type *Ty = I.getType();
2732   if (isa<Constant>(I.getOperand(0)) &&
2733       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2734     SDValue Op2 = getValue(I.getOperand(1));
2735     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2736                              Op2.getValueType(), Op2));
2737     return;
2738   }
2739 
2740   visitBinary(I, ISD::FSUB);
2741 }
2742 
2743 /// Checks if the given instruction performs a vector reduction, in which case
2744 /// we have the freedom to alter the elements in the result as long as the
2745 /// reduction of them stays unchanged.
2746 static bool isVectorReductionOp(const User *I) {
2747   const Instruction *Inst = dyn_cast<Instruction>(I);
2748   if (!Inst || !Inst->getType()->isVectorTy())
2749     return false;
2750 
2751   auto OpCode = Inst->getOpcode();
2752   switch (OpCode) {
2753   case Instruction::Add:
2754   case Instruction::Mul:
2755   case Instruction::And:
2756   case Instruction::Or:
2757   case Instruction::Xor:
2758     break;
2759   case Instruction::FAdd:
2760   case Instruction::FMul:
2761     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2762       if (FPOp->getFastMathFlags().isFast())
2763         break;
2764     LLVM_FALLTHROUGH;
2765   default:
2766     return false;
2767   }
2768 
2769   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2770   // Ensure the reduction size is a power of 2.
2771   if (!isPowerOf2_32(ElemNum))
2772     return false;
2773 
2774   unsigned ElemNumToReduce = ElemNum;
2775 
2776   // Do DFS search on the def-use chain from the given instruction. We only
2777   // allow four kinds of operations during the search until we reach the
2778   // instruction that extracts the first element from the vector:
2779   //
2780   //   1. The reduction operation of the same opcode as the given instruction.
2781   //
2782   //   2. PHI node.
2783   //
2784   //   3. ShuffleVector instruction together with a reduction operation that
2785   //      does a partial reduction.
2786   //
2787   //   4. ExtractElement that extracts the first element from the vector, and we
2788   //      stop searching the def-use chain here.
2789   //
2790   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2791   // from 1-3 to the stack to continue the DFS. The given instruction is not
2792   // a reduction operation if we meet any other instructions other than those
2793   // listed above.
2794 
2795   SmallVector<const User *, 16> UsersToVisit{Inst};
2796   SmallPtrSet<const User *, 16> Visited;
2797   bool ReduxExtracted = false;
2798 
2799   while (!UsersToVisit.empty()) {
2800     auto User = UsersToVisit.back();
2801     UsersToVisit.pop_back();
2802     if (!Visited.insert(User).second)
2803       continue;
2804 
2805     for (const auto &U : User->users()) {
2806       auto Inst = dyn_cast<Instruction>(U);
2807       if (!Inst)
2808         return false;
2809 
2810       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2811         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2812           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2813             return false;
2814         UsersToVisit.push_back(U);
2815       } else if (const ShuffleVectorInst *ShufInst =
2816                      dyn_cast<ShuffleVectorInst>(U)) {
2817         // Detect the following pattern: A ShuffleVector instruction together
2818         // with a reduction that do partial reduction on the first and second
2819         // ElemNumToReduce / 2 elements, and store the result in
2820         // ElemNumToReduce / 2 elements in another vector.
2821 
2822         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2823         if (ResultElements < ElemNum)
2824           return false;
2825 
2826         if (ElemNumToReduce == 1)
2827           return false;
2828         if (!isa<UndefValue>(U->getOperand(1)))
2829           return false;
2830         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2831           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2832             return false;
2833         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2834           if (ShufInst->getMaskValue(i) != -1)
2835             return false;
2836 
2837         // There is only one user of this ShuffleVector instruction, which
2838         // must be a reduction operation.
2839         if (!U->hasOneUse())
2840           return false;
2841 
2842         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2843         if (!U2 || U2->getOpcode() != OpCode)
2844           return false;
2845 
2846         // Check operands of the reduction operation.
2847         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2848             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2849           UsersToVisit.push_back(U2);
2850           ElemNumToReduce /= 2;
2851         } else
2852           return false;
2853       } else if (isa<ExtractElementInst>(U)) {
2854         // At this moment we should have reduced all elements in the vector.
2855         if (ElemNumToReduce != 1)
2856           return false;
2857 
2858         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2859         if (!Val || !Val->isZero())
2860           return false;
2861 
2862         ReduxExtracted = true;
2863       } else
2864         return false;
2865     }
2866   }
2867   return ReduxExtracted;
2868 }
2869 
2870 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2871   SDNodeFlags Flags;
2872 
2873   SDValue Op = getValue(I.getOperand(0));
2874   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2875                                     Op, Flags);
2876   setValue(&I, UnNodeValue);
2877 }
2878 
2879 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2880   SDNodeFlags Flags;
2881   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2882     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2883     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2884   }
2885   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2886     Flags.setExact(ExactOp->isExact());
2887   }
2888   if (isVectorReductionOp(&I)) {
2889     Flags.setVectorReduction(true);
2890     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2891   }
2892 
2893   SDValue Op1 = getValue(I.getOperand(0));
2894   SDValue Op2 = getValue(I.getOperand(1));
2895   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2896                                      Op1, Op2, Flags);
2897   setValue(&I, BinNodeValue);
2898 }
2899 
2900 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2901   SDValue Op1 = getValue(I.getOperand(0));
2902   SDValue Op2 = getValue(I.getOperand(1));
2903 
2904   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2905       Op1.getValueType(), DAG.getDataLayout());
2906 
2907   // Coerce the shift amount to the right type if we can.
2908   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2909     unsigned ShiftSize = ShiftTy.getSizeInBits();
2910     unsigned Op2Size = Op2.getValueSizeInBits();
2911     SDLoc DL = getCurSDLoc();
2912 
2913     // If the operand is smaller than the shift count type, promote it.
2914     if (ShiftSize > Op2Size)
2915       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2916 
2917     // If the operand is larger than the shift count type but the shift
2918     // count type has enough bits to represent any shift value, truncate
2919     // it now. This is a common case and it exposes the truncate to
2920     // optimization early.
2921     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2922       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2923     // Otherwise we'll need to temporarily settle for some other convenient
2924     // type.  Type legalization will make adjustments once the shiftee is split.
2925     else
2926       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2927   }
2928 
2929   bool nuw = false;
2930   bool nsw = false;
2931   bool exact = false;
2932 
2933   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2934 
2935     if (const OverflowingBinaryOperator *OFBinOp =
2936             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2937       nuw = OFBinOp->hasNoUnsignedWrap();
2938       nsw = OFBinOp->hasNoSignedWrap();
2939     }
2940     if (const PossiblyExactOperator *ExactOp =
2941             dyn_cast<const PossiblyExactOperator>(&I))
2942       exact = ExactOp->isExact();
2943   }
2944   SDNodeFlags Flags;
2945   Flags.setExact(exact);
2946   Flags.setNoSignedWrap(nsw);
2947   Flags.setNoUnsignedWrap(nuw);
2948   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2949                             Flags);
2950   setValue(&I, Res);
2951 }
2952 
2953 void SelectionDAGBuilder::visitSDiv(const User &I) {
2954   SDValue Op1 = getValue(I.getOperand(0));
2955   SDValue Op2 = getValue(I.getOperand(1));
2956 
2957   SDNodeFlags Flags;
2958   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2959                  cast<PossiblyExactOperator>(&I)->isExact());
2960   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2961                            Op2, Flags));
2962 }
2963 
2964 void SelectionDAGBuilder::visitICmp(const User &I) {
2965   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2966   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2967     predicate = IC->getPredicate();
2968   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2969     predicate = ICmpInst::Predicate(IC->getPredicate());
2970   SDValue Op1 = getValue(I.getOperand(0));
2971   SDValue Op2 = getValue(I.getOperand(1));
2972   ISD::CondCode Opcode = getICmpCondCode(predicate);
2973 
2974   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2975                                                         I.getType());
2976   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2977 }
2978 
2979 void SelectionDAGBuilder::visitFCmp(const User &I) {
2980   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2981   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2982     predicate = FC->getPredicate();
2983   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2984     predicate = FCmpInst::Predicate(FC->getPredicate());
2985   SDValue Op1 = getValue(I.getOperand(0));
2986   SDValue Op2 = getValue(I.getOperand(1));
2987 
2988   ISD::CondCode Condition = getFCmpCondCode(predicate);
2989   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2990   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2991     Condition = getFCmpCodeWithoutNaN(Condition);
2992 
2993   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2994                                                         I.getType());
2995   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2996 }
2997 
2998 // Check if the condition of the select has one use or two users that are both
2999 // selects with the same condition.
3000 static bool hasOnlySelectUsers(const Value *Cond) {
3001   return llvm::all_of(Cond->users(), [](const Value *V) {
3002     return isa<SelectInst>(V);
3003   });
3004 }
3005 
3006 void SelectionDAGBuilder::visitSelect(const User &I) {
3007   SmallVector<EVT, 4> ValueVTs;
3008   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3009                   ValueVTs);
3010   unsigned NumValues = ValueVTs.size();
3011   if (NumValues == 0) return;
3012 
3013   SmallVector<SDValue, 4> Values(NumValues);
3014   SDValue Cond     = getValue(I.getOperand(0));
3015   SDValue LHSVal   = getValue(I.getOperand(1));
3016   SDValue RHSVal   = getValue(I.getOperand(2));
3017   auto BaseOps = {Cond};
3018   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3019     ISD::VSELECT : ISD::SELECT;
3020 
3021   // Min/max matching is only viable if all output VTs are the same.
3022   if (is_splat(ValueVTs)) {
3023     EVT VT = ValueVTs[0];
3024     LLVMContext &Ctx = *DAG.getContext();
3025     auto &TLI = DAG.getTargetLoweringInfo();
3026 
3027     // We care about the legality of the operation after it has been type
3028     // legalized.
3029     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3030            VT != TLI.getTypeToTransformTo(Ctx, VT))
3031       VT = TLI.getTypeToTransformTo(Ctx, VT);
3032 
3033     // If the vselect is legal, assume we want to leave this as a vector setcc +
3034     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3035     // min/max is legal on the scalar type.
3036     bool UseScalarMinMax = VT.isVector() &&
3037       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3038 
3039     Value *LHS, *RHS;
3040     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3041     ISD::NodeType Opc = ISD::DELETED_NODE;
3042     switch (SPR.Flavor) {
3043     case SPF_UMAX:    Opc = ISD::UMAX; break;
3044     case SPF_UMIN:    Opc = ISD::UMIN; break;
3045     case SPF_SMAX:    Opc = ISD::SMAX; break;
3046     case SPF_SMIN:    Opc = ISD::SMIN; break;
3047     case SPF_FMINNUM:
3048       switch (SPR.NaNBehavior) {
3049       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3050       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3051       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3052       case SPNB_RETURNS_ANY: {
3053         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3054           Opc = ISD::FMINNUM;
3055         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3056           Opc = ISD::FMINIMUM;
3057         else if (UseScalarMinMax)
3058           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3059             ISD::FMINNUM : ISD::FMINIMUM;
3060         break;
3061       }
3062       }
3063       break;
3064     case SPF_FMAXNUM:
3065       switch (SPR.NaNBehavior) {
3066       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3067       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3068       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3069       case SPNB_RETURNS_ANY:
3070 
3071         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3072           Opc = ISD::FMAXNUM;
3073         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3074           Opc = ISD::FMAXIMUM;
3075         else if (UseScalarMinMax)
3076           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3077             ISD::FMAXNUM : ISD::FMAXIMUM;
3078         break;
3079       }
3080       break;
3081     default: break;
3082     }
3083 
3084     if (Opc != ISD::DELETED_NODE &&
3085         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3086          (UseScalarMinMax &&
3087           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3088         // If the underlying comparison instruction is used by any other
3089         // instruction, the consumed instructions won't be destroyed, so it is
3090         // not profitable to convert to a min/max.
3091         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3092       OpCode = Opc;
3093       LHSVal = getValue(LHS);
3094       RHSVal = getValue(RHS);
3095       BaseOps = {};
3096     }
3097   }
3098 
3099   for (unsigned i = 0; i != NumValues; ++i) {
3100     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3101     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3102     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3103     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3104                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3105                             Ops);
3106   }
3107 
3108   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3109                            DAG.getVTList(ValueVTs), Values));
3110 }
3111 
3112 void SelectionDAGBuilder::visitTrunc(const User &I) {
3113   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3114   SDValue N = getValue(I.getOperand(0));
3115   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3116                                                         I.getType());
3117   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3118 }
3119 
3120 void SelectionDAGBuilder::visitZExt(const User &I) {
3121   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3122   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3123   SDValue N = getValue(I.getOperand(0));
3124   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3125                                                         I.getType());
3126   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3127 }
3128 
3129 void SelectionDAGBuilder::visitSExt(const User &I) {
3130   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3131   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3132   SDValue N = getValue(I.getOperand(0));
3133   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3134                                                         I.getType());
3135   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3136 }
3137 
3138 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3139   // FPTrunc is never a no-op cast, no need to check
3140   SDValue N = getValue(I.getOperand(0));
3141   SDLoc dl = getCurSDLoc();
3142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3143   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3144   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3145                            DAG.getTargetConstant(
3146                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3147 }
3148 
3149 void SelectionDAGBuilder::visitFPExt(const User &I) {
3150   // FPExt is never a no-op cast, no need to check
3151   SDValue N = getValue(I.getOperand(0));
3152   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3153                                                         I.getType());
3154   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3155 }
3156 
3157 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3158   // FPToUI is never a no-op cast, no need to check
3159   SDValue N = getValue(I.getOperand(0));
3160   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3161                                                         I.getType());
3162   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3163 }
3164 
3165 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3166   // FPToSI is never a no-op cast, no need to check
3167   SDValue N = getValue(I.getOperand(0));
3168   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3169                                                         I.getType());
3170   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3171 }
3172 
3173 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3174   // UIToFP is never a no-op cast, no need to check
3175   SDValue N = getValue(I.getOperand(0));
3176   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3177                                                         I.getType());
3178   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3179 }
3180 
3181 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3182   // SIToFP is never a no-op cast, no need to check
3183   SDValue N = getValue(I.getOperand(0));
3184   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3185                                                         I.getType());
3186   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3187 }
3188 
3189 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3190   // What to do depends on the size of the integer and the size of the pointer.
3191   // We can either truncate, zero extend, or no-op, accordingly.
3192   SDValue N = getValue(I.getOperand(0));
3193   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3194                                                         I.getType());
3195   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3196 }
3197 
3198 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3199   // What to do depends on the size of the integer and the size of the pointer.
3200   // We can either truncate, zero extend, or no-op, accordingly.
3201   SDValue N = getValue(I.getOperand(0));
3202   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3203                                                         I.getType());
3204   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3205 }
3206 
3207 void SelectionDAGBuilder::visitBitCast(const User &I) {
3208   SDValue N = getValue(I.getOperand(0));
3209   SDLoc dl = getCurSDLoc();
3210   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3211                                                         I.getType());
3212 
3213   // BitCast assures us that source and destination are the same size so this is
3214   // either a BITCAST or a no-op.
3215   if (DestVT != N.getValueType())
3216     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3217                              DestVT, N)); // convert types.
3218   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3219   // might fold any kind of constant expression to an integer constant and that
3220   // is not what we are looking for. Only recognize a bitcast of a genuine
3221   // constant integer as an opaque constant.
3222   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3223     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3224                                  /*isOpaque*/true));
3225   else
3226     setValue(&I, N);            // noop cast.
3227 }
3228 
3229 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3231   const Value *SV = I.getOperand(0);
3232   SDValue N = getValue(SV);
3233   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3234 
3235   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3236   unsigned DestAS = I.getType()->getPointerAddressSpace();
3237 
3238   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3239     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3240 
3241   setValue(&I, N);
3242 }
3243 
3244 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3246   SDValue InVec = getValue(I.getOperand(0));
3247   SDValue InVal = getValue(I.getOperand(1));
3248   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3249                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3250   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3251                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3252                            InVec, InVal, InIdx));
3253 }
3254 
3255 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3257   SDValue InVec = getValue(I.getOperand(0));
3258   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3259                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3260   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3261                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3262                            InVec, InIdx));
3263 }
3264 
3265 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3266   SDValue Src1 = getValue(I.getOperand(0));
3267   SDValue Src2 = getValue(I.getOperand(1));
3268   SDLoc DL = getCurSDLoc();
3269 
3270   SmallVector<int, 8> Mask;
3271   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3272   unsigned MaskNumElts = Mask.size();
3273 
3274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3276   EVT SrcVT = Src1.getValueType();
3277   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3278 
3279   if (SrcNumElts == MaskNumElts) {
3280     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3281     return;
3282   }
3283 
3284   // Normalize the shuffle vector since mask and vector length don't match.
3285   if (SrcNumElts < MaskNumElts) {
3286     // Mask is longer than the source vectors. We can use concatenate vector to
3287     // make the mask and vectors lengths match.
3288 
3289     if (MaskNumElts % SrcNumElts == 0) {
3290       // Mask length is a multiple of the source vector length.
3291       // Check if the shuffle is some kind of concatenation of the input
3292       // vectors.
3293       unsigned NumConcat = MaskNumElts / SrcNumElts;
3294       bool IsConcat = true;
3295       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3296       for (unsigned i = 0; i != MaskNumElts; ++i) {
3297         int Idx = Mask[i];
3298         if (Idx < 0)
3299           continue;
3300         // Ensure the indices in each SrcVT sized piece are sequential and that
3301         // the same source is used for the whole piece.
3302         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3303             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3304              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3305           IsConcat = false;
3306           break;
3307         }
3308         // Remember which source this index came from.
3309         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3310       }
3311 
3312       // The shuffle is concatenating multiple vectors together. Just emit
3313       // a CONCAT_VECTORS operation.
3314       if (IsConcat) {
3315         SmallVector<SDValue, 8> ConcatOps;
3316         for (auto Src : ConcatSrcs) {
3317           if (Src < 0)
3318             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3319           else if (Src == 0)
3320             ConcatOps.push_back(Src1);
3321           else
3322             ConcatOps.push_back(Src2);
3323         }
3324         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3325         return;
3326       }
3327     }
3328 
3329     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3330     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3331     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3332                                     PaddedMaskNumElts);
3333 
3334     // Pad both vectors with undefs to make them the same length as the mask.
3335     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3336 
3337     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3338     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3339     MOps1[0] = Src1;
3340     MOps2[0] = Src2;
3341 
3342     Src1 = Src1.isUndef()
3343                ? DAG.getUNDEF(PaddedVT)
3344                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3345     Src2 = Src2.isUndef()
3346                ? DAG.getUNDEF(PaddedVT)
3347                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3348 
3349     // Readjust mask for new input vector length.
3350     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3351     for (unsigned i = 0; i != MaskNumElts; ++i) {
3352       int Idx = Mask[i];
3353       if (Idx >= (int)SrcNumElts)
3354         Idx -= SrcNumElts - PaddedMaskNumElts;
3355       MappedOps[i] = Idx;
3356     }
3357 
3358     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3359 
3360     // If the concatenated vector was padded, extract a subvector with the
3361     // correct number of elements.
3362     if (MaskNumElts != PaddedMaskNumElts)
3363       Result = DAG.getNode(
3364           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3365           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3366 
3367     setValue(&I, Result);
3368     return;
3369   }
3370 
3371   if (SrcNumElts > MaskNumElts) {
3372     // Analyze the access pattern of the vector to see if we can extract
3373     // two subvectors and do the shuffle.
3374     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3375     bool CanExtract = true;
3376     for (int Idx : Mask) {
3377       unsigned Input = 0;
3378       if (Idx < 0)
3379         continue;
3380 
3381       if (Idx >= (int)SrcNumElts) {
3382         Input = 1;
3383         Idx -= SrcNumElts;
3384       }
3385 
3386       // If all the indices come from the same MaskNumElts sized portion of
3387       // the sources we can use extract. Also make sure the extract wouldn't
3388       // extract past the end of the source.
3389       int NewStartIdx = alignDown(Idx, MaskNumElts);
3390       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3391           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3392         CanExtract = false;
3393       // Make sure we always update StartIdx as we use it to track if all
3394       // elements are undef.
3395       StartIdx[Input] = NewStartIdx;
3396     }
3397 
3398     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3399       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3400       return;
3401     }
3402     if (CanExtract) {
3403       // Extract appropriate subvector and generate a vector shuffle
3404       for (unsigned Input = 0; Input < 2; ++Input) {
3405         SDValue &Src = Input == 0 ? Src1 : Src2;
3406         if (StartIdx[Input] < 0)
3407           Src = DAG.getUNDEF(VT);
3408         else {
3409           Src = DAG.getNode(
3410               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3411               DAG.getConstant(StartIdx[Input], DL,
3412                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3413         }
3414       }
3415 
3416       // Calculate new mask.
3417       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3418       for (int &Idx : MappedOps) {
3419         if (Idx >= (int)SrcNumElts)
3420           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3421         else if (Idx >= 0)
3422           Idx -= StartIdx[0];
3423       }
3424 
3425       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3426       return;
3427     }
3428   }
3429 
3430   // We can't use either concat vectors or extract subvectors so fall back to
3431   // replacing the shuffle with extract and build vector.
3432   // to insert and build vector.
3433   EVT EltVT = VT.getVectorElementType();
3434   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3435   SmallVector<SDValue,8> Ops;
3436   for (int Idx : Mask) {
3437     SDValue Res;
3438 
3439     if (Idx < 0) {
3440       Res = DAG.getUNDEF(EltVT);
3441     } else {
3442       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3443       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3444 
3445       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3446                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3447     }
3448 
3449     Ops.push_back(Res);
3450   }
3451 
3452   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3453 }
3454 
3455 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3456   ArrayRef<unsigned> Indices;
3457   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3458     Indices = IV->getIndices();
3459   else
3460     Indices = cast<ConstantExpr>(&I)->getIndices();
3461 
3462   const Value *Op0 = I.getOperand(0);
3463   const Value *Op1 = I.getOperand(1);
3464   Type *AggTy = I.getType();
3465   Type *ValTy = Op1->getType();
3466   bool IntoUndef = isa<UndefValue>(Op0);
3467   bool FromUndef = isa<UndefValue>(Op1);
3468 
3469   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3470 
3471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3472   SmallVector<EVT, 4> AggValueVTs;
3473   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3474   SmallVector<EVT, 4> ValValueVTs;
3475   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3476 
3477   unsigned NumAggValues = AggValueVTs.size();
3478   unsigned NumValValues = ValValueVTs.size();
3479   SmallVector<SDValue, 4> Values(NumAggValues);
3480 
3481   // Ignore an insertvalue that produces an empty object
3482   if (!NumAggValues) {
3483     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3484     return;
3485   }
3486 
3487   SDValue Agg = getValue(Op0);
3488   unsigned i = 0;
3489   // Copy the beginning value(s) from the original aggregate.
3490   for (; i != LinearIndex; ++i)
3491     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3492                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3493   // Copy values from the inserted value(s).
3494   if (NumValValues) {
3495     SDValue Val = getValue(Op1);
3496     for (; i != LinearIndex + NumValValues; ++i)
3497       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3498                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3499   }
3500   // Copy remaining value(s) from the original aggregate.
3501   for (; i != NumAggValues; ++i)
3502     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3503                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3504 
3505   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3506                            DAG.getVTList(AggValueVTs), Values));
3507 }
3508 
3509 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3510   ArrayRef<unsigned> Indices;
3511   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3512     Indices = EV->getIndices();
3513   else
3514     Indices = cast<ConstantExpr>(&I)->getIndices();
3515 
3516   const Value *Op0 = I.getOperand(0);
3517   Type *AggTy = Op0->getType();
3518   Type *ValTy = I.getType();
3519   bool OutOfUndef = isa<UndefValue>(Op0);
3520 
3521   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3522 
3523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3524   SmallVector<EVT, 4> ValValueVTs;
3525   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3526 
3527   unsigned NumValValues = ValValueVTs.size();
3528 
3529   // Ignore a extractvalue that produces an empty object
3530   if (!NumValValues) {
3531     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3532     return;
3533   }
3534 
3535   SmallVector<SDValue, 4> Values(NumValValues);
3536 
3537   SDValue Agg = getValue(Op0);
3538   // Copy out the selected value(s).
3539   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3540     Values[i - LinearIndex] =
3541       OutOfUndef ?
3542         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3543         SDValue(Agg.getNode(), Agg.getResNo() + i);
3544 
3545   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3546                            DAG.getVTList(ValValueVTs), Values));
3547 }
3548 
3549 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3550   Value *Op0 = I.getOperand(0);
3551   // Note that the pointer operand may be a vector of pointers. Take the scalar
3552   // element which holds a pointer.
3553   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3554   SDValue N = getValue(Op0);
3555   SDLoc dl = getCurSDLoc();
3556 
3557   // Normalize Vector GEP - all scalar operands should be converted to the
3558   // splat vector.
3559   unsigned VectorWidth = I.getType()->isVectorTy() ?
3560     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3561 
3562   if (VectorWidth && !N.getValueType().isVector()) {
3563     LLVMContext &Context = *DAG.getContext();
3564     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3565     N = DAG.getSplatBuildVector(VT, dl, N);
3566   }
3567 
3568   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3569        GTI != E; ++GTI) {
3570     const Value *Idx = GTI.getOperand();
3571     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3572       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3573       if (Field) {
3574         // N = N + Offset
3575         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3576 
3577         // In an inbounds GEP with an offset that is nonnegative even when
3578         // interpreted as signed, assume there is no unsigned overflow.
3579         SDNodeFlags Flags;
3580         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3581           Flags.setNoUnsignedWrap(true);
3582 
3583         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3584                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3585       }
3586     } else {
3587       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3588       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3589       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3590 
3591       // If this is a scalar constant or a splat vector of constants,
3592       // handle it quickly.
3593       const auto *CI = dyn_cast<ConstantInt>(Idx);
3594       if (!CI && isa<ConstantDataVector>(Idx) &&
3595           cast<ConstantDataVector>(Idx)->getSplatValue())
3596         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3597 
3598       if (CI) {
3599         if (CI->isZero())
3600           continue;
3601         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3602         LLVMContext &Context = *DAG.getContext();
3603         SDValue OffsVal = VectorWidth ?
3604           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3605           DAG.getConstant(Offs, dl, IdxTy);
3606 
3607         // In an inbouds GEP with an offset that is nonnegative even when
3608         // interpreted as signed, assume there is no unsigned overflow.
3609         SDNodeFlags Flags;
3610         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3611           Flags.setNoUnsignedWrap(true);
3612 
3613         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3614         continue;
3615       }
3616 
3617       // N = N + Idx * ElementSize;
3618       SDValue IdxN = getValue(Idx);
3619 
3620       if (!IdxN.getValueType().isVector() && VectorWidth) {
3621         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3622         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3623       }
3624 
3625       // If the index is smaller or larger than intptr_t, truncate or extend
3626       // it.
3627       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3628 
3629       // If this is a multiply by a power of two, turn it into a shl
3630       // immediately.  This is a very common case.
3631       if (ElementSize != 1) {
3632         if (ElementSize.isPowerOf2()) {
3633           unsigned Amt = ElementSize.logBase2();
3634           IdxN = DAG.getNode(ISD::SHL, dl,
3635                              N.getValueType(), IdxN,
3636                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3637         } else {
3638           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3639           IdxN = DAG.getNode(ISD::MUL, dl,
3640                              N.getValueType(), IdxN, Scale);
3641         }
3642       }
3643 
3644       N = DAG.getNode(ISD::ADD, dl,
3645                       N.getValueType(), N, IdxN);
3646     }
3647   }
3648 
3649   setValue(&I, N);
3650 }
3651 
3652 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3653   // If this is a fixed sized alloca in the entry block of the function,
3654   // allocate it statically on the stack.
3655   if (FuncInfo.StaticAllocaMap.count(&I))
3656     return;   // getValue will auto-populate this.
3657 
3658   SDLoc dl = getCurSDLoc();
3659   Type *Ty = I.getAllocatedType();
3660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3661   auto &DL = DAG.getDataLayout();
3662   uint64_t TySize = DL.getTypeAllocSize(Ty);
3663   unsigned Align =
3664       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3665 
3666   SDValue AllocSize = getValue(I.getArraySize());
3667 
3668   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3669   if (AllocSize.getValueType() != IntPtr)
3670     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3671 
3672   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3673                           AllocSize,
3674                           DAG.getConstant(TySize, dl, IntPtr));
3675 
3676   // Handle alignment.  If the requested alignment is less than or equal to
3677   // the stack alignment, ignore it.  If the size is greater than or equal to
3678   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3679   unsigned StackAlign =
3680       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3681   if (Align <= StackAlign)
3682     Align = 0;
3683 
3684   // Round the size of the allocation up to the stack alignment size
3685   // by add SA-1 to the size. This doesn't overflow because we're computing
3686   // an address inside an alloca.
3687   SDNodeFlags Flags;
3688   Flags.setNoUnsignedWrap(true);
3689   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3690                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3691 
3692   // Mask out the low bits for alignment purposes.
3693   AllocSize =
3694       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3695                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3696 
3697   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3698   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3699   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3700   setValue(&I, DSA);
3701   DAG.setRoot(DSA.getValue(1));
3702 
3703   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3704 }
3705 
3706 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3707   if (I.isAtomic())
3708     return visitAtomicLoad(I);
3709 
3710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3711   const Value *SV = I.getOperand(0);
3712   if (TLI.supportSwiftError()) {
3713     // Swifterror values can come from either a function parameter with
3714     // swifterror attribute or an alloca with swifterror attribute.
3715     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3716       if (Arg->hasSwiftErrorAttr())
3717         return visitLoadFromSwiftError(I);
3718     }
3719 
3720     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3721       if (Alloca->isSwiftError())
3722         return visitLoadFromSwiftError(I);
3723     }
3724   }
3725 
3726   SDValue Ptr = getValue(SV);
3727 
3728   Type *Ty = I.getType();
3729 
3730   bool isVolatile = I.isVolatile();
3731   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3732   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3733   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3734   unsigned Alignment = I.getAlignment();
3735 
3736   AAMDNodes AAInfo;
3737   I.getAAMetadata(AAInfo);
3738   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3739 
3740   SmallVector<EVT, 4> ValueVTs;
3741   SmallVector<uint64_t, 4> Offsets;
3742   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3743   unsigned NumValues = ValueVTs.size();
3744   if (NumValues == 0)
3745     return;
3746 
3747   SDValue Root;
3748   bool ConstantMemory = false;
3749   if (isVolatile || NumValues > MaxParallelChains)
3750     // Serialize volatile loads with other side effects.
3751     Root = getRoot();
3752   else if (AA &&
3753            AA->pointsToConstantMemory(MemoryLocation(
3754                SV,
3755                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3756                AAInfo))) {
3757     // Do not serialize (non-volatile) loads of constant memory with anything.
3758     Root = DAG.getEntryNode();
3759     ConstantMemory = true;
3760   } else {
3761     // Do not serialize non-volatile loads against each other.
3762     Root = DAG.getRoot();
3763   }
3764 
3765   SDLoc dl = getCurSDLoc();
3766 
3767   if (isVolatile)
3768     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3769 
3770   // An aggregate load cannot wrap around the address space, so offsets to its
3771   // parts don't wrap either.
3772   SDNodeFlags Flags;
3773   Flags.setNoUnsignedWrap(true);
3774 
3775   SmallVector<SDValue, 4> Values(NumValues);
3776   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3777   EVT PtrVT = Ptr.getValueType();
3778   unsigned ChainI = 0;
3779   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3780     // Serializing loads here may result in excessive register pressure, and
3781     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3782     // could recover a bit by hoisting nodes upward in the chain by recognizing
3783     // they are side-effect free or do not alias. The optimizer should really
3784     // avoid this case by converting large object/array copies to llvm.memcpy
3785     // (MaxParallelChains should always remain as failsafe).
3786     if (ChainI == MaxParallelChains) {
3787       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3788       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3789                                   makeArrayRef(Chains.data(), ChainI));
3790       Root = Chain;
3791       ChainI = 0;
3792     }
3793     SDValue A = DAG.getNode(ISD::ADD, dl,
3794                             PtrVT, Ptr,
3795                             DAG.getConstant(Offsets[i], dl, PtrVT),
3796                             Flags);
3797     auto MMOFlags = MachineMemOperand::MONone;
3798     if (isVolatile)
3799       MMOFlags |= MachineMemOperand::MOVolatile;
3800     if (isNonTemporal)
3801       MMOFlags |= MachineMemOperand::MONonTemporal;
3802     if (isInvariant)
3803       MMOFlags |= MachineMemOperand::MOInvariant;
3804     if (isDereferenceable)
3805       MMOFlags |= MachineMemOperand::MODereferenceable;
3806     MMOFlags |= TLI.getMMOFlags(I);
3807 
3808     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3809                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3810                             MMOFlags, AAInfo, Ranges);
3811 
3812     Values[i] = L;
3813     Chains[ChainI] = L.getValue(1);
3814   }
3815 
3816   if (!ConstantMemory) {
3817     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3818                                 makeArrayRef(Chains.data(), ChainI));
3819     if (isVolatile)
3820       DAG.setRoot(Chain);
3821     else
3822       PendingLoads.push_back(Chain);
3823   }
3824 
3825   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3826                            DAG.getVTList(ValueVTs), Values));
3827 }
3828 
3829 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3830   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3831          "call visitStoreToSwiftError when backend supports swifterror");
3832 
3833   SmallVector<EVT, 4> ValueVTs;
3834   SmallVector<uint64_t, 4> Offsets;
3835   const Value *SrcV = I.getOperand(0);
3836   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3837                   SrcV->getType(), ValueVTs, &Offsets);
3838   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3839          "expect a single EVT for swifterror");
3840 
3841   SDValue Src = getValue(SrcV);
3842   // Create a virtual register, then update the virtual register.
3843   unsigned VReg; bool CreatedVReg;
3844   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3845   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3846   // Chain can be getRoot or getControlRoot.
3847   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3848                                       SDValue(Src.getNode(), Src.getResNo()));
3849   DAG.setRoot(CopyNode);
3850   if (CreatedVReg)
3851     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3852 }
3853 
3854 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3855   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3856          "call visitLoadFromSwiftError when backend supports swifterror");
3857 
3858   assert(!I.isVolatile() &&
3859          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3860          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3861          "Support volatile, non temporal, invariant for load_from_swift_error");
3862 
3863   const Value *SV = I.getOperand(0);
3864   Type *Ty = I.getType();
3865   AAMDNodes AAInfo;
3866   I.getAAMetadata(AAInfo);
3867   assert(
3868       (!AA ||
3869        !AA->pointsToConstantMemory(MemoryLocation(
3870            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3871            AAInfo))) &&
3872       "load_from_swift_error should not be constant memory");
3873 
3874   SmallVector<EVT, 4> ValueVTs;
3875   SmallVector<uint64_t, 4> Offsets;
3876   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3877                   ValueVTs, &Offsets);
3878   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3879          "expect a single EVT for swifterror");
3880 
3881   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3882   SDValue L = DAG.getCopyFromReg(
3883       getRoot(), getCurSDLoc(),
3884       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3885       ValueVTs[0]);
3886 
3887   setValue(&I, L);
3888 }
3889 
3890 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3891   if (I.isAtomic())
3892     return visitAtomicStore(I);
3893 
3894   const Value *SrcV = I.getOperand(0);
3895   const Value *PtrV = I.getOperand(1);
3896 
3897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3898   if (TLI.supportSwiftError()) {
3899     // Swifterror values can come from either a function parameter with
3900     // swifterror attribute or an alloca with swifterror attribute.
3901     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3902       if (Arg->hasSwiftErrorAttr())
3903         return visitStoreToSwiftError(I);
3904     }
3905 
3906     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3907       if (Alloca->isSwiftError())
3908         return visitStoreToSwiftError(I);
3909     }
3910   }
3911 
3912   SmallVector<EVT, 4> ValueVTs;
3913   SmallVector<uint64_t, 4> Offsets;
3914   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3915                   SrcV->getType(), ValueVTs, &Offsets);
3916   unsigned NumValues = ValueVTs.size();
3917   if (NumValues == 0)
3918     return;
3919 
3920   // Get the lowered operands. Note that we do this after
3921   // checking if NumResults is zero, because with zero results
3922   // the operands won't have values in the map.
3923   SDValue Src = getValue(SrcV);
3924   SDValue Ptr = getValue(PtrV);
3925 
3926   SDValue Root = getRoot();
3927   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3928   SDLoc dl = getCurSDLoc();
3929   EVT PtrVT = Ptr.getValueType();
3930   unsigned Alignment = I.getAlignment();
3931   AAMDNodes AAInfo;
3932   I.getAAMetadata(AAInfo);
3933 
3934   auto MMOFlags = MachineMemOperand::MONone;
3935   if (I.isVolatile())
3936     MMOFlags |= MachineMemOperand::MOVolatile;
3937   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3938     MMOFlags |= MachineMemOperand::MONonTemporal;
3939   MMOFlags |= TLI.getMMOFlags(I);
3940 
3941   // An aggregate load cannot wrap around the address space, so offsets to its
3942   // parts don't wrap either.
3943   SDNodeFlags Flags;
3944   Flags.setNoUnsignedWrap(true);
3945 
3946   unsigned ChainI = 0;
3947   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3948     // See visitLoad comments.
3949     if (ChainI == MaxParallelChains) {
3950       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3951                                   makeArrayRef(Chains.data(), ChainI));
3952       Root = Chain;
3953       ChainI = 0;
3954     }
3955     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3956                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3957     SDValue St = DAG.getStore(
3958         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3959         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3960     Chains[ChainI] = St;
3961   }
3962 
3963   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3964                                   makeArrayRef(Chains.data(), ChainI));
3965   DAG.setRoot(StoreNode);
3966 }
3967 
3968 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3969                                            bool IsCompressing) {
3970   SDLoc sdl = getCurSDLoc();
3971 
3972   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3973                            unsigned& Alignment) {
3974     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3975     Src0 = I.getArgOperand(0);
3976     Ptr = I.getArgOperand(1);
3977     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3978     Mask = I.getArgOperand(3);
3979   };
3980   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3981                            unsigned& Alignment) {
3982     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3983     Src0 = I.getArgOperand(0);
3984     Ptr = I.getArgOperand(1);
3985     Mask = I.getArgOperand(2);
3986     Alignment = 0;
3987   };
3988 
3989   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3990   unsigned Alignment;
3991   if (IsCompressing)
3992     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3993   else
3994     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3995 
3996   SDValue Ptr = getValue(PtrOperand);
3997   SDValue Src0 = getValue(Src0Operand);
3998   SDValue Mask = getValue(MaskOperand);
3999 
4000   EVT VT = Src0.getValueType();
4001   if (!Alignment)
4002     Alignment = DAG.getEVTAlignment(VT);
4003 
4004   AAMDNodes AAInfo;
4005   I.getAAMetadata(AAInfo);
4006 
4007   MachineMemOperand *MMO =
4008     DAG.getMachineFunction().
4009     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4010                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4011                           Alignment, AAInfo);
4012   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4013                                          MMO, false /* Truncating */,
4014                                          IsCompressing);
4015   DAG.setRoot(StoreNode);
4016   setValue(&I, StoreNode);
4017 }
4018 
4019 // Get a uniform base for the Gather/Scatter intrinsic.
4020 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4021 // We try to represent it as a base pointer + vector of indices.
4022 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4023 // The first operand of the GEP may be a single pointer or a vector of pointers
4024 // Example:
4025 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4026 //  or
4027 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4028 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4029 //
4030 // When the first GEP operand is a single pointer - it is the uniform base we
4031 // are looking for. If first operand of the GEP is a splat vector - we
4032 // extract the splat value and use it as a uniform base.
4033 // In all other cases the function returns 'false'.
4034 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4035                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4036   SelectionDAG& DAG = SDB->DAG;
4037   LLVMContext &Context = *DAG.getContext();
4038 
4039   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4040   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4041   if (!GEP)
4042     return false;
4043 
4044   const Value *GEPPtr = GEP->getPointerOperand();
4045   if (!GEPPtr->getType()->isVectorTy())
4046     Ptr = GEPPtr;
4047   else if (!(Ptr = getSplatValue(GEPPtr)))
4048     return false;
4049 
4050   unsigned FinalIndex = GEP->getNumOperands() - 1;
4051   Value *IndexVal = GEP->getOperand(FinalIndex);
4052 
4053   // Ensure all the other indices are 0.
4054   for (unsigned i = 1; i < FinalIndex; ++i) {
4055     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4056     if (!C || !C->isZero())
4057       return false;
4058   }
4059 
4060   // The operands of the GEP may be defined in another basic block.
4061   // In this case we'll not find nodes for the operands.
4062   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4063     return false;
4064 
4065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4066   const DataLayout &DL = DAG.getDataLayout();
4067   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4068                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4069   Base = SDB->getValue(Ptr);
4070   Index = SDB->getValue(IndexVal);
4071 
4072   if (!Index.getValueType().isVector()) {
4073     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4074     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4075     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4076   }
4077   return true;
4078 }
4079 
4080 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4081   SDLoc sdl = getCurSDLoc();
4082 
4083   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4084   const Value *Ptr = I.getArgOperand(1);
4085   SDValue Src0 = getValue(I.getArgOperand(0));
4086   SDValue Mask = getValue(I.getArgOperand(3));
4087   EVT VT = Src0.getValueType();
4088   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4089   if (!Alignment)
4090     Alignment = DAG.getEVTAlignment(VT);
4091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4092 
4093   AAMDNodes AAInfo;
4094   I.getAAMetadata(AAInfo);
4095 
4096   SDValue Base;
4097   SDValue Index;
4098   SDValue Scale;
4099   const Value *BasePtr = Ptr;
4100   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4101 
4102   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4103   MachineMemOperand *MMO = DAG.getMachineFunction().
4104     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4105                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4106                          Alignment, AAInfo);
4107   if (!UniformBase) {
4108     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4109     Index = getValue(Ptr);
4110     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4111   }
4112   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4113   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4114                                          Ops, MMO);
4115   DAG.setRoot(Scatter);
4116   setValue(&I, Scatter);
4117 }
4118 
4119 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4120   SDLoc sdl = getCurSDLoc();
4121 
4122   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4123                            unsigned& Alignment) {
4124     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4125     Ptr = I.getArgOperand(0);
4126     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4127     Mask = I.getArgOperand(2);
4128     Src0 = I.getArgOperand(3);
4129   };
4130   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4131                            unsigned& Alignment) {
4132     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4133     Ptr = I.getArgOperand(0);
4134     Alignment = 0;
4135     Mask = I.getArgOperand(1);
4136     Src0 = I.getArgOperand(2);
4137   };
4138 
4139   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4140   unsigned Alignment;
4141   if (IsExpanding)
4142     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4143   else
4144     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4145 
4146   SDValue Ptr = getValue(PtrOperand);
4147   SDValue Src0 = getValue(Src0Operand);
4148   SDValue Mask = getValue(MaskOperand);
4149 
4150   EVT VT = Src0.getValueType();
4151   if (!Alignment)
4152     Alignment = DAG.getEVTAlignment(VT);
4153 
4154   AAMDNodes AAInfo;
4155   I.getAAMetadata(AAInfo);
4156   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4157 
4158   // Do not serialize masked loads of constant memory with anything.
4159   bool AddToChain =
4160       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4161                  PtrOperand,
4162                  LocationSize::precise(
4163                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4164                  AAInfo));
4165   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4166 
4167   MachineMemOperand *MMO =
4168     DAG.getMachineFunction().
4169     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4170                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4171                           Alignment, AAInfo, Ranges);
4172 
4173   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4174                                    ISD::NON_EXTLOAD, IsExpanding);
4175   if (AddToChain)
4176     PendingLoads.push_back(Load.getValue(1));
4177   setValue(&I, Load);
4178 }
4179 
4180 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4181   SDLoc sdl = getCurSDLoc();
4182 
4183   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4184   const Value *Ptr = I.getArgOperand(0);
4185   SDValue Src0 = getValue(I.getArgOperand(3));
4186   SDValue Mask = getValue(I.getArgOperand(2));
4187 
4188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4189   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4190   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4191   if (!Alignment)
4192     Alignment = DAG.getEVTAlignment(VT);
4193 
4194   AAMDNodes AAInfo;
4195   I.getAAMetadata(AAInfo);
4196   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4197 
4198   SDValue Root = DAG.getRoot();
4199   SDValue Base;
4200   SDValue Index;
4201   SDValue Scale;
4202   const Value *BasePtr = Ptr;
4203   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4204   bool ConstantMemory = false;
4205   if (UniformBase && AA &&
4206       AA->pointsToConstantMemory(
4207           MemoryLocation(BasePtr,
4208                          LocationSize::precise(
4209                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4210                          AAInfo))) {
4211     // Do not serialize (non-volatile) loads of constant memory with anything.
4212     Root = DAG.getEntryNode();
4213     ConstantMemory = true;
4214   }
4215 
4216   MachineMemOperand *MMO =
4217     DAG.getMachineFunction().
4218     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4219                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4220                          Alignment, AAInfo, Ranges);
4221 
4222   if (!UniformBase) {
4223     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4224     Index = getValue(Ptr);
4225     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4226   }
4227   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4228   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4229                                        Ops, MMO);
4230 
4231   SDValue OutChain = Gather.getValue(1);
4232   if (!ConstantMemory)
4233     PendingLoads.push_back(OutChain);
4234   setValue(&I, Gather);
4235 }
4236 
4237 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4238   SDLoc dl = getCurSDLoc();
4239   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4240   AtomicOrdering FailureOrder = I.getFailureOrdering();
4241   SyncScope::ID SSID = I.getSyncScopeID();
4242 
4243   SDValue InChain = getRoot();
4244 
4245   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4246   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4247   SDValue L = DAG.getAtomicCmpSwap(
4248       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4249       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4250       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4251       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4252 
4253   SDValue OutChain = L.getValue(2);
4254 
4255   setValue(&I, L);
4256   DAG.setRoot(OutChain);
4257 }
4258 
4259 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4260   SDLoc dl = getCurSDLoc();
4261   ISD::NodeType NT;
4262   switch (I.getOperation()) {
4263   default: llvm_unreachable("Unknown atomicrmw operation");
4264   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4265   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4266   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4267   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4268   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4269   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4270   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4271   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4272   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4273   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4274   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4275   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4276   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4277   }
4278   AtomicOrdering Order = I.getOrdering();
4279   SyncScope::ID SSID = I.getSyncScopeID();
4280 
4281   SDValue InChain = getRoot();
4282 
4283   SDValue L =
4284     DAG.getAtomic(NT, dl,
4285                   getValue(I.getValOperand()).getSimpleValueType(),
4286                   InChain,
4287                   getValue(I.getPointerOperand()),
4288                   getValue(I.getValOperand()),
4289                   I.getPointerOperand(),
4290                   /* Alignment=*/ 0, Order, SSID);
4291 
4292   SDValue OutChain = L.getValue(1);
4293 
4294   setValue(&I, L);
4295   DAG.setRoot(OutChain);
4296 }
4297 
4298 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4299   SDLoc dl = getCurSDLoc();
4300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4301   SDValue Ops[3];
4302   Ops[0] = getRoot();
4303   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4304                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4305   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4306                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4307   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4308 }
4309 
4310 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4311   SDLoc dl = getCurSDLoc();
4312   AtomicOrdering Order = I.getOrdering();
4313   SyncScope::ID SSID = I.getSyncScopeID();
4314 
4315   SDValue InChain = getRoot();
4316 
4317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4318   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4319 
4320   if (!TLI.supportsUnalignedAtomics() &&
4321       I.getAlignment() < VT.getStoreSize())
4322     report_fatal_error("Cannot generate unaligned atomic load");
4323 
4324   MachineMemOperand *MMO =
4325       DAG.getMachineFunction().
4326       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4327                            MachineMemOperand::MOVolatile |
4328                            MachineMemOperand::MOLoad,
4329                            VT.getStoreSize(),
4330                            I.getAlignment() ? I.getAlignment() :
4331                                               DAG.getEVTAlignment(VT),
4332                            AAMDNodes(), nullptr, SSID, Order);
4333 
4334   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4335   SDValue L =
4336       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4337                     getValue(I.getPointerOperand()), MMO);
4338 
4339   SDValue OutChain = L.getValue(1);
4340 
4341   setValue(&I, L);
4342   DAG.setRoot(OutChain);
4343 }
4344 
4345 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4346   SDLoc dl = getCurSDLoc();
4347 
4348   AtomicOrdering Order = I.getOrdering();
4349   SyncScope::ID SSID = I.getSyncScopeID();
4350 
4351   SDValue InChain = getRoot();
4352 
4353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4354   EVT VT =
4355       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4356 
4357   if (I.getAlignment() < VT.getStoreSize())
4358     report_fatal_error("Cannot generate unaligned atomic store");
4359 
4360   SDValue OutChain =
4361     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4362                   InChain,
4363                   getValue(I.getPointerOperand()),
4364                   getValue(I.getValueOperand()),
4365                   I.getPointerOperand(), I.getAlignment(),
4366                   Order, SSID);
4367 
4368   DAG.setRoot(OutChain);
4369 }
4370 
4371 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4372 /// node.
4373 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4374                                                unsigned Intrinsic) {
4375   // Ignore the callsite's attributes. A specific call site may be marked with
4376   // readnone, but the lowering code will expect the chain based on the
4377   // definition.
4378   const Function *F = I.getCalledFunction();
4379   bool HasChain = !F->doesNotAccessMemory();
4380   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4381 
4382   // Build the operand list.
4383   SmallVector<SDValue, 8> Ops;
4384   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4385     if (OnlyLoad) {
4386       // We don't need to serialize loads against other loads.
4387       Ops.push_back(DAG.getRoot());
4388     } else {
4389       Ops.push_back(getRoot());
4390     }
4391   }
4392 
4393   // Info is set by getTgtMemInstrinsic
4394   TargetLowering::IntrinsicInfo Info;
4395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4396   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4397                                                DAG.getMachineFunction(),
4398                                                Intrinsic);
4399 
4400   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4401   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4402       Info.opc == ISD::INTRINSIC_W_CHAIN)
4403     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4404                                         TLI.getPointerTy(DAG.getDataLayout())));
4405 
4406   // Add all operands of the call to the operand list.
4407   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4408     SDValue Op = getValue(I.getArgOperand(i));
4409     Ops.push_back(Op);
4410   }
4411 
4412   SmallVector<EVT, 4> ValueVTs;
4413   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4414 
4415   if (HasChain)
4416     ValueVTs.push_back(MVT::Other);
4417 
4418   SDVTList VTs = DAG.getVTList(ValueVTs);
4419 
4420   // Create the node.
4421   SDValue Result;
4422   if (IsTgtIntrinsic) {
4423     // This is target intrinsic that touches memory
4424     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4425       Ops, Info.memVT,
4426       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4427       Info.flags, Info.size);
4428   } else if (!HasChain) {
4429     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4430   } else if (!I.getType()->isVoidTy()) {
4431     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4432   } else {
4433     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4434   }
4435 
4436   if (HasChain) {
4437     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4438     if (OnlyLoad)
4439       PendingLoads.push_back(Chain);
4440     else
4441       DAG.setRoot(Chain);
4442   }
4443 
4444   if (!I.getType()->isVoidTy()) {
4445     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4446       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4447       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4448     } else
4449       Result = lowerRangeToAssertZExt(DAG, I, Result);
4450 
4451     setValue(&I, Result);
4452   }
4453 }
4454 
4455 /// GetSignificand - Get the significand and build it into a floating-point
4456 /// number with exponent of 1:
4457 ///
4458 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4459 ///
4460 /// where Op is the hexadecimal representation of floating point value.
4461 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4462   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4463                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4464   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4465                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4466   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4467 }
4468 
4469 /// GetExponent - Get the exponent:
4470 ///
4471 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4472 ///
4473 /// where Op is the hexadecimal representation of floating point value.
4474 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4475                            const TargetLowering &TLI, const SDLoc &dl) {
4476   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4477                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4478   SDValue t1 = DAG.getNode(
4479       ISD::SRL, dl, MVT::i32, t0,
4480       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4481   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4482                            DAG.getConstant(127, dl, MVT::i32));
4483   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4484 }
4485 
4486 /// getF32Constant - Get 32-bit floating point constant.
4487 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4488                               const SDLoc &dl) {
4489   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4490                            MVT::f32);
4491 }
4492 
4493 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4494                                        SelectionDAG &DAG) {
4495   // TODO: What fast-math-flags should be set on the floating-point nodes?
4496 
4497   //   IntegerPartOfX = ((int32_t)(t0);
4498   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4499 
4500   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4501   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4502   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4503 
4504   //   IntegerPartOfX <<= 23;
4505   IntegerPartOfX = DAG.getNode(
4506       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4507       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4508                                   DAG.getDataLayout())));
4509 
4510   SDValue TwoToFractionalPartOfX;
4511   if (LimitFloatPrecision <= 6) {
4512     // For floating-point precision of 6:
4513     //
4514     //   TwoToFractionalPartOfX =
4515     //     0.997535578f +
4516     //       (0.735607626f + 0.252464424f * x) * x;
4517     //
4518     // error 0.0144103317, which is 6 bits
4519     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4520                              getF32Constant(DAG, 0x3e814304, dl));
4521     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4522                              getF32Constant(DAG, 0x3f3c50c8, dl));
4523     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4524     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4525                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4526   } else if (LimitFloatPrecision <= 12) {
4527     // For floating-point precision of 12:
4528     //
4529     //   TwoToFractionalPartOfX =
4530     //     0.999892986f +
4531     //       (0.696457318f +
4532     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4533     //
4534     // error 0.000107046256, which is 13 to 14 bits
4535     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4536                              getF32Constant(DAG, 0x3da235e3, dl));
4537     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4538                              getF32Constant(DAG, 0x3e65b8f3, dl));
4539     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4540     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4541                              getF32Constant(DAG, 0x3f324b07, dl));
4542     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4543     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4544                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4545   } else { // LimitFloatPrecision <= 18
4546     // For floating-point precision of 18:
4547     //
4548     //   TwoToFractionalPartOfX =
4549     //     0.999999982f +
4550     //       (0.693148872f +
4551     //         (0.240227044f +
4552     //           (0.554906021e-1f +
4553     //             (0.961591928e-2f +
4554     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4555     // error 2.47208000*10^(-7), which is better than 18 bits
4556     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4557                              getF32Constant(DAG, 0x3924b03e, dl));
4558     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4559                              getF32Constant(DAG, 0x3ab24b87, dl));
4560     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4561     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4562                              getF32Constant(DAG, 0x3c1d8c17, dl));
4563     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4564     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4565                              getF32Constant(DAG, 0x3d634a1d, dl));
4566     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4567     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4568                              getF32Constant(DAG, 0x3e75fe14, dl));
4569     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4570     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4571                               getF32Constant(DAG, 0x3f317234, dl));
4572     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4573     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4574                                          getF32Constant(DAG, 0x3f800000, dl));
4575   }
4576 
4577   // Add the exponent into the result in integer domain.
4578   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4579   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4580                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4581 }
4582 
4583 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4584 /// limited-precision mode.
4585 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4586                          const TargetLowering &TLI) {
4587   if (Op.getValueType() == MVT::f32 &&
4588       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4589 
4590     // Put the exponent in the right bit position for later addition to the
4591     // final result:
4592     //
4593     //   #define LOG2OFe 1.4426950f
4594     //   t0 = Op * LOG2OFe
4595 
4596     // TODO: What fast-math-flags should be set here?
4597     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4598                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4599     return getLimitedPrecisionExp2(t0, dl, DAG);
4600   }
4601 
4602   // No special expansion.
4603   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4604 }
4605 
4606 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4607 /// limited-precision mode.
4608 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4609                          const TargetLowering &TLI) {
4610   // TODO: What fast-math-flags should be set on the floating-point nodes?
4611 
4612   if (Op.getValueType() == MVT::f32 &&
4613       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4614     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4615 
4616     // Scale the exponent by log(2) [0.69314718f].
4617     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4618     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4619                                         getF32Constant(DAG, 0x3f317218, dl));
4620 
4621     // Get the significand and build it into a floating-point number with
4622     // exponent of 1.
4623     SDValue X = GetSignificand(DAG, Op1, dl);
4624 
4625     SDValue LogOfMantissa;
4626     if (LimitFloatPrecision <= 6) {
4627       // For floating-point precision of 6:
4628       //
4629       //   LogofMantissa =
4630       //     -1.1609546f +
4631       //       (1.4034025f - 0.23903021f * x) * x;
4632       //
4633       // error 0.0034276066, which is better than 8 bits
4634       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4635                                getF32Constant(DAG, 0xbe74c456, dl));
4636       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4637                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4638       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4639       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4640                                   getF32Constant(DAG, 0x3f949a29, dl));
4641     } else if (LimitFloatPrecision <= 12) {
4642       // For floating-point precision of 12:
4643       //
4644       //   LogOfMantissa =
4645       //     -1.7417939f +
4646       //       (2.8212026f +
4647       //         (-1.4699568f +
4648       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4649       //
4650       // error 0.000061011436, which is 14 bits
4651       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4652                                getF32Constant(DAG, 0xbd67b6d6, dl));
4653       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4654                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4655       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4656       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4657                                getF32Constant(DAG, 0x3fbc278b, dl));
4658       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4659       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4660                                getF32Constant(DAG, 0x40348e95, dl));
4661       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4662       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4663                                   getF32Constant(DAG, 0x3fdef31a, dl));
4664     } else { // LimitFloatPrecision <= 18
4665       // For floating-point precision of 18:
4666       //
4667       //   LogOfMantissa =
4668       //     -2.1072184f +
4669       //       (4.2372794f +
4670       //         (-3.7029485f +
4671       //           (2.2781945f +
4672       //             (-0.87823314f +
4673       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4674       //
4675       // error 0.0000023660568, which is better than 18 bits
4676       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4677                                getF32Constant(DAG, 0xbc91e5ac, dl));
4678       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4679                                getF32Constant(DAG, 0x3e4350aa, dl));
4680       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4681       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4682                                getF32Constant(DAG, 0x3f60d3e3, dl));
4683       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4684       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4685                                getF32Constant(DAG, 0x4011cdf0, dl));
4686       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4687       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4688                                getF32Constant(DAG, 0x406cfd1c, dl));
4689       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4690       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4691                                getF32Constant(DAG, 0x408797cb, dl));
4692       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4693       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4694                                   getF32Constant(DAG, 0x4006dcab, dl));
4695     }
4696 
4697     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4698   }
4699 
4700   // No special expansion.
4701   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4702 }
4703 
4704 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4705 /// limited-precision mode.
4706 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4707                           const TargetLowering &TLI) {
4708   // TODO: What fast-math-flags should be set on the floating-point nodes?
4709 
4710   if (Op.getValueType() == MVT::f32 &&
4711       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4712     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4713 
4714     // Get the exponent.
4715     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4716 
4717     // Get the significand and build it into a floating-point number with
4718     // exponent of 1.
4719     SDValue X = GetSignificand(DAG, Op1, dl);
4720 
4721     // Different possible minimax approximations of significand in
4722     // floating-point for various degrees of accuracy over [1,2].
4723     SDValue Log2ofMantissa;
4724     if (LimitFloatPrecision <= 6) {
4725       // For floating-point precision of 6:
4726       //
4727       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4728       //
4729       // error 0.0049451742, which is more than 7 bits
4730       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4731                                getF32Constant(DAG, 0xbeb08fe0, dl));
4732       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4733                                getF32Constant(DAG, 0x40019463, dl));
4734       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4735       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4736                                    getF32Constant(DAG, 0x3fd6633d, dl));
4737     } else if (LimitFloatPrecision <= 12) {
4738       // For floating-point precision of 12:
4739       //
4740       //   Log2ofMantissa =
4741       //     -2.51285454f +
4742       //       (4.07009056f +
4743       //         (-2.12067489f +
4744       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4745       //
4746       // error 0.0000876136000, which is better than 13 bits
4747       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4748                                getF32Constant(DAG, 0xbda7262e, dl));
4749       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4750                                getF32Constant(DAG, 0x3f25280b, dl));
4751       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4752       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4753                                getF32Constant(DAG, 0x4007b923, dl));
4754       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4755       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4756                                getF32Constant(DAG, 0x40823e2f, dl));
4757       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4758       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4759                                    getF32Constant(DAG, 0x4020d29c, dl));
4760     } else { // LimitFloatPrecision <= 18
4761       // For floating-point precision of 18:
4762       //
4763       //   Log2ofMantissa =
4764       //     -3.0400495f +
4765       //       (6.1129976f +
4766       //         (-5.3420409f +
4767       //           (3.2865683f +
4768       //             (-1.2669343f +
4769       //               (0.27515199f -
4770       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4771       //
4772       // error 0.0000018516, which is better than 18 bits
4773       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4774                                getF32Constant(DAG, 0xbcd2769e, dl));
4775       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4776                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4777       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4778       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4779                                getF32Constant(DAG, 0x3fa22ae7, dl));
4780       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4781       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4782                                getF32Constant(DAG, 0x40525723, dl));
4783       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4784       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4785                                getF32Constant(DAG, 0x40aaf200, dl));
4786       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4787       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4788                                getF32Constant(DAG, 0x40c39dad, dl));
4789       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4790       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4791                                    getF32Constant(DAG, 0x4042902c, dl));
4792     }
4793 
4794     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4795   }
4796 
4797   // No special expansion.
4798   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4799 }
4800 
4801 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4802 /// limited-precision mode.
4803 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4804                            const TargetLowering &TLI) {
4805   // TODO: What fast-math-flags should be set on the floating-point nodes?
4806 
4807   if (Op.getValueType() == MVT::f32 &&
4808       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4809     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4810 
4811     // Scale the exponent by log10(2) [0.30102999f].
4812     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4813     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4814                                         getF32Constant(DAG, 0x3e9a209a, dl));
4815 
4816     // Get the significand and build it into a floating-point number with
4817     // exponent of 1.
4818     SDValue X = GetSignificand(DAG, Op1, dl);
4819 
4820     SDValue Log10ofMantissa;
4821     if (LimitFloatPrecision <= 6) {
4822       // For floating-point precision of 6:
4823       //
4824       //   Log10ofMantissa =
4825       //     -0.50419619f +
4826       //       (0.60948995f - 0.10380950f * x) * x;
4827       //
4828       // error 0.0014886165, which is 6 bits
4829       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4830                                getF32Constant(DAG, 0xbdd49a13, dl));
4831       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4832                                getF32Constant(DAG, 0x3f1c0789, dl));
4833       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4834       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4835                                     getF32Constant(DAG, 0x3f011300, dl));
4836     } else if (LimitFloatPrecision <= 12) {
4837       // For floating-point precision of 12:
4838       //
4839       //   Log10ofMantissa =
4840       //     -0.64831180f +
4841       //       (0.91751397f +
4842       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4843       //
4844       // error 0.00019228036, which is better than 12 bits
4845       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4846                                getF32Constant(DAG, 0x3d431f31, dl));
4847       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4848                                getF32Constant(DAG, 0x3ea21fb2, dl));
4849       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4850       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4851                                getF32Constant(DAG, 0x3f6ae232, dl));
4852       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4853       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4854                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4855     } else { // LimitFloatPrecision <= 18
4856       // For floating-point precision of 18:
4857       //
4858       //   Log10ofMantissa =
4859       //     -0.84299375f +
4860       //       (1.5327582f +
4861       //         (-1.0688956f +
4862       //           (0.49102474f +
4863       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4864       //
4865       // error 0.0000037995730, which is better than 18 bits
4866       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4867                                getF32Constant(DAG, 0x3c5d51ce, dl));
4868       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4869                                getF32Constant(DAG, 0x3e00685a, dl));
4870       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4871       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4872                                getF32Constant(DAG, 0x3efb6798, dl));
4873       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4874       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4875                                getF32Constant(DAG, 0x3f88d192, dl));
4876       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4877       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4878                                getF32Constant(DAG, 0x3fc4316c, dl));
4879       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4880       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4881                                     getF32Constant(DAG, 0x3f57ce70, dl));
4882     }
4883 
4884     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4885   }
4886 
4887   // No special expansion.
4888   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4889 }
4890 
4891 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4892 /// limited-precision mode.
4893 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4894                           const TargetLowering &TLI) {
4895   if (Op.getValueType() == MVT::f32 &&
4896       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4897     return getLimitedPrecisionExp2(Op, dl, DAG);
4898 
4899   // No special expansion.
4900   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4901 }
4902 
4903 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4904 /// limited-precision mode with x == 10.0f.
4905 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4906                          SelectionDAG &DAG, const TargetLowering &TLI) {
4907   bool IsExp10 = false;
4908   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4909       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4910     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4911       APFloat Ten(10.0f);
4912       IsExp10 = LHSC->isExactlyValue(Ten);
4913     }
4914   }
4915 
4916   // TODO: What fast-math-flags should be set on the FMUL node?
4917   if (IsExp10) {
4918     // Put the exponent in the right bit position for later addition to the
4919     // final result:
4920     //
4921     //   #define LOG2OF10 3.3219281f
4922     //   t0 = Op * LOG2OF10;
4923     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4924                              getF32Constant(DAG, 0x40549a78, dl));
4925     return getLimitedPrecisionExp2(t0, dl, DAG);
4926   }
4927 
4928   // No special expansion.
4929   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4930 }
4931 
4932 /// ExpandPowI - Expand a llvm.powi intrinsic.
4933 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4934                           SelectionDAG &DAG) {
4935   // If RHS is a constant, we can expand this out to a multiplication tree,
4936   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4937   // optimizing for size, we only want to do this if the expansion would produce
4938   // a small number of multiplies, otherwise we do the full expansion.
4939   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4940     // Get the exponent as a positive value.
4941     unsigned Val = RHSC->getSExtValue();
4942     if ((int)Val < 0) Val = -Val;
4943 
4944     // powi(x, 0) -> 1.0
4945     if (Val == 0)
4946       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4947 
4948     const Function &F = DAG.getMachineFunction().getFunction();
4949     if (!F.optForSize() ||
4950         // If optimizing for size, don't insert too many multiplies.
4951         // This inserts up to 5 multiplies.
4952         countPopulation(Val) + Log2_32(Val) < 7) {
4953       // We use the simple binary decomposition method to generate the multiply
4954       // sequence.  There are more optimal ways to do this (for example,
4955       // powi(x,15) generates one more multiply than it should), but this has
4956       // the benefit of being both really simple and much better than a libcall.
4957       SDValue Res;  // Logically starts equal to 1.0
4958       SDValue CurSquare = LHS;
4959       // TODO: Intrinsics should have fast-math-flags that propagate to these
4960       // nodes.
4961       while (Val) {
4962         if (Val & 1) {
4963           if (Res.getNode())
4964             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4965           else
4966             Res = CurSquare;  // 1.0*CurSquare.
4967         }
4968 
4969         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4970                                 CurSquare, CurSquare);
4971         Val >>= 1;
4972       }
4973 
4974       // If the original was negative, invert the result, producing 1/(x*x*x).
4975       if (RHSC->getSExtValue() < 0)
4976         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4977                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4978       return Res;
4979     }
4980   }
4981 
4982   // Otherwise, expand to a libcall.
4983   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4984 }
4985 
4986 // getUnderlyingArgReg - Find underlying register used for a truncated or
4987 // bitcasted argument.
4988 static unsigned getUnderlyingArgReg(const SDValue &N) {
4989   switch (N.getOpcode()) {
4990   case ISD::CopyFromReg:
4991     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4992   case ISD::BITCAST:
4993   case ISD::AssertZext:
4994   case ISD::AssertSext:
4995   case ISD::TRUNCATE:
4996     return getUnderlyingArgReg(N.getOperand(0));
4997   default:
4998     return 0;
4999   }
5000 }
5001 
5002 /// If the DbgValueInst is a dbg_value of a function argument, create the
5003 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5004 /// instruction selection, they will be inserted to the entry BB.
5005 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5006     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5007     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5008   const Argument *Arg = dyn_cast<Argument>(V);
5009   if (!Arg)
5010     return false;
5011 
5012   if (!IsDbgDeclare) {
5013     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5014     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5015     // the entry block.
5016     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5017     if (!IsInEntryBlock)
5018       return false;
5019 
5020     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5021     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5022     // variable that also is a param.
5023     //
5024     // Although, if we are at the top of the entry block already, we can still
5025     // emit using ArgDbgValue. This might catch some situations when the
5026     // dbg.value refers to an argument that isn't used in the entry block, so
5027     // any CopyToReg node would be optimized out and the only way to express
5028     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5029     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5030     // we should only emit as ArgDbgValue if the Variable is an argument to the
5031     // current function, and the dbg.value intrinsic is found in the entry
5032     // block.
5033     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5034         !DL->getInlinedAt();
5035     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5036     if (!IsInPrologue && !VariableIsFunctionInputArg)
5037       return false;
5038 
5039     // Here we assume that a function argument on IR level only can be used to
5040     // describe one input parameter on source level. If we for example have
5041     // source code like this
5042     //
5043     //    struct A { long x, y; };
5044     //    void foo(struct A a, long b) {
5045     //      ...
5046     //      b = a.x;
5047     //      ...
5048     //    }
5049     //
5050     // and IR like this
5051     //
5052     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5053     //  entry:
5054     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5055     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5056     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5057     //    ...
5058     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5059     //    ...
5060     //
5061     // then the last dbg.value is describing a parameter "b" using a value that
5062     // is an argument. But since we already has used %a1 to describe a parameter
5063     // we should not handle that last dbg.value here (that would result in an
5064     // incorrect hoisting of the DBG_VALUE to the function entry).
5065     // Notice that we allow one dbg.value per IR level argument, to accomodate
5066     // for the situation with fragments above.
5067     if (VariableIsFunctionInputArg) {
5068       unsigned ArgNo = Arg->getArgNo();
5069       if (ArgNo >= FuncInfo.DescribedArgs.size())
5070         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5071       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5072         return false;
5073       FuncInfo.DescribedArgs.set(ArgNo);
5074     }
5075   }
5076 
5077   MachineFunction &MF = DAG.getMachineFunction();
5078   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5079 
5080   bool IsIndirect = false;
5081   Optional<MachineOperand> Op;
5082   // Some arguments' frame index is recorded during argument lowering.
5083   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5084   if (FI != std::numeric_limits<int>::max())
5085     Op = MachineOperand::CreateFI(FI);
5086 
5087   if (!Op && N.getNode()) {
5088     unsigned Reg = getUnderlyingArgReg(N);
5089     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5090       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5091       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5092       if (PR)
5093         Reg = PR;
5094     }
5095     if (Reg) {
5096       Op = MachineOperand::CreateReg(Reg, false);
5097       IsIndirect = IsDbgDeclare;
5098     }
5099   }
5100 
5101   if (!Op && N.getNode())
5102     // Check if frame index is available.
5103     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
5104       if (FrameIndexSDNode *FINode =
5105           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5106         Op = MachineOperand::CreateFI(FINode->getIndex());
5107 
5108   if (!Op) {
5109     // Check if ValueMap has reg number.
5110     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5111     if (VMI != FuncInfo.ValueMap.end()) {
5112       const auto &TLI = DAG.getTargetLoweringInfo();
5113       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5114                        V->getType(), getABIRegCopyCC(V));
5115       if (RFV.occupiesMultipleRegs()) {
5116         unsigned Offset = 0;
5117         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5118           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5119           auto FragmentExpr = DIExpression::createFragmentExpression(
5120               Expr, Offset, RegAndSize.second);
5121           if (!FragmentExpr)
5122             continue;
5123           FuncInfo.ArgDbgValues.push_back(
5124               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5125                       Op->getReg(), Variable, *FragmentExpr));
5126           Offset += RegAndSize.second;
5127         }
5128         return true;
5129       }
5130       Op = MachineOperand::CreateReg(VMI->second, false);
5131       IsIndirect = IsDbgDeclare;
5132     }
5133   }
5134 
5135   if (!Op)
5136     return false;
5137 
5138   assert(Variable->isValidLocationForIntrinsic(DL) &&
5139          "Expected inlined-at fields to agree");
5140   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5141   FuncInfo.ArgDbgValues.push_back(
5142       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5143               *Op, Variable, Expr));
5144 
5145   return true;
5146 }
5147 
5148 /// Return the appropriate SDDbgValue based on N.
5149 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5150                                              DILocalVariable *Variable,
5151                                              DIExpression *Expr,
5152                                              const DebugLoc &dl,
5153                                              unsigned DbgSDNodeOrder) {
5154   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5155     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5156     // stack slot locations.
5157     //
5158     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5159     // debug values here after optimization:
5160     //
5161     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5162     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5163     //
5164     // Both describe the direct values of their associated variables.
5165     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5166                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5167   }
5168   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5169                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5170 }
5171 
5172 // VisualStudio defines setjmp as _setjmp
5173 #if defined(_MSC_VER) && defined(setjmp) && \
5174                          !defined(setjmp_undefined_for_msvc)
5175 #  pragma push_macro("setjmp")
5176 #  undef setjmp
5177 #  define setjmp_undefined_for_msvc
5178 #endif
5179 
5180 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5181   switch (Intrinsic) {
5182   case Intrinsic::smul_fix:
5183     return ISD::SMULFIX;
5184   case Intrinsic::umul_fix:
5185     return ISD::UMULFIX;
5186   default:
5187     llvm_unreachable("Unhandled fixed point intrinsic");
5188   }
5189 }
5190 
5191 /// Lower the call to the specified intrinsic function. If we want to emit this
5192 /// as a call to a named external function, return the name. Otherwise, lower it
5193 /// and return null.
5194 const char *
5195 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5197   SDLoc sdl = getCurSDLoc();
5198   DebugLoc dl = getCurDebugLoc();
5199   SDValue Res;
5200 
5201   switch (Intrinsic) {
5202   default:
5203     // By default, turn this into a target intrinsic node.
5204     visitTargetIntrinsic(I, Intrinsic);
5205     return nullptr;
5206   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5207   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5208   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5209   case Intrinsic::returnaddress:
5210     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5211                              TLI.getPointerTy(DAG.getDataLayout()),
5212                              getValue(I.getArgOperand(0))));
5213     return nullptr;
5214   case Intrinsic::addressofreturnaddress:
5215     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5216                              TLI.getPointerTy(DAG.getDataLayout())));
5217     return nullptr;
5218   case Intrinsic::sponentry:
5219     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5220                              TLI.getPointerTy(DAG.getDataLayout())));
5221     return nullptr;
5222   case Intrinsic::frameaddress:
5223     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5224                              TLI.getPointerTy(DAG.getDataLayout()),
5225                              getValue(I.getArgOperand(0))));
5226     return nullptr;
5227   case Intrinsic::read_register: {
5228     Value *Reg = I.getArgOperand(0);
5229     SDValue Chain = getRoot();
5230     SDValue RegName =
5231         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5232     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5233     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5234       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5235     setValue(&I, Res);
5236     DAG.setRoot(Res.getValue(1));
5237     return nullptr;
5238   }
5239   case Intrinsic::write_register: {
5240     Value *Reg = I.getArgOperand(0);
5241     Value *RegValue = I.getArgOperand(1);
5242     SDValue Chain = getRoot();
5243     SDValue RegName =
5244         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5245     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5246                             RegName, getValue(RegValue)));
5247     return nullptr;
5248   }
5249   case Intrinsic::setjmp:
5250     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5251   case Intrinsic::longjmp:
5252     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5253   case Intrinsic::memcpy: {
5254     const auto &MCI = cast<MemCpyInst>(I);
5255     SDValue Op1 = getValue(I.getArgOperand(0));
5256     SDValue Op2 = getValue(I.getArgOperand(1));
5257     SDValue Op3 = getValue(I.getArgOperand(2));
5258     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5259     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5260     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5261     unsigned Align = MinAlign(DstAlign, SrcAlign);
5262     bool isVol = MCI.isVolatile();
5263     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5264     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5265     // node.
5266     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5267                                false, isTC,
5268                                MachinePointerInfo(I.getArgOperand(0)),
5269                                MachinePointerInfo(I.getArgOperand(1)));
5270     updateDAGForMaybeTailCall(MC);
5271     return nullptr;
5272   }
5273   case Intrinsic::memset: {
5274     const auto &MSI = cast<MemSetInst>(I);
5275     SDValue Op1 = getValue(I.getArgOperand(0));
5276     SDValue Op2 = getValue(I.getArgOperand(1));
5277     SDValue Op3 = getValue(I.getArgOperand(2));
5278     // @llvm.memset defines 0 and 1 to both mean no alignment.
5279     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5280     bool isVol = MSI.isVolatile();
5281     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5282     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5283                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5284     updateDAGForMaybeTailCall(MS);
5285     return nullptr;
5286   }
5287   case Intrinsic::memmove: {
5288     const auto &MMI = cast<MemMoveInst>(I);
5289     SDValue Op1 = getValue(I.getArgOperand(0));
5290     SDValue Op2 = getValue(I.getArgOperand(1));
5291     SDValue Op3 = getValue(I.getArgOperand(2));
5292     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5293     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5294     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5295     unsigned Align = MinAlign(DstAlign, SrcAlign);
5296     bool isVol = MMI.isVolatile();
5297     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5298     // FIXME: Support passing different dest/src alignments to the memmove DAG
5299     // node.
5300     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5301                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5302                                 MachinePointerInfo(I.getArgOperand(1)));
5303     updateDAGForMaybeTailCall(MM);
5304     return nullptr;
5305   }
5306   case Intrinsic::memcpy_element_unordered_atomic: {
5307     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5308     SDValue Dst = getValue(MI.getRawDest());
5309     SDValue Src = getValue(MI.getRawSource());
5310     SDValue Length = getValue(MI.getLength());
5311 
5312     unsigned DstAlign = MI.getDestAlignment();
5313     unsigned SrcAlign = MI.getSourceAlignment();
5314     Type *LengthTy = MI.getLength()->getType();
5315     unsigned ElemSz = MI.getElementSizeInBytes();
5316     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5317     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5318                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5319                                      MachinePointerInfo(MI.getRawDest()),
5320                                      MachinePointerInfo(MI.getRawSource()));
5321     updateDAGForMaybeTailCall(MC);
5322     return nullptr;
5323   }
5324   case Intrinsic::memmove_element_unordered_atomic: {
5325     auto &MI = cast<AtomicMemMoveInst>(I);
5326     SDValue Dst = getValue(MI.getRawDest());
5327     SDValue Src = getValue(MI.getRawSource());
5328     SDValue Length = getValue(MI.getLength());
5329 
5330     unsigned DstAlign = MI.getDestAlignment();
5331     unsigned SrcAlign = MI.getSourceAlignment();
5332     Type *LengthTy = MI.getLength()->getType();
5333     unsigned ElemSz = MI.getElementSizeInBytes();
5334     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5335     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5336                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5337                                       MachinePointerInfo(MI.getRawDest()),
5338                                       MachinePointerInfo(MI.getRawSource()));
5339     updateDAGForMaybeTailCall(MC);
5340     return nullptr;
5341   }
5342   case Intrinsic::memset_element_unordered_atomic: {
5343     auto &MI = cast<AtomicMemSetInst>(I);
5344     SDValue Dst = getValue(MI.getRawDest());
5345     SDValue Val = getValue(MI.getValue());
5346     SDValue Length = getValue(MI.getLength());
5347 
5348     unsigned DstAlign = MI.getDestAlignment();
5349     Type *LengthTy = MI.getLength()->getType();
5350     unsigned ElemSz = MI.getElementSizeInBytes();
5351     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5352     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5353                                      LengthTy, ElemSz, isTC,
5354                                      MachinePointerInfo(MI.getRawDest()));
5355     updateDAGForMaybeTailCall(MC);
5356     return nullptr;
5357   }
5358   case Intrinsic::dbg_addr:
5359   case Intrinsic::dbg_declare: {
5360     const auto &DI = cast<DbgVariableIntrinsic>(I);
5361     DILocalVariable *Variable = DI.getVariable();
5362     DIExpression *Expression = DI.getExpression();
5363     dropDanglingDebugInfo(Variable, Expression);
5364     assert(Variable && "Missing variable");
5365 
5366     // Check if address has undef value.
5367     const Value *Address = DI.getVariableLocation();
5368     if (!Address || isa<UndefValue>(Address) ||
5369         (Address->use_empty() && !isa<Argument>(Address))) {
5370       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5371       return nullptr;
5372     }
5373 
5374     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5375 
5376     // Check if this variable can be described by a frame index, typically
5377     // either as a static alloca or a byval parameter.
5378     int FI = std::numeric_limits<int>::max();
5379     if (const auto *AI =
5380             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5381       if (AI->isStaticAlloca()) {
5382         auto I = FuncInfo.StaticAllocaMap.find(AI);
5383         if (I != FuncInfo.StaticAllocaMap.end())
5384           FI = I->second;
5385       }
5386     } else if (const auto *Arg = dyn_cast<Argument>(
5387                    Address->stripInBoundsConstantOffsets())) {
5388       FI = FuncInfo.getArgumentFrameIndex(Arg);
5389     }
5390 
5391     // llvm.dbg.addr is control dependent and always generates indirect
5392     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5393     // the MachineFunction variable table.
5394     if (FI != std::numeric_limits<int>::max()) {
5395       if (Intrinsic == Intrinsic::dbg_addr) {
5396         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5397             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5398         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5399       }
5400       return nullptr;
5401     }
5402 
5403     SDValue &N = NodeMap[Address];
5404     if (!N.getNode() && isa<Argument>(Address))
5405       // Check unused arguments map.
5406       N = UnusedArgNodeMap[Address];
5407     SDDbgValue *SDV;
5408     if (N.getNode()) {
5409       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5410         Address = BCI->getOperand(0);
5411       // Parameters are handled specially.
5412       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5413       if (isParameter && FINode) {
5414         // Byval parameter. We have a frame index at this point.
5415         SDV =
5416             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5417                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5418       } else if (isa<Argument>(Address)) {
5419         // Address is an argument, so try to emit its dbg value using
5420         // virtual register info from the FuncInfo.ValueMap.
5421         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5422         return nullptr;
5423       } else {
5424         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5425                               true, dl, SDNodeOrder);
5426       }
5427       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5428     } else {
5429       // If Address is an argument then try to emit its dbg value using
5430       // virtual register info from the FuncInfo.ValueMap.
5431       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5432                                     N)) {
5433         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5434       }
5435     }
5436     return nullptr;
5437   }
5438   case Intrinsic::dbg_label: {
5439     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5440     DILabel *Label = DI.getLabel();
5441     assert(Label && "Missing label");
5442 
5443     SDDbgLabel *SDV;
5444     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5445     DAG.AddDbgLabel(SDV);
5446     return nullptr;
5447   }
5448   case Intrinsic::dbg_value: {
5449     const DbgValueInst &DI = cast<DbgValueInst>(I);
5450     assert(DI.getVariable() && "Missing variable");
5451 
5452     DILocalVariable *Variable = DI.getVariable();
5453     DIExpression *Expression = DI.getExpression();
5454     dropDanglingDebugInfo(Variable, Expression);
5455     const Value *V = DI.getValue();
5456     if (!V)
5457       return nullptr;
5458 
5459     SDDbgValue *SDV;
5460     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
5461         isa<ConstantPointerNull>(V)) {
5462       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5463       DAG.AddDbgValue(SDV, nullptr, false);
5464       return nullptr;
5465     }
5466 
5467     // If the Value is a frame index, we can create a FrameIndex debug value
5468     // without relying on the DAG at all.
5469     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5470       auto SI = FuncInfo.StaticAllocaMap.find(AI);
5471       if (SI != FuncInfo.StaticAllocaMap.end()) {
5472         auto SDV =
5473             DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
5474                                       /*IsIndirect*/ false, dl, SDNodeOrder);
5475         // Do not attach the SDNodeDbgValue to an SDNode: this variable location
5476         // is still available even if the SDNode gets optimized out.
5477         DAG.AddDbgValue(SDV, nullptr, false);
5478         return nullptr;
5479       }
5480     }
5481 
5482     // Do not use getValue() in here; we don't want to generate code at
5483     // this point if it hasn't been done yet.
5484     SDValue N = NodeMap[V];
5485     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5486       N = UnusedArgNodeMap[V];
5487     if (N.getNode()) {
5488       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5489         return nullptr;
5490       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5491       DAG.AddDbgValue(SDV, N.getNode(), false);
5492       return nullptr;
5493     }
5494 
5495     // The value is not used in this block yet (or it would have an SDNode).
5496     // We still want the value to appear for the user if possible -- if it has
5497     // an associated VReg, we can refer to that instead.
5498     if (!isa<Argument>(V)) {
5499       auto VMI = FuncInfo.ValueMap.find(V);
5500       if (VMI != FuncInfo.ValueMap.end()) {
5501         unsigned Reg = VMI->second;
5502         // If this is a PHI node, it may be split up into several MI PHI nodes
5503         // (in FunctionLoweringInfo::set).
5504         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5505                          V->getType(), None);
5506         if (RFV.occupiesMultipleRegs()) {
5507           unsigned Offset = 0;
5508           unsigned BitsToDescribe = 0;
5509           if (auto VarSize = Variable->getSizeInBits())
5510             BitsToDescribe = *VarSize;
5511           if (auto Fragment = Expression->getFragmentInfo())
5512             BitsToDescribe = Fragment->SizeInBits;
5513           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5514             unsigned RegisterSize = RegAndSize.second;
5515             // Bail out if all bits are described already.
5516             if (Offset >= BitsToDescribe)
5517               break;
5518             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5519                 ? BitsToDescribe - Offset
5520                 : RegisterSize;
5521             auto FragmentExpr = DIExpression::createFragmentExpression(
5522                 Expression, Offset, FragmentSize);
5523             if (!FragmentExpr)
5524                 continue;
5525             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5526                                       false, dl, SDNodeOrder);
5527             DAG.AddDbgValue(SDV, nullptr, false);
5528             Offset += RegisterSize;
5529           }
5530         } else {
5531           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5532                                     SDNodeOrder);
5533           DAG.AddDbgValue(SDV, nullptr, false);
5534         }
5535         return nullptr;
5536       }
5537     }
5538 
5539     // TODO: When we get here we will either drop the dbg.value completely, or
5540     // we try to move it forward by letting it dangle for awhile. So we should
5541     // probably add an extra DbgValue to the DAG here, with a reference to
5542     // "noreg", to indicate that we have lost the debug location for the
5543     // variable.
5544 
5545     if (!V->use_empty() ) {
5546       // Do not call getValue(V) yet, as we don't want to generate code.
5547       // Remember it for later.
5548       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5549       return nullptr;
5550     }
5551 
5552     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5553     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5554     return nullptr;
5555   }
5556 
5557   case Intrinsic::eh_typeid_for: {
5558     // Find the type id for the given typeinfo.
5559     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5560     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5561     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5562     setValue(&I, Res);
5563     return nullptr;
5564   }
5565 
5566   case Intrinsic::eh_return_i32:
5567   case Intrinsic::eh_return_i64:
5568     DAG.getMachineFunction().setCallsEHReturn(true);
5569     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5570                             MVT::Other,
5571                             getControlRoot(),
5572                             getValue(I.getArgOperand(0)),
5573                             getValue(I.getArgOperand(1))));
5574     return nullptr;
5575   case Intrinsic::eh_unwind_init:
5576     DAG.getMachineFunction().setCallsUnwindInit(true);
5577     return nullptr;
5578   case Intrinsic::eh_dwarf_cfa:
5579     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5580                              TLI.getPointerTy(DAG.getDataLayout()),
5581                              getValue(I.getArgOperand(0))));
5582     return nullptr;
5583   case Intrinsic::eh_sjlj_callsite: {
5584     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5585     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5586     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5587     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5588 
5589     MMI.setCurrentCallSite(CI->getZExtValue());
5590     return nullptr;
5591   }
5592   case Intrinsic::eh_sjlj_functioncontext: {
5593     // Get and store the index of the function context.
5594     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5595     AllocaInst *FnCtx =
5596       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5597     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5598     MFI.setFunctionContextIndex(FI);
5599     return nullptr;
5600   }
5601   case Intrinsic::eh_sjlj_setjmp: {
5602     SDValue Ops[2];
5603     Ops[0] = getRoot();
5604     Ops[1] = getValue(I.getArgOperand(0));
5605     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5606                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5607     setValue(&I, Op.getValue(0));
5608     DAG.setRoot(Op.getValue(1));
5609     return nullptr;
5610   }
5611   case Intrinsic::eh_sjlj_longjmp:
5612     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5613                             getRoot(), getValue(I.getArgOperand(0))));
5614     return nullptr;
5615   case Intrinsic::eh_sjlj_setup_dispatch:
5616     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5617                             getRoot()));
5618     return nullptr;
5619   case Intrinsic::masked_gather:
5620     visitMaskedGather(I);
5621     return nullptr;
5622   case Intrinsic::masked_load:
5623     visitMaskedLoad(I);
5624     return nullptr;
5625   case Intrinsic::masked_scatter:
5626     visitMaskedScatter(I);
5627     return nullptr;
5628   case Intrinsic::masked_store:
5629     visitMaskedStore(I);
5630     return nullptr;
5631   case Intrinsic::masked_expandload:
5632     visitMaskedLoad(I, true /* IsExpanding */);
5633     return nullptr;
5634   case Intrinsic::masked_compressstore:
5635     visitMaskedStore(I, true /* IsCompressing */);
5636     return nullptr;
5637   case Intrinsic::x86_mmx_pslli_w:
5638   case Intrinsic::x86_mmx_pslli_d:
5639   case Intrinsic::x86_mmx_pslli_q:
5640   case Intrinsic::x86_mmx_psrli_w:
5641   case Intrinsic::x86_mmx_psrli_d:
5642   case Intrinsic::x86_mmx_psrli_q:
5643   case Intrinsic::x86_mmx_psrai_w:
5644   case Intrinsic::x86_mmx_psrai_d: {
5645     SDValue ShAmt = getValue(I.getArgOperand(1));
5646     if (isa<ConstantSDNode>(ShAmt)) {
5647       visitTargetIntrinsic(I, Intrinsic);
5648       return nullptr;
5649     }
5650     unsigned NewIntrinsic = 0;
5651     EVT ShAmtVT = MVT::v2i32;
5652     switch (Intrinsic) {
5653     case Intrinsic::x86_mmx_pslli_w:
5654       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5655       break;
5656     case Intrinsic::x86_mmx_pslli_d:
5657       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5658       break;
5659     case Intrinsic::x86_mmx_pslli_q:
5660       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5661       break;
5662     case Intrinsic::x86_mmx_psrli_w:
5663       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5664       break;
5665     case Intrinsic::x86_mmx_psrli_d:
5666       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5667       break;
5668     case Intrinsic::x86_mmx_psrli_q:
5669       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5670       break;
5671     case Intrinsic::x86_mmx_psrai_w:
5672       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5673       break;
5674     case Intrinsic::x86_mmx_psrai_d:
5675       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5676       break;
5677     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5678     }
5679 
5680     // The vector shift intrinsics with scalars uses 32b shift amounts but
5681     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5682     // to be zero.
5683     // We must do this early because v2i32 is not a legal type.
5684     SDValue ShOps[2];
5685     ShOps[0] = ShAmt;
5686     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5687     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5688     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5689     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5690     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5691                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5692                        getValue(I.getArgOperand(0)), ShAmt);
5693     setValue(&I, Res);
5694     return nullptr;
5695   }
5696   case Intrinsic::powi:
5697     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5698                             getValue(I.getArgOperand(1)), DAG));
5699     return nullptr;
5700   case Intrinsic::log:
5701     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5702     return nullptr;
5703   case Intrinsic::log2:
5704     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5705     return nullptr;
5706   case Intrinsic::log10:
5707     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5708     return nullptr;
5709   case Intrinsic::exp:
5710     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5711     return nullptr;
5712   case Intrinsic::exp2:
5713     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5714     return nullptr;
5715   case Intrinsic::pow:
5716     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5717                            getValue(I.getArgOperand(1)), DAG, TLI));
5718     return nullptr;
5719   case Intrinsic::sqrt:
5720   case Intrinsic::fabs:
5721   case Intrinsic::sin:
5722   case Intrinsic::cos:
5723   case Intrinsic::floor:
5724   case Intrinsic::ceil:
5725   case Intrinsic::trunc:
5726   case Intrinsic::rint:
5727   case Intrinsic::nearbyint:
5728   case Intrinsic::round:
5729   case Intrinsic::canonicalize: {
5730     unsigned Opcode;
5731     switch (Intrinsic) {
5732     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5733     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5734     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5735     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5736     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5737     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5738     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5739     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5740     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5741     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5742     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5743     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5744     }
5745 
5746     setValue(&I, DAG.getNode(Opcode, sdl,
5747                              getValue(I.getArgOperand(0)).getValueType(),
5748                              getValue(I.getArgOperand(0))));
5749     return nullptr;
5750   }
5751   case Intrinsic::minnum: {
5752     auto VT = getValue(I.getArgOperand(0)).getValueType();
5753     unsigned Opc =
5754         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5755             ? ISD::FMINIMUM
5756             : ISD::FMINNUM;
5757     setValue(&I, DAG.getNode(Opc, sdl, VT,
5758                              getValue(I.getArgOperand(0)),
5759                              getValue(I.getArgOperand(1))));
5760     return nullptr;
5761   }
5762   case Intrinsic::maxnum: {
5763     auto VT = getValue(I.getArgOperand(0)).getValueType();
5764     unsigned Opc =
5765         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5766             ? ISD::FMAXIMUM
5767             : ISD::FMAXNUM;
5768     setValue(&I, DAG.getNode(Opc, sdl, VT,
5769                              getValue(I.getArgOperand(0)),
5770                              getValue(I.getArgOperand(1))));
5771     return nullptr;
5772   }
5773   case Intrinsic::minimum:
5774     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5775                              getValue(I.getArgOperand(0)).getValueType(),
5776                              getValue(I.getArgOperand(0)),
5777                              getValue(I.getArgOperand(1))));
5778     return nullptr;
5779   case Intrinsic::maximum:
5780     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5781                              getValue(I.getArgOperand(0)).getValueType(),
5782                              getValue(I.getArgOperand(0)),
5783                              getValue(I.getArgOperand(1))));
5784     return nullptr;
5785   case Intrinsic::copysign:
5786     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5787                              getValue(I.getArgOperand(0)).getValueType(),
5788                              getValue(I.getArgOperand(0)),
5789                              getValue(I.getArgOperand(1))));
5790     return nullptr;
5791   case Intrinsic::fma:
5792     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5793                              getValue(I.getArgOperand(0)).getValueType(),
5794                              getValue(I.getArgOperand(0)),
5795                              getValue(I.getArgOperand(1)),
5796                              getValue(I.getArgOperand(2))));
5797     return nullptr;
5798   case Intrinsic::experimental_constrained_fadd:
5799   case Intrinsic::experimental_constrained_fsub:
5800   case Intrinsic::experimental_constrained_fmul:
5801   case Intrinsic::experimental_constrained_fdiv:
5802   case Intrinsic::experimental_constrained_frem:
5803   case Intrinsic::experimental_constrained_fma:
5804   case Intrinsic::experimental_constrained_sqrt:
5805   case Intrinsic::experimental_constrained_pow:
5806   case Intrinsic::experimental_constrained_powi:
5807   case Intrinsic::experimental_constrained_sin:
5808   case Intrinsic::experimental_constrained_cos:
5809   case Intrinsic::experimental_constrained_exp:
5810   case Intrinsic::experimental_constrained_exp2:
5811   case Intrinsic::experimental_constrained_log:
5812   case Intrinsic::experimental_constrained_log10:
5813   case Intrinsic::experimental_constrained_log2:
5814   case Intrinsic::experimental_constrained_rint:
5815   case Intrinsic::experimental_constrained_nearbyint:
5816   case Intrinsic::experimental_constrained_maxnum:
5817   case Intrinsic::experimental_constrained_minnum:
5818   case Intrinsic::experimental_constrained_ceil:
5819   case Intrinsic::experimental_constrained_floor:
5820   case Intrinsic::experimental_constrained_round:
5821   case Intrinsic::experimental_constrained_trunc:
5822     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5823     return nullptr;
5824   case Intrinsic::fmuladd: {
5825     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5826     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5827         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5828       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5829                                getValue(I.getArgOperand(0)).getValueType(),
5830                                getValue(I.getArgOperand(0)),
5831                                getValue(I.getArgOperand(1)),
5832                                getValue(I.getArgOperand(2))));
5833     } else {
5834       // TODO: Intrinsic calls should have fast-math-flags.
5835       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5836                                 getValue(I.getArgOperand(0)).getValueType(),
5837                                 getValue(I.getArgOperand(0)),
5838                                 getValue(I.getArgOperand(1)));
5839       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5840                                 getValue(I.getArgOperand(0)).getValueType(),
5841                                 Mul,
5842                                 getValue(I.getArgOperand(2)));
5843       setValue(&I, Add);
5844     }
5845     return nullptr;
5846   }
5847   case Intrinsic::convert_to_fp16:
5848     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5849                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5850                                          getValue(I.getArgOperand(0)),
5851                                          DAG.getTargetConstant(0, sdl,
5852                                                                MVT::i32))));
5853     return nullptr;
5854   case Intrinsic::convert_from_fp16:
5855     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5856                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5857                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5858                                          getValue(I.getArgOperand(0)))));
5859     return nullptr;
5860   case Intrinsic::pcmarker: {
5861     SDValue Tmp = getValue(I.getArgOperand(0));
5862     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5863     return nullptr;
5864   }
5865   case Intrinsic::readcyclecounter: {
5866     SDValue Op = getRoot();
5867     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5868                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5869     setValue(&I, Res);
5870     DAG.setRoot(Res.getValue(1));
5871     return nullptr;
5872   }
5873   case Intrinsic::bitreverse:
5874     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5875                              getValue(I.getArgOperand(0)).getValueType(),
5876                              getValue(I.getArgOperand(0))));
5877     return nullptr;
5878   case Intrinsic::bswap:
5879     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5880                              getValue(I.getArgOperand(0)).getValueType(),
5881                              getValue(I.getArgOperand(0))));
5882     return nullptr;
5883   case Intrinsic::cttz: {
5884     SDValue Arg = getValue(I.getArgOperand(0));
5885     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5886     EVT Ty = Arg.getValueType();
5887     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5888                              sdl, Ty, Arg));
5889     return nullptr;
5890   }
5891   case Intrinsic::ctlz: {
5892     SDValue Arg = getValue(I.getArgOperand(0));
5893     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5894     EVT Ty = Arg.getValueType();
5895     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5896                              sdl, Ty, Arg));
5897     return nullptr;
5898   }
5899   case Intrinsic::ctpop: {
5900     SDValue Arg = getValue(I.getArgOperand(0));
5901     EVT Ty = Arg.getValueType();
5902     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5903     return nullptr;
5904   }
5905   case Intrinsic::fshl:
5906   case Intrinsic::fshr: {
5907     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5908     SDValue X = getValue(I.getArgOperand(0));
5909     SDValue Y = getValue(I.getArgOperand(1));
5910     SDValue Z = getValue(I.getArgOperand(2));
5911     EVT VT = X.getValueType();
5912     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5913     SDValue Zero = DAG.getConstant(0, sdl, VT);
5914     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5915 
5916     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
5917     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
5918       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
5919       return nullptr;
5920     }
5921 
5922     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5923     // avoid the select that is necessary in the general case to filter out
5924     // the 0-shift possibility that leads to UB.
5925     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5926       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5927       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5928         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5929         return nullptr;
5930       }
5931 
5932       // Some targets only rotate one way. Try the opposite direction.
5933       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5934       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5935         // Negate the shift amount because it is safe to ignore the high bits.
5936         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5937         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5938         return nullptr;
5939       }
5940 
5941       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5942       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5943       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5944       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5945       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5946       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5947       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5948       return nullptr;
5949     }
5950 
5951     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5952     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5953     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5954     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5955     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5956     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5957 
5958     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5959     // and that is undefined. We must compare and select to avoid UB.
5960     EVT CCVT = MVT::i1;
5961     if (VT.isVector())
5962       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5963 
5964     // For fshl, 0-shift returns the 1st arg (X).
5965     // For fshr, 0-shift returns the 2nd arg (Y).
5966     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5967     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5968     return nullptr;
5969   }
5970   case Intrinsic::sadd_sat: {
5971     SDValue Op1 = getValue(I.getArgOperand(0));
5972     SDValue Op2 = getValue(I.getArgOperand(1));
5973     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5974     return nullptr;
5975   }
5976   case Intrinsic::uadd_sat: {
5977     SDValue Op1 = getValue(I.getArgOperand(0));
5978     SDValue Op2 = getValue(I.getArgOperand(1));
5979     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5980     return nullptr;
5981   }
5982   case Intrinsic::ssub_sat: {
5983     SDValue Op1 = getValue(I.getArgOperand(0));
5984     SDValue Op2 = getValue(I.getArgOperand(1));
5985     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5986     return nullptr;
5987   }
5988   case Intrinsic::usub_sat: {
5989     SDValue Op1 = getValue(I.getArgOperand(0));
5990     SDValue Op2 = getValue(I.getArgOperand(1));
5991     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5992     return nullptr;
5993   }
5994   case Intrinsic::smul_fix:
5995   case Intrinsic::umul_fix: {
5996     SDValue Op1 = getValue(I.getArgOperand(0));
5997     SDValue Op2 = getValue(I.getArgOperand(1));
5998     SDValue Op3 = getValue(I.getArgOperand(2));
5999     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6000                              Op1.getValueType(), Op1, Op2, Op3));
6001     return nullptr;
6002   }
6003   case Intrinsic::stacksave: {
6004     SDValue Op = getRoot();
6005     Res = DAG.getNode(
6006         ISD::STACKSAVE, sdl,
6007         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6008     setValue(&I, Res);
6009     DAG.setRoot(Res.getValue(1));
6010     return nullptr;
6011   }
6012   case Intrinsic::stackrestore:
6013     Res = getValue(I.getArgOperand(0));
6014     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6015     return nullptr;
6016   case Intrinsic::get_dynamic_area_offset: {
6017     SDValue Op = getRoot();
6018     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6019     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6020     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6021     // target.
6022     if (PtrTy != ResTy)
6023       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6024                          " intrinsic!");
6025     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6026                       Op);
6027     DAG.setRoot(Op);
6028     setValue(&I, Res);
6029     return nullptr;
6030   }
6031   case Intrinsic::stackguard: {
6032     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6033     MachineFunction &MF = DAG.getMachineFunction();
6034     const Module &M = *MF.getFunction().getParent();
6035     SDValue Chain = getRoot();
6036     if (TLI.useLoadStackGuardNode()) {
6037       Res = getLoadStackGuard(DAG, sdl, Chain);
6038     } else {
6039       const Value *Global = TLI.getSDagStackGuard(M);
6040       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6041       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6042                         MachinePointerInfo(Global, 0), Align,
6043                         MachineMemOperand::MOVolatile);
6044     }
6045     if (TLI.useStackGuardXorFP())
6046       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6047     DAG.setRoot(Chain);
6048     setValue(&I, Res);
6049     return nullptr;
6050   }
6051   case Intrinsic::stackprotector: {
6052     // Emit code into the DAG to store the stack guard onto the stack.
6053     MachineFunction &MF = DAG.getMachineFunction();
6054     MachineFrameInfo &MFI = MF.getFrameInfo();
6055     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6056     SDValue Src, Chain = getRoot();
6057 
6058     if (TLI.useLoadStackGuardNode())
6059       Src = getLoadStackGuard(DAG, sdl, Chain);
6060     else
6061       Src = getValue(I.getArgOperand(0));   // The guard's value.
6062 
6063     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6064 
6065     int FI = FuncInfo.StaticAllocaMap[Slot];
6066     MFI.setStackProtectorIndex(FI);
6067 
6068     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6069 
6070     // Store the stack protector onto the stack.
6071     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6072                                                  DAG.getMachineFunction(), FI),
6073                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6074     setValue(&I, Res);
6075     DAG.setRoot(Res);
6076     return nullptr;
6077   }
6078   case Intrinsic::objectsize: {
6079     // If we don't know by now, we're never going to know.
6080     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6081 
6082     assert(CI && "Non-constant type in __builtin_object_size?");
6083 
6084     SDValue Arg = getValue(I.getCalledValue());
6085     EVT Ty = Arg.getValueType();
6086 
6087     if (CI->isZero())
6088       Res = DAG.getConstant(-1ULL, sdl, Ty);
6089     else
6090       Res = DAG.getConstant(0, sdl, Ty);
6091 
6092     setValue(&I, Res);
6093     return nullptr;
6094   }
6095 
6096   case Intrinsic::is_constant:
6097     // If this wasn't constant-folded away by now, then it's not a
6098     // constant.
6099     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6100     return nullptr;
6101 
6102   case Intrinsic::annotation:
6103   case Intrinsic::ptr_annotation:
6104   case Intrinsic::launder_invariant_group:
6105   case Intrinsic::strip_invariant_group:
6106     // Drop the intrinsic, but forward the value
6107     setValue(&I, getValue(I.getOperand(0)));
6108     return nullptr;
6109   case Intrinsic::assume:
6110   case Intrinsic::var_annotation:
6111   case Intrinsic::sideeffect:
6112     // Discard annotate attributes, assumptions, and artificial side-effects.
6113     return nullptr;
6114 
6115   case Intrinsic::codeview_annotation: {
6116     // Emit a label associated with this metadata.
6117     MachineFunction &MF = DAG.getMachineFunction();
6118     MCSymbol *Label =
6119         MF.getMMI().getContext().createTempSymbol("annotation", true);
6120     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6121     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6122     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6123     DAG.setRoot(Res);
6124     return nullptr;
6125   }
6126 
6127   case Intrinsic::init_trampoline: {
6128     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6129 
6130     SDValue Ops[6];
6131     Ops[0] = getRoot();
6132     Ops[1] = getValue(I.getArgOperand(0));
6133     Ops[2] = getValue(I.getArgOperand(1));
6134     Ops[3] = getValue(I.getArgOperand(2));
6135     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6136     Ops[5] = DAG.getSrcValue(F);
6137 
6138     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6139 
6140     DAG.setRoot(Res);
6141     return nullptr;
6142   }
6143   case Intrinsic::adjust_trampoline:
6144     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6145                              TLI.getPointerTy(DAG.getDataLayout()),
6146                              getValue(I.getArgOperand(0))));
6147     return nullptr;
6148   case Intrinsic::gcroot: {
6149     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6150            "only valid in functions with gc specified, enforced by Verifier");
6151     assert(GFI && "implied by previous");
6152     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6153     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6154 
6155     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6156     GFI->addStackRoot(FI->getIndex(), TypeMap);
6157     return nullptr;
6158   }
6159   case Intrinsic::gcread:
6160   case Intrinsic::gcwrite:
6161     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6162   case Intrinsic::flt_rounds:
6163     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6164     return nullptr;
6165 
6166   case Intrinsic::expect:
6167     // Just replace __builtin_expect(exp, c) with EXP.
6168     setValue(&I, getValue(I.getArgOperand(0)));
6169     return nullptr;
6170 
6171   case Intrinsic::debugtrap:
6172   case Intrinsic::trap: {
6173     StringRef TrapFuncName =
6174         I.getAttributes()
6175             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6176             .getValueAsString();
6177     if (TrapFuncName.empty()) {
6178       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6179         ISD::TRAP : ISD::DEBUGTRAP;
6180       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6181       return nullptr;
6182     }
6183     TargetLowering::ArgListTy Args;
6184 
6185     TargetLowering::CallLoweringInfo CLI(DAG);
6186     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6187         CallingConv::C, I.getType(),
6188         DAG.getExternalSymbol(TrapFuncName.data(),
6189                               TLI.getPointerTy(DAG.getDataLayout())),
6190         std::move(Args));
6191 
6192     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6193     DAG.setRoot(Result.second);
6194     return nullptr;
6195   }
6196 
6197   case Intrinsic::uadd_with_overflow:
6198   case Intrinsic::sadd_with_overflow:
6199   case Intrinsic::usub_with_overflow:
6200   case Intrinsic::ssub_with_overflow:
6201   case Intrinsic::umul_with_overflow:
6202   case Intrinsic::smul_with_overflow: {
6203     ISD::NodeType Op;
6204     switch (Intrinsic) {
6205     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6206     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6207     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6208     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6209     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6210     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6211     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6212     }
6213     SDValue Op1 = getValue(I.getArgOperand(0));
6214     SDValue Op2 = getValue(I.getArgOperand(1));
6215 
6216     EVT ResultVT = Op1.getValueType();
6217     EVT OverflowVT = MVT::i1;
6218     if (ResultVT.isVector())
6219       OverflowVT = EVT::getVectorVT(
6220           *Context, OverflowVT, ResultVT.getVectorNumElements());
6221 
6222     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6223     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6224     return nullptr;
6225   }
6226   case Intrinsic::prefetch: {
6227     SDValue Ops[5];
6228     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6229     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6230     Ops[0] = DAG.getRoot();
6231     Ops[1] = getValue(I.getArgOperand(0));
6232     Ops[2] = getValue(I.getArgOperand(1));
6233     Ops[3] = getValue(I.getArgOperand(2));
6234     Ops[4] = getValue(I.getArgOperand(3));
6235     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6236                                              DAG.getVTList(MVT::Other), Ops,
6237                                              EVT::getIntegerVT(*Context, 8),
6238                                              MachinePointerInfo(I.getArgOperand(0)),
6239                                              0, /* align */
6240                                              Flags);
6241 
6242     // Chain the prefetch in parallell with any pending loads, to stay out of
6243     // the way of later optimizations.
6244     PendingLoads.push_back(Result);
6245     Result = getRoot();
6246     DAG.setRoot(Result);
6247     return nullptr;
6248   }
6249   case Intrinsic::lifetime_start:
6250   case Intrinsic::lifetime_end: {
6251     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6252     // Stack coloring is not enabled in O0, discard region information.
6253     if (TM.getOptLevel() == CodeGenOpt::None)
6254       return nullptr;
6255 
6256     SmallVector<Value *, 4> Allocas;
6257     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6258 
6259     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6260            E = Allocas.end(); Object != E; ++Object) {
6261       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6262 
6263       // Could not find an Alloca.
6264       if (!LifetimeObject)
6265         continue;
6266 
6267       // First check that the Alloca is static, otherwise it won't have a
6268       // valid frame index.
6269       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6270       if (SI == FuncInfo.StaticAllocaMap.end())
6271         return nullptr;
6272 
6273       int FI = SI->second;
6274 
6275       SDValue Ops[2];
6276       Ops[0] = getRoot();
6277       Ops[1] =
6278           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6279       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6280 
6281       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6282       DAG.setRoot(Res);
6283     }
6284     return nullptr;
6285   }
6286   case Intrinsic::invariant_start:
6287     // Discard region information.
6288     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6289     return nullptr;
6290   case Intrinsic::invariant_end:
6291     // Discard region information.
6292     return nullptr;
6293   case Intrinsic::clear_cache:
6294     return TLI.getClearCacheBuiltinName();
6295   case Intrinsic::donothing:
6296     // ignore
6297     return nullptr;
6298   case Intrinsic::experimental_stackmap:
6299     visitStackmap(I);
6300     return nullptr;
6301   case Intrinsic::experimental_patchpoint_void:
6302   case Intrinsic::experimental_patchpoint_i64:
6303     visitPatchpoint(&I);
6304     return nullptr;
6305   case Intrinsic::experimental_gc_statepoint:
6306     LowerStatepoint(ImmutableStatepoint(&I));
6307     return nullptr;
6308   case Intrinsic::experimental_gc_result:
6309     visitGCResult(cast<GCResultInst>(I));
6310     return nullptr;
6311   case Intrinsic::experimental_gc_relocate:
6312     visitGCRelocate(cast<GCRelocateInst>(I));
6313     return nullptr;
6314   case Intrinsic::instrprof_increment:
6315     llvm_unreachable("instrprof failed to lower an increment");
6316   case Intrinsic::instrprof_value_profile:
6317     llvm_unreachable("instrprof failed to lower a value profiling call");
6318   case Intrinsic::localescape: {
6319     MachineFunction &MF = DAG.getMachineFunction();
6320     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6321 
6322     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6323     // is the same on all targets.
6324     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6325       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6326       if (isa<ConstantPointerNull>(Arg))
6327         continue; // Skip null pointers. They represent a hole in index space.
6328       AllocaInst *Slot = cast<AllocaInst>(Arg);
6329       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6330              "can only escape static allocas");
6331       int FI = FuncInfo.StaticAllocaMap[Slot];
6332       MCSymbol *FrameAllocSym =
6333           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6334               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6335       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6336               TII->get(TargetOpcode::LOCAL_ESCAPE))
6337           .addSym(FrameAllocSym)
6338           .addFrameIndex(FI);
6339     }
6340 
6341     return nullptr;
6342   }
6343 
6344   case Intrinsic::localrecover: {
6345     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6346     MachineFunction &MF = DAG.getMachineFunction();
6347     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6348 
6349     // Get the symbol that defines the frame offset.
6350     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6351     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6352     unsigned IdxVal =
6353         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6354     MCSymbol *FrameAllocSym =
6355         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6356             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6357 
6358     // Create a MCSymbol for the label to avoid any target lowering
6359     // that would make this PC relative.
6360     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6361     SDValue OffsetVal =
6362         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6363 
6364     // Add the offset to the FP.
6365     Value *FP = I.getArgOperand(1);
6366     SDValue FPVal = getValue(FP);
6367     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6368     setValue(&I, Add);
6369 
6370     return nullptr;
6371   }
6372 
6373   case Intrinsic::eh_exceptionpointer:
6374   case Intrinsic::eh_exceptioncode: {
6375     // Get the exception pointer vreg, copy from it, and resize it to fit.
6376     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6377     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6378     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6379     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6380     SDValue N =
6381         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6382     if (Intrinsic == Intrinsic::eh_exceptioncode)
6383       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6384     setValue(&I, N);
6385     return nullptr;
6386   }
6387   case Intrinsic::xray_customevent: {
6388     // Here we want to make sure that the intrinsic behaves as if it has a
6389     // specific calling convention, and only for x86_64.
6390     // FIXME: Support other platforms later.
6391     const auto &Triple = DAG.getTarget().getTargetTriple();
6392     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6393       return nullptr;
6394 
6395     SDLoc DL = getCurSDLoc();
6396     SmallVector<SDValue, 8> Ops;
6397 
6398     // We want to say that we always want the arguments in registers.
6399     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6400     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6401     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6402     SDValue Chain = getRoot();
6403     Ops.push_back(LogEntryVal);
6404     Ops.push_back(StrSizeVal);
6405     Ops.push_back(Chain);
6406 
6407     // We need to enforce the calling convention for the callsite, so that
6408     // argument ordering is enforced correctly, and that register allocation can
6409     // see that some registers may be assumed clobbered and have to preserve
6410     // them across calls to the intrinsic.
6411     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6412                                            DL, NodeTys, Ops);
6413     SDValue patchableNode = SDValue(MN, 0);
6414     DAG.setRoot(patchableNode);
6415     setValue(&I, patchableNode);
6416     return nullptr;
6417   }
6418   case Intrinsic::xray_typedevent: {
6419     // Here we want to make sure that the intrinsic behaves as if it has a
6420     // specific calling convention, and only for x86_64.
6421     // FIXME: Support other platforms later.
6422     const auto &Triple = DAG.getTarget().getTargetTriple();
6423     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6424       return nullptr;
6425 
6426     SDLoc DL = getCurSDLoc();
6427     SmallVector<SDValue, 8> Ops;
6428 
6429     // We want to say that we always want the arguments in registers.
6430     // It's unclear to me how manipulating the selection DAG here forces callers
6431     // to provide arguments in registers instead of on the stack.
6432     SDValue LogTypeId = getValue(I.getArgOperand(0));
6433     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6434     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6435     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6436     SDValue Chain = getRoot();
6437     Ops.push_back(LogTypeId);
6438     Ops.push_back(LogEntryVal);
6439     Ops.push_back(StrSizeVal);
6440     Ops.push_back(Chain);
6441 
6442     // We need to enforce the calling convention for the callsite, so that
6443     // argument ordering is enforced correctly, and that register allocation can
6444     // see that some registers may be assumed clobbered and have to preserve
6445     // them across calls to the intrinsic.
6446     MachineSDNode *MN = DAG.getMachineNode(
6447         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6448     SDValue patchableNode = SDValue(MN, 0);
6449     DAG.setRoot(patchableNode);
6450     setValue(&I, patchableNode);
6451     return nullptr;
6452   }
6453   case Intrinsic::experimental_deoptimize:
6454     LowerDeoptimizeCall(&I);
6455     return nullptr;
6456 
6457   case Intrinsic::experimental_vector_reduce_fadd:
6458   case Intrinsic::experimental_vector_reduce_fmul:
6459   case Intrinsic::experimental_vector_reduce_add:
6460   case Intrinsic::experimental_vector_reduce_mul:
6461   case Intrinsic::experimental_vector_reduce_and:
6462   case Intrinsic::experimental_vector_reduce_or:
6463   case Intrinsic::experimental_vector_reduce_xor:
6464   case Intrinsic::experimental_vector_reduce_smax:
6465   case Intrinsic::experimental_vector_reduce_smin:
6466   case Intrinsic::experimental_vector_reduce_umax:
6467   case Intrinsic::experimental_vector_reduce_umin:
6468   case Intrinsic::experimental_vector_reduce_fmax:
6469   case Intrinsic::experimental_vector_reduce_fmin:
6470     visitVectorReduce(I, Intrinsic);
6471     return nullptr;
6472 
6473   case Intrinsic::icall_branch_funnel: {
6474     SmallVector<SDValue, 16> Ops;
6475     Ops.push_back(DAG.getRoot());
6476     Ops.push_back(getValue(I.getArgOperand(0)));
6477 
6478     int64_t Offset;
6479     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6480         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6481     if (!Base)
6482       report_fatal_error(
6483           "llvm.icall.branch.funnel operand must be a GlobalValue");
6484     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6485 
6486     struct BranchFunnelTarget {
6487       int64_t Offset;
6488       SDValue Target;
6489     };
6490     SmallVector<BranchFunnelTarget, 8> Targets;
6491 
6492     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6493       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6494           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6495       if (ElemBase != Base)
6496         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6497                            "to the same GlobalValue");
6498 
6499       SDValue Val = getValue(I.getArgOperand(Op + 1));
6500       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6501       if (!GA)
6502         report_fatal_error(
6503             "llvm.icall.branch.funnel operand must be a GlobalValue");
6504       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6505                                      GA->getGlobal(), getCurSDLoc(),
6506                                      Val.getValueType(), GA->getOffset())});
6507     }
6508     llvm::sort(Targets,
6509                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6510                  return T1.Offset < T2.Offset;
6511                });
6512 
6513     for (auto &T : Targets) {
6514       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6515       Ops.push_back(T.Target);
6516     }
6517 
6518     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6519                                  getCurSDLoc(), MVT::Other, Ops),
6520               0);
6521     DAG.setRoot(N);
6522     setValue(&I, N);
6523     HasTailCall = true;
6524     return nullptr;
6525   }
6526 
6527   case Intrinsic::wasm_landingpad_index:
6528     // Information this intrinsic contained has been transferred to
6529     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6530     // delete it now.
6531     return nullptr;
6532   }
6533 }
6534 
6535 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6536     const ConstrainedFPIntrinsic &FPI) {
6537   SDLoc sdl = getCurSDLoc();
6538   unsigned Opcode;
6539   switch (FPI.getIntrinsicID()) {
6540   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6541   case Intrinsic::experimental_constrained_fadd:
6542     Opcode = ISD::STRICT_FADD;
6543     break;
6544   case Intrinsic::experimental_constrained_fsub:
6545     Opcode = ISD::STRICT_FSUB;
6546     break;
6547   case Intrinsic::experimental_constrained_fmul:
6548     Opcode = ISD::STRICT_FMUL;
6549     break;
6550   case Intrinsic::experimental_constrained_fdiv:
6551     Opcode = ISD::STRICT_FDIV;
6552     break;
6553   case Intrinsic::experimental_constrained_frem:
6554     Opcode = ISD::STRICT_FREM;
6555     break;
6556   case Intrinsic::experimental_constrained_fma:
6557     Opcode = ISD::STRICT_FMA;
6558     break;
6559   case Intrinsic::experimental_constrained_sqrt:
6560     Opcode = ISD::STRICT_FSQRT;
6561     break;
6562   case Intrinsic::experimental_constrained_pow:
6563     Opcode = ISD::STRICT_FPOW;
6564     break;
6565   case Intrinsic::experimental_constrained_powi:
6566     Opcode = ISD::STRICT_FPOWI;
6567     break;
6568   case Intrinsic::experimental_constrained_sin:
6569     Opcode = ISD::STRICT_FSIN;
6570     break;
6571   case Intrinsic::experimental_constrained_cos:
6572     Opcode = ISD::STRICT_FCOS;
6573     break;
6574   case Intrinsic::experimental_constrained_exp:
6575     Opcode = ISD::STRICT_FEXP;
6576     break;
6577   case Intrinsic::experimental_constrained_exp2:
6578     Opcode = ISD::STRICT_FEXP2;
6579     break;
6580   case Intrinsic::experimental_constrained_log:
6581     Opcode = ISD::STRICT_FLOG;
6582     break;
6583   case Intrinsic::experimental_constrained_log10:
6584     Opcode = ISD::STRICT_FLOG10;
6585     break;
6586   case Intrinsic::experimental_constrained_log2:
6587     Opcode = ISD::STRICT_FLOG2;
6588     break;
6589   case Intrinsic::experimental_constrained_rint:
6590     Opcode = ISD::STRICT_FRINT;
6591     break;
6592   case Intrinsic::experimental_constrained_nearbyint:
6593     Opcode = ISD::STRICT_FNEARBYINT;
6594     break;
6595   case Intrinsic::experimental_constrained_maxnum:
6596     Opcode = ISD::STRICT_FMAXNUM;
6597     break;
6598   case Intrinsic::experimental_constrained_minnum:
6599     Opcode = ISD::STRICT_FMINNUM;
6600     break;
6601   case Intrinsic::experimental_constrained_ceil:
6602     Opcode = ISD::STRICT_FCEIL;
6603     break;
6604   case Intrinsic::experimental_constrained_floor:
6605     Opcode = ISD::STRICT_FFLOOR;
6606     break;
6607   case Intrinsic::experimental_constrained_round:
6608     Opcode = ISD::STRICT_FROUND;
6609     break;
6610   case Intrinsic::experimental_constrained_trunc:
6611     Opcode = ISD::STRICT_FTRUNC;
6612     break;
6613   }
6614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6615   SDValue Chain = getRoot();
6616   SmallVector<EVT, 4> ValueVTs;
6617   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6618   ValueVTs.push_back(MVT::Other); // Out chain
6619 
6620   SDVTList VTs = DAG.getVTList(ValueVTs);
6621   SDValue Result;
6622   if (FPI.isUnaryOp())
6623     Result = DAG.getNode(Opcode, sdl, VTs,
6624                          { Chain, getValue(FPI.getArgOperand(0)) });
6625   else if (FPI.isTernaryOp())
6626     Result = DAG.getNode(Opcode, sdl, VTs,
6627                          { Chain, getValue(FPI.getArgOperand(0)),
6628                                   getValue(FPI.getArgOperand(1)),
6629                                   getValue(FPI.getArgOperand(2)) });
6630   else
6631     Result = DAG.getNode(Opcode, sdl, VTs,
6632                          { Chain, getValue(FPI.getArgOperand(0)),
6633                            getValue(FPI.getArgOperand(1))  });
6634 
6635   assert(Result.getNode()->getNumValues() == 2);
6636   SDValue OutChain = Result.getValue(1);
6637   DAG.setRoot(OutChain);
6638   SDValue FPResult = Result.getValue(0);
6639   setValue(&FPI, FPResult);
6640 }
6641 
6642 std::pair<SDValue, SDValue>
6643 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6644                                     const BasicBlock *EHPadBB) {
6645   MachineFunction &MF = DAG.getMachineFunction();
6646   MachineModuleInfo &MMI = MF.getMMI();
6647   MCSymbol *BeginLabel = nullptr;
6648 
6649   if (EHPadBB) {
6650     // Insert a label before the invoke call to mark the try range.  This can be
6651     // used to detect deletion of the invoke via the MachineModuleInfo.
6652     BeginLabel = MMI.getContext().createTempSymbol();
6653 
6654     // For SjLj, keep track of which landing pads go with which invokes
6655     // so as to maintain the ordering of pads in the LSDA.
6656     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6657     if (CallSiteIndex) {
6658       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6659       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6660 
6661       // Now that the call site is handled, stop tracking it.
6662       MMI.setCurrentCallSite(0);
6663     }
6664 
6665     // Both PendingLoads and PendingExports must be flushed here;
6666     // this call might not return.
6667     (void)getRoot();
6668     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6669 
6670     CLI.setChain(getRoot());
6671   }
6672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6673   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6674 
6675   assert((CLI.IsTailCall || Result.second.getNode()) &&
6676          "Non-null chain expected with non-tail call!");
6677   assert((Result.second.getNode() || !Result.first.getNode()) &&
6678          "Null value expected with tail call!");
6679 
6680   if (!Result.second.getNode()) {
6681     // As a special case, a null chain means that a tail call has been emitted
6682     // and the DAG root is already updated.
6683     HasTailCall = true;
6684 
6685     // Since there's no actual continuation from this block, nothing can be
6686     // relying on us setting vregs for them.
6687     PendingExports.clear();
6688   } else {
6689     DAG.setRoot(Result.second);
6690   }
6691 
6692   if (EHPadBB) {
6693     // Insert a label at the end of the invoke call to mark the try range.  This
6694     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6695     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6696     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6697 
6698     // Inform MachineModuleInfo of range.
6699     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6700     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6701     // actually use outlined funclets and their LSDA info style.
6702     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6703       assert(CLI.CS);
6704       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6705       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6706                                 BeginLabel, EndLabel);
6707     } else if (!isScopedEHPersonality(Pers)) {
6708       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6709     }
6710   }
6711 
6712   return Result;
6713 }
6714 
6715 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6716                                       bool isTailCall,
6717                                       const BasicBlock *EHPadBB) {
6718   auto &DL = DAG.getDataLayout();
6719   FunctionType *FTy = CS.getFunctionType();
6720   Type *RetTy = CS.getType();
6721 
6722   TargetLowering::ArgListTy Args;
6723   Args.reserve(CS.arg_size());
6724 
6725   const Value *SwiftErrorVal = nullptr;
6726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6727 
6728   // We can't tail call inside a function with a swifterror argument. Lowering
6729   // does not support this yet. It would have to move into the swifterror
6730   // register before the call.
6731   auto *Caller = CS.getInstruction()->getParent()->getParent();
6732   if (TLI.supportSwiftError() &&
6733       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6734     isTailCall = false;
6735 
6736   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6737        i != e; ++i) {
6738     TargetLowering::ArgListEntry Entry;
6739     const Value *V = *i;
6740 
6741     // Skip empty types
6742     if (V->getType()->isEmptyTy())
6743       continue;
6744 
6745     SDValue ArgNode = getValue(V);
6746     Entry.Node = ArgNode; Entry.Ty = V->getType();
6747 
6748     Entry.setAttributes(&CS, i - CS.arg_begin());
6749 
6750     // Use swifterror virtual register as input to the call.
6751     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6752       SwiftErrorVal = V;
6753       // We find the virtual register for the actual swifterror argument.
6754       // Instead of using the Value, we use the virtual register instead.
6755       Entry.Node = DAG.getRegister(FuncInfo
6756                                        .getOrCreateSwiftErrorVRegUseAt(
6757                                            CS.getInstruction(), FuncInfo.MBB, V)
6758                                        .first,
6759                                    EVT(TLI.getPointerTy(DL)));
6760     }
6761 
6762     Args.push_back(Entry);
6763 
6764     // If we have an explicit sret argument that is an Instruction, (i.e., it
6765     // might point to function-local memory), we can't meaningfully tail-call.
6766     if (Entry.IsSRet && isa<Instruction>(V))
6767       isTailCall = false;
6768   }
6769 
6770   // Check if target-independent constraints permit a tail call here.
6771   // Target-dependent constraints are checked within TLI->LowerCallTo.
6772   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6773     isTailCall = false;
6774 
6775   // Disable tail calls if there is an swifterror argument. Targets have not
6776   // been updated to support tail calls.
6777   if (TLI.supportSwiftError() && SwiftErrorVal)
6778     isTailCall = false;
6779 
6780   TargetLowering::CallLoweringInfo CLI(DAG);
6781   CLI.setDebugLoc(getCurSDLoc())
6782       .setChain(getRoot())
6783       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6784       .setTailCall(isTailCall)
6785       .setConvergent(CS.isConvergent());
6786   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6787 
6788   if (Result.first.getNode()) {
6789     const Instruction *Inst = CS.getInstruction();
6790     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6791     setValue(Inst, Result.first);
6792   }
6793 
6794   // The last element of CLI.InVals has the SDValue for swifterror return.
6795   // Here we copy it to a virtual register and update SwiftErrorMap for
6796   // book-keeping.
6797   if (SwiftErrorVal && TLI.supportSwiftError()) {
6798     // Get the last element of InVals.
6799     SDValue Src = CLI.InVals.back();
6800     unsigned VReg; bool CreatedVReg;
6801     std::tie(VReg, CreatedVReg) =
6802         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6803     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6804     // We update the virtual register for the actual swifterror argument.
6805     if (CreatedVReg)
6806       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6807     DAG.setRoot(CopyNode);
6808   }
6809 }
6810 
6811 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6812                              SelectionDAGBuilder &Builder) {
6813   // Check to see if this load can be trivially constant folded, e.g. if the
6814   // input is from a string literal.
6815   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6816     // Cast pointer to the type we really want to load.
6817     Type *LoadTy =
6818         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6819     if (LoadVT.isVector())
6820       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6821 
6822     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6823                                          PointerType::getUnqual(LoadTy));
6824 
6825     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6826             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6827       return Builder.getValue(LoadCst);
6828   }
6829 
6830   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6831   // still constant memory, the input chain can be the entry node.
6832   SDValue Root;
6833   bool ConstantMemory = false;
6834 
6835   // Do not serialize (non-volatile) loads of constant memory with anything.
6836   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6837     Root = Builder.DAG.getEntryNode();
6838     ConstantMemory = true;
6839   } else {
6840     // Do not serialize non-volatile loads against each other.
6841     Root = Builder.DAG.getRoot();
6842   }
6843 
6844   SDValue Ptr = Builder.getValue(PtrVal);
6845   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6846                                         Ptr, MachinePointerInfo(PtrVal),
6847                                         /* Alignment = */ 1);
6848 
6849   if (!ConstantMemory)
6850     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6851   return LoadVal;
6852 }
6853 
6854 /// Record the value for an instruction that produces an integer result,
6855 /// converting the type where necessary.
6856 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6857                                                   SDValue Value,
6858                                                   bool IsSigned) {
6859   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6860                                                     I.getType(), true);
6861   if (IsSigned)
6862     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6863   else
6864     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6865   setValue(&I, Value);
6866 }
6867 
6868 /// See if we can lower a memcmp 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::visitMemCmpCall(const CallInst &I) {
6874   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6875   const Value *Size = I.getArgOperand(2);
6876   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6877   if (CSize && CSize->getZExtValue() == 0) {
6878     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6879                                                           I.getType(), true);
6880     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6881     return true;
6882   }
6883 
6884   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6885   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6886       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6887       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6888   if (Res.first.getNode()) {
6889     processIntegerCallValue(I, Res.first, true);
6890     PendingLoads.push_back(Res.second);
6891     return true;
6892   }
6893 
6894   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6895   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6896   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6897     return false;
6898 
6899   // If the target has a fast compare for the given size, it will return a
6900   // preferred load type for that size. Require that the load VT is legal and
6901   // that the target supports unaligned loads of that type. Otherwise, return
6902   // INVALID.
6903   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6904     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6905     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6906     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6907       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6908       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6909       // TODO: Check alignment of src and dest ptrs.
6910       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6911       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6912       if (!TLI.isTypeLegal(LVT) ||
6913           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6914           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6915         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6916     }
6917 
6918     return LVT;
6919   };
6920 
6921   // This turns into unaligned loads. We only do this if the target natively
6922   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6923   // we'll only produce a small number of byte loads.
6924   MVT LoadVT;
6925   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6926   switch (NumBitsToCompare) {
6927   default:
6928     return false;
6929   case 16:
6930     LoadVT = MVT::i16;
6931     break;
6932   case 32:
6933     LoadVT = MVT::i32;
6934     break;
6935   case 64:
6936   case 128:
6937   case 256:
6938     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6939     break;
6940   }
6941 
6942   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6943     return false;
6944 
6945   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6946   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6947 
6948   // Bitcast to a wide integer type if the loads are vectors.
6949   if (LoadVT.isVector()) {
6950     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6951     LoadL = DAG.getBitcast(CmpVT, LoadL);
6952     LoadR = DAG.getBitcast(CmpVT, LoadR);
6953   }
6954 
6955   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6956   processIntegerCallValue(I, Cmp, false);
6957   return true;
6958 }
6959 
6960 /// See if we can lower a memchr call into an optimized form. If so, return
6961 /// true and lower it. Otherwise return false, and it will be lowered like a
6962 /// normal call.
6963 /// The caller already checked that \p I calls the appropriate LibFunc with a
6964 /// correct prototype.
6965 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6966   const Value *Src = I.getArgOperand(0);
6967   const Value *Char = I.getArgOperand(1);
6968   const Value *Length = I.getArgOperand(2);
6969 
6970   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6971   std::pair<SDValue, SDValue> Res =
6972     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6973                                 getValue(Src), getValue(Char), getValue(Length),
6974                                 MachinePointerInfo(Src));
6975   if (Res.first.getNode()) {
6976     setValue(&I, Res.first);
6977     PendingLoads.push_back(Res.second);
6978     return true;
6979   }
6980 
6981   return false;
6982 }
6983 
6984 /// See if we can lower a mempcpy call into an optimized form. If so, return
6985 /// true and lower it. Otherwise return false, and it will be lowered like a
6986 /// normal call.
6987 /// The caller already checked that \p I calls the appropriate LibFunc with a
6988 /// correct prototype.
6989 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6990   SDValue Dst = getValue(I.getArgOperand(0));
6991   SDValue Src = getValue(I.getArgOperand(1));
6992   SDValue Size = getValue(I.getArgOperand(2));
6993 
6994   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6995   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6996   unsigned Align = std::min(DstAlign, SrcAlign);
6997   if (Align == 0) // Alignment of one or both could not be inferred.
6998     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6999 
7000   bool isVol = false;
7001   SDLoc sdl = getCurSDLoc();
7002 
7003   // In the mempcpy context we need to pass in a false value for isTailCall
7004   // because the return pointer needs to be adjusted by the size of
7005   // the copied memory.
7006   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7007                              false, /*isTailCall=*/false,
7008                              MachinePointerInfo(I.getArgOperand(0)),
7009                              MachinePointerInfo(I.getArgOperand(1)));
7010   assert(MC.getNode() != nullptr &&
7011          "** memcpy should not be lowered as TailCall in mempcpy context **");
7012   DAG.setRoot(MC);
7013 
7014   // Check if Size needs to be truncated or extended.
7015   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7016 
7017   // Adjust return pointer to point just past the last dst byte.
7018   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7019                                     Dst, Size);
7020   setValue(&I, DstPlusSize);
7021   return true;
7022 }
7023 
7024 /// See if we can lower a strcpy call into an optimized form.  If so, return
7025 /// true and lower it, otherwise return false and it will be lowered like a
7026 /// normal call.
7027 /// The caller already checked that \p I calls the appropriate LibFunc with a
7028 /// correct prototype.
7029 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7030   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7031 
7032   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7033   std::pair<SDValue, SDValue> Res =
7034     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7035                                 getValue(Arg0), getValue(Arg1),
7036                                 MachinePointerInfo(Arg0),
7037                                 MachinePointerInfo(Arg1), isStpcpy);
7038   if (Res.first.getNode()) {
7039     setValue(&I, Res.first);
7040     DAG.setRoot(Res.second);
7041     return true;
7042   }
7043 
7044   return false;
7045 }
7046 
7047 /// See if we can lower a strcmp call into an optimized form.  If so, return
7048 /// true and lower it, otherwise return false and it will be lowered like a
7049 /// normal call.
7050 /// The caller already checked that \p I calls the appropriate LibFunc with a
7051 /// correct prototype.
7052 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7053   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7054 
7055   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7056   std::pair<SDValue, SDValue> Res =
7057     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7058                                 getValue(Arg0), getValue(Arg1),
7059                                 MachinePointerInfo(Arg0),
7060                                 MachinePointerInfo(Arg1));
7061   if (Res.first.getNode()) {
7062     processIntegerCallValue(I, Res.first, true);
7063     PendingLoads.push_back(Res.second);
7064     return true;
7065   }
7066 
7067   return false;
7068 }
7069 
7070 /// See if we can lower a strlen call into an optimized form.  If so, return
7071 /// true and lower it, otherwise return false and it will be lowered like a
7072 /// normal call.
7073 /// The caller already checked that \p I calls the appropriate LibFunc with a
7074 /// correct prototype.
7075 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7076   const Value *Arg0 = I.getArgOperand(0);
7077 
7078   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7079   std::pair<SDValue, SDValue> Res =
7080     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7081                                 getValue(Arg0), MachinePointerInfo(Arg0));
7082   if (Res.first.getNode()) {
7083     processIntegerCallValue(I, Res.first, false);
7084     PendingLoads.push_back(Res.second);
7085     return true;
7086   }
7087 
7088   return false;
7089 }
7090 
7091 /// See if we can lower a strnlen call into an optimized form.  If so, return
7092 /// true and lower it, otherwise return false and it will be lowered like a
7093 /// normal call.
7094 /// The caller already checked that \p I calls the appropriate LibFunc with a
7095 /// correct prototype.
7096 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7097   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7098 
7099   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7100   std::pair<SDValue, SDValue> Res =
7101     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7102                                  getValue(Arg0), getValue(Arg1),
7103                                  MachinePointerInfo(Arg0));
7104   if (Res.first.getNode()) {
7105     processIntegerCallValue(I, Res.first, false);
7106     PendingLoads.push_back(Res.second);
7107     return true;
7108   }
7109 
7110   return false;
7111 }
7112 
7113 /// See if we can lower a unary floating-point operation into an SDNode with
7114 /// the specified Opcode.  If so, return true and lower it, otherwise return
7115 /// false and it will be lowered like a normal call.
7116 /// The caller already checked that \p I calls the appropriate LibFunc with a
7117 /// correct prototype.
7118 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7119                                               unsigned Opcode) {
7120   // We already checked this call's prototype; verify it doesn't modify errno.
7121   if (!I.onlyReadsMemory())
7122     return false;
7123 
7124   SDValue Tmp = getValue(I.getArgOperand(0));
7125   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7126   return true;
7127 }
7128 
7129 /// See if we can lower a binary floating-point operation into an SDNode with
7130 /// the specified Opcode. If so, return true and lower it. Otherwise return
7131 /// false, and it will be lowered like a normal call.
7132 /// The caller already checked that \p I calls the appropriate LibFunc with a
7133 /// correct prototype.
7134 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7135                                                unsigned Opcode) {
7136   // We already checked this call's prototype; verify it doesn't modify errno.
7137   if (!I.onlyReadsMemory())
7138     return false;
7139 
7140   SDValue Tmp0 = getValue(I.getArgOperand(0));
7141   SDValue Tmp1 = getValue(I.getArgOperand(1));
7142   EVT VT = Tmp0.getValueType();
7143   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7144   return true;
7145 }
7146 
7147 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7148   // Handle inline assembly differently.
7149   if (isa<InlineAsm>(I.getCalledValue())) {
7150     visitInlineAsm(&I);
7151     return;
7152   }
7153 
7154   const char *RenameFn = nullptr;
7155   if (Function *F = I.getCalledFunction()) {
7156     if (F->isDeclaration()) {
7157       // Is this an LLVM intrinsic or a target-specific intrinsic?
7158       unsigned IID = F->getIntrinsicID();
7159       if (!IID)
7160         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7161           IID = II->getIntrinsicID(F);
7162 
7163       if (IID) {
7164         RenameFn = visitIntrinsicCall(I, IID);
7165         if (!RenameFn)
7166           return;
7167       }
7168     }
7169 
7170     // Check for well-known libc/libm calls.  If the function is internal, it
7171     // can't be a library call.  Don't do the check if marked as nobuiltin for
7172     // some reason or the call site requires strict floating point semantics.
7173     LibFunc Func;
7174     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7175         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7176         LibInfo->hasOptimizedCodeGen(Func)) {
7177       switch (Func) {
7178       default: break;
7179       case LibFunc_copysign:
7180       case LibFunc_copysignf:
7181       case LibFunc_copysignl:
7182         // We already checked this call's prototype; verify it doesn't modify
7183         // errno.
7184         if (I.onlyReadsMemory()) {
7185           SDValue LHS = getValue(I.getArgOperand(0));
7186           SDValue RHS = getValue(I.getArgOperand(1));
7187           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7188                                    LHS.getValueType(), LHS, RHS));
7189           return;
7190         }
7191         break;
7192       case LibFunc_fabs:
7193       case LibFunc_fabsf:
7194       case LibFunc_fabsl:
7195         if (visitUnaryFloatCall(I, ISD::FABS))
7196           return;
7197         break;
7198       case LibFunc_fmin:
7199       case LibFunc_fminf:
7200       case LibFunc_fminl:
7201         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7202           return;
7203         break;
7204       case LibFunc_fmax:
7205       case LibFunc_fmaxf:
7206       case LibFunc_fmaxl:
7207         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7208           return;
7209         break;
7210       case LibFunc_sin:
7211       case LibFunc_sinf:
7212       case LibFunc_sinl:
7213         if (visitUnaryFloatCall(I, ISD::FSIN))
7214           return;
7215         break;
7216       case LibFunc_cos:
7217       case LibFunc_cosf:
7218       case LibFunc_cosl:
7219         if (visitUnaryFloatCall(I, ISD::FCOS))
7220           return;
7221         break;
7222       case LibFunc_sqrt:
7223       case LibFunc_sqrtf:
7224       case LibFunc_sqrtl:
7225       case LibFunc_sqrt_finite:
7226       case LibFunc_sqrtf_finite:
7227       case LibFunc_sqrtl_finite:
7228         if (visitUnaryFloatCall(I, ISD::FSQRT))
7229           return;
7230         break;
7231       case LibFunc_floor:
7232       case LibFunc_floorf:
7233       case LibFunc_floorl:
7234         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7235           return;
7236         break;
7237       case LibFunc_nearbyint:
7238       case LibFunc_nearbyintf:
7239       case LibFunc_nearbyintl:
7240         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7241           return;
7242         break;
7243       case LibFunc_ceil:
7244       case LibFunc_ceilf:
7245       case LibFunc_ceill:
7246         if (visitUnaryFloatCall(I, ISD::FCEIL))
7247           return;
7248         break;
7249       case LibFunc_rint:
7250       case LibFunc_rintf:
7251       case LibFunc_rintl:
7252         if (visitUnaryFloatCall(I, ISD::FRINT))
7253           return;
7254         break;
7255       case LibFunc_round:
7256       case LibFunc_roundf:
7257       case LibFunc_roundl:
7258         if (visitUnaryFloatCall(I, ISD::FROUND))
7259           return;
7260         break;
7261       case LibFunc_trunc:
7262       case LibFunc_truncf:
7263       case LibFunc_truncl:
7264         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7265           return;
7266         break;
7267       case LibFunc_log2:
7268       case LibFunc_log2f:
7269       case LibFunc_log2l:
7270         if (visitUnaryFloatCall(I, ISD::FLOG2))
7271           return;
7272         break;
7273       case LibFunc_exp2:
7274       case LibFunc_exp2f:
7275       case LibFunc_exp2l:
7276         if (visitUnaryFloatCall(I, ISD::FEXP2))
7277           return;
7278         break;
7279       case LibFunc_memcmp:
7280         if (visitMemCmpCall(I))
7281           return;
7282         break;
7283       case LibFunc_mempcpy:
7284         if (visitMemPCpyCall(I))
7285           return;
7286         break;
7287       case LibFunc_memchr:
7288         if (visitMemChrCall(I))
7289           return;
7290         break;
7291       case LibFunc_strcpy:
7292         if (visitStrCpyCall(I, false))
7293           return;
7294         break;
7295       case LibFunc_stpcpy:
7296         if (visitStrCpyCall(I, true))
7297           return;
7298         break;
7299       case LibFunc_strcmp:
7300         if (visitStrCmpCall(I))
7301           return;
7302         break;
7303       case LibFunc_strlen:
7304         if (visitStrLenCall(I))
7305           return;
7306         break;
7307       case LibFunc_strnlen:
7308         if (visitStrNLenCall(I))
7309           return;
7310         break;
7311       }
7312     }
7313   }
7314 
7315   SDValue Callee;
7316   if (!RenameFn)
7317     Callee = getValue(I.getCalledValue());
7318   else
7319     Callee = DAG.getExternalSymbol(
7320         RenameFn,
7321         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7322 
7323   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7324   // have to do anything here to lower funclet bundles.
7325   assert(!I.hasOperandBundlesOtherThan(
7326              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7327          "Cannot lower calls with arbitrary operand bundles!");
7328 
7329   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7330     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7331   else
7332     // Check if we can potentially perform a tail call. More detailed checking
7333     // is be done within LowerCallTo, after more information about the call is
7334     // known.
7335     LowerCallTo(&I, Callee, I.isTailCall());
7336 }
7337 
7338 namespace {
7339 
7340 /// AsmOperandInfo - This contains information for each constraint that we are
7341 /// lowering.
7342 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7343 public:
7344   /// CallOperand - If this is the result output operand or a clobber
7345   /// this is null, otherwise it is the incoming operand to the CallInst.
7346   /// This gets modified as the asm is processed.
7347   SDValue CallOperand;
7348 
7349   /// AssignedRegs - If this is a register or register class operand, this
7350   /// contains the set of register corresponding to the operand.
7351   RegsForValue AssignedRegs;
7352 
7353   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7354     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7355   }
7356 
7357   /// Whether or not this operand accesses memory
7358   bool hasMemory(const TargetLowering &TLI) const {
7359     // Indirect operand accesses access memory.
7360     if (isIndirect)
7361       return true;
7362 
7363     for (const auto &Code : Codes)
7364       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7365         return true;
7366 
7367     return false;
7368   }
7369 
7370   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7371   /// corresponds to.  If there is no Value* for this operand, it returns
7372   /// MVT::Other.
7373   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7374                            const DataLayout &DL) const {
7375     if (!CallOperandVal) return MVT::Other;
7376 
7377     if (isa<BasicBlock>(CallOperandVal))
7378       return TLI.getPointerTy(DL);
7379 
7380     llvm::Type *OpTy = CallOperandVal->getType();
7381 
7382     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7383     // If this is an indirect operand, the operand is a pointer to the
7384     // accessed type.
7385     if (isIndirect) {
7386       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7387       if (!PtrTy)
7388         report_fatal_error("Indirect operand for inline asm not a pointer!");
7389       OpTy = PtrTy->getElementType();
7390     }
7391 
7392     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7393     if (StructType *STy = dyn_cast<StructType>(OpTy))
7394       if (STy->getNumElements() == 1)
7395         OpTy = STy->getElementType(0);
7396 
7397     // If OpTy is not a single value, it may be a struct/union that we
7398     // can tile with integers.
7399     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7400       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7401       switch (BitSize) {
7402       default: break;
7403       case 1:
7404       case 8:
7405       case 16:
7406       case 32:
7407       case 64:
7408       case 128:
7409         OpTy = IntegerType::get(Context, BitSize);
7410         break;
7411       }
7412     }
7413 
7414     return TLI.getValueType(DL, OpTy, true);
7415   }
7416 };
7417 
7418 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7419 
7420 } // end anonymous namespace
7421 
7422 /// Make sure that the output operand \p OpInfo and its corresponding input
7423 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7424 /// out).
7425 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7426                                SDISelAsmOperandInfo &MatchingOpInfo,
7427                                SelectionDAG &DAG) {
7428   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7429     return;
7430 
7431   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7432   const auto &TLI = DAG.getTargetLoweringInfo();
7433 
7434   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7435       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7436                                        OpInfo.ConstraintVT);
7437   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7438       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7439                                        MatchingOpInfo.ConstraintVT);
7440   if ((OpInfo.ConstraintVT.isInteger() !=
7441        MatchingOpInfo.ConstraintVT.isInteger()) ||
7442       (MatchRC.second != InputRC.second)) {
7443     // FIXME: error out in a more elegant fashion
7444     report_fatal_error("Unsupported asm: input constraint"
7445                        " with a matching output constraint of"
7446                        " incompatible type!");
7447   }
7448   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7449 }
7450 
7451 /// Get a direct memory input to behave well as an indirect operand.
7452 /// This may introduce stores, hence the need for a \p Chain.
7453 /// \return The (possibly updated) chain.
7454 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7455                                         SDISelAsmOperandInfo &OpInfo,
7456                                         SelectionDAG &DAG) {
7457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7458 
7459   // If we don't have an indirect input, put it in the constpool if we can,
7460   // otherwise spill it to a stack slot.
7461   // TODO: This isn't quite right. We need to handle these according to
7462   // the addressing mode that the constraint wants. Also, this may take
7463   // an additional register for the computation and we don't want that
7464   // either.
7465 
7466   // If the operand is a float, integer, or vector constant, spill to a
7467   // constant pool entry to get its address.
7468   const Value *OpVal = OpInfo.CallOperandVal;
7469   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7470       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7471     OpInfo.CallOperand = DAG.getConstantPool(
7472         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7473     return Chain;
7474   }
7475 
7476   // Otherwise, create a stack slot and emit a store to it before the asm.
7477   Type *Ty = OpVal->getType();
7478   auto &DL = DAG.getDataLayout();
7479   uint64_t TySize = DL.getTypeAllocSize(Ty);
7480   unsigned Align = DL.getPrefTypeAlignment(Ty);
7481   MachineFunction &MF = DAG.getMachineFunction();
7482   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7483   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7484   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7485                        MachinePointerInfo::getFixedStack(MF, SSFI));
7486   OpInfo.CallOperand = StackSlot;
7487 
7488   return Chain;
7489 }
7490 
7491 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7492 /// specified operand.  We prefer to assign virtual registers, to allow the
7493 /// register allocator to handle the assignment process.  However, if the asm
7494 /// uses features that we can't model on machineinstrs, we have SDISel do the
7495 /// allocation.  This produces generally horrible, but correct, code.
7496 ///
7497 ///   OpInfo describes the operand
7498 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7499 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7500                                  SDISelAsmOperandInfo &OpInfo,
7501                                  SDISelAsmOperandInfo &RefOpInfo) {
7502   LLVMContext &Context = *DAG.getContext();
7503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7504 
7505   MachineFunction &MF = DAG.getMachineFunction();
7506   SmallVector<unsigned, 4> Regs;
7507   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7508 
7509   // No work to do for memory operations.
7510   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7511     return;
7512 
7513   // If this is a constraint for a single physreg, or a constraint for a
7514   // register class, find it.
7515   unsigned AssignedReg;
7516   const TargetRegisterClass *RC;
7517   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7518       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7519   // RC is unset only on failure. Return immediately.
7520   if (!RC)
7521     return;
7522 
7523   // Get the actual register value type.  This is important, because the user
7524   // may have asked for (e.g.) the AX register in i32 type.  We need to
7525   // remember that AX is actually i16 to get the right extension.
7526   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7527 
7528   if (OpInfo.ConstraintVT != MVT::Other) {
7529     // If this is an FP operand in an integer register (or visa versa), or more
7530     // generally if the operand value disagrees with the register class we plan
7531     // to stick it in, fix the operand type.
7532     //
7533     // If this is an input value, the bitcast to the new type is done now.
7534     // Bitcast for output value is done at the end of visitInlineAsm().
7535     if ((OpInfo.Type == InlineAsm::isOutput ||
7536          OpInfo.Type == InlineAsm::isInput) &&
7537         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7538       // Try to convert to the first EVT that the reg class contains.  If the
7539       // types are identical size, use a bitcast to convert (e.g. two differing
7540       // vector types).  Note: output bitcast is done at the end of
7541       // visitInlineAsm().
7542       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7543         // Exclude indirect inputs while they are unsupported because the code
7544         // to perform the load is missing and thus OpInfo.CallOperand still
7545         // refers to the input address rather than the pointed-to value.
7546         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7547           OpInfo.CallOperand =
7548               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7549         OpInfo.ConstraintVT = RegVT;
7550         // If the operand is an FP value and we want it in integer registers,
7551         // use the corresponding integer type. This turns an f64 value into
7552         // i64, which can be passed with two i32 values on a 32-bit machine.
7553       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7554         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7555         if (OpInfo.Type == InlineAsm::isInput)
7556           OpInfo.CallOperand =
7557               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7558         OpInfo.ConstraintVT = VT;
7559       }
7560     }
7561   }
7562 
7563   // No need to allocate a matching input constraint since the constraint it's
7564   // matching to has already been allocated.
7565   if (OpInfo.isMatchingInputConstraint())
7566     return;
7567 
7568   EVT ValueVT = OpInfo.ConstraintVT;
7569   if (OpInfo.ConstraintVT == MVT::Other)
7570     ValueVT = RegVT;
7571 
7572   // Initialize NumRegs.
7573   unsigned NumRegs = 1;
7574   if (OpInfo.ConstraintVT != MVT::Other)
7575     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7576 
7577   // If this is a constraint for a specific physical register, like {r17},
7578   // assign it now.
7579 
7580   // If this associated to a specific register, initialize iterator to correct
7581   // place. If virtual, make sure we have enough registers
7582 
7583   // Initialize iterator if necessary
7584   TargetRegisterClass::iterator I = RC->begin();
7585   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7586 
7587   // Do not check for single registers.
7588   if (AssignedReg) {
7589       for (; *I != AssignedReg; ++I)
7590         assert(I != RC->end() && "AssignedReg should be member of RC");
7591   }
7592 
7593   for (; NumRegs; --NumRegs, ++I) {
7594     assert(I != RC->end() && "Ran out of registers to allocate!");
7595     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7596     Regs.push_back(R);
7597   }
7598 
7599   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7600 }
7601 
7602 static unsigned
7603 findMatchingInlineAsmOperand(unsigned OperandNo,
7604                              const std::vector<SDValue> &AsmNodeOperands) {
7605   // Scan until we find the definition we already emitted of this operand.
7606   unsigned CurOp = InlineAsm::Op_FirstOperand;
7607   for (; OperandNo; --OperandNo) {
7608     // Advance to the next operand.
7609     unsigned OpFlag =
7610         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7611     assert((InlineAsm::isRegDefKind(OpFlag) ||
7612             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7613             InlineAsm::isMemKind(OpFlag)) &&
7614            "Skipped past definitions?");
7615     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7616   }
7617   return CurOp;
7618 }
7619 
7620 namespace {
7621 
7622 class ExtraFlags {
7623   unsigned Flags = 0;
7624 
7625 public:
7626   explicit ExtraFlags(ImmutableCallSite CS) {
7627     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7628     if (IA->hasSideEffects())
7629       Flags |= InlineAsm::Extra_HasSideEffects;
7630     if (IA->isAlignStack())
7631       Flags |= InlineAsm::Extra_IsAlignStack;
7632     if (CS.isConvergent())
7633       Flags |= InlineAsm::Extra_IsConvergent;
7634     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7635   }
7636 
7637   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7638     // Ideally, we would only check against memory constraints.  However, the
7639     // meaning of an Other constraint can be target-specific and we can't easily
7640     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7641     // for Other constraints as well.
7642     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7643         OpInfo.ConstraintType == TargetLowering::C_Other) {
7644       if (OpInfo.Type == InlineAsm::isInput)
7645         Flags |= InlineAsm::Extra_MayLoad;
7646       else if (OpInfo.Type == InlineAsm::isOutput)
7647         Flags |= InlineAsm::Extra_MayStore;
7648       else if (OpInfo.Type == InlineAsm::isClobber)
7649         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7650     }
7651   }
7652 
7653   unsigned get() const { return Flags; }
7654 };
7655 
7656 } // end anonymous namespace
7657 
7658 /// visitInlineAsm - Handle a call to an InlineAsm object.
7659 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7660   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7661 
7662   /// ConstraintOperands - Information about all of the constraints.
7663   SDISelAsmOperandInfoVector ConstraintOperands;
7664 
7665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7666   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7667       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7668 
7669   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7670   // AsmDialect, MayLoad, MayStore).
7671   bool HasSideEffect = IA->hasSideEffects();
7672   ExtraFlags ExtraInfo(CS);
7673 
7674   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7675   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7676   for (auto &T : TargetConstraints) {
7677     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7678     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7679 
7680     // Compute the value type for each operand.
7681     if (OpInfo.Type == InlineAsm::isInput ||
7682         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7683       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7684 
7685       // Process the call argument. BasicBlocks are labels, currently appearing
7686       // only in asm's.
7687       const Instruction *I = CS.getInstruction();
7688       if (isa<CallBrInst>(I) &&
7689           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7690                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7691         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7692         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7693         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7694       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7695         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7696       } else {
7697         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7698       }
7699 
7700       OpInfo.ConstraintVT =
7701           OpInfo
7702               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7703               .getSimpleVT();
7704     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7705       // The return value of the call is this value.  As such, there is no
7706       // corresponding argument.
7707       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7708       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7709         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7710             DAG.getDataLayout(), STy->getElementType(ResNo));
7711       } else {
7712         assert(ResNo == 0 && "Asm only has one result!");
7713         OpInfo.ConstraintVT =
7714             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7715       }
7716       ++ResNo;
7717     } else {
7718       OpInfo.ConstraintVT = MVT::Other;
7719     }
7720 
7721     if (!HasSideEffect)
7722       HasSideEffect = OpInfo.hasMemory(TLI);
7723 
7724     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7725     // FIXME: Could we compute this on OpInfo rather than T?
7726 
7727     // Compute the constraint code and ConstraintType to use.
7728     TLI.ComputeConstraintToUse(T, SDValue());
7729 
7730     ExtraInfo.update(T);
7731   }
7732 
7733   // We won't need to flush pending loads if this asm doesn't touch
7734   // memory and is nonvolatile.
7735   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7736 
7737   // Second pass over the constraints: compute which constraint option to use.
7738   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7739     // If this is an output operand with a matching input operand, look up the
7740     // matching input. If their types mismatch, e.g. one is an integer, the
7741     // other is floating point, or their sizes are different, flag it as an
7742     // error.
7743     if (OpInfo.hasMatchingInput()) {
7744       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7745       patchMatchingInput(OpInfo, Input, DAG);
7746     }
7747 
7748     // Compute the constraint code and ConstraintType to use.
7749     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7750 
7751     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7752         OpInfo.Type == InlineAsm::isClobber)
7753       continue;
7754 
7755     // If this is a memory input, and if the operand is not indirect, do what we
7756     // need to provide an address for the memory input.
7757     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7758         !OpInfo.isIndirect) {
7759       assert((OpInfo.isMultipleAlternative ||
7760               (OpInfo.Type == InlineAsm::isInput)) &&
7761              "Can only indirectify direct input operands!");
7762 
7763       // Memory operands really want the address of the value.
7764       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7765 
7766       // There is no longer a Value* corresponding to this operand.
7767       OpInfo.CallOperandVal = nullptr;
7768 
7769       // It is now an indirect operand.
7770       OpInfo.isIndirect = true;
7771     }
7772 
7773   }
7774 
7775   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7776   std::vector<SDValue> AsmNodeOperands;
7777   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7778   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7779       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7780 
7781   // If we have a !srcloc metadata node associated with it, we want to attach
7782   // this to the ultimately generated inline asm machineinstr.  To do this, we
7783   // pass in the third operand as this (potentially null) inline asm MDNode.
7784   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7785   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7786 
7787   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7788   // bits as operand 3.
7789   AsmNodeOperands.push_back(DAG.getTargetConstant(
7790       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7791 
7792   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7793   // this, assign virtual and physical registers for inputs and otput.
7794   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7795     // Assign Registers.
7796     SDISelAsmOperandInfo &RefOpInfo =
7797         OpInfo.isMatchingInputConstraint()
7798             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7799             : OpInfo;
7800     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7801 
7802     switch (OpInfo.Type) {
7803     case InlineAsm::isOutput:
7804       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7805           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7806            OpInfo.isIndirect)) {
7807         unsigned ConstraintID =
7808             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7809         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7810                "Failed to convert memory constraint code to constraint id.");
7811 
7812         // Add information to the INLINEASM node to know about this output.
7813         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7814         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7815         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7816                                                         MVT::i32));
7817         AsmNodeOperands.push_back(OpInfo.CallOperand);
7818         break;
7819       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7820                   !OpInfo.isIndirect) ||
7821                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7822                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7823         // Otherwise, this outputs to a register (directly for C_Register /
7824         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7825         // register that we can use.
7826         if (OpInfo.AssignedRegs.Regs.empty()) {
7827           emitInlineAsmError(
7828               CS, "couldn't allocate output register for constraint '" +
7829                       Twine(OpInfo.ConstraintCode) + "'");
7830           return;
7831         }
7832 
7833         // Add information to the INLINEASM node to know that this register is
7834         // set.
7835         OpInfo.AssignedRegs.AddInlineAsmOperands(
7836             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7837                                   : InlineAsm::Kind_RegDef,
7838             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7839       }
7840       break;
7841 
7842     case InlineAsm::isInput: {
7843       SDValue InOperandVal = OpInfo.CallOperand;
7844 
7845       if (OpInfo.isMatchingInputConstraint()) {
7846         // If this is required to match an output register we have already set,
7847         // just use its register.
7848         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7849                                                   AsmNodeOperands);
7850         unsigned OpFlag =
7851           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7852         if (InlineAsm::isRegDefKind(OpFlag) ||
7853             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7854           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7855           if (OpInfo.isIndirect) {
7856             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7857             emitInlineAsmError(CS, "inline asm not supported yet:"
7858                                    " don't know how to handle tied "
7859                                    "indirect register inputs");
7860             return;
7861           }
7862 
7863           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7864           SmallVector<unsigned, 4> Regs;
7865 
7866           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7867             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7868             MachineRegisterInfo &RegInfo =
7869                 DAG.getMachineFunction().getRegInfo();
7870             for (unsigned i = 0; i != NumRegs; ++i)
7871               Regs.push_back(RegInfo.createVirtualRegister(RC));
7872           } else {
7873             emitInlineAsmError(CS, "inline asm error: This value type register "
7874                                    "class is not natively supported!");
7875             return;
7876           }
7877 
7878           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7879 
7880           SDLoc dl = getCurSDLoc();
7881           // Use the produced MatchedRegs object to
7882           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7883                                     CS.getInstruction());
7884           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7885                                            true, OpInfo.getMatchedOperand(), dl,
7886                                            DAG, AsmNodeOperands);
7887           break;
7888         }
7889 
7890         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7891         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7892                "Unexpected number of operands");
7893         // Add information to the INLINEASM node to know about this input.
7894         // See InlineAsm.h isUseOperandTiedToDef.
7895         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7896         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7897                                                     OpInfo.getMatchedOperand());
7898         AsmNodeOperands.push_back(DAG.getTargetConstant(
7899             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7900         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7901         break;
7902       }
7903 
7904       // Treat indirect 'X' constraint as memory.
7905       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7906           OpInfo.isIndirect)
7907         OpInfo.ConstraintType = TargetLowering::C_Memory;
7908 
7909       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7910         std::vector<SDValue> Ops;
7911         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7912                                           Ops, DAG);
7913         if (Ops.empty()) {
7914           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7915                                      Twine(OpInfo.ConstraintCode) + "'");
7916           return;
7917         }
7918 
7919         // Add information to the INLINEASM node to know about this input.
7920         unsigned ResOpType =
7921           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7922         AsmNodeOperands.push_back(DAG.getTargetConstant(
7923             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7924         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7925         break;
7926       }
7927 
7928       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7929         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7930         assert(InOperandVal.getValueType() ==
7931                    TLI.getPointerTy(DAG.getDataLayout()) &&
7932                "Memory operands expect pointer values");
7933 
7934         unsigned ConstraintID =
7935             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7936         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7937                "Failed to convert memory constraint code to constraint id.");
7938 
7939         // Add information to the INLINEASM node to know about this input.
7940         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7941         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7942         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7943                                                         getCurSDLoc(),
7944                                                         MVT::i32));
7945         AsmNodeOperands.push_back(InOperandVal);
7946         break;
7947       }
7948 
7949       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7950               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7951              "Unknown constraint type!");
7952 
7953       // TODO: Support this.
7954       if (OpInfo.isIndirect) {
7955         emitInlineAsmError(
7956             CS, "Don't know how to handle indirect register inputs yet "
7957                 "for constraint '" +
7958                     Twine(OpInfo.ConstraintCode) + "'");
7959         return;
7960       }
7961 
7962       // Copy the input into the appropriate registers.
7963       if (OpInfo.AssignedRegs.Regs.empty()) {
7964         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7965                                    Twine(OpInfo.ConstraintCode) + "'");
7966         return;
7967       }
7968 
7969       SDLoc dl = getCurSDLoc();
7970 
7971       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7972                                         Chain, &Flag, CS.getInstruction());
7973 
7974       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7975                                                dl, DAG, AsmNodeOperands);
7976       break;
7977     }
7978     case InlineAsm::isClobber:
7979       // Add the clobbered value to the operand list, so that the register
7980       // allocator is aware that the physreg got clobbered.
7981       if (!OpInfo.AssignedRegs.Regs.empty())
7982         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7983                                                  false, 0, getCurSDLoc(), DAG,
7984                                                  AsmNodeOperands);
7985       break;
7986     }
7987   }
7988 
7989   // Finish up input operands.  Set the input chain and add the flag last.
7990   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7991   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7992 
7993   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM;
7994   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
7995                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7996   Flag = Chain.getValue(1);
7997 
7998   // Do additional work to generate outputs.
7999 
8000   SmallVector<EVT, 1> ResultVTs;
8001   SmallVector<SDValue, 1> ResultValues;
8002   SmallVector<SDValue, 8> OutChains;
8003 
8004   llvm::Type *CSResultType = CS.getType();
8005   ArrayRef<Type *> ResultTypes;
8006   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8007     ResultTypes = StructResult->elements();
8008   else if (!CSResultType->isVoidTy())
8009     ResultTypes = makeArrayRef(CSResultType);
8010 
8011   auto CurResultType = ResultTypes.begin();
8012   auto handleRegAssign = [&](SDValue V) {
8013     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8014     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8015     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8016     ++CurResultType;
8017     // If the type of the inline asm call site return value is different but has
8018     // same size as the type of the asm output bitcast it.  One example of this
8019     // is for vectors with different width / number of elements.  This can
8020     // happen for register classes that can contain multiple different value
8021     // types.  The preg or vreg allocated may not have the same VT as was
8022     // expected.
8023     //
8024     // This can also happen for a return value that disagrees with the register
8025     // class it is put in, eg. a double in a general-purpose register on a
8026     // 32-bit machine.
8027     if (ResultVT != V.getValueType() &&
8028         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8029       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8030     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8031              V.getValueType().isInteger()) {
8032       // If a result value was tied to an input value, the computed result
8033       // may have a wider width than the expected result.  Extract the
8034       // relevant portion.
8035       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8036     }
8037     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8038     ResultVTs.push_back(ResultVT);
8039     ResultValues.push_back(V);
8040   };
8041 
8042   // Deal with output operands.
8043   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8044     if (OpInfo.Type == InlineAsm::isOutput) {
8045       SDValue Val;
8046       // Skip trivial output operands.
8047       if (OpInfo.AssignedRegs.Regs.empty())
8048         continue;
8049 
8050       switch (OpInfo.ConstraintType) {
8051       case TargetLowering::C_Register:
8052       case TargetLowering::C_RegisterClass:
8053         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8054             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8055         break;
8056       case TargetLowering::C_Other:
8057         Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(),
8058                                               OpInfo, DAG);
8059         break;
8060       case TargetLowering::C_Memory:
8061         break; // Already handled.
8062       case TargetLowering::C_Unknown:
8063         assert(false && "Unexpected unknown constraint");
8064       }
8065 
8066       // Indirect output manifest as stores. Record output chains.
8067       if (OpInfo.isIndirect) {
8068 
8069         const Value *Ptr = OpInfo.CallOperandVal;
8070         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8071         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8072                                      MachinePointerInfo(Ptr));
8073         OutChains.push_back(Store);
8074       } else {
8075         // generate CopyFromRegs to associated registers.
8076         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8077         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8078           for (const SDValue &V : Val->op_values())
8079             handleRegAssign(V);
8080         } else
8081           handleRegAssign(Val);
8082       }
8083     }
8084   }
8085 
8086   // Set results.
8087   if (!ResultValues.empty()) {
8088     assert(CurResultType == ResultTypes.end() &&
8089            "Mismatch in number of ResultTypes");
8090     assert(ResultValues.size() == ResultTypes.size() &&
8091            "Mismatch in number of output operands in asm result");
8092 
8093     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8094                             DAG.getVTList(ResultVTs), ResultValues);
8095     setValue(CS.getInstruction(), V);
8096   }
8097 
8098   // Collect store chains.
8099   if (!OutChains.empty())
8100     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8101 
8102   // Only Update Root if inline assembly has a memory effect.
8103   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8104     DAG.setRoot(Chain);
8105 }
8106 
8107 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8108                                              const Twine &Message) {
8109   LLVMContext &Ctx = *DAG.getContext();
8110   Ctx.emitError(CS.getInstruction(), Message);
8111 
8112   // Make sure we leave the DAG in a valid state
8113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8114   SmallVector<EVT, 1> ValueVTs;
8115   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8116 
8117   if (ValueVTs.empty())
8118     return;
8119 
8120   SmallVector<SDValue, 1> Ops;
8121   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8122     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8123 
8124   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8125 }
8126 
8127 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8128   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8129                           MVT::Other, getRoot(),
8130                           getValue(I.getArgOperand(0)),
8131                           DAG.getSrcValue(I.getArgOperand(0))));
8132 }
8133 
8134 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8136   const DataLayout &DL = DAG.getDataLayout();
8137   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8138                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8139                            DAG.getSrcValue(I.getOperand(0)),
8140                            DL.getABITypeAlignment(I.getType()));
8141   setValue(&I, V);
8142   DAG.setRoot(V.getValue(1));
8143 }
8144 
8145 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8146   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8147                           MVT::Other, getRoot(),
8148                           getValue(I.getArgOperand(0)),
8149                           DAG.getSrcValue(I.getArgOperand(0))));
8150 }
8151 
8152 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8153   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8154                           MVT::Other, getRoot(),
8155                           getValue(I.getArgOperand(0)),
8156                           getValue(I.getArgOperand(1)),
8157                           DAG.getSrcValue(I.getArgOperand(0)),
8158                           DAG.getSrcValue(I.getArgOperand(1))));
8159 }
8160 
8161 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8162                                                     const Instruction &I,
8163                                                     SDValue Op) {
8164   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8165   if (!Range)
8166     return Op;
8167 
8168   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8169   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8170     return Op;
8171 
8172   APInt Lo = CR.getUnsignedMin();
8173   if (!Lo.isMinValue())
8174     return Op;
8175 
8176   APInt Hi = CR.getUnsignedMax();
8177   unsigned Bits = std::max(Hi.getActiveBits(),
8178                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8179 
8180   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8181 
8182   SDLoc SL = getCurSDLoc();
8183 
8184   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8185                              DAG.getValueType(SmallVT));
8186   unsigned NumVals = Op.getNode()->getNumValues();
8187   if (NumVals == 1)
8188     return ZExt;
8189 
8190   SmallVector<SDValue, 4> Ops;
8191 
8192   Ops.push_back(ZExt);
8193   for (unsigned I = 1; I != NumVals; ++I)
8194     Ops.push_back(Op.getValue(I));
8195 
8196   return DAG.getMergeValues(Ops, SL);
8197 }
8198 
8199 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8200 /// the call being lowered.
8201 ///
8202 /// This is a helper for lowering intrinsics that follow a target calling
8203 /// convention or require stack pointer adjustment. Only a subset of the
8204 /// intrinsic's operands need to participate in the calling convention.
8205 void SelectionDAGBuilder::populateCallLoweringInfo(
8206     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8207     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8208     bool IsPatchPoint) {
8209   TargetLowering::ArgListTy Args;
8210   Args.reserve(NumArgs);
8211 
8212   // Populate the argument list.
8213   // Attributes for args start at offset 1, after the return attribute.
8214   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8215        ArgI != ArgE; ++ArgI) {
8216     const Value *V = Call->getOperand(ArgI);
8217 
8218     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8219 
8220     TargetLowering::ArgListEntry Entry;
8221     Entry.Node = getValue(V);
8222     Entry.Ty = V->getType();
8223     Entry.setAttributes(Call, ArgI);
8224     Args.push_back(Entry);
8225   }
8226 
8227   CLI.setDebugLoc(getCurSDLoc())
8228       .setChain(getRoot())
8229       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8230       .setDiscardResult(Call->use_empty())
8231       .setIsPatchPoint(IsPatchPoint);
8232 }
8233 
8234 /// Add a stack map intrinsic call's live variable operands to a stackmap
8235 /// or patchpoint target node's operand list.
8236 ///
8237 /// Constants are converted to TargetConstants purely as an optimization to
8238 /// avoid constant materialization and register allocation.
8239 ///
8240 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8241 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8242 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8243 /// address materialization and register allocation, but may also be required
8244 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8245 /// alloca in the entry block, then the runtime may assume that the alloca's
8246 /// StackMap location can be read immediately after compilation and that the
8247 /// location is valid at any point during execution (this is similar to the
8248 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8249 /// only available in a register, then the runtime would need to trap when
8250 /// execution reaches the StackMap in order to read the alloca's location.
8251 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8252                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8253                                 SelectionDAGBuilder &Builder) {
8254   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8255     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8256     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8257       Ops.push_back(
8258         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8259       Ops.push_back(
8260         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8261     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8262       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8263       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8264           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8265     } else
8266       Ops.push_back(OpVal);
8267   }
8268 }
8269 
8270 /// Lower llvm.experimental.stackmap directly to its target opcode.
8271 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8272   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8273   //                                  [live variables...])
8274 
8275   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8276 
8277   SDValue Chain, InFlag, Callee, NullPtr;
8278   SmallVector<SDValue, 32> Ops;
8279 
8280   SDLoc DL = getCurSDLoc();
8281   Callee = getValue(CI.getCalledValue());
8282   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8283 
8284   // The stackmap intrinsic only records the live variables (the arguemnts
8285   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8286   // intrinsic, this won't be lowered to a function call. This means we don't
8287   // have to worry about calling conventions and target specific lowering code.
8288   // Instead we perform the call lowering right here.
8289   //
8290   // chain, flag = CALLSEQ_START(chain, 0, 0)
8291   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8292   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8293   //
8294   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8295   InFlag = Chain.getValue(1);
8296 
8297   // Add the <id> and <numBytes> constants.
8298   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8299   Ops.push_back(DAG.getTargetConstant(
8300                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8301   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8302   Ops.push_back(DAG.getTargetConstant(
8303                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8304                   MVT::i32));
8305 
8306   // Push live variables for the stack map.
8307   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8308 
8309   // We are not pushing any register mask info here on the operands list,
8310   // because the stackmap doesn't clobber anything.
8311 
8312   // Push the chain and the glue flag.
8313   Ops.push_back(Chain);
8314   Ops.push_back(InFlag);
8315 
8316   // Create the STACKMAP node.
8317   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8318   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8319   Chain = SDValue(SM, 0);
8320   InFlag = Chain.getValue(1);
8321 
8322   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8323 
8324   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8325 
8326   // Set the root to the target-lowered call chain.
8327   DAG.setRoot(Chain);
8328 
8329   // Inform the Frame Information that we have a stackmap in this function.
8330   FuncInfo.MF->getFrameInfo().setHasStackMap();
8331 }
8332 
8333 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8334 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8335                                           const BasicBlock *EHPadBB) {
8336   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8337   //                                                 i32 <numBytes>,
8338   //                                                 i8* <target>,
8339   //                                                 i32 <numArgs>,
8340   //                                                 [Args...],
8341   //                                                 [live variables...])
8342 
8343   CallingConv::ID CC = CS.getCallingConv();
8344   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8345   bool HasDef = !CS->getType()->isVoidTy();
8346   SDLoc dl = getCurSDLoc();
8347   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8348 
8349   // Handle immediate and symbolic callees.
8350   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8351     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8352                                    /*isTarget=*/true);
8353   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8354     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8355                                          SDLoc(SymbolicCallee),
8356                                          SymbolicCallee->getValueType(0));
8357 
8358   // Get the real number of arguments participating in the call <numArgs>
8359   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8360   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8361 
8362   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8363   // Intrinsics include all meta-operands up to but not including CC.
8364   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8365   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8366          "Not enough arguments provided to the patchpoint intrinsic");
8367 
8368   // For AnyRegCC the arguments are lowered later on manually.
8369   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8370   Type *ReturnTy =
8371     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8372 
8373   TargetLowering::CallLoweringInfo CLI(DAG);
8374   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8375                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8376   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8377 
8378   SDNode *CallEnd = Result.second.getNode();
8379   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8380     CallEnd = CallEnd->getOperand(0).getNode();
8381 
8382   /// Get a call instruction from the call sequence chain.
8383   /// Tail calls are not allowed.
8384   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8385          "Expected a callseq node.");
8386   SDNode *Call = CallEnd->getOperand(0).getNode();
8387   bool HasGlue = Call->getGluedNode();
8388 
8389   // Replace the target specific call node with the patchable intrinsic.
8390   SmallVector<SDValue, 8> Ops;
8391 
8392   // Add the <id> and <numBytes> constants.
8393   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8394   Ops.push_back(DAG.getTargetConstant(
8395                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8396   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8397   Ops.push_back(DAG.getTargetConstant(
8398                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8399                   MVT::i32));
8400 
8401   // Add the callee.
8402   Ops.push_back(Callee);
8403 
8404   // Adjust <numArgs> to account for any arguments that have been passed on the
8405   // stack instead.
8406   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8407   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8408   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8409   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8410 
8411   // Add the calling convention
8412   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8413 
8414   // Add the arguments we omitted previously. The register allocator should
8415   // place these in any free register.
8416   if (IsAnyRegCC)
8417     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8418       Ops.push_back(getValue(CS.getArgument(i)));
8419 
8420   // Push the arguments from the call instruction up to the register mask.
8421   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8422   Ops.append(Call->op_begin() + 2, e);
8423 
8424   // Push live variables for the stack map.
8425   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8426 
8427   // Push the register mask info.
8428   if (HasGlue)
8429     Ops.push_back(*(Call->op_end()-2));
8430   else
8431     Ops.push_back(*(Call->op_end()-1));
8432 
8433   // Push the chain (this is originally the first operand of the call, but
8434   // becomes now the last or second to last operand).
8435   Ops.push_back(*(Call->op_begin()));
8436 
8437   // Push the glue flag (last operand).
8438   if (HasGlue)
8439     Ops.push_back(*(Call->op_end()-1));
8440 
8441   SDVTList NodeTys;
8442   if (IsAnyRegCC && HasDef) {
8443     // Create the return types based on the intrinsic definition
8444     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8445     SmallVector<EVT, 3> ValueVTs;
8446     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8447     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8448 
8449     // There is always a chain and a glue type at the end
8450     ValueVTs.push_back(MVT::Other);
8451     ValueVTs.push_back(MVT::Glue);
8452     NodeTys = DAG.getVTList(ValueVTs);
8453   } else
8454     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8455 
8456   // Replace the target specific call node with a PATCHPOINT node.
8457   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8458                                          dl, NodeTys, Ops);
8459 
8460   // Update the NodeMap.
8461   if (HasDef) {
8462     if (IsAnyRegCC)
8463       setValue(CS.getInstruction(), SDValue(MN, 0));
8464     else
8465       setValue(CS.getInstruction(), Result.first);
8466   }
8467 
8468   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8469   // call sequence. Furthermore the location of the chain and glue can change
8470   // when the AnyReg calling convention is used and the intrinsic returns a
8471   // value.
8472   if (IsAnyRegCC && HasDef) {
8473     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8474     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8475     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8476   } else
8477     DAG.ReplaceAllUsesWith(Call, MN);
8478   DAG.DeleteNode(Call);
8479 
8480   // Inform the Frame Information that we have a patchpoint in this function.
8481   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8482 }
8483 
8484 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8485                                             unsigned Intrinsic) {
8486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8487   SDValue Op1 = getValue(I.getArgOperand(0));
8488   SDValue Op2;
8489   if (I.getNumArgOperands() > 1)
8490     Op2 = getValue(I.getArgOperand(1));
8491   SDLoc dl = getCurSDLoc();
8492   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8493   SDValue Res;
8494   FastMathFlags FMF;
8495   if (isa<FPMathOperator>(I))
8496     FMF = I.getFastMathFlags();
8497 
8498   switch (Intrinsic) {
8499   case Intrinsic::experimental_vector_reduce_fadd:
8500     if (FMF.isFast())
8501       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8502     else
8503       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8504     break;
8505   case Intrinsic::experimental_vector_reduce_fmul:
8506     if (FMF.isFast())
8507       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8508     else
8509       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8510     break;
8511   case Intrinsic::experimental_vector_reduce_add:
8512     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8513     break;
8514   case Intrinsic::experimental_vector_reduce_mul:
8515     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8516     break;
8517   case Intrinsic::experimental_vector_reduce_and:
8518     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8519     break;
8520   case Intrinsic::experimental_vector_reduce_or:
8521     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8522     break;
8523   case Intrinsic::experimental_vector_reduce_xor:
8524     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8525     break;
8526   case Intrinsic::experimental_vector_reduce_smax:
8527     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8528     break;
8529   case Intrinsic::experimental_vector_reduce_smin:
8530     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8531     break;
8532   case Intrinsic::experimental_vector_reduce_umax:
8533     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8534     break;
8535   case Intrinsic::experimental_vector_reduce_umin:
8536     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8537     break;
8538   case Intrinsic::experimental_vector_reduce_fmax:
8539     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8540     break;
8541   case Intrinsic::experimental_vector_reduce_fmin:
8542     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8543     break;
8544   default:
8545     llvm_unreachable("Unhandled vector reduce intrinsic");
8546   }
8547   setValue(&I, Res);
8548 }
8549 
8550 /// Returns an AttributeList representing the attributes applied to the return
8551 /// value of the given call.
8552 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8553   SmallVector<Attribute::AttrKind, 2> Attrs;
8554   if (CLI.RetSExt)
8555     Attrs.push_back(Attribute::SExt);
8556   if (CLI.RetZExt)
8557     Attrs.push_back(Attribute::ZExt);
8558   if (CLI.IsInReg)
8559     Attrs.push_back(Attribute::InReg);
8560 
8561   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8562                             Attrs);
8563 }
8564 
8565 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8566 /// implementation, which just calls LowerCall.
8567 /// FIXME: When all targets are
8568 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8569 std::pair<SDValue, SDValue>
8570 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8571   // Handle the incoming return values from the call.
8572   CLI.Ins.clear();
8573   Type *OrigRetTy = CLI.RetTy;
8574   SmallVector<EVT, 4> RetTys;
8575   SmallVector<uint64_t, 4> Offsets;
8576   auto &DL = CLI.DAG.getDataLayout();
8577   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8578 
8579   if (CLI.IsPostTypeLegalization) {
8580     // If we are lowering a libcall after legalization, split the return type.
8581     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8582     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8583     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8584       EVT RetVT = OldRetTys[i];
8585       uint64_t Offset = OldOffsets[i];
8586       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8587       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8588       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8589       RetTys.append(NumRegs, RegisterVT);
8590       for (unsigned j = 0; j != NumRegs; ++j)
8591         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8592     }
8593   }
8594 
8595   SmallVector<ISD::OutputArg, 4> Outs;
8596   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8597 
8598   bool CanLowerReturn =
8599       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8600                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8601 
8602   SDValue DemoteStackSlot;
8603   int DemoteStackIdx = -100;
8604   if (!CanLowerReturn) {
8605     // FIXME: equivalent assert?
8606     // assert(!CS.hasInAllocaArgument() &&
8607     //        "sret demotion is incompatible with inalloca");
8608     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8609     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8610     MachineFunction &MF = CLI.DAG.getMachineFunction();
8611     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8612     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8613                                               DL.getAllocaAddrSpace());
8614 
8615     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8616     ArgListEntry Entry;
8617     Entry.Node = DemoteStackSlot;
8618     Entry.Ty = StackSlotPtrType;
8619     Entry.IsSExt = false;
8620     Entry.IsZExt = false;
8621     Entry.IsInReg = false;
8622     Entry.IsSRet = true;
8623     Entry.IsNest = false;
8624     Entry.IsByVal = false;
8625     Entry.IsReturned = false;
8626     Entry.IsSwiftSelf = false;
8627     Entry.IsSwiftError = false;
8628     Entry.Alignment = Align;
8629     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8630     CLI.NumFixedArgs += 1;
8631     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8632 
8633     // sret demotion isn't compatible with tail-calls, since the sret argument
8634     // points into the callers stack frame.
8635     CLI.IsTailCall = false;
8636   } else {
8637     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8638       EVT VT = RetTys[I];
8639       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8640                                                      CLI.CallConv, VT);
8641       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8642                                                        CLI.CallConv, VT);
8643       for (unsigned i = 0; i != NumRegs; ++i) {
8644         ISD::InputArg MyFlags;
8645         MyFlags.VT = RegisterVT;
8646         MyFlags.ArgVT = VT;
8647         MyFlags.Used = CLI.IsReturnValueUsed;
8648         if (CLI.RetSExt)
8649           MyFlags.Flags.setSExt();
8650         if (CLI.RetZExt)
8651           MyFlags.Flags.setZExt();
8652         if (CLI.IsInReg)
8653           MyFlags.Flags.setInReg();
8654         CLI.Ins.push_back(MyFlags);
8655       }
8656     }
8657   }
8658 
8659   // We push in swifterror return as the last element of CLI.Ins.
8660   ArgListTy &Args = CLI.getArgs();
8661   if (supportSwiftError()) {
8662     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8663       if (Args[i].IsSwiftError) {
8664         ISD::InputArg MyFlags;
8665         MyFlags.VT = getPointerTy(DL);
8666         MyFlags.ArgVT = EVT(getPointerTy(DL));
8667         MyFlags.Flags.setSwiftError();
8668         CLI.Ins.push_back(MyFlags);
8669       }
8670     }
8671   }
8672 
8673   // Handle all of the outgoing arguments.
8674   CLI.Outs.clear();
8675   CLI.OutVals.clear();
8676   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8677     SmallVector<EVT, 4> ValueVTs;
8678     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8679     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8680     Type *FinalType = Args[i].Ty;
8681     if (Args[i].IsByVal)
8682       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8683     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8684         FinalType, CLI.CallConv, CLI.IsVarArg);
8685     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8686          ++Value) {
8687       EVT VT = ValueVTs[Value];
8688       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8689       SDValue Op = SDValue(Args[i].Node.getNode(),
8690                            Args[i].Node.getResNo() + Value);
8691       ISD::ArgFlagsTy Flags;
8692 
8693       // Certain targets (such as MIPS), may have a different ABI alignment
8694       // for a type depending on the context. Give the target a chance to
8695       // specify the alignment it wants.
8696       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8697 
8698       if (Args[i].IsZExt)
8699         Flags.setZExt();
8700       if (Args[i].IsSExt)
8701         Flags.setSExt();
8702       if (Args[i].IsInReg) {
8703         // If we are using vectorcall calling convention, a structure that is
8704         // passed InReg - is surely an HVA
8705         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8706             isa<StructType>(FinalType)) {
8707           // The first value of a structure is marked
8708           if (0 == Value)
8709             Flags.setHvaStart();
8710           Flags.setHva();
8711         }
8712         // Set InReg Flag
8713         Flags.setInReg();
8714       }
8715       if (Args[i].IsSRet)
8716         Flags.setSRet();
8717       if (Args[i].IsSwiftSelf)
8718         Flags.setSwiftSelf();
8719       if (Args[i].IsSwiftError)
8720         Flags.setSwiftError();
8721       if (Args[i].IsByVal)
8722         Flags.setByVal();
8723       if (Args[i].IsInAlloca) {
8724         Flags.setInAlloca();
8725         // Set the byval flag for CCAssignFn callbacks that don't know about
8726         // inalloca.  This way we can know how many bytes we should've allocated
8727         // and how many bytes a callee cleanup function will pop.  If we port
8728         // inalloca to more targets, we'll have to add custom inalloca handling
8729         // in the various CC lowering callbacks.
8730         Flags.setByVal();
8731       }
8732       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8733         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8734         Type *ElementTy = Ty->getElementType();
8735         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8736         // For ByVal, alignment should come from FE.  BE will guess if this
8737         // info is not there but there are cases it cannot get right.
8738         unsigned FrameAlign;
8739         if (Args[i].Alignment)
8740           FrameAlign = Args[i].Alignment;
8741         else
8742           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8743         Flags.setByValAlign(FrameAlign);
8744       }
8745       if (Args[i].IsNest)
8746         Flags.setNest();
8747       if (NeedsRegBlock)
8748         Flags.setInConsecutiveRegs();
8749       Flags.setOrigAlign(OriginalAlignment);
8750 
8751       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8752                                                  CLI.CallConv, VT);
8753       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8754                                                         CLI.CallConv, VT);
8755       SmallVector<SDValue, 4> Parts(NumParts);
8756       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8757 
8758       if (Args[i].IsSExt)
8759         ExtendKind = ISD::SIGN_EXTEND;
8760       else if (Args[i].IsZExt)
8761         ExtendKind = ISD::ZERO_EXTEND;
8762 
8763       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8764       // for now.
8765       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8766           CanLowerReturn) {
8767         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8768                "unexpected use of 'returned'");
8769         // Before passing 'returned' to the target lowering code, ensure that
8770         // either the register MVT and the actual EVT are the same size or that
8771         // the return value and argument are extended in the same way; in these
8772         // cases it's safe to pass the argument register value unchanged as the
8773         // return register value (although it's at the target's option whether
8774         // to do so)
8775         // TODO: allow code generation to take advantage of partially preserved
8776         // registers rather than clobbering the entire register when the
8777         // parameter extension method is not compatible with the return
8778         // extension method
8779         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8780             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8781              CLI.RetZExt == Args[i].IsZExt))
8782           Flags.setReturned();
8783       }
8784 
8785       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8786                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8787 
8788       for (unsigned j = 0; j != NumParts; ++j) {
8789         // if it isn't first piece, alignment must be 1
8790         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8791                                i < CLI.NumFixedArgs,
8792                                i, j*Parts[j].getValueType().getStoreSize());
8793         if (NumParts > 1 && j == 0)
8794           MyFlags.Flags.setSplit();
8795         else if (j != 0) {
8796           MyFlags.Flags.setOrigAlign(1);
8797           if (j == NumParts - 1)
8798             MyFlags.Flags.setSplitEnd();
8799         }
8800 
8801         CLI.Outs.push_back(MyFlags);
8802         CLI.OutVals.push_back(Parts[j]);
8803       }
8804 
8805       if (NeedsRegBlock && Value == NumValues - 1)
8806         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8807     }
8808   }
8809 
8810   SmallVector<SDValue, 4> InVals;
8811   CLI.Chain = LowerCall(CLI, InVals);
8812 
8813   // Update CLI.InVals to use outside of this function.
8814   CLI.InVals = InVals;
8815 
8816   // Verify that the target's LowerCall behaved as expected.
8817   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8818          "LowerCall didn't return a valid chain!");
8819   assert((!CLI.IsTailCall || InVals.empty()) &&
8820          "LowerCall emitted a return value for a tail call!");
8821   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8822          "LowerCall didn't emit the correct number of values!");
8823 
8824   // For a tail call, the return value is merely live-out and there aren't
8825   // any nodes in the DAG representing it. Return a special value to
8826   // indicate that a tail call has been emitted and no more Instructions
8827   // should be processed in the current block.
8828   if (CLI.IsTailCall) {
8829     CLI.DAG.setRoot(CLI.Chain);
8830     return std::make_pair(SDValue(), SDValue());
8831   }
8832 
8833 #ifndef NDEBUG
8834   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8835     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8836     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8837            "LowerCall emitted a value with the wrong type!");
8838   }
8839 #endif
8840 
8841   SmallVector<SDValue, 4> ReturnValues;
8842   if (!CanLowerReturn) {
8843     // The instruction result is the result of loading from the
8844     // hidden sret parameter.
8845     SmallVector<EVT, 1> PVTs;
8846     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8847 
8848     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8849     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8850     EVT PtrVT = PVTs[0];
8851 
8852     unsigned NumValues = RetTys.size();
8853     ReturnValues.resize(NumValues);
8854     SmallVector<SDValue, 4> Chains(NumValues);
8855 
8856     // An aggregate return value cannot wrap around the address space, so
8857     // offsets to its parts don't wrap either.
8858     SDNodeFlags Flags;
8859     Flags.setNoUnsignedWrap(true);
8860 
8861     for (unsigned i = 0; i < NumValues; ++i) {
8862       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8863                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8864                                                         PtrVT), Flags);
8865       SDValue L = CLI.DAG.getLoad(
8866           RetTys[i], CLI.DL, CLI.Chain, Add,
8867           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8868                                             DemoteStackIdx, Offsets[i]),
8869           /* Alignment = */ 1);
8870       ReturnValues[i] = L;
8871       Chains[i] = L.getValue(1);
8872     }
8873 
8874     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8875   } else {
8876     // Collect the legal value parts into potentially illegal values
8877     // that correspond to the original function's return values.
8878     Optional<ISD::NodeType> AssertOp;
8879     if (CLI.RetSExt)
8880       AssertOp = ISD::AssertSext;
8881     else if (CLI.RetZExt)
8882       AssertOp = ISD::AssertZext;
8883     unsigned CurReg = 0;
8884     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8885       EVT VT = RetTys[I];
8886       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8887                                                      CLI.CallConv, VT);
8888       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8889                                                        CLI.CallConv, VT);
8890 
8891       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8892                                               NumRegs, RegisterVT, VT, nullptr,
8893                                               CLI.CallConv, AssertOp));
8894       CurReg += NumRegs;
8895     }
8896 
8897     // For a function returning void, there is no return value. We can't create
8898     // such a node, so we just return a null return value in that case. In
8899     // that case, nothing will actually look at the value.
8900     if (ReturnValues.empty())
8901       return std::make_pair(SDValue(), CLI.Chain);
8902   }
8903 
8904   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8905                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8906   return std::make_pair(Res, CLI.Chain);
8907 }
8908 
8909 void TargetLowering::LowerOperationWrapper(SDNode *N,
8910                                            SmallVectorImpl<SDValue> &Results,
8911                                            SelectionDAG &DAG) const {
8912   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8913     Results.push_back(Res);
8914 }
8915 
8916 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8917   llvm_unreachable("LowerOperation not implemented for this target!");
8918 }
8919 
8920 void
8921 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8922   SDValue Op = getNonRegisterValue(V);
8923   assert((Op.getOpcode() != ISD::CopyFromReg ||
8924           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8925          "Copy from a reg to the same reg!");
8926   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8927 
8928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8929   // If this is an InlineAsm we have to match the registers required, not the
8930   // notional registers required by the type.
8931 
8932   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8933                    None); // This is not an ABI copy.
8934   SDValue Chain = DAG.getEntryNode();
8935 
8936   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8937                               FuncInfo.PreferredExtendType.end())
8938                                  ? ISD::ANY_EXTEND
8939                                  : FuncInfo.PreferredExtendType[V];
8940   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8941   PendingExports.push_back(Chain);
8942 }
8943 
8944 #include "llvm/CodeGen/SelectionDAGISel.h"
8945 
8946 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8947 /// entry block, return true.  This includes arguments used by switches, since
8948 /// the switch may expand into multiple basic blocks.
8949 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8950   // With FastISel active, we may be splitting blocks, so force creation
8951   // of virtual registers for all non-dead arguments.
8952   if (FastISel)
8953     return A->use_empty();
8954 
8955   const BasicBlock &Entry = A->getParent()->front();
8956   for (const User *U : A->users())
8957     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8958       return false;  // Use not in entry block.
8959 
8960   return true;
8961 }
8962 
8963 using ArgCopyElisionMapTy =
8964     DenseMap<const Argument *,
8965              std::pair<const AllocaInst *, const StoreInst *>>;
8966 
8967 /// Scan the entry block of the function in FuncInfo for arguments that look
8968 /// like copies into a local alloca. Record any copied arguments in
8969 /// ArgCopyElisionCandidates.
8970 static void
8971 findArgumentCopyElisionCandidates(const DataLayout &DL,
8972                                   FunctionLoweringInfo *FuncInfo,
8973                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8974   // Record the state of every static alloca used in the entry block. Argument
8975   // allocas are all used in the entry block, so we need approximately as many
8976   // entries as we have arguments.
8977   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8978   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8979   unsigned NumArgs = FuncInfo->Fn->arg_size();
8980   StaticAllocas.reserve(NumArgs * 2);
8981 
8982   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8983     if (!V)
8984       return nullptr;
8985     V = V->stripPointerCasts();
8986     const auto *AI = dyn_cast<AllocaInst>(V);
8987     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8988       return nullptr;
8989     auto Iter = StaticAllocas.insert({AI, Unknown});
8990     return &Iter.first->second;
8991   };
8992 
8993   // Look for stores of arguments to static allocas. Look through bitcasts and
8994   // GEPs to handle type coercions, as long as the alloca is fully initialized
8995   // by the store. Any non-store use of an alloca escapes it and any subsequent
8996   // unanalyzed store might write it.
8997   // FIXME: Handle structs initialized with multiple stores.
8998   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8999     // Look for stores, and handle non-store uses conservatively.
9000     const auto *SI = dyn_cast<StoreInst>(&I);
9001     if (!SI) {
9002       // We will look through cast uses, so ignore them completely.
9003       if (I.isCast())
9004         continue;
9005       // Ignore debug info intrinsics, they don't escape or store to allocas.
9006       if (isa<DbgInfoIntrinsic>(I))
9007         continue;
9008       // This is an unknown instruction. Assume it escapes or writes to all
9009       // static alloca operands.
9010       for (const Use &U : I.operands()) {
9011         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9012           *Info = StaticAllocaInfo::Clobbered;
9013       }
9014       continue;
9015     }
9016 
9017     // If the stored value is a static alloca, mark it as escaped.
9018     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9019       *Info = StaticAllocaInfo::Clobbered;
9020 
9021     // Check if the destination is a static alloca.
9022     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9023     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9024     if (!Info)
9025       continue;
9026     const AllocaInst *AI = cast<AllocaInst>(Dst);
9027 
9028     // Skip allocas that have been initialized or clobbered.
9029     if (*Info != StaticAllocaInfo::Unknown)
9030       continue;
9031 
9032     // Check if the stored value is an argument, and that this store fully
9033     // initializes the alloca. Don't elide copies from the same argument twice.
9034     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9035     const auto *Arg = dyn_cast<Argument>(Val);
9036     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9037         Arg->getType()->isEmptyTy() ||
9038         DL.getTypeStoreSize(Arg->getType()) !=
9039             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9040         ArgCopyElisionCandidates.count(Arg)) {
9041       *Info = StaticAllocaInfo::Clobbered;
9042       continue;
9043     }
9044 
9045     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9046                       << '\n');
9047 
9048     // Mark this alloca and store for argument copy elision.
9049     *Info = StaticAllocaInfo::Elidable;
9050     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9051 
9052     // Stop scanning if we've seen all arguments. This will happen early in -O0
9053     // builds, which is useful, because -O0 builds have large entry blocks and
9054     // many allocas.
9055     if (ArgCopyElisionCandidates.size() == NumArgs)
9056       break;
9057   }
9058 }
9059 
9060 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9061 /// ArgVal is a load from a suitable fixed stack object.
9062 static void tryToElideArgumentCopy(
9063     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9064     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9065     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9066     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9067     SDValue ArgVal, bool &ArgHasUses) {
9068   // Check if this is a load from a fixed stack object.
9069   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9070   if (!LNode)
9071     return;
9072   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9073   if (!FINode)
9074     return;
9075 
9076   // Check that the fixed stack object is the right size and alignment.
9077   // Look at the alignment that the user wrote on the alloca instead of looking
9078   // at the stack object.
9079   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9080   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9081   const AllocaInst *AI = ArgCopyIter->second.first;
9082   int FixedIndex = FINode->getIndex();
9083   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9084   int OldIndex = AllocaIndex;
9085   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9086   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9087     LLVM_DEBUG(
9088         dbgs() << "  argument copy elision failed due to bad fixed stack "
9089                   "object size\n");
9090     return;
9091   }
9092   unsigned RequiredAlignment = AI->getAlignment();
9093   if (!RequiredAlignment) {
9094     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9095         AI->getAllocatedType());
9096   }
9097   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9098     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9099                          "greater than stack argument alignment ("
9100                       << RequiredAlignment << " vs "
9101                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9102     return;
9103   }
9104 
9105   // Perform the elision. Delete the old stack object and replace its only use
9106   // in the variable info map. Mark the stack object as mutable.
9107   LLVM_DEBUG({
9108     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9109            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9110            << '\n';
9111   });
9112   MFI.RemoveStackObject(OldIndex);
9113   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9114   AllocaIndex = FixedIndex;
9115   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9116   Chains.push_back(ArgVal.getValue(1));
9117 
9118   // Avoid emitting code for the store implementing the copy.
9119   const StoreInst *SI = ArgCopyIter->second.second;
9120   ElidedArgCopyInstrs.insert(SI);
9121 
9122   // Check for uses of the argument again so that we can avoid exporting ArgVal
9123   // if it is't used by anything other than the store.
9124   for (const Value *U : Arg.users()) {
9125     if (U != SI) {
9126       ArgHasUses = true;
9127       break;
9128     }
9129   }
9130 }
9131 
9132 void SelectionDAGISel::LowerArguments(const Function &F) {
9133   SelectionDAG &DAG = SDB->DAG;
9134   SDLoc dl = SDB->getCurSDLoc();
9135   const DataLayout &DL = DAG.getDataLayout();
9136   SmallVector<ISD::InputArg, 16> Ins;
9137 
9138   if (!FuncInfo->CanLowerReturn) {
9139     // Put in an sret pointer parameter before all the other parameters.
9140     SmallVector<EVT, 1> ValueVTs;
9141     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9142                     F.getReturnType()->getPointerTo(
9143                         DAG.getDataLayout().getAllocaAddrSpace()),
9144                     ValueVTs);
9145 
9146     // NOTE: Assuming that a pointer will never break down to more than one VT
9147     // or one register.
9148     ISD::ArgFlagsTy Flags;
9149     Flags.setSRet();
9150     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9151     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9152                          ISD::InputArg::NoArgIndex, 0);
9153     Ins.push_back(RetArg);
9154   }
9155 
9156   // Look for stores of arguments to static allocas. Mark such arguments with a
9157   // flag to ask the target to give us the memory location of that argument if
9158   // available.
9159   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9160   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9161 
9162   // Set up the incoming argument description vector.
9163   for (const Argument &Arg : F.args()) {
9164     unsigned ArgNo = Arg.getArgNo();
9165     SmallVector<EVT, 4> ValueVTs;
9166     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9167     bool isArgValueUsed = !Arg.use_empty();
9168     unsigned PartBase = 0;
9169     Type *FinalType = Arg.getType();
9170     if (Arg.hasAttribute(Attribute::ByVal))
9171       FinalType = cast<PointerType>(FinalType)->getElementType();
9172     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9173         FinalType, F.getCallingConv(), F.isVarArg());
9174     for (unsigned Value = 0, NumValues = ValueVTs.size();
9175          Value != NumValues; ++Value) {
9176       EVT VT = ValueVTs[Value];
9177       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9178       ISD::ArgFlagsTy Flags;
9179 
9180       // Certain targets (such as MIPS), may have a different ABI alignment
9181       // for a type depending on the context. Give the target a chance to
9182       // specify the alignment it wants.
9183       unsigned OriginalAlignment =
9184           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9185 
9186       if (Arg.hasAttribute(Attribute::ZExt))
9187         Flags.setZExt();
9188       if (Arg.hasAttribute(Attribute::SExt))
9189         Flags.setSExt();
9190       if (Arg.hasAttribute(Attribute::InReg)) {
9191         // If we are using vectorcall calling convention, a structure that is
9192         // passed InReg - is surely an HVA
9193         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9194             isa<StructType>(Arg.getType())) {
9195           // The first value of a structure is marked
9196           if (0 == Value)
9197             Flags.setHvaStart();
9198           Flags.setHva();
9199         }
9200         // Set InReg Flag
9201         Flags.setInReg();
9202       }
9203       if (Arg.hasAttribute(Attribute::StructRet))
9204         Flags.setSRet();
9205       if (Arg.hasAttribute(Attribute::SwiftSelf))
9206         Flags.setSwiftSelf();
9207       if (Arg.hasAttribute(Attribute::SwiftError))
9208         Flags.setSwiftError();
9209       if (Arg.hasAttribute(Attribute::ByVal))
9210         Flags.setByVal();
9211       if (Arg.hasAttribute(Attribute::InAlloca)) {
9212         Flags.setInAlloca();
9213         // Set the byval flag for CCAssignFn callbacks that don't know about
9214         // inalloca.  This way we can know how many bytes we should've allocated
9215         // and how many bytes a callee cleanup function will pop.  If we port
9216         // inalloca to more targets, we'll have to add custom inalloca handling
9217         // in the various CC lowering callbacks.
9218         Flags.setByVal();
9219       }
9220       if (F.getCallingConv() == CallingConv::X86_INTR) {
9221         // IA Interrupt passes frame (1st parameter) by value in the stack.
9222         if (ArgNo == 0)
9223           Flags.setByVal();
9224       }
9225       if (Flags.isByVal() || Flags.isInAlloca()) {
9226         PointerType *Ty = cast<PointerType>(Arg.getType());
9227         Type *ElementTy = Ty->getElementType();
9228         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9229         // For ByVal, alignment should be passed from FE.  BE will guess if
9230         // this info is not there but there are cases it cannot get right.
9231         unsigned FrameAlign;
9232         if (Arg.getParamAlignment())
9233           FrameAlign = Arg.getParamAlignment();
9234         else
9235           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9236         Flags.setByValAlign(FrameAlign);
9237       }
9238       if (Arg.hasAttribute(Attribute::Nest))
9239         Flags.setNest();
9240       if (NeedsRegBlock)
9241         Flags.setInConsecutiveRegs();
9242       Flags.setOrigAlign(OriginalAlignment);
9243       if (ArgCopyElisionCandidates.count(&Arg))
9244         Flags.setCopyElisionCandidate();
9245 
9246       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9247           *CurDAG->getContext(), F.getCallingConv(), VT);
9248       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9249           *CurDAG->getContext(), F.getCallingConv(), VT);
9250       for (unsigned i = 0; i != NumRegs; ++i) {
9251         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9252                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9253         if (NumRegs > 1 && i == 0)
9254           MyFlags.Flags.setSplit();
9255         // if it isn't first piece, alignment must be 1
9256         else if (i > 0) {
9257           MyFlags.Flags.setOrigAlign(1);
9258           if (i == NumRegs - 1)
9259             MyFlags.Flags.setSplitEnd();
9260         }
9261         Ins.push_back(MyFlags);
9262       }
9263       if (NeedsRegBlock && Value == NumValues - 1)
9264         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9265       PartBase += VT.getStoreSize();
9266     }
9267   }
9268 
9269   // Call the target to set up the argument values.
9270   SmallVector<SDValue, 8> InVals;
9271   SDValue NewRoot = TLI->LowerFormalArguments(
9272       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9273 
9274   // Verify that the target's LowerFormalArguments behaved as expected.
9275   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9276          "LowerFormalArguments didn't return a valid chain!");
9277   assert(InVals.size() == Ins.size() &&
9278          "LowerFormalArguments didn't emit the correct number of values!");
9279   LLVM_DEBUG({
9280     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9281       assert(InVals[i].getNode() &&
9282              "LowerFormalArguments emitted a null value!");
9283       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9284              "LowerFormalArguments emitted a value with the wrong type!");
9285     }
9286   });
9287 
9288   // Update the DAG with the new chain value resulting from argument lowering.
9289   DAG.setRoot(NewRoot);
9290 
9291   // Set up the argument values.
9292   unsigned i = 0;
9293   if (!FuncInfo->CanLowerReturn) {
9294     // Create a virtual register for the sret pointer, and put in a copy
9295     // from the sret argument into it.
9296     SmallVector<EVT, 1> ValueVTs;
9297     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9298                     F.getReturnType()->getPointerTo(
9299                         DAG.getDataLayout().getAllocaAddrSpace()),
9300                     ValueVTs);
9301     MVT VT = ValueVTs[0].getSimpleVT();
9302     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9303     Optional<ISD::NodeType> AssertOp = None;
9304     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9305                                         nullptr, F.getCallingConv(), AssertOp);
9306 
9307     MachineFunction& MF = SDB->DAG.getMachineFunction();
9308     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9309     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9310     FuncInfo->DemoteRegister = SRetReg;
9311     NewRoot =
9312         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9313     DAG.setRoot(NewRoot);
9314 
9315     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9316     ++i;
9317   }
9318 
9319   SmallVector<SDValue, 4> Chains;
9320   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9321   for (const Argument &Arg : F.args()) {
9322     SmallVector<SDValue, 4> ArgValues;
9323     SmallVector<EVT, 4> ValueVTs;
9324     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9325     unsigned NumValues = ValueVTs.size();
9326     if (NumValues == 0)
9327       continue;
9328 
9329     bool ArgHasUses = !Arg.use_empty();
9330 
9331     // Elide the copying store if the target loaded this argument from a
9332     // suitable fixed stack object.
9333     if (Ins[i].Flags.isCopyElisionCandidate()) {
9334       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9335                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9336                              InVals[i], ArgHasUses);
9337     }
9338 
9339     // If this argument is unused then remember its value. It is used to generate
9340     // debugging information.
9341     bool isSwiftErrorArg =
9342         TLI->supportSwiftError() &&
9343         Arg.hasAttribute(Attribute::SwiftError);
9344     if (!ArgHasUses && !isSwiftErrorArg) {
9345       SDB->setUnusedArgValue(&Arg, InVals[i]);
9346 
9347       // Also remember any frame index for use in FastISel.
9348       if (FrameIndexSDNode *FI =
9349           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9350         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9351     }
9352 
9353     for (unsigned Val = 0; Val != NumValues; ++Val) {
9354       EVT VT = ValueVTs[Val];
9355       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9356                                                       F.getCallingConv(), VT);
9357       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9358           *CurDAG->getContext(), F.getCallingConv(), VT);
9359 
9360       // Even an apparant 'unused' swifterror argument needs to be returned. So
9361       // we do generate a copy for it that can be used on return from the
9362       // function.
9363       if (ArgHasUses || isSwiftErrorArg) {
9364         Optional<ISD::NodeType> AssertOp;
9365         if (Arg.hasAttribute(Attribute::SExt))
9366           AssertOp = ISD::AssertSext;
9367         else if (Arg.hasAttribute(Attribute::ZExt))
9368           AssertOp = ISD::AssertZext;
9369 
9370         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9371                                              PartVT, VT, nullptr,
9372                                              F.getCallingConv(), AssertOp));
9373       }
9374 
9375       i += NumParts;
9376     }
9377 
9378     // We don't need to do anything else for unused arguments.
9379     if (ArgValues.empty())
9380       continue;
9381 
9382     // Note down frame index.
9383     if (FrameIndexSDNode *FI =
9384         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9385       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9386 
9387     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9388                                      SDB->getCurSDLoc());
9389 
9390     SDB->setValue(&Arg, Res);
9391     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9392       // We want to associate the argument with the frame index, among
9393       // involved operands, that correspond to the lowest address. The
9394       // getCopyFromParts function, called earlier, is swapping the order of
9395       // the operands to BUILD_PAIR depending on endianness. The result of
9396       // that swapping is that the least significant bits of the argument will
9397       // be in the first operand of the BUILD_PAIR node, and the most
9398       // significant bits will be in the second operand.
9399       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9400       if (LoadSDNode *LNode =
9401           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9402         if (FrameIndexSDNode *FI =
9403             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9404           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9405     }
9406 
9407     // Update the SwiftErrorVRegDefMap.
9408     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9409       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9410       if (TargetRegisterInfo::isVirtualRegister(Reg))
9411         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9412                                            FuncInfo->SwiftErrorArg, Reg);
9413     }
9414 
9415     // If this argument is live outside of the entry block, insert a copy from
9416     // wherever we got it to the vreg that other BB's will reference it as.
9417     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9418       // If we can, though, try to skip creating an unnecessary vreg.
9419       // FIXME: This isn't very clean... it would be nice to make this more
9420       // general.  It's also subtly incompatible with the hacks FastISel
9421       // uses with vregs.
9422       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9423       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9424         FuncInfo->ValueMap[&Arg] = Reg;
9425         continue;
9426       }
9427     }
9428     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9429       FuncInfo->InitializeRegForValue(&Arg);
9430       SDB->CopyToExportRegsIfNeeded(&Arg);
9431     }
9432   }
9433 
9434   if (!Chains.empty()) {
9435     Chains.push_back(NewRoot);
9436     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9437   }
9438 
9439   DAG.setRoot(NewRoot);
9440 
9441   assert(i == InVals.size() && "Argument register count mismatch!");
9442 
9443   // If any argument copy elisions occurred and we have debug info, update the
9444   // stale frame indices used in the dbg.declare variable info table.
9445   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9446   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9447     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9448       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9449       if (I != ArgCopyElisionFrameIndexMap.end())
9450         VI.Slot = I->second;
9451     }
9452   }
9453 
9454   // Finally, if the target has anything special to do, allow it to do so.
9455   EmitFunctionEntryCode();
9456 }
9457 
9458 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9459 /// ensure constants are generated when needed.  Remember the virtual registers
9460 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9461 /// directly add them, because expansion might result in multiple MBB's for one
9462 /// BB.  As such, the start of the BB might correspond to a different MBB than
9463 /// the end.
9464 void
9465 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9466   const Instruction *TI = LLVMBB->getTerminator();
9467 
9468   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9469 
9470   // Check PHI nodes in successors that expect a value to be available from this
9471   // block.
9472   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9473     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9474     if (!isa<PHINode>(SuccBB->begin())) continue;
9475     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9476 
9477     // If this terminator has multiple identical successors (common for
9478     // switches), only handle each succ once.
9479     if (!SuccsHandled.insert(SuccMBB).second)
9480       continue;
9481 
9482     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9483 
9484     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9485     // nodes and Machine PHI nodes, but the incoming operands have not been
9486     // emitted yet.
9487     for (const PHINode &PN : SuccBB->phis()) {
9488       // Ignore dead phi's.
9489       if (PN.use_empty())
9490         continue;
9491 
9492       // Skip empty types
9493       if (PN.getType()->isEmptyTy())
9494         continue;
9495 
9496       unsigned Reg;
9497       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9498 
9499       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9500         unsigned &RegOut = ConstantsOut[C];
9501         if (RegOut == 0) {
9502           RegOut = FuncInfo.CreateRegs(C->getType());
9503           CopyValueToVirtualRegister(C, RegOut);
9504         }
9505         Reg = RegOut;
9506       } else {
9507         DenseMap<const Value *, unsigned>::iterator I =
9508           FuncInfo.ValueMap.find(PHIOp);
9509         if (I != FuncInfo.ValueMap.end())
9510           Reg = I->second;
9511         else {
9512           assert(isa<AllocaInst>(PHIOp) &&
9513                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9514                  "Didn't codegen value into a register!??");
9515           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9516           CopyValueToVirtualRegister(PHIOp, Reg);
9517         }
9518       }
9519 
9520       // Remember that this register needs to added to the machine PHI node as
9521       // the input for this MBB.
9522       SmallVector<EVT, 4> ValueVTs;
9523       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9524       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9525       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9526         EVT VT = ValueVTs[vti];
9527         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9528         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9529           FuncInfo.PHINodesToUpdate.push_back(
9530               std::make_pair(&*MBBI++, Reg + i));
9531         Reg += NumRegisters;
9532       }
9533     }
9534   }
9535 
9536   ConstantsOut.clear();
9537 }
9538 
9539 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9540 /// is 0.
9541 MachineBasicBlock *
9542 SelectionDAGBuilder::StackProtectorDescriptor::
9543 AddSuccessorMBB(const BasicBlock *BB,
9544                 MachineBasicBlock *ParentMBB,
9545                 bool IsLikely,
9546                 MachineBasicBlock *SuccMBB) {
9547   // If SuccBB has not been created yet, create it.
9548   if (!SuccMBB) {
9549     MachineFunction *MF = ParentMBB->getParent();
9550     MachineFunction::iterator BBI(ParentMBB);
9551     SuccMBB = MF->CreateMachineBasicBlock(BB);
9552     MF->insert(++BBI, SuccMBB);
9553   }
9554   // Add it as a successor of ParentMBB.
9555   ParentMBB->addSuccessor(
9556       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9557   return SuccMBB;
9558 }
9559 
9560 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9561   MachineFunction::iterator I(MBB);
9562   if (++I == FuncInfo.MF->end())
9563     return nullptr;
9564   return &*I;
9565 }
9566 
9567 /// During lowering new call nodes can be created (such as memset, etc.).
9568 /// Those will become new roots of the current DAG, but complications arise
9569 /// when they are tail calls. In such cases, the call lowering will update
9570 /// the root, but the builder still needs to know that a tail call has been
9571 /// lowered in order to avoid generating an additional return.
9572 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9573   // If the node is null, we do have a tail call.
9574   if (MaybeTC.getNode() != nullptr)
9575     DAG.setRoot(MaybeTC);
9576   else
9577     HasTailCall = true;
9578 }
9579 
9580 uint64_t
9581 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9582                                        unsigned First, unsigned Last) const {
9583   assert(Last >= First);
9584   const APInt &LowCase = Clusters[First].Low->getValue();
9585   const APInt &HighCase = Clusters[Last].High->getValue();
9586   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9587 
9588   // FIXME: A range of consecutive cases has 100% density, but only requires one
9589   // comparison to lower. We should discriminate against such consecutive ranges
9590   // in jump tables.
9591 
9592   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9593 }
9594 
9595 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9596     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9597     unsigned Last) const {
9598   assert(Last >= First);
9599   assert(TotalCases[Last] >= TotalCases[First]);
9600   uint64_t NumCases =
9601       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9602   return NumCases;
9603 }
9604 
9605 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9606                                          unsigned First, unsigned Last,
9607                                          const SwitchInst *SI,
9608                                          MachineBasicBlock *DefaultMBB,
9609                                          CaseCluster &JTCluster) {
9610   assert(First <= Last);
9611 
9612   auto Prob = BranchProbability::getZero();
9613   unsigned NumCmps = 0;
9614   std::vector<MachineBasicBlock*> Table;
9615   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9616 
9617   // Initialize probabilities in JTProbs.
9618   for (unsigned I = First; I <= Last; ++I)
9619     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9620 
9621   for (unsigned I = First; I <= Last; ++I) {
9622     assert(Clusters[I].Kind == CC_Range);
9623     Prob += Clusters[I].Prob;
9624     const APInt &Low = Clusters[I].Low->getValue();
9625     const APInt &High = Clusters[I].High->getValue();
9626     NumCmps += (Low == High) ? 1 : 2;
9627     if (I != First) {
9628       // Fill the gap between this and the previous cluster.
9629       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9630       assert(PreviousHigh.slt(Low));
9631       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9632       for (uint64_t J = 0; J < Gap; J++)
9633         Table.push_back(DefaultMBB);
9634     }
9635     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9636     for (uint64_t J = 0; J < ClusterSize; ++J)
9637       Table.push_back(Clusters[I].MBB);
9638     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9639   }
9640 
9641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9642   unsigned NumDests = JTProbs.size();
9643   if (TLI.isSuitableForBitTests(
9644           NumDests, NumCmps, Clusters[First].Low->getValue(),
9645           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9646     // Clusters[First..Last] should be lowered as bit tests instead.
9647     return false;
9648   }
9649 
9650   // Create the MBB that will load from and jump through the table.
9651   // Note: We create it here, but it's not inserted into the function yet.
9652   MachineFunction *CurMF = FuncInfo.MF;
9653   MachineBasicBlock *JumpTableMBB =
9654       CurMF->CreateMachineBasicBlock(SI->getParent());
9655 
9656   // Add successors. Note: use table order for determinism.
9657   SmallPtrSet<MachineBasicBlock *, 8> Done;
9658   for (MachineBasicBlock *Succ : Table) {
9659     if (Done.count(Succ))
9660       continue;
9661     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9662     Done.insert(Succ);
9663   }
9664   JumpTableMBB->normalizeSuccProbs();
9665 
9666   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9667                      ->createJumpTableIndex(Table);
9668 
9669   // Set up the jump table info.
9670   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9671   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9672                       Clusters[Last].High->getValue(), SI->getCondition(),
9673                       nullptr, false);
9674   JTCases.emplace_back(std::move(JTH), std::move(JT));
9675 
9676   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9677                                      JTCases.size() - 1, Prob);
9678   return true;
9679 }
9680 
9681 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9682                                          const SwitchInst *SI,
9683                                          MachineBasicBlock *DefaultMBB) {
9684 #ifndef NDEBUG
9685   // Clusters must be non-empty, sorted, and only contain Range clusters.
9686   assert(!Clusters.empty());
9687   for (CaseCluster &C : Clusters)
9688     assert(C.Kind == CC_Range);
9689   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9690     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9691 #endif
9692 
9693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9694   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9695     return;
9696 
9697   const int64_t N = Clusters.size();
9698   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9699   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9700 
9701   if (N < 2 || N < MinJumpTableEntries)
9702     return;
9703 
9704   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9705   SmallVector<unsigned, 8> TotalCases(N);
9706   for (unsigned i = 0; i < N; ++i) {
9707     const APInt &Hi = Clusters[i].High->getValue();
9708     const APInt &Lo = Clusters[i].Low->getValue();
9709     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9710     if (i != 0)
9711       TotalCases[i] += TotalCases[i - 1];
9712   }
9713 
9714   // Cheap case: the whole range may be suitable for jump table.
9715   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9716   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9717   assert(NumCases < UINT64_MAX / 100);
9718   assert(Range >= NumCases);
9719   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9720     CaseCluster JTCluster;
9721     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9722       Clusters[0] = JTCluster;
9723       Clusters.resize(1);
9724       return;
9725     }
9726   }
9727 
9728   // The algorithm below is not suitable for -O0.
9729   if (TM.getOptLevel() == CodeGenOpt::None)
9730     return;
9731 
9732   // Split Clusters into minimum number of dense partitions. The algorithm uses
9733   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9734   // for the Case Statement'" (1994), but builds the MinPartitions array in
9735   // reverse order to make it easier to reconstruct the partitions in ascending
9736   // order. In the choice between two optimal partitionings, it picks the one
9737   // which yields more jump tables.
9738 
9739   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9740   SmallVector<unsigned, 8> MinPartitions(N);
9741   // LastElement[i] is the last element of the partition starting at i.
9742   SmallVector<unsigned, 8> LastElement(N);
9743   // PartitionsScore[i] is used to break ties when choosing between two
9744   // partitionings resulting in the same number of partitions.
9745   SmallVector<unsigned, 8> PartitionsScore(N);
9746   // For PartitionsScore, a small number of comparisons is considered as good as
9747   // a jump table and a single comparison is considered better than a jump
9748   // table.
9749   enum PartitionScores : unsigned {
9750     NoTable = 0,
9751     Table = 1,
9752     FewCases = 1,
9753     SingleCase = 2
9754   };
9755 
9756   // Base case: There is only one way to partition Clusters[N-1].
9757   MinPartitions[N - 1] = 1;
9758   LastElement[N - 1] = N - 1;
9759   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9760 
9761   // Note: loop indexes are signed to avoid underflow.
9762   for (int64_t i = N - 2; i >= 0; i--) {
9763     // Find optimal partitioning of Clusters[i..N-1].
9764     // Baseline: Put Clusters[i] into a partition on its own.
9765     MinPartitions[i] = MinPartitions[i + 1] + 1;
9766     LastElement[i] = i;
9767     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9768 
9769     // Search for a solution that results in fewer partitions.
9770     for (int64_t j = N - 1; j > i; j--) {
9771       // Try building a partition from Clusters[i..j].
9772       uint64_t Range = getJumpTableRange(Clusters, i, j);
9773       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9774       assert(NumCases < UINT64_MAX / 100);
9775       assert(Range >= NumCases);
9776       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9777         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9778         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9779         int64_t NumEntries = j - i + 1;
9780 
9781         if (NumEntries == 1)
9782           Score += PartitionScores::SingleCase;
9783         else if (NumEntries <= SmallNumberOfEntries)
9784           Score += PartitionScores::FewCases;
9785         else if (NumEntries >= MinJumpTableEntries)
9786           Score += PartitionScores::Table;
9787 
9788         // If this leads to fewer partitions, or to the same number of
9789         // partitions with better score, it is a better partitioning.
9790         if (NumPartitions < MinPartitions[i] ||
9791             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9792           MinPartitions[i] = NumPartitions;
9793           LastElement[i] = j;
9794           PartitionsScore[i] = Score;
9795         }
9796       }
9797     }
9798   }
9799 
9800   // Iterate over the partitions, replacing some with jump tables in-place.
9801   unsigned DstIndex = 0;
9802   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9803     Last = LastElement[First];
9804     assert(Last >= First);
9805     assert(DstIndex <= First);
9806     unsigned NumClusters = Last - First + 1;
9807 
9808     CaseCluster JTCluster;
9809     if (NumClusters >= MinJumpTableEntries &&
9810         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9811       Clusters[DstIndex++] = JTCluster;
9812     } else {
9813       for (unsigned I = First; I <= Last; ++I)
9814         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9815     }
9816   }
9817   Clusters.resize(DstIndex);
9818 }
9819 
9820 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9821                                         unsigned First, unsigned Last,
9822                                         const SwitchInst *SI,
9823                                         CaseCluster &BTCluster) {
9824   assert(First <= Last);
9825   if (First == Last)
9826     return false;
9827 
9828   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9829   unsigned NumCmps = 0;
9830   for (int64_t I = First; I <= Last; ++I) {
9831     assert(Clusters[I].Kind == CC_Range);
9832     Dests.set(Clusters[I].MBB->getNumber());
9833     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9834   }
9835   unsigned NumDests = Dests.count();
9836 
9837   APInt Low = Clusters[First].Low->getValue();
9838   APInt High = Clusters[Last].High->getValue();
9839   assert(Low.slt(High));
9840 
9841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9842   const DataLayout &DL = DAG.getDataLayout();
9843   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9844     return false;
9845 
9846   APInt LowBound;
9847   APInt CmpRange;
9848 
9849   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9850   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9851          "Case range must fit in bit mask!");
9852 
9853   // Check if the clusters cover a contiguous range such that no value in the
9854   // range will jump to the default statement.
9855   bool ContiguousRange = true;
9856   for (int64_t I = First + 1; I <= Last; ++I) {
9857     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9858       ContiguousRange = false;
9859       break;
9860     }
9861   }
9862 
9863   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9864     // Optimize the case where all the case values fit in a word without having
9865     // to subtract minValue. In this case, we can optimize away the subtraction.
9866     LowBound = APInt::getNullValue(Low.getBitWidth());
9867     CmpRange = High;
9868     ContiguousRange = false;
9869   } else {
9870     LowBound = Low;
9871     CmpRange = High - Low;
9872   }
9873 
9874   CaseBitsVector CBV;
9875   auto TotalProb = BranchProbability::getZero();
9876   for (unsigned i = First; i <= Last; ++i) {
9877     // Find the CaseBits for this destination.
9878     unsigned j;
9879     for (j = 0; j < CBV.size(); ++j)
9880       if (CBV[j].BB == Clusters[i].MBB)
9881         break;
9882     if (j == CBV.size())
9883       CBV.push_back(
9884           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9885     CaseBits *CB = &CBV[j];
9886 
9887     // Update Mask, Bits and ExtraProb.
9888     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9889     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9890     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9891     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9892     CB->Bits += Hi - Lo + 1;
9893     CB->ExtraProb += Clusters[i].Prob;
9894     TotalProb += Clusters[i].Prob;
9895   }
9896 
9897   BitTestInfo BTI;
9898   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9899     // Sort by probability first, number of bits second, bit mask third.
9900     if (a.ExtraProb != b.ExtraProb)
9901       return a.ExtraProb > b.ExtraProb;
9902     if (a.Bits != b.Bits)
9903       return a.Bits > b.Bits;
9904     return a.Mask < b.Mask;
9905   });
9906 
9907   for (auto &CB : CBV) {
9908     MachineBasicBlock *BitTestBB =
9909         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9910     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9911   }
9912   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9913                             SI->getCondition(), -1U, MVT::Other, false,
9914                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9915                             TotalProb);
9916 
9917   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9918                                     BitTestCases.size() - 1, TotalProb);
9919   return true;
9920 }
9921 
9922 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9923                                               const SwitchInst *SI) {
9924 // Partition Clusters into as few subsets as possible, where each subset has a
9925 // range that fits in a machine word and has <= 3 unique destinations.
9926 
9927 #ifndef NDEBUG
9928   // Clusters must be sorted and contain Range or JumpTable clusters.
9929   assert(!Clusters.empty());
9930   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9931   for (const CaseCluster &C : Clusters)
9932     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9933   for (unsigned i = 1; i < Clusters.size(); ++i)
9934     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9935 #endif
9936 
9937   // The algorithm below is not suitable for -O0.
9938   if (TM.getOptLevel() == CodeGenOpt::None)
9939     return;
9940 
9941   // If target does not have legal shift left, do not emit bit tests at all.
9942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9943   const DataLayout &DL = DAG.getDataLayout();
9944 
9945   EVT PTy = TLI.getPointerTy(DL);
9946   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9947     return;
9948 
9949   int BitWidth = PTy.getSizeInBits();
9950   const int64_t N = Clusters.size();
9951 
9952   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9953   SmallVector<unsigned, 8> MinPartitions(N);
9954   // LastElement[i] is the last element of the partition starting at i.
9955   SmallVector<unsigned, 8> LastElement(N);
9956 
9957   // FIXME: This might not be the best algorithm for finding bit test clusters.
9958 
9959   // Base case: There is only one way to partition Clusters[N-1].
9960   MinPartitions[N - 1] = 1;
9961   LastElement[N - 1] = N - 1;
9962 
9963   // Note: loop indexes are signed to avoid underflow.
9964   for (int64_t i = N - 2; i >= 0; --i) {
9965     // Find optimal partitioning of Clusters[i..N-1].
9966     // Baseline: Put Clusters[i] into a partition on its own.
9967     MinPartitions[i] = MinPartitions[i + 1] + 1;
9968     LastElement[i] = i;
9969 
9970     // Search for a solution that results in fewer partitions.
9971     // Note: the search is limited by BitWidth, reducing time complexity.
9972     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9973       // Try building a partition from Clusters[i..j].
9974 
9975       // Check the range.
9976       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9977                                Clusters[j].High->getValue(), DL))
9978         continue;
9979 
9980       // Check nbr of destinations and cluster types.
9981       // FIXME: This works, but doesn't seem very efficient.
9982       bool RangesOnly = true;
9983       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9984       for (int64_t k = i; k <= j; k++) {
9985         if (Clusters[k].Kind != CC_Range) {
9986           RangesOnly = false;
9987           break;
9988         }
9989         Dests.set(Clusters[k].MBB->getNumber());
9990       }
9991       if (!RangesOnly || Dests.count() > 3)
9992         break;
9993 
9994       // Check if it's a better partition.
9995       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9996       if (NumPartitions < MinPartitions[i]) {
9997         // Found a better partition.
9998         MinPartitions[i] = NumPartitions;
9999         LastElement[i] = j;
10000       }
10001     }
10002   }
10003 
10004   // Iterate over the partitions, replacing with bit-test clusters in-place.
10005   unsigned DstIndex = 0;
10006   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10007     Last = LastElement[First];
10008     assert(First <= Last);
10009     assert(DstIndex <= First);
10010 
10011     CaseCluster BitTestCluster;
10012     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10013       Clusters[DstIndex++] = BitTestCluster;
10014     } else {
10015       size_t NumClusters = Last - First + 1;
10016       std::memmove(&Clusters[DstIndex], &Clusters[First],
10017                    sizeof(Clusters[0]) * NumClusters);
10018       DstIndex += NumClusters;
10019     }
10020   }
10021   Clusters.resize(DstIndex);
10022 }
10023 
10024 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10025                                         MachineBasicBlock *SwitchMBB,
10026                                         MachineBasicBlock *DefaultMBB) {
10027   MachineFunction *CurMF = FuncInfo.MF;
10028   MachineBasicBlock *NextMBB = nullptr;
10029   MachineFunction::iterator BBI(W.MBB);
10030   if (++BBI != FuncInfo.MF->end())
10031     NextMBB = &*BBI;
10032 
10033   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10034 
10035   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10036 
10037   if (Size == 2 && W.MBB == SwitchMBB) {
10038     // If any two of the cases has the same destination, and if one value
10039     // is the same as the other, but has one bit unset that the other has set,
10040     // use bit manipulation to do two compares at once.  For example:
10041     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10042     // TODO: This could be extended to merge any 2 cases in switches with 3
10043     // cases.
10044     // TODO: Handle cases where W.CaseBB != SwitchBB.
10045     CaseCluster &Small = *W.FirstCluster;
10046     CaseCluster &Big = *W.LastCluster;
10047 
10048     if (Small.Low == Small.High && Big.Low == Big.High &&
10049         Small.MBB == Big.MBB) {
10050       const APInt &SmallValue = Small.Low->getValue();
10051       const APInt &BigValue = Big.Low->getValue();
10052 
10053       // Check that there is only one bit different.
10054       APInt CommonBit = BigValue ^ SmallValue;
10055       if (CommonBit.isPowerOf2()) {
10056         SDValue CondLHS = getValue(Cond);
10057         EVT VT = CondLHS.getValueType();
10058         SDLoc DL = getCurSDLoc();
10059 
10060         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10061                                  DAG.getConstant(CommonBit, DL, VT));
10062         SDValue Cond = DAG.getSetCC(
10063             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10064             ISD::SETEQ);
10065 
10066         // Update successor info.
10067         // Both Small and Big will jump to Small.BB, so we sum up the
10068         // probabilities.
10069         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10070         if (BPI)
10071           addSuccessorWithProb(
10072               SwitchMBB, DefaultMBB,
10073               // The default destination is the first successor in IR.
10074               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10075         else
10076           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10077 
10078         // Insert the true branch.
10079         SDValue BrCond =
10080             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10081                         DAG.getBasicBlock(Small.MBB));
10082         // Insert the false branch.
10083         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10084                              DAG.getBasicBlock(DefaultMBB));
10085 
10086         DAG.setRoot(BrCond);
10087         return;
10088       }
10089     }
10090   }
10091 
10092   if (TM.getOptLevel() != CodeGenOpt::None) {
10093     // Here, we order cases by probability so the most likely case will be
10094     // checked first. However, two clusters can have the same probability in
10095     // which case their relative ordering is non-deterministic. So we use Low
10096     // as a tie-breaker as clusters are guaranteed to never overlap.
10097     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10098                [](const CaseCluster &a, const CaseCluster &b) {
10099       return a.Prob != b.Prob ?
10100              a.Prob > b.Prob :
10101              a.Low->getValue().slt(b.Low->getValue());
10102     });
10103 
10104     // Rearrange the case blocks so that the last one falls through if possible
10105     // without changing the order of probabilities.
10106     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10107       --I;
10108       if (I->Prob > W.LastCluster->Prob)
10109         break;
10110       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10111         std::swap(*I, *W.LastCluster);
10112         break;
10113       }
10114     }
10115   }
10116 
10117   // Compute total probability.
10118   BranchProbability DefaultProb = W.DefaultProb;
10119   BranchProbability UnhandledProbs = DefaultProb;
10120   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10121     UnhandledProbs += I->Prob;
10122 
10123   MachineBasicBlock *CurMBB = W.MBB;
10124   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10125     MachineBasicBlock *Fallthrough;
10126     if (I == W.LastCluster) {
10127       // For the last cluster, fall through to the default destination.
10128       Fallthrough = DefaultMBB;
10129     } else {
10130       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10131       CurMF->insert(BBI, Fallthrough);
10132       // Put Cond in a virtual register to make it available from the new blocks.
10133       ExportFromCurrentBlock(Cond);
10134     }
10135     UnhandledProbs -= I->Prob;
10136 
10137     switch (I->Kind) {
10138       case CC_JumpTable: {
10139         // FIXME: Optimize away range check based on pivot comparisons.
10140         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10141         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10142 
10143         // The jump block hasn't been inserted yet; insert it here.
10144         MachineBasicBlock *JumpMBB = JT->MBB;
10145         CurMF->insert(BBI, JumpMBB);
10146 
10147         auto JumpProb = I->Prob;
10148         auto FallthroughProb = UnhandledProbs;
10149 
10150         // If the default statement is a target of the jump table, we evenly
10151         // distribute the default probability to successors of CurMBB. Also
10152         // update the probability on the edge from JumpMBB to Fallthrough.
10153         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10154                                               SE = JumpMBB->succ_end();
10155              SI != SE; ++SI) {
10156           if (*SI == DefaultMBB) {
10157             JumpProb += DefaultProb / 2;
10158             FallthroughProb -= DefaultProb / 2;
10159             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10160             JumpMBB->normalizeSuccProbs();
10161             break;
10162           }
10163         }
10164 
10165         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10166         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10167         CurMBB->normalizeSuccProbs();
10168 
10169         // The jump table header will be inserted in our current block, do the
10170         // range check, and fall through to our fallthrough block.
10171         JTH->HeaderBB = CurMBB;
10172         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10173 
10174         // If we're in the right place, emit the jump table header right now.
10175         if (CurMBB == SwitchMBB) {
10176           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10177           JTH->Emitted = true;
10178         }
10179         break;
10180       }
10181       case CC_BitTests: {
10182         // FIXME: Optimize away range check based on pivot comparisons.
10183         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10184 
10185         // The bit test blocks haven't been inserted yet; insert them here.
10186         for (BitTestCase &BTC : BTB->Cases)
10187           CurMF->insert(BBI, BTC.ThisBB);
10188 
10189         // Fill in fields of the BitTestBlock.
10190         BTB->Parent = CurMBB;
10191         BTB->Default = Fallthrough;
10192 
10193         BTB->DefaultProb = UnhandledProbs;
10194         // If the cases in bit test don't form a contiguous range, we evenly
10195         // distribute the probability on the edge to Fallthrough to two
10196         // successors of CurMBB.
10197         if (!BTB->ContiguousRange) {
10198           BTB->Prob += DefaultProb / 2;
10199           BTB->DefaultProb -= DefaultProb / 2;
10200         }
10201 
10202         // If we're in the right place, emit the bit test header right now.
10203         if (CurMBB == SwitchMBB) {
10204           visitBitTestHeader(*BTB, SwitchMBB);
10205           BTB->Emitted = true;
10206         }
10207         break;
10208       }
10209       case CC_Range: {
10210         const Value *RHS, *LHS, *MHS;
10211         ISD::CondCode CC;
10212         if (I->Low == I->High) {
10213           // Check Cond == I->Low.
10214           CC = ISD::SETEQ;
10215           LHS = Cond;
10216           RHS=I->Low;
10217           MHS = nullptr;
10218         } else {
10219           // Check I->Low <= Cond <= I->High.
10220           CC = ISD::SETLE;
10221           LHS = I->Low;
10222           MHS = Cond;
10223           RHS = I->High;
10224         }
10225 
10226         // The false probability is the sum of all unhandled cases.
10227         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10228                      getCurSDLoc(), I->Prob, UnhandledProbs);
10229 
10230         if (CurMBB == SwitchMBB)
10231           visitSwitchCase(CB, SwitchMBB);
10232         else
10233           SwitchCases.push_back(CB);
10234 
10235         break;
10236       }
10237     }
10238     CurMBB = Fallthrough;
10239   }
10240 }
10241 
10242 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10243                                               CaseClusterIt First,
10244                                               CaseClusterIt Last) {
10245   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10246     if (X.Prob != CC.Prob)
10247       return X.Prob > CC.Prob;
10248 
10249     // Ties are broken by comparing the case value.
10250     return X.Low->getValue().slt(CC.Low->getValue());
10251   });
10252 }
10253 
10254 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10255                                         const SwitchWorkListItem &W,
10256                                         Value *Cond,
10257                                         MachineBasicBlock *SwitchMBB) {
10258   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10259          "Clusters not sorted?");
10260 
10261   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10262 
10263   // Balance the tree based on branch probabilities to create a near-optimal (in
10264   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10265   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10266   CaseClusterIt LastLeft = W.FirstCluster;
10267   CaseClusterIt FirstRight = W.LastCluster;
10268   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10269   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10270 
10271   // Move LastLeft and FirstRight towards each other from opposite directions to
10272   // find a partitioning of the clusters which balances the probability on both
10273   // sides. If LeftProb and RightProb are equal, alternate which side is
10274   // taken to ensure 0-probability nodes are distributed evenly.
10275   unsigned I = 0;
10276   while (LastLeft + 1 < FirstRight) {
10277     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10278       LeftProb += (++LastLeft)->Prob;
10279     else
10280       RightProb += (--FirstRight)->Prob;
10281     I++;
10282   }
10283 
10284   while (true) {
10285     // Our binary search tree differs from a typical BST in that ours can have up
10286     // to three values in each leaf. The pivot selection above doesn't take that
10287     // into account, which means the tree might require more nodes and be less
10288     // efficient. We compensate for this here.
10289 
10290     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10291     unsigned NumRight = W.LastCluster - FirstRight + 1;
10292 
10293     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10294       // If one side has less than 3 clusters, and the other has more than 3,
10295       // consider taking a cluster from the other side.
10296 
10297       if (NumLeft < NumRight) {
10298         // Consider moving the first cluster on the right to the left side.
10299         CaseCluster &CC = *FirstRight;
10300         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10301         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10302         if (LeftSideRank <= RightSideRank) {
10303           // Moving the cluster to the left does not demote it.
10304           ++LastLeft;
10305           ++FirstRight;
10306           continue;
10307         }
10308       } else {
10309         assert(NumRight < NumLeft);
10310         // Consider moving the last element on the left to the right side.
10311         CaseCluster &CC = *LastLeft;
10312         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10313         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10314         if (RightSideRank <= LeftSideRank) {
10315           // Moving the cluster to the right does not demot it.
10316           --LastLeft;
10317           --FirstRight;
10318           continue;
10319         }
10320       }
10321     }
10322     break;
10323   }
10324 
10325   assert(LastLeft + 1 == FirstRight);
10326   assert(LastLeft >= W.FirstCluster);
10327   assert(FirstRight <= W.LastCluster);
10328 
10329   // Use the first element on the right as pivot since we will make less-than
10330   // comparisons against it.
10331   CaseClusterIt PivotCluster = FirstRight;
10332   assert(PivotCluster > W.FirstCluster);
10333   assert(PivotCluster <= W.LastCluster);
10334 
10335   CaseClusterIt FirstLeft = W.FirstCluster;
10336   CaseClusterIt LastRight = W.LastCluster;
10337 
10338   const ConstantInt *Pivot = PivotCluster->Low;
10339 
10340   // New blocks will be inserted immediately after the current one.
10341   MachineFunction::iterator BBI(W.MBB);
10342   ++BBI;
10343 
10344   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10345   // we can branch to its destination directly if it's squeezed exactly in
10346   // between the known lower bound and Pivot - 1.
10347   MachineBasicBlock *LeftMBB;
10348   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10349       FirstLeft->Low == W.GE &&
10350       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10351     LeftMBB = FirstLeft->MBB;
10352   } else {
10353     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10354     FuncInfo.MF->insert(BBI, LeftMBB);
10355     WorkList.push_back(
10356         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10357     // Put Cond in a virtual register to make it available from the new blocks.
10358     ExportFromCurrentBlock(Cond);
10359   }
10360 
10361   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10362   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10363   // directly if RHS.High equals the current upper bound.
10364   MachineBasicBlock *RightMBB;
10365   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10366       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10367     RightMBB = FirstRight->MBB;
10368   } else {
10369     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10370     FuncInfo.MF->insert(BBI, RightMBB);
10371     WorkList.push_back(
10372         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10373     // Put Cond in a virtual register to make it available from the new blocks.
10374     ExportFromCurrentBlock(Cond);
10375   }
10376 
10377   // Create the CaseBlock record that will be used to lower the branch.
10378   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10379                getCurSDLoc(), LeftProb, RightProb);
10380 
10381   if (W.MBB == SwitchMBB)
10382     visitSwitchCase(CB, SwitchMBB);
10383   else
10384     SwitchCases.push_back(CB);
10385 }
10386 
10387 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10388 // from the swith statement.
10389 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10390                                             BranchProbability PeeledCaseProb) {
10391   if (PeeledCaseProb == BranchProbability::getOne())
10392     return BranchProbability::getZero();
10393   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10394 
10395   uint32_t Numerator = CaseProb.getNumerator();
10396   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10397   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10398 }
10399 
10400 // Try to peel the top probability case if it exceeds the threshold.
10401 // Return current MachineBasicBlock for the switch statement if the peeling
10402 // does not occur.
10403 // If the peeling is performed, return the newly created MachineBasicBlock
10404 // for the peeled switch statement. Also update Clusters to remove the peeled
10405 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10406 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10407     const SwitchInst &SI, CaseClusterVector &Clusters,
10408     BranchProbability &PeeledCaseProb) {
10409   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10410   // Don't perform if there is only one cluster or optimizing for size.
10411   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10412       TM.getOptLevel() == CodeGenOpt::None ||
10413       SwitchMBB->getParent()->getFunction().optForMinSize())
10414     return SwitchMBB;
10415 
10416   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10417   unsigned PeeledCaseIndex = 0;
10418   bool SwitchPeeled = false;
10419   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10420     CaseCluster &CC = Clusters[Index];
10421     if (CC.Prob < TopCaseProb)
10422       continue;
10423     TopCaseProb = CC.Prob;
10424     PeeledCaseIndex = Index;
10425     SwitchPeeled = true;
10426   }
10427   if (!SwitchPeeled)
10428     return SwitchMBB;
10429 
10430   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10431                     << TopCaseProb << "\n");
10432 
10433   // Record the MBB for the peeled switch statement.
10434   MachineFunction::iterator BBI(SwitchMBB);
10435   ++BBI;
10436   MachineBasicBlock *PeeledSwitchMBB =
10437       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10438   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10439 
10440   ExportFromCurrentBlock(SI.getCondition());
10441   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10442   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10443                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10444   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10445 
10446   Clusters.erase(PeeledCaseIt);
10447   for (CaseCluster &CC : Clusters) {
10448     LLVM_DEBUG(
10449         dbgs() << "Scale the probablity for one cluster, before scaling: "
10450                << CC.Prob << "\n");
10451     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10452     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10453   }
10454   PeeledCaseProb = TopCaseProb;
10455   return PeeledSwitchMBB;
10456 }
10457 
10458 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10459   // Extract cases from the switch.
10460   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10461   CaseClusterVector Clusters;
10462   Clusters.reserve(SI.getNumCases());
10463   for (auto I : SI.cases()) {
10464     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10465     const ConstantInt *CaseVal = I.getCaseValue();
10466     BranchProbability Prob =
10467         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10468             : BranchProbability(1, SI.getNumCases() + 1);
10469     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10470   }
10471 
10472   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10473 
10474   // Cluster adjacent cases with the same destination. We do this at all
10475   // optimization levels because it's cheap to do and will make codegen faster
10476   // if there are many clusters.
10477   sortAndRangeify(Clusters);
10478 
10479   if (TM.getOptLevel() != CodeGenOpt::None) {
10480     // Replace an unreachable default with the most popular destination.
10481     // FIXME: Exploit unreachable default more aggressively.
10482     bool UnreachableDefault =
10483         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10484     if (UnreachableDefault && !Clusters.empty()) {
10485       DenseMap<const BasicBlock *, unsigned> Popularity;
10486       unsigned MaxPop = 0;
10487       const BasicBlock *MaxBB = nullptr;
10488       for (auto I : SI.cases()) {
10489         const BasicBlock *BB = I.getCaseSuccessor();
10490         if (++Popularity[BB] > MaxPop) {
10491           MaxPop = Popularity[BB];
10492           MaxBB = BB;
10493         }
10494       }
10495       // Set new default.
10496       assert(MaxPop > 0 && MaxBB);
10497       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10498 
10499       // Remove cases that were pointing to the destination that is now the
10500       // default.
10501       CaseClusterVector New;
10502       New.reserve(Clusters.size());
10503       for (CaseCluster &CC : Clusters) {
10504         if (CC.MBB != DefaultMBB)
10505           New.push_back(CC);
10506       }
10507       Clusters = std::move(New);
10508     }
10509   }
10510 
10511   // The branch probablity of the peeled case.
10512   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10513   MachineBasicBlock *PeeledSwitchMBB =
10514       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10515 
10516   // If there is only the default destination, jump there directly.
10517   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10518   if (Clusters.empty()) {
10519     assert(PeeledSwitchMBB == SwitchMBB);
10520     SwitchMBB->addSuccessor(DefaultMBB);
10521     if (DefaultMBB != NextBlock(SwitchMBB)) {
10522       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10523                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10524     }
10525     return;
10526   }
10527 
10528   findJumpTables(Clusters, &SI, DefaultMBB);
10529   findBitTestClusters(Clusters, &SI);
10530 
10531   LLVM_DEBUG({
10532     dbgs() << "Case clusters: ";
10533     for (const CaseCluster &C : Clusters) {
10534       if (C.Kind == CC_JumpTable)
10535         dbgs() << "JT:";
10536       if (C.Kind == CC_BitTests)
10537         dbgs() << "BT:";
10538 
10539       C.Low->getValue().print(dbgs(), true);
10540       if (C.Low != C.High) {
10541         dbgs() << '-';
10542         C.High->getValue().print(dbgs(), true);
10543       }
10544       dbgs() << ' ';
10545     }
10546     dbgs() << '\n';
10547   });
10548 
10549   assert(!Clusters.empty());
10550   SwitchWorkList WorkList;
10551   CaseClusterIt First = Clusters.begin();
10552   CaseClusterIt Last = Clusters.end() - 1;
10553   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10554   // Scale the branchprobability for DefaultMBB if the peel occurs and
10555   // DefaultMBB is not replaced.
10556   if (PeeledCaseProb != BranchProbability::getZero() &&
10557       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10558     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10559   WorkList.push_back(
10560       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10561 
10562   while (!WorkList.empty()) {
10563     SwitchWorkListItem W = WorkList.back();
10564     WorkList.pop_back();
10565     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10566 
10567     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10568         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10569       // For optimized builds, lower large range as a balanced binary tree.
10570       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10571       continue;
10572     }
10573 
10574     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10575   }
10576 }
10577