xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 74b874ac4c6c079f85edd1f2957b1d96e0127ea5)
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 "llvm/Transforms/Utils/Local.h"
112 #include <algorithm>
113 #include <cassert>
114 #include <cstddef>
115 #include <cstdint>
116 #include <cstring>
117 #include <iterator>
118 #include <limits>
119 #include <numeric>
120 #include <tuple>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using namespace PatternMatch;
126 
127 #define DEBUG_TYPE "isel"
128 
129 /// LimitFloatPrecision - Generate low-precision inline sequences for
130 /// some float libcalls (6, 8 or 12 bits).
131 static unsigned LimitFloatPrecision;
132 
133 static cl::opt<unsigned, true>
134     LimitFPPrecision("limit-float-precision",
135                      cl::desc("Generate low-precision inline sequences "
136                               "for some float libcalls"),
137                      cl::location(LimitFloatPrecision), cl::Hidden,
138                      cl::init(0));
139 
140 static cl::opt<unsigned> SwitchPeelThreshold(
141     "switch-peel-threshold", cl::Hidden, cl::init(66),
142     cl::desc("Set the case probability threshold for peeling the case from a "
143              "switch statement. A value greater than 100 will void this "
144              "optimization"));
145 
146 // Limit the width of DAG chains. This is important in general to prevent
147 // DAG-based analysis from blowing up. For example, alias analysis and
148 // load clustering may not complete in reasonable time. It is difficult to
149 // recognize and avoid this situation within each individual analysis, and
150 // future analyses are likely to have the same behavior. Limiting DAG width is
151 // the safe approach and will be especially important with global DAGs.
152 //
153 // MaxParallelChains default is arbitrarily high to avoid affecting
154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
155 // sequence over this should have been converted to llvm.memcpy by the
156 // frontend. It is easy to induce this behavior with .ll code such as:
157 // %buffer = alloca [4096 x i8]
158 // %data = load [4096 x i8]* %argPtr
159 // store [4096 x i8] %data, [4096 x i8]* %buffer
160 static const unsigned MaxParallelChains = 64;
161 
162 // Return the calling convention if the Value passed requires ABI mangling as it
163 // is a parameter to a function or a return value from a function which is not
164 // an intrinsic.
165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
166   if (auto *R = dyn_cast<ReturnInst>(V))
167     return R->getParent()->getParent()->getCallingConv();
168 
169   if (auto *CI = dyn_cast<CallInst>(V)) {
170     const bool IsInlineAsm = CI->isInlineAsm();
171     const bool IsIndirectFunctionCall =
172         !IsInlineAsm && !CI->getCalledFunction();
173 
174     // It is possible that the call instruction is an inline asm statement or an
175     // indirect function call in which case the return value of
176     // getCalledFunction() would be nullptr.
177     const bool IsInstrinsicCall =
178         !IsInlineAsm && !IsIndirectFunctionCall &&
179         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
180 
181     if (!IsInlineAsm && !IsInstrinsicCall)
182       return CI->getCallingConv();
183   }
184 
185   return None;
186 }
187 
188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
189                                       const SDValue *Parts, unsigned NumParts,
190                                       MVT PartVT, EVT ValueVT, const Value *V,
191                                       Optional<CallingConv::ID> CC);
192 
193 /// getCopyFromParts - Create a value that contains the specified legal parts
194 /// combined into the value they represent.  If the parts combine to a type
195 /// larger than ValueVT then AssertOp can be used to specify whether the extra
196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
197 /// (ISD::AssertSext).
198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
199                                 const SDValue *Parts, unsigned NumParts,
200                                 MVT PartVT, EVT ValueVT, const Value *V,
201                                 Optional<CallingConv::ID> CC = None,
202                                 Optional<ISD::NodeType> AssertOp = None) {
203   if (ValueVT.isVector())
204     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
205                                   CC);
206 
207   assert(NumParts > 0 && "No parts to assemble!");
208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
209   SDValue Val = Parts[0];
210 
211   if (NumParts > 1) {
212     // Assemble the value from multiple parts.
213     if (ValueVT.isInteger()) {
214       unsigned PartBits = PartVT.getSizeInBits();
215       unsigned ValueBits = ValueVT.getSizeInBits();
216 
217       // Assemble the power of 2 part.
218       unsigned RoundParts = NumParts & (NumParts - 1) ?
219         1 << Log2_32(NumParts) : NumParts;
220       unsigned RoundBits = PartBits * RoundParts;
221       EVT RoundVT = RoundBits == ValueBits ?
222         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
223       SDValue Lo, Hi;
224 
225       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
226 
227       if (RoundParts > 2) {
228         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
229                               PartVT, HalfVT, V);
230         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
231                               RoundParts / 2, PartVT, HalfVT, V);
232       } else {
233         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
234         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
235       }
236 
237       if (DAG.getDataLayout().isBigEndian())
238         std::swap(Lo, Hi);
239 
240       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
241 
242       if (RoundParts < NumParts) {
243         // Assemble the trailing non-power-of-2 part.
244         unsigned OddParts = NumParts - RoundParts;
245         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
246         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
247                               OddVT, V, CC);
248 
249         // Combine the round and odd parts.
250         Lo = Val;
251         if (DAG.getDataLayout().isBigEndian())
252           std::swap(Lo, Hi);
253         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
254         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
255         Hi =
256             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
257                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
258                                         TLI.getPointerTy(DAG.getDataLayout())));
259         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
260         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
261       }
262     } else if (PartVT.isFloatingPoint()) {
263       // FP split into multiple FP parts (for ppcf128)
264       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
265              "Unexpected split");
266       SDValue Lo, Hi;
267       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
268       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
269       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
270         std::swap(Lo, Hi);
271       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
272     } else {
273       // FP split into integer parts (soft fp)
274       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
275              !PartVT.isVector() && "Unexpected split");
276       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
277       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
278     }
279   }
280 
281   // There is now one part, held in Val.  Correct it to match ValueVT.
282   // PartEVT is the type of the register class that holds the value.
283   // ValueVT is the type of the inline asm operation.
284   EVT PartEVT = Val.getValueType();
285 
286   if (PartEVT == ValueVT)
287     return Val;
288 
289   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
290       ValueVT.bitsLT(PartEVT)) {
291     // For an FP value in an integer part, we need to truncate to the right
292     // width first.
293     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
294     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
295   }
296 
297   // Handle types that have the same size.
298   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
299     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
300 
301   // Handle types with different sizes.
302   if (PartEVT.isInteger() && ValueVT.isInteger()) {
303     if (ValueVT.bitsLT(PartEVT)) {
304       // For a truncate, see if we have any information to
305       // indicate whether the truncated bits will always be
306       // zero or sign-extension.
307       if (AssertOp.hasValue())
308         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
309                           DAG.getValueType(ValueVT));
310       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
311     }
312     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
313   }
314 
315   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316     // FP_ROUND's are always exact here.
317     if (ValueVT.bitsLT(Val.getValueType()))
318       return DAG.getNode(
319           ISD::FP_ROUND, DL, ValueVT, Val,
320           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
321 
322     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
323   }
324 
325   llvm_unreachable("Unknown mismatch!");
326 }
327 
328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
329                                               const Twine &ErrMsg) {
330   const Instruction *I = dyn_cast_or_null<Instruction>(V);
331   if (!V)
332     return Ctx.emitError(ErrMsg);
333 
334   const char *AsmError = ", possible invalid constraint for vector type";
335   if (const CallInst *CI = dyn_cast<CallInst>(I))
336     if (isa<InlineAsm>(CI->getCalledValue()))
337       return Ctx.emitError(I, ErrMsg + AsmError);
338 
339   return Ctx.emitError(I, ErrMsg);
340 }
341 
342 /// getCopyFromPartsVector - Create a value that contains the specified legal
343 /// parts combined into the value they represent.  If the parts combine to a
344 /// type larger than ValueVT then AssertOp can be used to specify whether the
345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
346 /// ValueVT (ISD::AssertSext).
347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
348                                       const SDValue *Parts, unsigned NumParts,
349                                       MVT PartVT, EVT ValueVT, const Value *V,
350                                       Optional<CallingConv::ID> CallConv) {
351   assert(ValueVT.isVector() && "Not a vector value");
352   assert(NumParts > 0 && "No parts to assemble!");
353   const bool IsABIRegCopy = CallConv.hasValue();
354 
355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
356   SDValue Val = Parts[0];
357 
358   // Handle a multi-element vector.
359   if (NumParts > 1) {
360     EVT IntermediateVT;
361     MVT RegisterVT;
362     unsigned NumIntermediates;
363     unsigned NumRegs;
364 
365     if (IsABIRegCopy) {
366       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
367           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
368           NumIntermediates, RegisterVT);
369     } else {
370       NumRegs =
371           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
372                                      NumIntermediates, RegisterVT);
373     }
374 
375     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
376     NumParts = NumRegs; // Silence a compiler warning.
377     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
378     assert(RegisterVT.getSizeInBits() ==
379            Parts[0].getSimpleValueType().getSizeInBits() &&
380            "Part type sizes don't match!");
381 
382     // Assemble the parts into intermediate operands.
383     SmallVector<SDValue, 8> Ops(NumIntermediates);
384     if (NumIntermediates == NumParts) {
385       // If the register was not expanded, truncate or copy the value,
386       // as appropriate.
387       for (unsigned i = 0; i != NumParts; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
389                                   PartVT, IntermediateVT, V);
390     } else if (NumParts > 0) {
391       // If the intermediate type was expanded, build the intermediate
392       // operands from the parts.
393       assert(NumParts % NumIntermediates == 0 &&
394              "Must expand into a divisible number of parts!");
395       unsigned Factor = NumParts / NumIntermediates;
396       for (unsigned i = 0; i != NumIntermediates; ++i)
397         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
398                                   PartVT, IntermediateVT, V);
399     }
400 
401     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
402     // intermediate operands.
403     EVT BuiltVectorTy =
404         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
405                          (IntermediateVT.isVector()
406                               ? IntermediateVT.getVectorNumElements() * NumParts
407                               : NumIntermediates));
408     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
409                                                 : ISD::BUILD_VECTOR,
410                       DL, BuiltVectorTy, Ops);
411   }
412 
413   // There is now one part, held in Val.  Correct it to match ValueVT.
414   EVT PartEVT = Val.getValueType();
415 
416   if (PartEVT == ValueVT)
417     return Val;
418 
419   if (PartEVT.isVector()) {
420     // If the element type of the source/dest vectors are the same, but the
421     // parts vector has more elements than the value vector, then we have a
422     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
423     // elements we want.
424     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
425       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
426              "Cannot narrow, it would be a lossy transformation");
427       return DAG.getNode(
428           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
429           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
430     }
431 
432     // Vector/Vector bitcast.
433     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
434       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
437       "Cannot handle this kind of promotion");
438     // Promoted vector extract
439     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
440 
441   }
442 
443   // Trivial bitcast if the types are the same size and the destination
444   // vector type is legal.
445   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
446       TLI.isTypeLegal(ValueVT))
447     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449   if (ValueVT.getVectorNumElements() != 1) {
450      // Certain ABIs require that vectors are passed as integers. For vectors
451      // are the same size, this is an obvious bitcast.
452      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
453        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
455        // Bitcast Val back the original type and extract the corresponding
456        // vector we want.
457        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
458        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
459                                            ValueVT.getVectorElementType(), Elts);
460        Val = DAG.getBitcast(WiderVecType, Val);
461        return DAG.getNode(
462            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
463            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
464      }
465 
466      diagnosePossiblyInvalidConstraint(
467          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468      return DAG.getUNDEF(ValueVT);
469   }
470 
471   // Handle cases such as i8 -> <1 x i1>
472   EVT ValueSVT = ValueVT.getVectorElementType();
473   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
474     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
475                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
476 
477   return DAG.getBuildVector(ValueVT, DL, Val);
478 }
479 
480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
481                                  SDValue Val, SDValue *Parts, unsigned NumParts,
482                                  MVT PartVT, const Value *V,
483                                  Optional<CallingConv::ID> CallConv);
484 
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts.  If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
489                            SDValue *Parts, unsigned NumParts, MVT PartVT,
490                            const Value *V,
491                            Optional<CallingConv::ID> CallConv = None,
492                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
493   EVT ValueVT = Val.getValueType();
494 
495   // Handle the vector case separately.
496   if (ValueVT.isVector())
497     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
498                                 CallConv);
499 
500   unsigned PartBits = PartVT.getSizeInBits();
501   unsigned OrigNumParts = NumParts;
502   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
503          "Copying to an illegal type!");
504 
505   if (NumParts == 0)
506     return;
507 
508   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
509   EVT PartEVT = PartVT;
510   if (PartEVT == ValueVT) {
511     assert(NumParts == 1 && "No-op copy with multiple parts!");
512     Parts[0] = Val;
513     return;
514   }
515 
516   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
517     // If the parts cover more bits than the value has, promote the value.
518     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
519       assert(NumParts == 1 && "Do not know what to promote to!");
520       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
521     } else {
522       if (ValueVT.isFloatingPoint()) {
523         // FP values need to be bitcast, then extended if they are being put
524         // into a larger container.
525         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
526         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
527       }
528       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529              ValueVT.isInteger() &&
530              "Unknown mismatch!");
531       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
533       if (PartVT == MVT::x86mmx)
534         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535     }
536   } else if (PartBits == ValueVT.getSizeInBits()) {
537     // Different types of the same size.
538     assert(NumParts == 1 && PartEVT != ValueVT);
539     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541     // If the parts cover less bits than value has, truncate the value.
542     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543            ValueVT.isInteger() &&
544            "Unknown mismatch!");
545     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
547     if (PartVT == MVT::x86mmx)
548       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   }
550 
551   // The value may have changed - recompute ValueVT.
552   ValueVT = Val.getValueType();
553   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
554          "Failed to tile the value with PartVT!");
555 
556   if (NumParts == 1) {
557     if (PartEVT != ValueVT) {
558       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
559                                         "scalar-to-vector conversion failed");
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561     }
562 
563     Parts[0] = Val;
564     return;
565   }
566 
567   // Expand the value into multiple parts.
568   if (NumParts & (NumParts - 1)) {
569     // The number of parts is not a power of 2.  Split off and copy the tail.
570     assert(PartVT.isInteger() && ValueVT.isInteger() &&
571            "Do not know what to expand to!");
572     unsigned RoundParts = 1 << Log2_32(NumParts);
573     unsigned RoundBits = RoundParts * PartBits;
574     unsigned OddParts = NumParts - RoundParts;
575     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
576       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
577 
578     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
579                    CallConv);
580 
581     if (DAG.getDataLayout().isBigEndian())
582       // The odd parts were reversed by getCopyToParts - unreverse them.
583       std::reverse(Parts + RoundParts, Parts + NumParts);
584 
585     NumParts = RoundParts;
586     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
587     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
588   }
589 
590   // The number of parts is a power of 2.  Repeatedly bisect the value using
591   // EXTRACT_ELEMENT.
592   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
593                          EVT::getIntegerVT(*DAG.getContext(),
594                                            ValueVT.getSizeInBits()),
595                          Val);
596 
597   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
598     for (unsigned i = 0; i < NumParts; i += StepSize) {
599       unsigned ThisBits = StepSize * PartBits / 2;
600       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
601       SDValue &Part0 = Parts[i];
602       SDValue &Part1 = Parts[i+StepSize/2];
603 
604       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
606       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
607                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
608 
609       if (ThisBits == PartBits && ThisVT != PartVT) {
610         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
611         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
612       }
613     }
614   }
615 
616   if (DAG.getDataLayout().isBigEndian())
617     std::reverse(Parts, Parts + OrigNumParts);
618 }
619 
620 static SDValue widenVectorToPartType(SelectionDAG &DAG,
621                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
622   if (!PartVT.isVector())
623     return SDValue();
624 
625   EVT ValueVT = Val.getValueType();
626   unsigned PartNumElts = PartVT.getVectorNumElements();
627   unsigned ValueNumElts = ValueVT.getVectorNumElements();
628   if (PartNumElts > ValueNumElts &&
629       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
630     EVT ElementVT = PartVT.getVectorElementType();
631     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
632     // undef elements.
633     SmallVector<SDValue, 16> Ops;
634     DAG.ExtractVectorElements(Val, Ops);
635     SDValue EltUndef = DAG.getUNDEF(ElementVT);
636     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
637       Ops.push_back(EltUndef);
638 
639     // FIXME: Use CONCAT for 2x -> 4x.
640     return DAG.getBuildVector(PartVT, DL, Ops);
641   }
642 
643   return SDValue();
644 }
645 
646 /// getCopyToPartsVector - Create a series of nodes that contain the specified
647 /// value split into legal parts.
648 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
649                                  SDValue Val, SDValue *Parts, unsigned NumParts,
650                                  MVT PartVT, const Value *V,
651                                  Optional<CallingConv::ID> CallConv) {
652   EVT ValueVT = Val.getValueType();
653   assert(ValueVT.isVector() && "Not a vector");
654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
655   const bool IsABIRegCopy = CallConv.hasValue();
656 
657   if (NumParts == 1) {
658     EVT PartEVT = PartVT;
659     if (PartEVT == ValueVT) {
660       // Nothing to do.
661     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
662       // Bitconvert vector->vector case.
663       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
664     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
665       Val = Widened;
666     } else if (PartVT.isVector() &&
667                PartEVT.getVectorElementType().bitsGE(
668                  ValueVT.getVectorElementType()) &&
669                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
670 
671       // Promoted vector extract
672       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
673     } else {
674       if (ValueVT.getVectorNumElements() == 1) {
675         Val = DAG.getNode(
676             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
677             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
678       } else {
679         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
680                "lossy conversion of vector to scalar type");
681         EVT IntermediateType =
682             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
683         Val = DAG.getBitcast(IntermediateType, Val);
684         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
685       }
686     }
687 
688     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
689     Parts[0] = Val;
690     return;
691   }
692 
693   // Handle a multi-element vector.
694   EVT IntermediateVT;
695   MVT RegisterVT;
696   unsigned NumIntermediates;
697   unsigned NumRegs;
698   if (IsABIRegCopy) {
699     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
700         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
701         NumIntermediates, RegisterVT);
702   } else {
703     NumRegs =
704         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
705                                    NumIntermediates, RegisterVT);
706   }
707 
708   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
709   NumParts = NumRegs; // Silence a compiler warning.
710   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
711 
712   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
713     IntermediateVT.getVectorNumElements() : 1;
714 
715   // Convert the vector to the appropiate type if necessary.
716   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
717 
718   EVT BuiltVectorTy = EVT::getVectorVT(
719       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
720   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
721   if (ValueVT != BuiltVectorTy) {
722     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
723       Val = Widened;
724 
725     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
726   }
727 
728   // Split the vector into intermediate operands.
729   SmallVector<SDValue, 8> Ops(NumIntermediates);
730   for (unsigned i = 0; i != NumIntermediates; ++i) {
731     if (IntermediateVT.isVector()) {
732       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
733                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
734     } else {
735       Ops[i] = DAG.getNode(
736           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
737           DAG.getConstant(i, DL, IdxVT));
738     }
739   }
740 
741   // Split the intermediate operands into legal parts.
742   if (NumParts == NumIntermediates) {
743     // If the register was not expanded, promote or copy the value,
744     // as appropriate.
745     for (unsigned i = 0; i != NumParts; ++i)
746       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
747   } else if (NumParts > 0) {
748     // If the intermediate type was expanded, split each the value into
749     // legal parts.
750     assert(NumIntermediates != 0 && "division by zero");
751     assert(NumParts % NumIntermediates == 0 &&
752            "Must expand into a divisible number of parts!");
753     unsigned Factor = NumParts / NumIntermediates;
754     for (unsigned i = 0; i != NumIntermediates; ++i)
755       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
756                      CallConv);
757   }
758 }
759 
760 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
761                            EVT valuevt, Optional<CallingConv::ID> CC)
762     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
763       RegCount(1, regs.size()), CallConv(CC) {}
764 
765 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
766                            const DataLayout &DL, unsigned Reg, Type *Ty,
767                            Optional<CallingConv::ID> CC) {
768   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
769 
770   CallConv = CC;
771 
772   for (EVT ValueVT : ValueVTs) {
773     unsigned NumRegs =
774         isABIMangled()
775             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
776             : TLI.getNumRegisters(Context, ValueVT);
777     MVT RegisterVT =
778         isABIMangled()
779             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
780             : TLI.getRegisterType(Context, ValueVT);
781     for (unsigned i = 0; i != NumRegs; ++i)
782       Regs.push_back(Reg + i);
783     RegVTs.push_back(RegisterVT);
784     RegCount.push_back(NumRegs);
785     Reg += NumRegs;
786   }
787 }
788 
789 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
790                                       FunctionLoweringInfo &FuncInfo,
791                                       const SDLoc &dl, SDValue &Chain,
792                                       SDValue *Flag, const Value *V) const {
793   // A Value with type {} or [0 x %t] needs no registers.
794   if (ValueVTs.empty())
795     return SDValue();
796 
797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
798 
799   // Assemble the legal parts into the final values.
800   SmallVector<SDValue, 4> Values(ValueVTs.size());
801   SmallVector<SDValue, 8> Parts;
802   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
803     // Copy the legal parts from the registers.
804     EVT ValueVT = ValueVTs[Value];
805     unsigned NumRegs = RegCount[Value];
806     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
807                                           *DAG.getContext(),
808                                           CallConv.getValue(), RegVTs[Value])
809                                     : RegVTs[Value];
810 
811     Parts.resize(NumRegs);
812     for (unsigned i = 0; i != NumRegs; ++i) {
813       SDValue P;
814       if (!Flag) {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
816       } else {
817         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
818         *Flag = P.getValue(2);
819       }
820 
821       Chain = P.getValue(1);
822       Parts[i] = P;
823 
824       // If the source register was virtual and if we know something about it,
825       // add an assert node.
826       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
827           !RegisterVT.isInteger())
828         continue;
829 
830       const FunctionLoweringInfo::LiveOutInfo *LOI =
831         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
832       if (!LOI)
833         continue;
834 
835       unsigned RegSize = RegisterVT.getScalarSizeInBits();
836       unsigned NumSignBits = LOI->NumSignBits;
837       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
838 
839       if (NumZeroBits == RegSize) {
840         // The current value is a zero.
841         // Explicitly express that as it would be easier for
842         // optimizations to kick in.
843         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
844         continue;
845       }
846 
847       // FIXME: We capture more information than the dag can represent.  For
848       // now, just use the tightest assertzext/assertsext possible.
849       bool isSExt;
850       EVT FromVT(MVT::Other);
851       if (NumZeroBits) {
852         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
853         isSExt = false;
854       } else if (NumSignBits > 1) {
855         FromVT =
856             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
857         isSExt = true;
858       } else {
859         continue;
860       }
861       // Add an assertion node.
862       assert(FromVT != MVT::Other);
863       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
864                              RegisterVT, P, DAG.getValueType(FromVT));
865     }
866 
867     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
868                                      RegisterVT, ValueVT, V, CallConv);
869     Part += NumRegs;
870     Parts.clear();
871   }
872 
873   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
874 }
875 
876 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
877                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
878                                  const Value *V,
879                                  ISD::NodeType PreferredExtendType) const {
880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
881   ISD::NodeType ExtendKind = PreferredExtendType;
882 
883   // Get the list of the values's legal parts.
884   unsigned NumRegs = Regs.size();
885   SmallVector<SDValue, 8> Parts(NumRegs);
886   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
887     unsigned NumParts = RegCount[Value];
888 
889     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
890                                           *DAG.getContext(),
891                                           CallConv.getValue(), RegVTs[Value])
892                                     : RegVTs[Value];
893 
894     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
895       ExtendKind = ISD::ZERO_EXTEND;
896 
897     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
898                    NumParts, RegisterVT, V, CallConv, ExtendKind);
899     Part += NumParts;
900   }
901 
902   // Copy the parts into the registers.
903   SmallVector<SDValue, 8> Chains(NumRegs);
904   for (unsigned i = 0; i != NumRegs; ++i) {
905     SDValue Part;
906     if (!Flag) {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
908     } else {
909       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
910       *Flag = Part.getValue(1);
911     }
912 
913     Chains[i] = Part.getValue(0);
914   }
915 
916   if (NumRegs == 1 || Flag)
917     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
918     // flagged to it. That is the CopyToReg nodes and the user are considered
919     // a single scheduling unit. If we create a TokenFactor and return it as
920     // chain, then the TokenFactor is both a predecessor (operand) of the
921     // user as well as a successor (the TF operands are flagged to the user).
922     // c1, f1 = CopyToReg
923     // c2, f2 = CopyToReg
924     // c3     = TokenFactor c1, c2
925     // ...
926     //        = op c3, ..., f2
927     Chain = Chains[NumRegs-1];
928   else
929     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
930 }
931 
932 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
933                                         unsigned MatchingIdx, const SDLoc &dl,
934                                         SelectionDAG &DAG,
935                                         std::vector<SDValue> &Ops) const {
936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
937 
938   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
939   if (HasMatching)
940     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
941   else if (!Regs.empty() &&
942            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
943     // Put the register class of the virtual registers in the flag word.  That
944     // way, later passes can recompute register class constraints for inline
945     // assembly as well as normal instructions.
946     // Don't do this for tied operands that can use the regclass information
947     // from the def.
948     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
949     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
950     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
951   }
952 
953   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
954   Ops.push_back(Res);
955 
956   if (Code == InlineAsm::Kind_Clobber) {
957     // Clobbers should always have a 1:1 mapping with registers, and may
958     // reference registers that have illegal (e.g. vector) types. Hence, we
959     // shouldn't try to apply any sort of splitting logic to them.
960     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
961            "No 1:1 mapping from clobbers to regs?");
962     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
963     (void)SP;
964     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
965       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
966       assert(
967           (Regs[I] != SP ||
968            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
969           "If we clobbered the stack pointer, MFI should know about it.");
970     }
971     return;
972   }
973 
974   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
976     MVT RegisterVT = RegVTs[Value];
977     for (unsigned i = 0; i != NumRegs; ++i) {
978       assert(Reg < Regs.size() && "Mismatch in # registers expected");
979       unsigned TheReg = Regs[Reg++];
980       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
981     }
982   }
983 }
984 
985 SmallVector<std::pair<unsigned, unsigned>, 4>
986 RegsForValue::getRegsAndSizes() const {
987   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
988   unsigned I = 0;
989   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
990     unsigned RegCount = std::get<0>(CountAndVT);
991     MVT RegisterVT = std::get<1>(CountAndVT);
992     unsigned RegisterSize = RegisterVT.getSizeInBits();
993     for (unsigned E = I + RegCount; I != E; ++I)
994       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
995   }
996   return OutVec;
997 }
998 
999 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1000                                const TargetLibraryInfo *li) {
1001   AA = aa;
1002   GFI = gfi;
1003   LibInfo = li;
1004   DL = &DAG.getDataLayout();
1005   Context = DAG.getContext();
1006   LPadToCallSiteMap.clear();
1007 }
1008 
1009 void SelectionDAGBuilder::clear() {
1010   NodeMap.clear();
1011   UnusedArgNodeMap.clear();
1012   PendingLoads.clear();
1013   PendingExports.clear();
1014   CurInst = nullptr;
1015   HasTailCall = false;
1016   SDNodeOrder = LowestSDNodeOrder;
1017   StatepointLowering.clear();
1018 }
1019 
1020 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1021   DanglingDebugInfoMap.clear();
1022 }
1023 
1024 SDValue SelectionDAGBuilder::getRoot() {
1025   if (PendingLoads.empty())
1026     return DAG.getRoot();
1027 
1028   if (PendingLoads.size() == 1) {
1029     SDValue Root = PendingLoads[0];
1030     DAG.setRoot(Root);
1031     PendingLoads.clear();
1032     return Root;
1033   }
1034 
1035   // Otherwise, we have to make a token factor node.
1036   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1037   PendingLoads.clear();
1038   DAG.setRoot(Root);
1039   return Root;
1040 }
1041 
1042 SDValue SelectionDAGBuilder::getControlRoot() {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (PendingExports.empty())
1046     return Root;
1047 
1048   // Turn all of the CopyToReg chains into one factored node.
1049   if (Root.getOpcode() != ISD::EntryToken) {
1050     unsigned i = 0, e = PendingExports.size();
1051     for (; i != e; ++i) {
1052       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1053       if (PendingExports[i].getNode()->getOperand(0) == Root)
1054         break;  // Don't add the root if we already indirectly depend on it.
1055     }
1056 
1057     if (i == e)
1058       PendingExports.push_back(Root);
1059   }
1060 
1061   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1062                      PendingExports);
1063   PendingExports.clear();
1064   DAG.setRoot(Root);
1065   return Root;
1066 }
1067 
1068 void SelectionDAGBuilder::visit(const Instruction &I) {
1069   // Set up outgoing PHI node register values before emitting the terminator.
1070   if (I.isTerminator()) {
1071     HandlePHINodesInSuccessorBlocks(I.getParent());
1072   }
1073 
1074   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1075   if (!isa<DbgInfoIntrinsic>(I))
1076     ++SDNodeOrder;
1077 
1078   CurInst = &I;
1079 
1080   visit(I.getOpcode(), I);
1081 
1082   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1083     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1084     // maps to this instruction.
1085     // TODO: We could handle all flags (nsw, etc) here.
1086     // TODO: If an IR instruction maps to >1 node, only the final node will have
1087     //       flags set.
1088     if (SDNode *Node = getNodeForIRValue(&I)) {
1089       SDNodeFlags IncomingFlags;
1090       IncomingFlags.copyFMF(*FPMO);
1091       if (!Node->getFlags().isDefined())
1092         Node->setFlags(IncomingFlags);
1093       else
1094         Node->intersectFlagsWith(IncomingFlags);
1095     }
1096   }
1097 
1098   if (!I.isTerminator() && !HasTailCall &&
1099       !isStatepoint(&I)) // statepoints handle their exports internally
1100     CopyToExportRegsIfNeeded(&I);
1101 
1102   CurInst = nullptr;
1103 }
1104 
1105 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1106   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1107 }
1108 
1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1110   // Note: this doesn't use InstVisitor, because it has to work with
1111   // ConstantExpr's in addition to instructions.
1112   switch (Opcode) {
1113   default: llvm_unreachable("Unknown instruction type encountered!");
1114     // Build the switch statement using the Instruction.def file.
1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1116     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1117 #include "llvm/IR/Instruction.def"
1118   }
1119 }
1120 
1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1122                                                 const DIExpression *Expr) {
1123   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1124     const DbgValueInst *DI = DDI.getDI();
1125     DIVariable *DanglingVariable = DI->getVariable();
1126     DIExpression *DanglingExpr = DI->getExpression();
1127     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1128       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1129       return true;
1130     }
1131     return false;
1132   };
1133 
1134   for (auto &DDIMI : DanglingDebugInfoMap) {
1135     DanglingDebugInfoVector &DDIV = DDIMI.second;
1136 
1137     // If debug info is to be dropped, run it through final checks to see
1138     // whether it can be salvaged.
1139     for (auto &DDI : DDIV)
1140       if (isMatchingDbgValue(DDI))
1141         salvageUnresolvedDbgValue(DDI);
1142 
1143     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1144   }
1145 }
1146 
1147 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1148 // generate the debug data structures now that we've seen its definition.
1149 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1150                                                    SDValue Val) {
1151   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1152   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1153     return;
1154 
1155   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1156   for (auto &DDI : DDIV) {
1157     const DbgValueInst *DI = DDI.getDI();
1158     assert(DI && "Ill-formed DanglingDebugInfo");
1159     DebugLoc dl = DDI.getdl();
1160     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1161     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1162     DILocalVariable *Variable = DI->getVariable();
1163     DIExpression *Expr = DI->getExpression();
1164     assert(Variable->isValidLocationForIntrinsic(dl) &&
1165            "Expected inlined-at fields to agree");
1166     SDDbgValue *SDV;
1167     if (Val.getNode()) {
1168       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1169       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1170       // we couldn't resolve it directly when examining the DbgValue intrinsic
1171       // in the first place we should not be more successful here). Unless we
1172       // have some test case that prove this to be correct we should avoid
1173       // calling EmitFuncArgumentDbgValue here.
1174       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1175         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1176                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1177         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1178         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1179         // inserted after the definition of Val when emitting the instructions
1180         // after ISel. An alternative could be to teach
1181         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1182         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1183                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1184                    << ValSDNodeOrder << "\n");
1185         SDV = getDbgValue(Val, Variable, Expr, dl,
1186                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1187         DAG.AddDbgValue(SDV, Val.getNode(), false);
1188       } else
1189         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1190                           << "in EmitFuncArgumentDbgValue\n");
1191     } else {
1192       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1193       auto Undef =
1194           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1195       auto SDV =
1196           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1197       DAG.AddDbgValue(SDV, nullptr, false);
1198     }
1199   }
1200   DDIV.clear();
1201 }
1202 
1203 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1204   Value *V = DDI.getDI()->getValue();
1205   DILocalVariable *Var = DDI.getDI()->getVariable();
1206   DIExpression *Expr = DDI.getDI()->getExpression();
1207   DebugLoc DL = DDI.getdl();
1208   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1209   unsigned SDOrder = DDI.getSDNodeOrder();
1210 
1211   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1212   // that DW_OP_stack_value is desired.
1213   assert(isa<DbgValueInst>(DDI.getDI()));
1214   bool StackValue = true;
1215 
1216   // Can this Value can be encoded without any further work?
1217   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1218     return;
1219 
1220   // Attempt to salvage back through as many instructions as possible. Bail if
1221   // a non-instruction is seen, such as a constant expression or global
1222   // variable. FIXME: Further work could recover those too.
1223   while (isa<Instruction>(V)) {
1224     Instruction &VAsInst = *cast<Instruction>(V);
1225     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1226 
1227     // If we cannot salvage any further, and haven't yet found a suitable debug
1228     // expression, bail out.
1229     if (!NewExpr)
1230       break;
1231 
1232     // New value and expr now represent this debuginfo.
1233     V = VAsInst.getOperand(0);
1234     Expr = NewExpr;
1235 
1236     // Some kind of simplification occurred: check whether the operand of the
1237     // salvaged debug expression can be encoded in this DAG.
1238     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1239       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1240                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1241       return;
1242     }
1243   }
1244 
1245   // This was the final opportunity to salvage this debug information, and it
1246   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1247   // any earlier variable location.
1248   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1249   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1250   DAG.AddDbgValue(SDV, nullptr, false);
1251 
1252   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1253                     << "\n");
1254   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1255                     << "\n");
1256 }
1257 
1258 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1259                                            DIExpression *Expr, DebugLoc dl,
1260                                            DebugLoc InstDL, unsigned Order) {
1261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1262   SDDbgValue *SDV;
1263   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1264       isa<ConstantPointerNull>(V)) {
1265     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1266     DAG.AddDbgValue(SDV, nullptr, false);
1267     return true;
1268   }
1269 
1270   // If the Value is a frame index, we can create a FrameIndex debug value
1271   // without relying on the DAG at all.
1272   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1273     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1274     if (SI != FuncInfo.StaticAllocaMap.end()) {
1275       auto SDV =
1276           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1277                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1278       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1279       // is still available even if the SDNode gets optimized out.
1280       DAG.AddDbgValue(SDV, nullptr, false);
1281       return true;
1282     }
1283   }
1284 
1285   // Do not use getValue() in here; we don't want to generate code at
1286   // this point if it hasn't been done yet.
1287   SDValue N = NodeMap[V];
1288   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1289     N = UnusedArgNodeMap[V];
1290   if (N.getNode()) {
1291     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1292       return true;
1293     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1294     DAG.AddDbgValue(SDV, N.getNode(), false);
1295     return true;
1296   }
1297 
1298   // Special rules apply for the first dbg.values of parameter variables in a
1299   // function. Identify them by the fact they reference Argument Values, that
1300   // they're parameters, and they are parameters of the current function. We
1301   // need to let them dangle until they get an SDNode.
1302   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1303                        !InstDL.getInlinedAt();
1304   if (!IsParamOfFunc) {
1305     // The value is not used in this block yet (or it would have an SDNode).
1306     // We still want the value to appear for the user if possible -- if it has
1307     // an associated VReg, we can refer to that instead.
1308     auto VMI = FuncInfo.ValueMap.find(V);
1309     if (VMI != FuncInfo.ValueMap.end()) {
1310       unsigned Reg = VMI->second;
1311       // If this is a PHI node, it may be split up into several MI PHI nodes
1312       // (in FunctionLoweringInfo::set).
1313       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1314                        V->getType(), None);
1315       if (RFV.occupiesMultipleRegs()) {
1316         unsigned Offset = 0;
1317         unsigned BitsToDescribe = 0;
1318         if (auto VarSize = Var->getSizeInBits())
1319           BitsToDescribe = *VarSize;
1320         if (auto Fragment = Expr->getFragmentInfo())
1321           BitsToDescribe = Fragment->SizeInBits;
1322         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1323           unsigned RegisterSize = RegAndSize.second;
1324           // Bail out if all bits are described already.
1325           if (Offset >= BitsToDescribe)
1326             break;
1327           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1328               ? BitsToDescribe - Offset
1329               : RegisterSize;
1330           auto FragmentExpr = DIExpression::createFragmentExpression(
1331               Expr, Offset, FragmentSize);
1332           if (!FragmentExpr)
1333               continue;
1334           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1335                                     false, dl, SDNodeOrder);
1336           DAG.AddDbgValue(SDV, nullptr, false);
1337           Offset += RegisterSize;
1338         }
1339       } else {
1340         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1341         DAG.AddDbgValue(SDV, nullptr, false);
1342       }
1343       return true;
1344     }
1345   }
1346 
1347   return false;
1348 }
1349 
1350 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1351   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1352   for (auto &Pair : DanglingDebugInfoMap)
1353     for (auto &DDI : Pair.second)
1354       salvageUnresolvedDbgValue(DDI);
1355   clearDanglingDebugInfo();
1356 }
1357 
1358 /// getCopyFromRegs - If there was virtual register allocated for the value V
1359 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1360 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1361   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1362   SDValue Result;
1363 
1364   if (It != FuncInfo.ValueMap.end()) {
1365     unsigned InReg = It->second;
1366 
1367     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1368                      DAG.getDataLayout(), InReg, Ty,
1369                      None); // This is not an ABI copy.
1370     SDValue Chain = DAG.getEntryNode();
1371     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1372                                  V);
1373     resolveDanglingDebugInfo(V, Result);
1374   }
1375 
1376   return Result;
1377 }
1378 
1379 /// getValue - Return an SDValue for the given Value.
1380 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1381   // If we already have an SDValue for this value, use it. It's important
1382   // to do this first, so that we don't create a CopyFromReg if we already
1383   // have a regular SDValue.
1384   SDValue &N = NodeMap[V];
1385   if (N.getNode()) return N;
1386 
1387   // If there's a virtual register allocated and initialized for this
1388   // value, use it.
1389   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1390     return copyFromReg;
1391 
1392   // Otherwise create a new SDValue and remember it.
1393   SDValue Val = getValueImpl(V);
1394   NodeMap[V] = Val;
1395   resolveDanglingDebugInfo(V, Val);
1396   return Val;
1397 }
1398 
1399 // Return true if SDValue exists for the given Value
1400 bool SelectionDAGBuilder::findValue(const Value *V) const {
1401   return (NodeMap.find(V) != NodeMap.end()) ||
1402     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1403 }
1404 
1405 /// getNonRegisterValue - Return an SDValue for the given Value, but
1406 /// don't look in FuncInfo.ValueMap for a virtual register.
1407 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1408   // If we already have an SDValue for this value, use it.
1409   SDValue &N = NodeMap[V];
1410   if (N.getNode()) {
1411     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1412       // Remove the debug location from the node as the node is about to be used
1413       // in a location which may differ from the original debug location.  This
1414       // is relevant to Constant and ConstantFP nodes because they can appear
1415       // as constant expressions inside PHI nodes.
1416       N->setDebugLoc(DebugLoc());
1417     }
1418     return N;
1419   }
1420 
1421   // Otherwise create a new SDValue and remember it.
1422   SDValue Val = getValueImpl(V);
1423   NodeMap[V] = Val;
1424   resolveDanglingDebugInfo(V, Val);
1425   return Val;
1426 }
1427 
1428 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1429 /// Create an SDValue for the given value.
1430 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1432 
1433   if (const Constant *C = dyn_cast<Constant>(V)) {
1434     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1435 
1436     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1437       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1438 
1439     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1440       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1441 
1442     if (isa<ConstantPointerNull>(C)) {
1443       unsigned AS = V->getType()->getPointerAddressSpace();
1444       return DAG.getConstant(0, getCurSDLoc(),
1445                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1446     }
1447 
1448     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1449       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1450 
1451     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1452       return DAG.getUNDEF(VT);
1453 
1454     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1455       visit(CE->getOpcode(), *CE);
1456       SDValue N1 = NodeMap[V];
1457       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1458       return N1;
1459     }
1460 
1461     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1462       SmallVector<SDValue, 4> Constants;
1463       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1464            OI != OE; ++OI) {
1465         SDNode *Val = getValue(*OI).getNode();
1466         // If the operand is an empty aggregate, there are no values.
1467         if (!Val) continue;
1468         // Add each leaf value from the operand to the Constants list
1469         // to form a flattened list of all the values.
1470         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1471           Constants.push_back(SDValue(Val, i));
1472       }
1473 
1474       return DAG.getMergeValues(Constants, getCurSDLoc());
1475     }
1476 
1477     if (const ConstantDataSequential *CDS =
1478           dyn_cast<ConstantDataSequential>(C)) {
1479       SmallVector<SDValue, 4> Ops;
1480       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1481         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1482         // Add each leaf value from the operand to the Constants list
1483         // to form a flattened list of all the values.
1484         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1485           Ops.push_back(SDValue(Val, i));
1486       }
1487 
1488       if (isa<ArrayType>(CDS->getType()))
1489         return DAG.getMergeValues(Ops, getCurSDLoc());
1490       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1491     }
1492 
1493     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1494       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1495              "Unknown struct or array constant!");
1496 
1497       SmallVector<EVT, 4> ValueVTs;
1498       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1499       unsigned NumElts = ValueVTs.size();
1500       if (NumElts == 0)
1501         return SDValue(); // empty struct
1502       SmallVector<SDValue, 4> Constants(NumElts);
1503       for (unsigned i = 0; i != NumElts; ++i) {
1504         EVT EltVT = ValueVTs[i];
1505         if (isa<UndefValue>(C))
1506           Constants[i] = DAG.getUNDEF(EltVT);
1507         else if (EltVT.isFloatingPoint())
1508           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1509         else
1510           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1511       }
1512 
1513       return DAG.getMergeValues(Constants, getCurSDLoc());
1514     }
1515 
1516     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1517       return DAG.getBlockAddress(BA, VT);
1518 
1519     VectorType *VecTy = cast<VectorType>(V->getType());
1520     unsigned NumElements = VecTy->getNumElements();
1521 
1522     // Now that we know the number and type of the elements, get that number of
1523     // elements into the Ops array based on what kind of constant it is.
1524     SmallVector<SDValue, 16> Ops;
1525     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1526       for (unsigned i = 0; i != NumElements; ++i)
1527         Ops.push_back(getValue(CV->getOperand(i)));
1528     } else {
1529       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1530       EVT EltVT =
1531           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1532 
1533       SDValue Op;
1534       if (EltVT.isFloatingPoint())
1535         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1536       else
1537         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1538       Ops.assign(NumElements, Op);
1539     }
1540 
1541     // Create a BUILD_VECTOR node.
1542     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1543   }
1544 
1545   // If this is a static alloca, generate it as the frameindex instead of
1546   // computation.
1547   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1548     DenseMap<const AllocaInst*, int>::iterator SI =
1549       FuncInfo.StaticAllocaMap.find(AI);
1550     if (SI != FuncInfo.StaticAllocaMap.end())
1551       return DAG.getFrameIndex(SI->second,
1552                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1553   }
1554 
1555   // If this is an instruction which fast-isel has deferred, select it now.
1556   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1557     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1558 
1559     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1560                      Inst->getType(), getABIRegCopyCC(V));
1561     SDValue Chain = DAG.getEntryNode();
1562     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1563   }
1564 
1565   llvm_unreachable("Can't get register for value!");
1566 }
1567 
1568 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1569   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1570   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1571   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1572   bool IsSEH = isAsynchronousEHPersonality(Pers);
1573   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1574   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1575   if (!IsSEH)
1576     CatchPadMBB->setIsEHScopeEntry();
1577   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1578   if (IsMSVCCXX || IsCoreCLR)
1579     CatchPadMBB->setIsEHFuncletEntry();
1580   // Wasm does not need catchpads anymore
1581   if (!IsWasmCXX)
1582     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1583                             getControlRoot()));
1584 }
1585 
1586 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1587   // Update machine-CFG edge.
1588   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1589   FuncInfo.MBB->addSuccessor(TargetMBB);
1590 
1591   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1592   bool IsSEH = isAsynchronousEHPersonality(Pers);
1593   if (IsSEH) {
1594     // If this is not a fall-through branch or optimizations are switched off,
1595     // emit the branch.
1596     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1597         TM.getOptLevel() == CodeGenOpt::None)
1598       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1599                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1600     return;
1601   }
1602 
1603   // Figure out the funclet membership for the catchret's successor.
1604   // This will be used by the FuncletLayout pass to determine how to order the
1605   // BB's.
1606   // A 'catchret' returns to the outer scope's color.
1607   Value *ParentPad = I.getCatchSwitchParentPad();
1608   const BasicBlock *SuccessorColor;
1609   if (isa<ConstantTokenNone>(ParentPad))
1610     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1611   else
1612     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1613   assert(SuccessorColor && "No parent funclet for catchret!");
1614   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1615   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1616 
1617   // Create the terminator node.
1618   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1619                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1620                             DAG.getBasicBlock(SuccessorColorMBB));
1621   DAG.setRoot(Ret);
1622 }
1623 
1624 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1625   // Don't emit any special code for the cleanuppad instruction. It just marks
1626   // the start of an EH scope/funclet.
1627   FuncInfo.MBB->setIsEHScopeEntry();
1628   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1629   if (Pers != EHPersonality::Wasm_CXX) {
1630     FuncInfo.MBB->setIsEHFuncletEntry();
1631     FuncInfo.MBB->setIsCleanupFuncletEntry();
1632   }
1633 }
1634 
1635 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1636 // the control flow always stops at the single catch pad, as it does for a
1637 // cleanup pad. In case the exception caught is not of the types the catch pad
1638 // catches, it will be rethrown by a rethrow.
1639 static void findWasmUnwindDestinations(
1640     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1641     BranchProbability Prob,
1642     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1643         &UnwindDests) {
1644   while (EHPadBB) {
1645     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1646     if (isa<CleanupPadInst>(Pad)) {
1647       // Stop on cleanup pads.
1648       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1649       UnwindDests.back().first->setIsEHScopeEntry();
1650       break;
1651     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1652       // Add the catchpad handlers to the possible destinations. We don't
1653       // continue to the unwind destination of the catchswitch for wasm.
1654       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1655         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1656         UnwindDests.back().first->setIsEHScopeEntry();
1657       }
1658       break;
1659     } else {
1660       continue;
1661     }
1662   }
1663 }
1664 
1665 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1666 /// many places it could ultimately go. In the IR, we have a single unwind
1667 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1668 /// This function skips over imaginary basic blocks that hold catchswitch
1669 /// instructions, and finds all the "real" machine
1670 /// basic block destinations. As those destinations may not be successors of
1671 /// EHPadBB, here we also calculate the edge probability to those destinations.
1672 /// The passed-in Prob is the edge probability to EHPadBB.
1673 static void findUnwindDestinations(
1674     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1675     BranchProbability Prob,
1676     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1677         &UnwindDests) {
1678   EHPersonality Personality =
1679     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1680   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1681   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1682   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1683   bool IsSEH = isAsynchronousEHPersonality(Personality);
1684 
1685   if (IsWasmCXX) {
1686     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1687     assert(UnwindDests.size() <= 1 &&
1688            "There should be at most one unwind destination for wasm");
1689     return;
1690   }
1691 
1692   while (EHPadBB) {
1693     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1694     BasicBlock *NewEHPadBB = nullptr;
1695     if (isa<LandingPadInst>(Pad)) {
1696       // Stop on landingpads. They are not funclets.
1697       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1698       break;
1699     } else if (isa<CleanupPadInst>(Pad)) {
1700       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1701       // personalities.
1702       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1703       UnwindDests.back().first->setIsEHScopeEntry();
1704       UnwindDests.back().first->setIsEHFuncletEntry();
1705       break;
1706     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1707       // Add the catchpad handlers to the possible destinations.
1708       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1709         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1710         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1711         if (IsMSVCCXX || IsCoreCLR)
1712           UnwindDests.back().first->setIsEHFuncletEntry();
1713         if (!IsSEH)
1714           UnwindDests.back().first->setIsEHScopeEntry();
1715       }
1716       NewEHPadBB = CatchSwitch->getUnwindDest();
1717     } else {
1718       continue;
1719     }
1720 
1721     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1722     if (BPI && NewEHPadBB)
1723       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1724     EHPadBB = NewEHPadBB;
1725   }
1726 }
1727 
1728 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1729   // Update successor info.
1730   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1731   auto UnwindDest = I.getUnwindDest();
1732   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1733   BranchProbability UnwindDestProb =
1734       (BPI && UnwindDest)
1735           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1736           : BranchProbability::getZero();
1737   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1738   for (auto &UnwindDest : UnwindDests) {
1739     UnwindDest.first->setIsEHPad();
1740     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1741   }
1742   FuncInfo.MBB->normalizeSuccProbs();
1743 
1744   // Create the terminator node.
1745   SDValue Ret =
1746       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1747   DAG.setRoot(Ret);
1748 }
1749 
1750 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1751   report_fatal_error("visitCatchSwitch not yet implemented!");
1752 }
1753 
1754 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1756   auto &DL = DAG.getDataLayout();
1757   SDValue Chain = getControlRoot();
1758   SmallVector<ISD::OutputArg, 8> Outs;
1759   SmallVector<SDValue, 8> OutVals;
1760 
1761   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1762   // lower
1763   //
1764   //   %val = call <ty> @llvm.experimental.deoptimize()
1765   //   ret <ty> %val
1766   //
1767   // differently.
1768   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1769     LowerDeoptimizingReturn();
1770     return;
1771   }
1772 
1773   if (!FuncInfo.CanLowerReturn) {
1774     unsigned DemoteReg = FuncInfo.DemoteRegister;
1775     const Function *F = I.getParent()->getParent();
1776 
1777     // Emit a store of the return value through the virtual register.
1778     // Leave Outs empty so that LowerReturn won't try to load return
1779     // registers the usual way.
1780     SmallVector<EVT, 1> PtrValueVTs;
1781     ComputeValueVTs(TLI, DL,
1782                     F->getReturnType()->getPointerTo(
1783                         DAG.getDataLayout().getAllocaAddrSpace()),
1784                     PtrValueVTs);
1785 
1786     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1787                                         DemoteReg, PtrValueVTs[0]);
1788     SDValue RetOp = getValue(I.getOperand(0));
1789 
1790     SmallVector<EVT, 4> ValueVTs;
1791     SmallVector<uint64_t, 4> Offsets;
1792     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1793     unsigned NumValues = ValueVTs.size();
1794 
1795     SmallVector<SDValue, 4> Chains(NumValues);
1796     for (unsigned i = 0; i != NumValues; ++i) {
1797       // An aggregate return value cannot wrap around the address space, so
1798       // offsets to its parts don't wrap either.
1799       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1800       Chains[i] = DAG.getStore(
1801           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1802           // FIXME: better loc info would be nice.
1803           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1804     }
1805 
1806     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1807                         MVT::Other, Chains);
1808   } else if (I.getNumOperands() != 0) {
1809     SmallVector<EVT, 4> ValueVTs;
1810     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1811     unsigned NumValues = ValueVTs.size();
1812     if (NumValues) {
1813       SDValue RetOp = getValue(I.getOperand(0));
1814 
1815       const Function *F = I.getParent()->getParent();
1816 
1817       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1818       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1819                                           Attribute::SExt))
1820         ExtendKind = ISD::SIGN_EXTEND;
1821       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1822                                                Attribute::ZExt))
1823         ExtendKind = ISD::ZERO_EXTEND;
1824 
1825       LLVMContext &Context = F->getContext();
1826       bool RetInReg = F->getAttributes().hasAttribute(
1827           AttributeList::ReturnIndex, Attribute::InReg);
1828 
1829       for (unsigned j = 0; j != NumValues; ++j) {
1830         EVT VT = ValueVTs[j];
1831 
1832         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1833           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1834 
1835         CallingConv::ID CC = F->getCallingConv();
1836 
1837         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1838         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1839         SmallVector<SDValue, 4> Parts(NumParts);
1840         getCopyToParts(DAG, getCurSDLoc(),
1841                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1842                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1843 
1844         // 'inreg' on function refers to return value
1845         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1846         if (RetInReg)
1847           Flags.setInReg();
1848 
1849         // Propagate extension type if any
1850         if (ExtendKind == ISD::SIGN_EXTEND)
1851           Flags.setSExt();
1852         else if (ExtendKind == ISD::ZERO_EXTEND)
1853           Flags.setZExt();
1854 
1855         for (unsigned i = 0; i < NumParts; ++i) {
1856           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1857                                         VT, /*isfixed=*/true, 0, 0));
1858           OutVals.push_back(Parts[i]);
1859         }
1860       }
1861     }
1862   }
1863 
1864   // Push in swifterror virtual register as the last element of Outs. This makes
1865   // sure swifterror virtual register will be returned in the swifterror
1866   // physical register.
1867   const Function *F = I.getParent()->getParent();
1868   if (TLI.supportSwiftError() &&
1869       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1870     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1871     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1872     Flags.setSwiftError();
1873     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1874                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1875                                   true /*isfixed*/, 1 /*origidx*/,
1876                                   0 /*partOffs*/));
1877     // Create SDNode for the swifterror virtual register.
1878     OutVals.push_back(
1879         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1880                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1881                         EVT(TLI.getPointerTy(DL))));
1882   }
1883 
1884   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1885   CallingConv::ID CallConv =
1886     DAG.getMachineFunction().getFunction().getCallingConv();
1887   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1888       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1889 
1890   // Verify that the target's LowerReturn behaved as expected.
1891   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1892          "LowerReturn didn't return a valid chain!");
1893 
1894   // Update the DAG with the new chain value resulting from return lowering.
1895   DAG.setRoot(Chain);
1896 }
1897 
1898 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1899 /// created for it, emit nodes to copy the value into the virtual
1900 /// registers.
1901 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1902   // Skip empty types
1903   if (V->getType()->isEmptyTy())
1904     return;
1905 
1906   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1907   if (VMI != FuncInfo.ValueMap.end()) {
1908     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1909     CopyValueToVirtualRegister(V, VMI->second);
1910   }
1911 }
1912 
1913 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1914 /// the current basic block, add it to ValueMap now so that we'll get a
1915 /// CopyTo/FromReg.
1916 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1917   // No need to export constants.
1918   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1919 
1920   // Already exported?
1921   if (FuncInfo.isExportedInst(V)) return;
1922 
1923   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1924   CopyValueToVirtualRegister(V, Reg);
1925 }
1926 
1927 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1928                                                      const BasicBlock *FromBB) {
1929   // The operands of the setcc have to be in this block.  We don't know
1930   // how to export them from some other block.
1931   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1932     // Can export from current BB.
1933     if (VI->getParent() == FromBB)
1934       return true;
1935 
1936     // Is already exported, noop.
1937     return FuncInfo.isExportedInst(V);
1938   }
1939 
1940   // If this is an argument, we can export it if the BB is the entry block or
1941   // if it is already exported.
1942   if (isa<Argument>(V)) {
1943     if (FromBB == &FromBB->getParent()->getEntryBlock())
1944       return true;
1945 
1946     // Otherwise, can only export this if it is already exported.
1947     return FuncInfo.isExportedInst(V);
1948   }
1949 
1950   // Otherwise, constants can always be exported.
1951   return true;
1952 }
1953 
1954 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1955 BranchProbability
1956 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1957                                         const MachineBasicBlock *Dst) const {
1958   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1959   const BasicBlock *SrcBB = Src->getBasicBlock();
1960   const BasicBlock *DstBB = Dst->getBasicBlock();
1961   if (!BPI) {
1962     // If BPI is not available, set the default probability as 1 / N, where N is
1963     // the number of successors.
1964     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1965     return BranchProbability(1, SuccSize);
1966   }
1967   return BPI->getEdgeProbability(SrcBB, DstBB);
1968 }
1969 
1970 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1971                                                MachineBasicBlock *Dst,
1972                                                BranchProbability Prob) {
1973   if (!FuncInfo.BPI)
1974     Src->addSuccessorWithoutProb(Dst);
1975   else {
1976     if (Prob.isUnknown())
1977       Prob = getEdgeProbability(Src, Dst);
1978     Src->addSuccessor(Dst, Prob);
1979   }
1980 }
1981 
1982 static bool InBlock(const Value *V, const BasicBlock *BB) {
1983   if (const Instruction *I = dyn_cast<Instruction>(V))
1984     return I->getParent() == BB;
1985   return true;
1986 }
1987 
1988 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1989 /// This function emits a branch and is used at the leaves of an OR or an
1990 /// AND operator tree.
1991 void
1992 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1993                                                   MachineBasicBlock *TBB,
1994                                                   MachineBasicBlock *FBB,
1995                                                   MachineBasicBlock *CurBB,
1996                                                   MachineBasicBlock *SwitchBB,
1997                                                   BranchProbability TProb,
1998                                                   BranchProbability FProb,
1999                                                   bool InvertCond) {
2000   const BasicBlock *BB = CurBB->getBasicBlock();
2001 
2002   // If the leaf of the tree is a comparison, merge the condition into
2003   // the caseblock.
2004   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2005     // The operands of the cmp have to be in this block.  We don't know
2006     // how to export them from some other block.  If this is the first block
2007     // of the sequence, no exporting is needed.
2008     if (CurBB == SwitchBB ||
2009         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2010          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2011       ISD::CondCode Condition;
2012       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2013         ICmpInst::Predicate Pred =
2014             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2015         Condition = getICmpCondCode(Pred);
2016       } else {
2017         const FCmpInst *FC = cast<FCmpInst>(Cond);
2018         FCmpInst::Predicate Pred =
2019             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2020         Condition = getFCmpCondCode(Pred);
2021         if (TM.Options.NoNaNsFPMath)
2022           Condition = getFCmpCodeWithoutNaN(Condition);
2023       }
2024 
2025       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2026                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2027       SwitchCases.push_back(CB);
2028       return;
2029     }
2030   }
2031 
2032   // Create a CaseBlock record representing this branch.
2033   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2034   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2035                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2036   SwitchCases.push_back(CB);
2037 }
2038 
2039 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2040                                                MachineBasicBlock *TBB,
2041                                                MachineBasicBlock *FBB,
2042                                                MachineBasicBlock *CurBB,
2043                                                MachineBasicBlock *SwitchBB,
2044                                                Instruction::BinaryOps Opc,
2045                                                BranchProbability TProb,
2046                                                BranchProbability FProb,
2047                                                bool InvertCond) {
2048   // Skip over not part of the tree and remember to invert op and operands at
2049   // next level.
2050   Value *NotCond;
2051   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2052       InBlock(NotCond, CurBB->getBasicBlock())) {
2053     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2054                          !InvertCond);
2055     return;
2056   }
2057 
2058   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2059   // Compute the effective opcode for Cond, taking into account whether it needs
2060   // to be inverted, e.g.
2061   //   and (not (or A, B)), C
2062   // gets lowered as
2063   //   and (and (not A, not B), C)
2064   unsigned BOpc = 0;
2065   if (BOp) {
2066     BOpc = BOp->getOpcode();
2067     if (InvertCond) {
2068       if (BOpc == Instruction::And)
2069         BOpc = Instruction::Or;
2070       else if (BOpc == Instruction::Or)
2071         BOpc = Instruction::And;
2072     }
2073   }
2074 
2075   // If this node is not part of the or/and tree, emit it as a branch.
2076   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2077       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2078       BOp->getParent() != CurBB->getBasicBlock() ||
2079       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2080       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2081     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2082                                  TProb, FProb, InvertCond);
2083     return;
2084   }
2085 
2086   //  Create TmpBB after CurBB.
2087   MachineFunction::iterator BBI(CurBB);
2088   MachineFunction &MF = DAG.getMachineFunction();
2089   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2090   CurBB->getParent()->insert(++BBI, TmpBB);
2091 
2092   if (Opc == Instruction::Or) {
2093     // Codegen X | Y as:
2094     // BB1:
2095     //   jmp_if_X TBB
2096     //   jmp TmpBB
2097     // TmpBB:
2098     //   jmp_if_Y TBB
2099     //   jmp FBB
2100     //
2101 
2102     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2103     // The requirement is that
2104     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2105     //     = TrueProb for original BB.
2106     // Assuming the original probabilities are A and B, one choice is to set
2107     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2108     // A/(1+B) and 2B/(1+B). This choice assumes that
2109     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2110     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2111     // TmpBB, but the math is more complicated.
2112 
2113     auto NewTrueProb = TProb / 2;
2114     auto NewFalseProb = TProb / 2 + FProb;
2115     // Emit the LHS condition.
2116     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2117                          NewTrueProb, NewFalseProb, InvertCond);
2118 
2119     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2120     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2121     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2122     // Emit the RHS condition into TmpBB.
2123     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2124                          Probs[0], Probs[1], InvertCond);
2125   } else {
2126     assert(Opc == Instruction::And && "Unknown merge op!");
2127     // Codegen X & Y as:
2128     // BB1:
2129     //   jmp_if_X TmpBB
2130     //   jmp FBB
2131     // TmpBB:
2132     //   jmp_if_Y TBB
2133     //   jmp FBB
2134     //
2135     //  This requires creation of TmpBB after CurBB.
2136 
2137     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2138     // The requirement is that
2139     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2140     //     = FalseProb for original BB.
2141     // Assuming the original probabilities are A and B, one choice is to set
2142     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2143     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2144     // TrueProb for BB1 * FalseProb for TmpBB.
2145 
2146     auto NewTrueProb = TProb + FProb / 2;
2147     auto NewFalseProb = FProb / 2;
2148     // Emit the LHS condition.
2149     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2150                          NewTrueProb, NewFalseProb, InvertCond);
2151 
2152     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2153     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2154     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2155     // Emit the RHS condition into TmpBB.
2156     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2157                          Probs[0], Probs[1], InvertCond);
2158   }
2159 }
2160 
2161 /// If the set of cases should be emitted as a series of branches, return true.
2162 /// If we should emit this as a bunch of and/or'd together conditions, return
2163 /// false.
2164 bool
2165 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2166   if (Cases.size() != 2) return true;
2167 
2168   // If this is two comparisons of the same values or'd or and'd together, they
2169   // will get folded into a single comparison, so don't emit two blocks.
2170   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2171        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2172       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2173        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2174     return false;
2175   }
2176 
2177   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2178   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2179   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2180       Cases[0].CC == Cases[1].CC &&
2181       isa<Constant>(Cases[0].CmpRHS) &&
2182       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2183     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2184       return false;
2185     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2186       return false;
2187   }
2188 
2189   return true;
2190 }
2191 
2192 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2193   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2194 
2195   // Update machine-CFG edges.
2196   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2197 
2198   if (I.isUnconditional()) {
2199     // Update machine-CFG edges.
2200     BrMBB->addSuccessor(Succ0MBB);
2201 
2202     // If this is not a fall-through branch or optimizations are switched off,
2203     // emit the branch.
2204     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2205       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2206                               MVT::Other, getControlRoot(),
2207                               DAG.getBasicBlock(Succ0MBB)));
2208 
2209     return;
2210   }
2211 
2212   // If this condition is one of the special cases we handle, do special stuff
2213   // now.
2214   const Value *CondVal = I.getCondition();
2215   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2216 
2217   // If this is a series of conditions that are or'd or and'd together, emit
2218   // this as a sequence of branches instead of setcc's with and/or operations.
2219   // As long as jumps are not expensive, this should improve performance.
2220   // For example, instead of something like:
2221   //     cmp A, B
2222   //     C = seteq
2223   //     cmp D, E
2224   //     F = setle
2225   //     or C, F
2226   //     jnz foo
2227   // Emit:
2228   //     cmp A, B
2229   //     je foo
2230   //     cmp D, E
2231   //     jle foo
2232   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2233     Instruction::BinaryOps Opcode = BOp->getOpcode();
2234     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2235         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2236         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2237       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2238                            Opcode,
2239                            getEdgeProbability(BrMBB, Succ0MBB),
2240                            getEdgeProbability(BrMBB, Succ1MBB),
2241                            /*InvertCond=*/false);
2242       // If the compares in later blocks need to use values not currently
2243       // exported from this block, export them now.  This block should always
2244       // be the first entry.
2245       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2246 
2247       // Allow some cases to be rejected.
2248       if (ShouldEmitAsBranches(SwitchCases)) {
2249         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2250           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2251           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2252         }
2253 
2254         // Emit the branch for this block.
2255         visitSwitchCase(SwitchCases[0], BrMBB);
2256         SwitchCases.erase(SwitchCases.begin());
2257         return;
2258       }
2259 
2260       // Okay, we decided not to do this, remove any inserted MBB's and clear
2261       // SwitchCases.
2262       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2263         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2264 
2265       SwitchCases.clear();
2266     }
2267   }
2268 
2269   // Create a CaseBlock record representing this branch.
2270   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2271                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2272 
2273   // Use visitSwitchCase to actually insert the fast branch sequence for this
2274   // cond branch.
2275   visitSwitchCase(CB, BrMBB);
2276 }
2277 
2278 /// visitSwitchCase - Emits the necessary code to represent a single node in
2279 /// the binary search tree resulting from lowering a switch instruction.
2280 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2281                                           MachineBasicBlock *SwitchBB) {
2282   SDValue Cond;
2283   SDValue CondLHS = getValue(CB.CmpLHS);
2284   SDLoc dl = CB.DL;
2285 
2286   // Build the setcc now.
2287   if (!CB.CmpMHS) {
2288     // Fold "(X == true)" to X and "(X == false)" to !X to
2289     // handle common cases produced by branch lowering.
2290     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2291         CB.CC == ISD::SETEQ)
2292       Cond = CondLHS;
2293     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2294              CB.CC == ISD::SETEQ) {
2295       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2296       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2297     } else
2298       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2299   } else {
2300     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2301 
2302     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2303     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2304 
2305     SDValue CmpOp = getValue(CB.CmpMHS);
2306     EVT VT = CmpOp.getValueType();
2307 
2308     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2309       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2310                           ISD::SETLE);
2311     } else {
2312       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2313                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2314       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2315                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2316     }
2317   }
2318 
2319   // Update successor info
2320   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2321   // TrueBB and FalseBB are always different unless the incoming IR is
2322   // degenerate. This only happens when running llc on weird IR.
2323   if (CB.TrueBB != CB.FalseBB)
2324     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2325   SwitchBB->normalizeSuccProbs();
2326 
2327   // If the lhs block is the next block, invert the condition so that we can
2328   // fall through to the lhs instead of the rhs block.
2329   if (CB.TrueBB == NextBlock(SwitchBB)) {
2330     std::swap(CB.TrueBB, CB.FalseBB);
2331     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2332     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2333   }
2334 
2335   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2336                                MVT::Other, getControlRoot(), Cond,
2337                                DAG.getBasicBlock(CB.TrueBB));
2338 
2339   // Insert the false branch. Do this even if it's a fall through branch,
2340   // this makes it easier to do DAG optimizations which require inverting
2341   // the branch condition.
2342   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2343                        DAG.getBasicBlock(CB.FalseBB));
2344 
2345   DAG.setRoot(BrCond);
2346 }
2347 
2348 /// visitJumpTable - Emit JumpTable node in the current MBB
2349 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2350   // Emit the code for the jump table
2351   assert(JT.Reg != -1U && "Should lower JT Header first!");
2352   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2353   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2354                                      JT.Reg, PTy);
2355   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2356   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2357                                     MVT::Other, Index.getValue(1),
2358                                     Table, Index);
2359   DAG.setRoot(BrJumpTable);
2360 }
2361 
2362 /// visitJumpTableHeader - This function emits necessary code to produce index
2363 /// in the JumpTable from switch case.
2364 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2365                                                JumpTableHeader &JTH,
2366                                                MachineBasicBlock *SwitchBB) {
2367   SDLoc dl = getCurSDLoc();
2368 
2369   // Subtract the lowest switch case value from the value being switched on and
2370   // conditional branch to default mbb if the result is greater than the
2371   // difference between smallest and largest cases.
2372   SDValue SwitchOp = getValue(JTH.SValue);
2373   EVT VT = SwitchOp.getValueType();
2374   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2375                             DAG.getConstant(JTH.First, dl, VT));
2376 
2377   // The SDNode we just created, which holds the value being switched on minus
2378   // the smallest case value, needs to be copied to a virtual register so it
2379   // can be used as an index into the jump table in a subsequent basic block.
2380   // This value may be smaller or larger than the target's pointer type, and
2381   // therefore require extension or truncating.
2382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2383   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2384 
2385   unsigned JumpTableReg =
2386       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2387   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2388                                     JumpTableReg, SwitchOp);
2389   JT.Reg = JumpTableReg;
2390 
2391   // Emit the range check for the jump table, and branch to the default block
2392   // for the switch statement if the value being switched on exceeds the largest
2393   // case in the switch.
2394   SDValue CMP = DAG.getSetCC(
2395       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2396                                  Sub.getValueType()),
2397       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2398 
2399   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2400                                MVT::Other, CopyTo, CMP,
2401                                DAG.getBasicBlock(JT.Default));
2402 
2403   // Avoid emitting unnecessary branches to the next block.
2404   if (JT.MBB != NextBlock(SwitchBB))
2405     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2406                          DAG.getBasicBlock(JT.MBB));
2407 
2408   DAG.setRoot(BrCond);
2409 }
2410 
2411 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2412 /// variable if there exists one.
2413 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2414                                  SDValue &Chain) {
2415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2416   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2417   MachineFunction &MF = DAG.getMachineFunction();
2418   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2419   MachineSDNode *Node =
2420       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2421   if (Global) {
2422     MachinePointerInfo MPInfo(Global);
2423     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2424                  MachineMemOperand::MODereferenceable;
2425     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2426         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2427     DAG.setNodeMemRefs(Node, {MemRef});
2428   }
2429   return SDValue(Node, 0);
2430 }
2431 
2432 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2433 /// tail spliced into a stack protector check success bb.
2434 ///
2435 /// For a high level explanation of how this fits into the stack protector
2436 /// generation see the comment on the declaration of class
2437 /// StackProtectorDescriptor.
2438 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2439                                                   MachineBasicBlock *ParentBB) {
2440 
2441   // First create the loads to the guard/stack slot for the comparison.
2442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2443   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2444 
2445   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2446   int FI = MFI.getStackProtectorIndex();
2447 
2448   SDValue Guard;
2449   SDLoc dl = getCurSDLoc();
2450   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2451   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2452   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2453 
2454   // Generate code to load the content of the guard slot.
2455   SDValue GuardVal = DAG.getLoad(
2456       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2457       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2458       MachineMemOperand::MOVolatile);
2459 
2460   if (TLI.useStackGuardXorFP())
2461     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2462 
2463   // Retrieve guard check function, nullptr if instrumentation is inlined.
2464   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2465     // The target provides a guard check function to validate the guard value.
2466     // Generate a call to that function with the content of the guard slot as
2467     // argument.
2468     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2469     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2470 
2471     TargetLowering::ArgListTy Args;
2472     TargetLowering::ArgListEntry Entry;
2473     Entry.Node = GuardVal;
2474     Entry.Ty = FnTy->getParamType(0);
2475     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2476       Entry.IsInReg = true;
2477     Args.push_back(Entry);
2478 
2479     TargetLowering::CallLoweringInfo CLI(DAG);
2480     CLI.setDebugLoc(getCurSDLoc())
2481         .setChain(DAG.getEntryNode())
2482         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2483                    getValue(GuardCheckFn), std::move(Args));
2484 
2485     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2486     DAG.setRoot(Result.second);
2487     return;
2488   }
2489 
2490   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2491   // Otherwise, emit a volatile load to retrieve the stack guard value.
2492   SDValue Chain = DAG.getEntryNode();
2493   if (TLI.useLoadStackGuardNode()) {
2494     Guard = getLoadStackGuard(DAG, dl, Chain);
2495   } else {
2496     const Value *IRGuard = TLI.getSDagStackGuard(M);
2497     SDValue GuardPtr = getValue(IRGuard);
2498 
2499     Guard =
2500         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2501                     Align, MachineMemOperand::MOVolatile);
2502   }
2503 
2504   // Perform the comparison via a subtract/getsetcc.
2505   EVT VT = Guard.getValueType();
2506   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2507 
2508   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2509                                                         *DAG.getContext(),
2510                                                         Sub.getValueType()),
2511                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2512 
2513   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2514   // branch to failure MBB.
2515   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2516                                MVT::Other, GuardVal.getOperand(0),
2517                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2518   // Otherwise branch to success MBB.
2519   SDValue Br = DAG.getNode(ISD::BR, dl,
2520                            MVT::Other, BrCond,
2521                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2522 
2523   DAG.setRoot(Br);
2524 }
2525 
2526 /// Codegen the failure basic block for a stack protector check.
2527 ///
2528 /// A failure stack protector machine basic block consists simply of a call to
2529 /// __stack_chk_fail().
2530 ///
2531 /// For a high level explanation of how this fits into the stack protector
2532 /// generation see the comment on the declaration of class
2533 /// StackProtectorDescriptor.
2534 void
2535 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2537   SDValue Chain =
2538       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2539                       None, false, getCurSDLoc(), false, false).second;
2540   // On PS4, the "return address" must still be within the calling function,
2541   // even if it's at the very end, so emit an explicit TRAP here.
2542   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2543   if (TM.getTargetTriple().isPS4CPU())
2544     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2545 
2546   DAG.setRoot(Chain);
2547 }
2548 
2549 /// visitBitTestHeader - This function emits necessary code to produce value
2550 /// suitable for "bit tests"
2551 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2552                                              MachineBasicBlock *SwitchBB) {
2553   SDLoc dl = getCurSDLoc();
2554 
2555   // Subtract the minimum value
2556   SDValue SwitchOp = getValue(B.SValue);
2557   EVT VT = SwitchOp.getValueType();
2558   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2559                             DAG.getConstant(B.First, dl, VT));
2560 
2561   // Check range
2562   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2563   SDValue RangeCmp = DAG.getSetCC(
2564       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2565                                  Sub.getValueType()),
2566       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2567 
2568   // Determine the type of the test operands.
2569   bool UsePtrType = false;
2570   if (!TLI.isTypeLegal(VT))
2571     UsePtrType = true;
2572   else {
2573     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2574       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2575         // Switch table case range are encoded into series of masks.
2576         // Just use pointer type, it's guaranteed to fit.
2577         UsePtrType = true;
2578         break;
2579       }
2580   }
2581   if (UsePtrType) {
2582     VT = TLI.getPointerTy(DAG.getDataLayout());
2583     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2584   }
2585 
2586   B.RegVT = VT.getSimpleVT();
2587   B.Reg = FuncInfo.CreateReg(B.RegVT);
2588   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2589 
2590   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2591 
2592   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2593   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2594   SwitchBB->normalizeSuccProbs();
2595 
2596   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2597                                 MVT::Other, CopyTo, RangeCmp,
2598                                 DAG.getBasicBlock(B.Default));
2599 
2600   // Avoid emitting unnecessary branches to the next block.
2601   if (MBB != NextBlock(SwitchBB))
2602     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2603                           DAG.getBasicBlock(MBB));
2604 
2605   DAG.setRoot(BrRange);
2606 }
2607 
2608 /// visitBitTestCase - this function produces one "bit test"
2609 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2610                                            MachineBasicBlock* NextMBB,
2611                                            BranchProbability BranchProbToNext,
2612                                            unsigned Reg,
2613                                            BitTestCase &B,
2614                                            MachineBasicBlock *SwitchBB) {
2615   SDLoc dl = getCurSDLoc();
2616   MVT VT = BB.RegVT;
2617   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2618   SDValue Cmp;
2619   unsigned PopCount = countPopulation(B.Mask);
2620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2621   if (PopCount == 1) {
2622     // Testing for a single bit; just compare the shift count with what it
2623     // would need to be to shift a 1 bit in that position.
2624     Cmp = DAG.getSetCC(
2625         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2626         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2627         ISD::SETEQ);
2628   } else if (PopCount == BB.Range) {
2629     // There is only one zero bit in the range, test for it directly.
2630     Cmp = DAG.getSetCC(
2631         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2632         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2633         ISD::SETNE);
2634   } else {
2635     // Make desired shift
2636     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2637                                     DAG.getConstant(1, dl, VT), ShiftOp);
2638 
2639     // Emit bit tests and jumps
2640     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2641                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2642     Cmp = DAG.getSetCC(
2643         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2644         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2645   }
2646 
2647   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2648   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2649   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2650   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2651   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2652   // one as they are relative probabilities (and thus work more like weights),
2653   // and hence we need to normalize them to let the sum of them become one.
2654   SwitchBB->normalizeSuccProbs();
2655 
2656   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2657                               MVT::Other, getControlRoot(),
2658                               Cmp, DAG.getBasicBlock(B.TargetBB));
2659 
2660   // Avoid emitting unnecessary branches to the next block.
2661   if (NextMBB != NextBlock(SwitchBB))
2662     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2663                         DAG.getBasicBlock(NextMBB));
2664 
2665   DAG.setRoot(BrAnd);
2666 }
2667 
2668 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2669   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2670 
2671   // Retrieve successors. Look through artificial IR level blocks like
2672   // catchswitch for successors.
2673   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2674   const BasicBlock *EHPadBB = I.getSuccessor(1);
2675 
2676   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2677   // have to do anything here to lower funclet bundles.
2678   assert(!I.hasOperandBundlesOtherThan(
2679              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2680          "Cannot lower invokes with arbitrary operand bundles yet!");
2681 
2682   const Value *Callee(I.getCalledValue());
2683   const Function *Fn = dyn_cast<Function>(Callee);
2684   if (isa<InlineAsm>(Callee))
2685     visitInlineAsm(&I);
2686   else if (Fn && Fn->isIntrinsic()) {
2687     switch (Fn->getIntrinsicID()) {
2688     default:
2689       llvm_unreachable("Cannot invoke this intrinsic");
2690     case Intrinsic::donothing:
2691       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2692       break;
2693     case Intrinsic::experimental_patchpoint_void:
2694     case Intrinsic::experimental_patchpoint_i64:
2695       visitPatchpoint(&I, EHPadBB);
2696       break;
2697     case Intrinsic::experimental_gc_statepoint:
2698       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2699       break;
2700     case Intrinsic::wasm_rethrow_in_catch: {
2701       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2702       // special because it can be invoked, so we manually lower it to a DAG
2703       // node here.
2704       SmallVector<SDValue, 8> Ops;
2705       Ops.push_back(getRoot()); // inchain
2706       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2707       Ops.push_back(
2708           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2709                                 TLI.getPointerTy(DAG.getDataLayout())));
2710       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2711       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2712       break;
2713     }
2714     }
2715   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2716     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2717     // Eventually we will support lowering the @llvm.experimental.deoptimize
2718     // intrinsic, and right now there are no plans to support other intrinsics
2719     // with deopt state.
2720     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2721   } else {
2722     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2723   }
2724 
2725   // If the value of the invoke is used outside of its defining block, make it
2726   // available as a virtual register.
2727   // We already took care of the exported value for the statepoint instruction
2728   // during call to the LowerStatepoint.
2729   if (!isStatepoint(I)) {
2730     CopyToExportRegsIfNeeded(&I);
2731   }
2732 
2733   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2734   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2735   BranchProbability EHPadBBProb =
2736       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2737           : BranchProbability::getZero();
2738   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2739 
2740   // Update successor info.
2741   addSuccessorWithProb(InvokeMBB, Return);
2742   for (auto &UnwindDest : UnwindDests) {
2743     UnwindDest.first->setIsEHPad();
2744     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2745   }
2746   InvokeMBB->normalizeSuccProbs();
2747 
2748   // Drop into normal successor.
2749   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2750                           DAG.getBasicBlock(Return)));
2751 }
2752 
2753 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2754   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2755 
2756   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2757   // have to do anything here to lower funclet bundles.
2758   assert(!I.hasOperandBundlesOtherThan(
2759              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2760          "Cannot lower callbrs with arbitrary operand bundles yet!");
2761 
2762   assert(isa<InlineAsm>(I.getCalledValue()) &&
2763          "Only know how to handle inlineasm callbr");
2764   visitInlineAsm(&I);
2765 
2766   // Retrieve successors.
2767   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2768 
2769   // Update successor info.
2770   addSuccessorWithProb(CallBrMBB, Return);
2771   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2772     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2773     addSuccessorWithProb(CallBrMBB, Target);
2774   }
2775   CallBrMBB->normalizeSuccProbs();
2776 
2777   // Drop into default successor.
2778   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2779                           MVT::Other, getControlRoot(),
2780                           DAG.getBasicBlock(Return)));
2781 }
2782 
2783 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2784   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2785 }
2786 
2787 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2788   assert(FuncInfo.MBB->isEHPad() &&
2789          "Call to landingpad not in landing pad!");
2790 
2791   // If there aren't registers to copy the values into (e.g., during SjLj
2792   // exceptions), then don't bother to create these DAG nodes.
2793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2794   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2795   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2796       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2797     return;
2798 
2799   // If landingpad's return type is token type, we don't create DAG nodes
2800   // for its exception pointer and selector value. The extraction of exception
2801   // pointer or selector value from token type landingpads is not currently
2802   // supported.
2803   if (LP.getType()->isTokenTy())
2804     return;
2805 
2806   SmallVector<EVT, 2> ValueVTs;
2807   SDLoc dl = getCurSDLoc();
2808   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2809   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2810 
2811   // Get the two live-in registers as SDValues. The physregs have already been
2812   // copied into virtual registers.
2813   SDValue Ops[2];
2814   if (FuncInfo.ExceptionPointerVirtReg) {
2815     Ops[0] = DAG.getZExtOrTrunc(
2816         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2817                            FuncInfo.ExceptionPointerVirtReg,
2818                            TLI.getPointerTy(DAG.getDataLayout())),
2819         dl, ValueVTs[0]);
2820   } else {
2821     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2822   }
2823   Ops[1] = DAG.getZExtOrTrunc(
2824       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2825                          FuncInfo.ExceptionSelectorVirtReg,
2826                          TLI.getPointerTy(DAG.getDataLayout())),
2827       dl, ValueVTs[1]);
2828 
2829   // Merge into one.
2830   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2831                             DAG.getVTList(ValueVTs), Ops);
2832   setValue(&LP, Res);
2833 }
2834 
2835 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2836 #ifndef NDEBUG
2837   for (const CaseCluster &CC : Clusters)
2838     assert(CC.Low == CC.High && "Input clusters must be single-case");
2839 #endif
2840 
2841   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2842     return a.Low->getValue().slt(b.Low->getValue());
2843   });
2844 
2845   // Merge adjacent clusters with the same destination.
2846   const unsigned N = Clusters.size();
2847   unsigned DstIndex = 0;
2848   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2849     CaseCluster &CC = Clusters[SrcIndex];
2850     const ConstantInt *CaseVal = CC.Low;
2851     MachineBasicBlock *Succ = CC.MBB;
2852 
2853     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2854         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2855       // If this case has the same successor and is a neighbour, merge it into
2856       // the previous cluster.
2857       Clusters[DstIndex - 1].High = CaseVal;
2858       Clusters[DstIndex - 1].Prob += CC.Prob;
2859     } else {
2860       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2861                    sizeof(Clusters[SrcIndex]));
2862     }
2863   }
2864   Clusters.resize(DstIndex);
2865 }
2866 
2867 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2868                                            MachineBasicBlock *Last) {
2869   // Update JTCases.
2870   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2871     if (JTCases[i].first.HeaderBB == First)
2872       JTCases[i].first.HeaderBB = Last;
2873 
2874   // Update BitTestCases.
2875   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2876     if (BitTestCases[i].Parent == First)
2877       BitTestCases[i].Parent = Last;
2878 }
2879 
2880 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2881   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2882 
2883   // Update machine-CFG edges with unique successors.
2884   SmallSet<BasicBlock*, 32> Done;
2885   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2886     BasicBlock *BB = I.getSuccessor(i);
2887     bool Inserted = Done.insert(BB).second;
2888     if (!Inserted)
2889         continue;
2890 
2891     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2892     addSuccessorWithProb(IndirectBrMBB, Succ);
2893   }
2894   IndirectBrMBB->normalizeSuccProbs();
2895 
2896   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2897                           MVT::Other, getControlRoot(),
2898                           getValue(I.getAddress())));
2899 }
2900 
2901 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2902   if (!DAG.getTarget().Options.TrapUnreachable)
2903     return;
2904 
2905   // We may be able to ignore unreachable behind a noreturn call.
2906   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2907     const BasicBlock &BB = *I.getParent();
2908     if (&I != &BB.front()) {
2909       BasicBlock::const_iterator PredI =
2910         std::prev(BasicBlock::const_iterator(&I));
2911       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2912         if (Call->doesNotReturn())
2913           return;
2914       }
2915     }
2916   }
2917 
2918   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2919 }
2920 
2921 void SelectionDAGBuilder::visitFSub(const User &I) {
2922   // -0.0 - X --> fneg
2923   Type *Ty = I.getType();
2924   if (isa<Constant>(I.getOperand(0)) &&
2925       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2926     SDValue Op2 = getValue(I.getOperand(1));
2927     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2928                              Op2.getValueType(), Op2));
2929     return;
2930   }
2931 
2932   visitBinary(I, ISD::FSUB);
2933 }
2934 
2935 /// Checks if the given instruction performs a vector reduction, in which case
2936 /// we have the freedom to alter the elements in the result as long as the
2937 /// reduction of them stays unchanged.
2938 static bool isVectorReductionOp(const User *I) {
2939   const Instruction *Inst = dyn_cast<Instruction>(I);
2940   if (!Inst || !Inst->getType()->isVectorTy())
2941     return false;
2942 
2943   auto OpCode = Inst->getOpcode();
2944   switch (OpCode) {
2945   case Instruction::Add:
2946   case Instruction::Mul:
2947   case Instruction::And:
2948   case Instruction::Or:
2949   case Instruction::Xor:
2950     break;
2951   case Instruction::FAdd:
2952   case Instruction::FMul:
2953     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2954       if (FPOp->getFastMathFlags().isFast())
2955         break;
2956     LLVM_FALLTHROUGH;
2957   default:
2958     return false;
2959   }
2960 
2961   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2962   // Ensure the reduction size is a power of 2.
2963   if (!isPowerOf2_32(ElemNum))
2964     return false;
2965 
2966   unsigned ElemNumToReduce = ElemNum;
2967 
2968   // Do DFS search on the def-use chain from the given instruction. We only
2969   // allow four kinds of operations during the search until we reach the
2970   // instruction that extracts the first element from the vector:
2971   //
2972   //   1. The reduction operation of the same opcode as the given instruction.
2973   //
2974   //   2. PHI node.
2975   //
2976   //   3. ShuffleVector instruction together with a reduction operation that
2977   //      does a partial reduction.
2978   //
2979   //   4. ExtractElement that extracts the first element from the vector, and we
2980   //      stop searching the def-use chain here.
2981   //
2982   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2983   // from 1-3 to the stack to continue the DFS. The given instruction is not
2984   // a reduction operation if we meet any other instructions other than those
2985   // listed above.
2986 
2987   SmallVector<const User *, 16> UsersToVisit{Inst};
2988   SmallPtrSet<const User *, 16> Visited;
2989   bool ReduxExtracted = false;
2990 
2991   while (!UsersToVisit.empty()) {
2992     auto User = UsersToVisit.back();
2993     UsersToVisit.pop_back();
2994     if (!Visited.insert(User).second)
2995       continue;
2996 
2997     for (const auto &U : User->users()) {
2998       auto Inst = dyn_cast<Instruction>(U);
2999       if (!Inst)
3000         return false;
3001 
3002       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3003         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3004           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3005             return false;
3006         UsersToVisit.push_back(U);
3007       } else if (const ShuffleVectorInst *ShufInst =
3008                      dyn_cast<ShuffleVectorInst>(U)) {
3009         // Detect the following pattern: A ShuffleVector instruction together
3010         // with a reduction that do partial reduction on the first and second
3011         // ElemNumToReduce / 2 elements, and store the result in
3012         // ElemNumToReduce / 2 elements in another vector.
3013 
3014         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3015         if (ResultElements < ElemNum)
3016           return false;
3017 
3018         if (ElemNumToReduce == 1)
3019           return false;
3020         if (!isa<UndefValue>(U->getOperand(1)))
3021           return false;
3022         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3023           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3024             return false;
3025         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3026           if (ShufInst->getMaskValue(i) != -1)
3027             return false;
3028 
3029         // There is only one user of this ShuffleVector instruction, which
3030         // must be a reduction operation.
3031         if (!U->hasOneUse())
3032           return false;
3033 
3034         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3035         if (!U2 || U2->getOpcode() != OpCode)
3036           return false;
3037 
3038         // Check operands of the reduction operation.
3039         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3040             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3041           UsersToVisit.push_back(U2);
3042           ElemNumToReduce /= 2;
3043         } else
3044           return false;
3045       } else if (isa<ExtractElementInst>(U)) {
3046         // At this moment we should have reduced all elements in the vector.
3047         if (ElemNumToReduce != 1)
3048           return false;
3049 
3050         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3051         if (!Val || !Val->isZero())
3052           return false;
3053 
3054         ReduxExtracted = true;
3055       } else
3056         return false;
3057     }
3058   }
3059   return ReduxExtracted;
3060 }
3061 
3062 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3063   SDNodeFlags Flags;
3064 
3065   SDValue Op = getValue(I.getOperand(0));
3066   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3067                                     Op, Flags);
3068   setValue(&I, UnNodeValue);
3069 }
3070 
3071 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3072   SDNodeFlags Flags;
3073   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3074     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3075     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3076   }
3077   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3078     Flags.setExact(ExactOp->isExact());
3079   }
3080   if (isVectorReductionOp(&I)) {
3081     Flags.setVectorReduction(true);
3082     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3083   }
3084 
3085   SDValue Op1 = getValue(I.getOperand(0));
3086   SDValue Op2 = getValue(I.getOperand(1));
3087   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3088                                      Op1, Op2, Flags);
3089   setValue(&I, BinNodeValue);
3090 }
3091 
3092 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3093   SDValue Op1 = getValue(I.getOperand(0));
3094   SDValue Op2 = getValue(I.getOperand(1));
3095 
3096   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3097       Op1.getValueType(), DAG.getDataLayout());
3098 
3099   // Coerce the shift amount to the right type if we can.
3100   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3101     unsigned ShiftSize = ShiftTy.getSizeInBits();
3102     unsigned Op2Size = Op2.getValueSizeInBits();
3103     SDLoc DL = getCurSDLoc();
3104 
3105     // If the operand is smaller than the shift count type, promote it.
3106     if (ShiftSize > Op2Size)
3107       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3108 
3109     // If the operand is larger than the shift count type but the shift
3110     // count type has enough bits to represent any shift value, truncate
3111     // it now. This is a common case and it exposes the truncate to
3112     // optimization early.
3113     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3114       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3115     // Otherwise we'll need to temporarily settle for some other convenient
3116     // type.  Type legalization will make adjustments once the shiftee is split.
3117     else
3118       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3119   }
3120 
3121   bool nuw = false;
3122   bool nsw = false;
3123   bool exact = false;
3124 
3125   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3126 
3127     if (const OverflowingBinaryOperator *OFBinOp =
3128             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3129       nuw = OFBinOp->hasNoUnsignedWrap();
3130       nsw = OFBinOp->hasNoSignedWrap();
3131     }
3132     if (const PossiblyExactOperator *ExactOp =
3133             dyn_cast<const PossiblyExactOperator>(&I))
3134       exact = ExactOp->isExact();
3135   }
3136   SDNodeFlags Flags;
3137   Flags.setExact(exact);
3138   Flags.setNoSignedWrap(nsw);
3139   Flags.setNoUnsignedWrap(nuw);
3140   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3141                             Flags);
3142   setValue(&I, Res);
3143 }
3144 
3145 void SelectionDAGBuilder::visitSDiv(const User &I) {
3146   SDValue Op1 = getValue(I.getOperand(0));
3147   SDValue Op2 = getValue(I.getOperand(1));
3148 
3149   SDNodeFlags Flags;
3150   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3151                  cast<PossiblyExactOperator>(&I)->isExact());
3152   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3153                            Op2, Flags));
3154 }
3155 
3156 void SelectionDAGBuilder::visitICmp(const User &I) {
3157   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3158   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3159     predicate = IC->getPredicate();
3160   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3161     predicate = ICmpInst::Predicate(IC->getPredicate());
3162   SDValue Op1 = getValue(I.getOperand(0));
3163   SDValue Op2 = getValue(I.getOperand(1));
3164   ISD::CondCode Opcode = getICmpCondCode(predicate);
3165 
3166   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3167                                                         I.getType());
3168   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3169 }
3170 
3171 void SelectionDAGBuilder::visitFCmp(const User &I) {
3172   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3173   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3174     predicate = FC->getPredicate();
3175   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3176     predicate = FCmpInst::Predicate(FC->getPredicate());
3177   SDValue Op1 = getValue(I.getOperand(0));
3178   SDValue Op2 = getValue(I.getOperand(1));
3179 
3180   ISD::CondCode Condition = getFCmpCondCode(predicate);
3181   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3182   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3183     Condition = getFCmpCodeWithoutNaN(Condition);
3184 
3185   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3186                                                         I.getType());
3187   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3188 }
3189 
3190 // Check if the condition of the select has one use or two users that are both
3191 // selects with the same condition.
3192 static bool hasOnlySelectUsers(const Value *Cond) {
3193   return llvm::all_of(Cond->users(), [](const Value *V) {
3194     return isa<SelectInst>(V);
3195   });
3196 }
3197 
3198 void SelectionDAGBuilder::visitSelect(const User &I) {
3199   SmallVector<EVT, 4> ValueVTs;
3200   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3201                   ValueVTs);
3202   unsigned NumValues = ValueVTs.size();
3203   if (NumValues == 0) return;
3204 
3205   SmallVector<SDValue, 4> Values(NumValues);
3206   SDValue Cond     = getValue(I.getOperand(0));
3207   SDValue LHSVal   = getValue(I.getOperand(1));
3208   SDValue RHSVal   = getValue(I.getOperand(2));
3209   auto BaseOps = {Cond};
3210   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3211     ISD::VSELECT : ISD::SELECT;
3212 
3213   bool IsUnaryAbs = false;
3214 
3215   // Min/max matching is only viable if all output VTs are the same.
3216   if (is_splat(ValueVTs)) {
3217     EVT VT = ValueVTs[0];
3218     LLVMContext &Ctx = *DAG.getContext();
3219     auto &TLI = DAG.getTargetLoweringInfo();
3220 
3221     // We care about the legality of the operation after it has been type
3222     // legalized.
3223     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3224            VT != TLI.getTypeToTransformTo(Ctx, VT))
3225       VT = TLI.getTypeToTransformTo(Ctx, VT);
3226 
3227     // If the vselect is legal, assume we want to leave this as a vector setcc +
3228     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3229     // min/max is legal on the scalar type.
3230     bool UseScalarMinMax = VT.isVector() &&
3231       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3232 
3233     Value *LHS, *RHS;
3234     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3235     ISD::NodeType Opc = ISD::DELETED_NODE;
3236     switch (SPR.Flavor) {
3237     case SPF_UMAX:    Opc = ISD::UMAX; break;
3238     case SPF_UMIN:    Opc = ISD::UMIN; break;
3239     case SPF_SMAX:    Opc = ISD::SMAX; break;
3240     case SPF_SMIN:    Opc = ISD::SMIN; break;
3241     case SPF_FMINNUM:
3242       switch (SPR.NaNBehavior) {
3243       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3244       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3245       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3246       case SPNB_RETURNS_ANY: {
3247         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3248           Opc = ISD::FMINNUM;
3249         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3250           Opc = ISD::FMINIMUM;
3251         else if (UseScalarMinMax)
3252           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3253             ISD::FMINNUM : ISD::FMINIMUM;
3254         break;
3255       }
3256       }
3257       break;
3258     case SPF_FMAXNUM:
3259       switch (SPR.NaNBehavior) {
3260       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3261       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3262       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3263       case SPNB_RETURNS_ANY:
3264 
3265         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3266           Opc = ISD::FMAXNUM;
3267         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3268           Opc = ISD::FMAXIMUM;
3269         else if (UseScalarMinMax)
3270           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3271             ISD::FMAXNUM : ISD::FMAXIMUM;
3272         break;
3273       }
3274       break;
3275     case SPF_ABS:
3276       IsUnaryAbs = true;
3277       Opc = ISD::ABS;
3278       break;
3279     case SPF_NABS:
3280       // TODO: we need to produce sub(0, abs(X)).
3281     default: break;
3282     }
3283 
3284     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3285         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3286          (UseScalarMinMax &&
3287           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3288         // If the underlying comparison instruction is used by any other
3289         // instruction, the consumed instructions won't be destroyed, so it is
3290         // not profitable to convert to a min/max.
3291         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3292       OpCode = Opc;
3293       LHSVal = getValue(LHS);
3294       RHSVal = getValue(RHS);
3295       BaseOps = {};
3296     }
3297 
3298     if (IsUnaryAbs) {
3299       OpCode = Opc;
3300       LHSVal = getValue(LHS);
3301       BaseOps = {};
3302     }
3303   }
3304 
3305   if (IsUnaryAbs) {
3306     for (unsigned i = 0; i != NumValues; ++i) {
3307       Values[i] =
3308           DAG.getNode(OpCode, getCurSDLoc(),
3309                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3310                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3311     }
3312   } else {
3313     for (unsigned i = 0; i != NumValues; ++i) {
3314       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3315       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3316       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3317       Values[i] = DAG.getNode(
3318           OpCode, getCurSDLoc(),
3319           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3320     }
3321   }
3322 
3323   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3324                            DAG.getVTList(ValueVTs), Values));
3325 }
3326 
3327 void SelectionDAGBuilder::visitTrunc(const User &I) {
3328   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3329   SDValue N = getValue(I.getOperand(0));
3330   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3331                                                         I.getType());
3332   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3333 }
3334 
3335 void SelectionDAGBuilder::visitZExt(const User &I) {
3336   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3337   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3338   SDValue N = getValue(I.getOperand(0));
3339   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3340                                                         I.getType());
3341   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3342 }
3343 
3344 void SelectionDAGBuilder::visitSExt(const User &I) {
3345   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3346   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3347   SDValue N = getValue(I.getOperand(0));
3348   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3349                                                         I.getType());
3350   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3351 }
3352 
3353 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3354   // FPTrunc is never a no-op cast, no need to check
3355   SDValue N = getValue(I.getOperand(0));
3356   SDLoc dl = getCurSDLoc();
3357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3358   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3359   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3360                            DAG.getTargetConstant(
3361                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3362 }
3363 
3364 void SelectionDAGBuilder::visitFPExt(const User &I) {
3365   // FPExt is never a no-op cast, no need to check
3366   SDValue N = getValue(I.getOperand(0));
3367   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3368                                                         I.getType());
3369   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3370 }
3371 
3372 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3373   // FPToUI is never a no-op cast, no need to check
3374   SDValue N = getValue(I.getOperand(0));
3375   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3376                                                         I.getType());
3377   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3378 }
3379 
3380 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3381   // FPToSI is never a no-op cast, no need to check
3382   SDValue N = getValue(I.getOperand(0));
3383   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3384                                                         I.getType());
3385   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3386 }
3387 
3388 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3389   // UIToFP is never a no-op cast, no need to check
3390   SDValue N = getValue(I.getOperand(0));
3391   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3392                                                         I.getType());
3393   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3394 }
3395 
3396 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3397   // SIToFP is never a no-op cast, no need to check
3398   SDValue N = getValue(I.getOperand(0));
3399   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3400                                                         I.getType());
3401   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3402 }
3403 
3404 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3405   // What to do depends on the size of the integer and the size of the pointer.
3406   // We can either truncate, zero extend, or no-op, accordingly.
3407   SDValue N = getValue(I.getOperand(0));
3408   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3409                                                         I.getType());
3410   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3411 }
3412 
3413 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3414   // What to do depends on the size of the integer and the size of the pointer.
3415   // We can either truncate, zero extend, or no-op, accordingly.
3416   SDValue N = getValue(I.getOperand(0));
3417   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3418                                                         I.getType());
3419   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3420 }
3421 
3422 void SelectionDAGBuilder::visitBitCast(const User &I) {
3423   SDValue N = getValue(I.getOperand(0));
3424   SDLoc dl = getCurSDLoc();
3425   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3426                                                         I.getType());
3427 
3428   // BitCast assures us that source and destination are the same size so this is
3429   // either a BITCAST or a no-op.
3430   if (DestVT != N.getValueType())
3431     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3432                              DestVT, N)); // convert types.
3433   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3434   // might fold any kind of constant expression to an integer constant and that
3435   // is not what we are looking for. Only recognize a bitcast of a genuine
3436   // constant integer as an opaque constant.
3437   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3438     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3439                                  /*isOpaque*/true));
3440   else
3441     setValue(&I, N);            // noop cast.
3442 }
3443 
3444 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3446   const Value *SV = I.getOperand(0);
3447   SDValue N = getValue(SV);
3448   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3449 
3450   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3451   unsigned DestAS = I.getType()->getPointerAddressSpace();
3452 
3453   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3454     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3455 
3456   setValue(&I, N);
3457 }
3458 
3459 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3460   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461   SDValue InVec = getValue(I.getOperand(0));
3462   SDValue InVal = getValue(I.getOperand(1));
3463   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3464                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3465   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3466                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3467                            InVec, InVal, InIdx));
3468 }
3469 
3470 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3472   SDValue InVec = getValue(I.getOperand(0));
3473   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3474                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3475   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3476                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3477                            InVec, InIdx));
3478 }
3479 
3480 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3481   SDValue Src1 = getValue(I.getOperand(0));
3482   SDValue Src2 = getValue(I.getOperand(1));
3483   SDLoc DL = getCurSDLoc();
3484 
3485   SmallVector<int, 8> Mask;
3486   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3487   unsigned MaskNumElts = Mask.size();
3488 
3489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3490   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3491   EVT SrcVT = Src1.getValueType();
3492   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3493 
3494   if (SrcNumElts == MaskNumElts) {
3495     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3496     return;
3497   }
3498 
3499   // Normalize the shuffle vector since mask and vector length don't match.
3500   if (SrcNumElts < MaskNumElts) {
3501     // Mask is longer than the source vectors. We can use concatenate vector to
3502     // make the mask and vectors lengths match.
3503 
3504     if (MaskNumElts % SrcNumElts == 0) {
3505       // Mask length is a multiple of the source vector length.
3506       // Check if the shuffle is some kind of concatenation of the input
3507       // vectors.
3508       unsigned NumConcat = MaskNumElts / SrcNumElts;
3509       bool IsConcat = true;
3510       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3511       for (unsigned i = 0; i != MaskNumElts; ++i) {
3512         int Idx = Mask[i];
3513         if (Idx < 0)
3514           continue;
3515         // Ensure the indices in each SrcVT sized piece are sequential and that
3516         // the same source is used for the whole piece.
3517         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3518             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3519              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3520           IsConcat = false;
3521           break;
3522         }
3523         // Remember which source this index came from.
3524         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3525       }
3526 
3527       // The shuffle is concatenating multiple vectors together. Just emit
3528       // a CONCAT_VECTORS operation.
3529       if (IsConcat) {
3530         SmallVector<SDValue, 8> ConcatOps;
3531         for (auto Src : ConcatSrcs) {
3532           if (Src < 0)
3533             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3534           else if (Src == 0)
3535             ConcatOps.push_back(Src1);
3536           else
3537             ConcatOps.push_back(Src2);
3538         }
3539         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3540         return;
3541       }
3542     }
3543 
3544     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3545     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3546     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3547                                     PaddedMaskNumElts);
3548 
3549     // Pad both vectors with undefs to make them the same length as the mask.
3550     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3551 
3552     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3553     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3554     MOps1[0] = Src1;
3555     MOps2[0] = Src2;
3556 
3557     Src1 = Src1.isUndef()
3558                ? DAG.getUNDEF(PaddedVT)
3559                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3560     Src2 = Src2.isUndef()
3561                ? DAG.getUNDEF(PaddedVT)
3562                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3563 
3564     // Readjust mask for new input vector length.
3565     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3566     for (unsigned i = 0; i != MaskNumElts; ++i) {
3567       int Idx = Mask[i];
3568       if (Idx >= (int)SrcNumElts)
3569         Idx -= SrcNumElts - PaddedMaskNumElts;
3570       MappedOps[i] = Idx;
3571     }
3572 
3573     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3574 
3575     // If the concatenated vector was padded, extract a subvector with the
3576     // correct number of elements.
3577     if (MaskNumElts != PaddedMaskNumElts)
3578       Result = DAG.getNode(
3579           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3580           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3581 
3582     setValue(&I, Result);
3583     return;
3584   }
3585 
3586   if (SrcNumElts > MaskNumElts) {
3587     // Analyze the access pattern of the vector to see if we can extract
3588     // two subvectors and do the shuffle.
3589     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3590     bool CanExtract = true;
3591     for (int Idx : Mask) {
3592       unsigned Input = 0;
3593       if (Idx < 0)
3594         continue;
3595 
3596       if (Idx >= (int)SrcNumElts) {
3597         Input = 1;
3598         Idx -= SrcNumElts;
3599       }
3600 
3601       // If all the indices come from the same MaskNumElts sized portion of
3602       // the sources we can use extract. Also make sure the extract wouldn't
3603       // extract past the end of the source.
3604       int NewStartIdx = alignDown(Idx, MaskNumElts);
3605       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3606           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3607         CanExtract = false;
3608       // Make sure we always update StartIdx as we use it to track if all
3609       // elements are undef.
3610       StartIdx[Input] = NewStartIdx;
3611     }
3612 
3613     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3614       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3615       return;
3616     }
3617     if (CanExtract) {
3618       // Extract appropriate subvector and generate a vector shuffle
3619       for (unsigned Input = 0; Input < 2; ++Input) {
3620         SDValue &Src = Input == 0 ? Src1 : Src2;
3621         if (StartIdx[Input] < 0)
3622           Src = DAG.getUNDEF(VT);
3623         else {
3624           Src = DAG.getNode(
3625               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3626               DAG.getConstant(StartIdx[Input], DL,
3627                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3628         }
3629       }
3630 
3631       // Calculate new mask.
3632       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3633       for (int &Idx : MappedOps) {
3634         if (Idx >= (int)SrcNumElts)
3635           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3636         else if (Idx >= 0)
3637           Idx -= StartIdx[0];
3638       }
3639 
3640       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3641       return;
3642     }
3643   }
3644 
3645   // We can't use either concat vectors or extract subvectors so fall back to
3646   // replacing the shuffle with extract and build vector.
3647   // to insert and build vector.
3648   EVT EltVT = VT.getVectorElementType();
3649   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3650   SmallVector<SDValue,8> Ops;
3651   for (int Idx : Mask) {
3652     SDValue Res;
3653 
3654     if (Idx < 0) {
3655       Res = DAG.getUNDEF(EltVT);
3656     } else {
3657       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3658       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3659 
3660       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3661                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3662     }
3663 
3664     Ops.push_back(Res);
3665   }
3666 
3667   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3668 }
3669 
3670 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3671   ArrayRef<unsigned> Indices;
3672   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3673     Indices = IV->getIndices();
3674   else
3675     Indices = cast<ConstantExpr>(&I)->getIndices();
3676 
3677   const Value *Op0 = I.getOperand(0);
3678   const Value *Op1 = I.getOperand(1);
3679   Type *AggTy = I.getType();
3680   Type *ValTy = Op1->getType();
3681   bool IntoUndef = isa<UndefValue>(Op0);
3682   bool FromUndef = isa<UndefValue>(Op1);
3683 
3684   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3685 
3686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3687   SmallVector<EVT, 4> AggValueVTs;
3688   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3689   SmallVector<EVT, 4> ValValueVTs;
3690   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3691 
3692   unsigned NumAggValues = AggValueVTs.size();
3693   unsigned NumValValues = ValValueVTs.size();
3694   SmallVector<SDValue, 4> Values(NumAggValues);
3695 
3696   // Ignore an insertvalue that produces an empty object
3697   if (!NumAggValues) {
3698     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3699     return;
3700   }
3701 
3702   SDValue Agg = getValue(Op0);
3703   unsigned i = 0;
3704   // Copy the beginning value(s) from the original aggregate.
3705   for (; i != LinearIndex; ++i)
3706     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3707                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3708   // Copy values from the inserted value(s).
3709   if (NumValValues) {
3710     SDValue Val = getValue(Op1);
3711     for (; i != LinearIndex + NumValValues; ++i)
3712       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3713                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3714   }
3715   // Copy remaining value(s) from the original aggregate.
3716   for (; i != NumAggValues; ++i)
3717     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3718                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3719 
3720   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3721                            DAG.getVTList(AggValueVTs), Values));
3722 }
3723 
3724 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3725   ArrayRef<unsigned> Indices;
3726   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3727     Indices = EV->getIndices();
3728   else
3729     Indices = cast<ConstantExpr>(&I)->getIndices();
3730 
3731   const Value *Op0 = I.getOperand(0);
3732   Type *AggTy = Op0->getType();
3733   Type *ValTy = I.getType();
3734   bool OutOfUndef = isa<UndefValue>(Op0);
3735 
3736   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3737 
3738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3739   SmallVector<EVT, 4> ValValueVTs;
3740   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3741 
3742   unsigned NumValValues = ValValueVTs.size();
3743 
3744   // Ignore a extractvalue that produces an empty object
3745   if (!NumValValues) {
3746     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3747     return;
3748   }
3749 
3750   SmallVector<SDValue, 4> Values(NumValValues);
3751 
3752   SDValue Agg = getValue(Op0);
3753   // Copy out the selected value(s).
3754   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3755     Values[i - LinearIndex] =
3756       OutOfUndef ?
3757         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3758         SDValue(Agg.getNode(), Agg.getResNo() + i);
3759 
3760   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3761                            DAG.getVTList(ValValueVTs), Values));
3762 }
3763 
3764 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3765   Value *Op0 = I.getOperand(0);
3766   // Note that the pointer operand may be a vector of pointers. Take the scalar
3767   // element which holds a pointer.
3768   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3769   SDValue N = getValue(Op0);
3770   SDLoc dl = getCurSDLoc();
3771 
3772   // Normalize Vector GEP - all scalar operands should be converted to the
3773   // splat vector.
3774   unsigned VectorWidth = I.getType()->isVectorTy() ?
3775     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3776 
3777   if (VectorWidth && !N.getValueType().isVector()) {
3778     LLVMContext &Context = *DAG.getContext();
3779     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3780     N = DAG.getSplatBuildVector(VT, dl, N);
3781   }
3782 
3783   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3784        GTI != E; ++GTI) {
3785     const Value *Idx = GTI.getOperand();
3786     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3787       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3788       if (Field) {
3789         // N = N + Offset
3790         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3791 
3792         // In an inbounds GEP with an offset that is nonnegative even when
3793         // interpreted as signed, assume there is no unsigned overflow.
3794         SDNodeFlags Flags;
3795         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3796           Flags.setNoUnsignedWrap(true);
3797 
3798         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3799                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3800       }
3801     } else {
3802       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3803       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3804       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3805 
3806       // If this is a scalar constant or a splat vector of constants,
3807       // handle it quickly.
3808       const auto *CI = dyn_cast<ConstantInt>(Idx);
3809       if (!CI && isa<ConstantDataVector>(Idx) &&
3810           cast<ConstantDataVector>(Idx)->getSplatValue())
3811         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3812 
3813       if (CI) {
3814         if (CI->isZero())
3815           continue;
3816         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3817         LLVMContext &Context = *DAG.getContext();
3818         SDValue OffsVal = VectorWidth ?
3819           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3820           DAG.getConstant(Offs, dl, IdxTy);
3821 
3822         // In an inbouds GEP with an offset that is nonnegative even when
3823         // interpreted as signed, assume there is no unsigned overflow.
3824         SDNodeFlags Flags;
3825         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3826           Flags.setNoUnsignedWrap(true);
3827 
3828         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3829         continue;
3830       }
3831 
3832       // N = N + Idx * ElementSize;
3833       SDValue IdxN = getValue(Idx);
3834 
3835       if (!IdxN.getValueType().isVector() && VectorWidth) {
3836         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3837         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3838       }
3839 
3840       // If the index is smaller or larger than intptr_t, truncate or extend
3841       // it.
3842       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3843 
3844       // If this is a multiply by a power of two, turn it into a shl
3845       // immediately.  This is a very common case.
3846       if (ElementSize != 1) {
3847         if (ElementSize.isPowerOf2()) {
3848           unsigned Amt = ElementSize.logBase2();
3849           IdxN = DAG.getNode(ISD::SHL, dl,
3850                              N.getValueType(), IdxN,
3851                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3852         } else {
3853           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3854           IdxN = DAG.getNode(ISD::MUL, dl,
3855                              N.getValueType(), IdxN, Scale);
3856         }
3857       }
3858 
3859       N = DAG.getNode(ISD::ADD, dl,
3860                       N.getValueType(), N, IdxN);
3861     }
3862   }
3863 
3864   setValue(&I, N);
3865 }
3866 
3867 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3868   // If this is a fixed sized alloca in the entry block of the function,
3869   // allocate it statically on the stack.
3870   if (FuncInfo.StaticAllocaMap.count(&I))
3871     return;   // getValue will auto-populate this.
3872 
3873   SDLoc dl = getCurSDLoc();
3874   Type *Ty = I.getAllocatedType();
3875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3876   auto &DL = DAG.getDataLayout();
3877   uint64_t TySize = DL.getTypeAllocSize(Ty);
3878   unsigned Align =
3879       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3880 
3881   SDValue AllocSize = getValue(I.getArraySize());
3882 
3883   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3884   if (AllocSize.getValueType() != IntPtr)
3885     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3886 
3887   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3888                           AllocSize,
3889                           DAG.getConstant(TySize, dl, IntPtr));
3890 
3891   // Handle alignment.  If the requested alignment is less than or equal to
3892   // the stack alignment, ignore it.  If the size is greater than or equal to
3893   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3894   unsigned StackAlign =
3895       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3896   if (Align <= StackAlign)
3897     Align = 0;
3898 
3899   // Round the size of the allocation up to the stack alignment size
3900   // by add SA-1 to the size. This doesn't overflow because we're computing
3901   // an address inside an alloca.
3902   SDNodeFlags Flags;
3903   Flags.setNoUnsignedWrap(true);
3904   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3905                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3906 
3907   // Mask out the low bits for alignment purposes.
3908   AllocSize =
3909       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3910                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3911 
3912   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3913   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3914   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3915   setValue(&I, DSA);
3916   DAG.setRoot(DSA.getValue(1));
3917 
3918   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3919 }
3920 
3921 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3922   if (I.isAtomic())
3923     return visitAtomicLoad(I);
3924 
3925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3926   const Value *SV = I.getOperand(0);
3927   if (TLI.supportSwiftError()) {
3928     // Swifterror values can come from either a function parameter with
3929     // swifterror attribute or an alloca with swifterror attribute.
3930     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3931       if (Arg->hasSwiftErrorAttr())
3932         return visitLoadFromSwiftError(I);
3933     }
3934 
3935     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3936       if (Alloca->isSwiftError())
3937         return visitLoadFromSwiftError(I);
3938     }
3939   }
3940 
3941   SDValue Ptr = getValue(SV);
3942 
3943   Type *Ty = I.getType();
3944 
3945   bool isVolatile = I.isVolatile();
3946   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3947   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3948   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3949   unsigned Alignment = I.getAlignment();
3950 
3951   AAMDNodes AAInfo;
3952   I.getAAMetadata(AAInfo);
3953   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3954 
3955   SmallVector<EVT, 4> ValueVTs;
3956   SmallVector<uint64_t, 4> Offsets;
3957   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3958   unsigned NumValues = ValueVTs.size();
3959   if (NumValues == 0)
3960     return;
3961 
3962   SDValue Root;
3963   bool ConstantMemory = false;
3964   if (isVolatile || NumValues > MaxParallelChains)
3965     // Serialize volatile loads with other side effects.
3966     Root = getRoot();
3967   else if (AA &&
3968            AA->pointsToConstantMemory(MemoryLocation(
3969                SV,
3970                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3971                AAInfo))) {
3972     // Do not serialize (non-volatile) loads of constant memory with anything.
3973     Root = DAG.getEntryNode();
3974     ConstantMemory = true;
3975   } else {
3976     // Do not serialize non-volatile loads against each other.
3977     Root = DAG.getRoot();
3978   }
3979 
3980   SDLoc dl = getCurSDLoc();
3981 
3982   if (isVolatile)
3983     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3984 
3985   // An aggregate load cannot wrap around the address space, so offsets to its
3986   // parts don't wrap either.
3987   SDNodeFlags Flags;
3988   Flags.setNoUnsignedWrap(true);
3989 
3990   SmallVector<SDValue, 4> Values(NumValues);
3991   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3992   EVT PtrVT = Ptr.getValueType();
3993   unsigned ChainI = 0;
3994   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3995     // Serializing loads here may result in excessive register pressure, and
3996     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3997     // could recover a bit by hoisting nodes upward in the chain by recognizing
3998     // they are side-effect free or do not alias. The optimizer should really
3999     // avoid this case by converting large object/array copies to llvm.memcpy
4000     // (MaxParallelChains should always remain as failsafe).
4001     if (ChainI == MaxParallelChains) {
4002       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4003       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4004                                   makeArrayRef(Chains.data(), ChainI));
4005       Root = Chain;
4006       ChainI = 0;
4007     }
4008     SDValue A = DAG.getNode(ISD::ADD, dl,
4009                             PtrVT, Ptr,
4010                             DAG.getConstant(Offsets[i], dl, PtrVT),
4011                             Flags);
4012     auto MMOFlags = MachineMemOperand::MONone;
4013     if (isVolatile)
4014       MMOFlags |= MachineMemOperand::MOVolatile;
4015     if (isNonTemporal)
4016       MMOFlags |= MachineMemOperand::MONonTemporal;
4017     if (isInvariant)
4018       MMOFlags |= MachineMemOperand::MOInvariant;
4019     if (isDereferenceable)
4020       MMOFlags |= MachineMemOperand::MODereferenceable;
4021     MMOFlags |= TLI.getMMOFlags(I);
4022 
4023     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
4024                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4025                             MMOFlags, AAInfo, Ranges);
4026 
4027     Values[i] = L;
4028     Chains[ChainI] = L.getValue(1);
4029   }
4030 
4031   if (!ConstantMemory) {
4032     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4033                                 makeArrayRef(Chains.data(), ChainI));
4034     if (isVolatile)
4035       DAG.setRoot(Chain);
4036     else
4037       PendingLoads.push_back(Chain);
4038   }
4039 
4040   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4041                            DAG.getVTList(ValueVTs), Values));
4042 }
4043 
4044 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4045   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4046          "call visitStoreToSwiftError when backend supports swifterror");
4047 
4048   SmallVector<EVT, 4> ValueVTs;
4049   SmallVector<uint64_t, 4> Offsets;
4050   const Value *SrcV = I.getOperand(0);
4051   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4052                   SrcV->getType(), ValueVTs, &Offsets);
4053   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4054          "expect a single EVT for swifterror");
4055 
4056   SDValue Src = getValue(SrcV);
4057   // Create a virtual register, then update the virtual register.
4058   unsigned VReg; bool CreatedVReg;
4059   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
4060   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4061   // Chain can be getRoot or getControlRoot.
4062   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4063                                       SDValue(Src.getNode(), Src.getResNo()));
4064   DAG.setRoot(CopyNode);
4065   if (CreatedVReg)
4066     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
4067 }
4068 
4069 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4070   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4071          "call visitLoadFromSwiftError when backend supports swifterror");
4072 
4073   assert(!I.isVolatile() &&
4074          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4075          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4076          "Support volatile, non temporal, invariant for load_from_swift_error");
4077 
4078   const Value *SV = I.getOperand(0);
4079   Type *Ty = I.getType();
4080   AAMDNodes AAInfo;
4081   I.getAAMetadata(AAInfo);
4082   assert(
4083       (!AA ||
4084        !AA->pointsToConstantMemory(MemoryLocation(
4085            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4086            AAInfo))) &&
4087       "load_from_swift_error should not be constant memory");
4088 
4089   SmallVector<EVT, 4> ValueVTs;
4090   SmallVector<uint64_t, 4> Offsets;
4091   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4092                   ValueVTs, &Offsets);
4093   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4094          "expect a single EVT for swifterror");
4095 
4096   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4097   SDValue L = DAG.getCopyFromReg(
4098       getRoot(), getCurSDLoc(),
4099       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
4100       ValueVTs[0]);
4101 
4102   setValue(&I, L);
4103 }
4104 
4105 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4106   if (I.isAtomic())
4107     return visitAtomicStore(I);
4108 
4109   const Value *SrcV = I.getOperand(0);
4110   const Value *PtrV = I.getOperand(1);
4111 
4112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4113   if (TLI.supportSwiftError()) {
4114     // Swifterror values can come from either a function parameter with
4115     // swifterror attribute or an alloca with swifterror attribute.
4116     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4117       if (Arg->hasSwiftErrorAttr())
4118         return visitStoreToSwiftError(I);
4119     }
4120 
4121     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4122       if (Alloca->isSwiftError())
4123         return visitStoreToSwiftError(I);
4124     }
4125   }
4126 
4127   SmallVector<EVT, 4> ValueVTs;
4128   SmallVector<uint64_t, 4> Offsets;
4129   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4130                   SrcV->getType(), ValueVTs, &Offsets);
4131   unsigned NumValues = ValueVTs.size();
4132   if (NumValues == 0)
4133     return;
4134 
4135   // Get the lowered operands. Note that we do this after
4136   // checking if NumResults is zero, because with zero results
4137   // the operands won't have values in the map.
4138   SDValue Src = getValue(SrcV);
4139   SDValue Ptr = getValue(PtrV);
4140 
4141   SDValue Root = getRoot();
4142   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4143   SDLoc dl = getCurSDLoc();
4144   EVT PtrVT = Ptr.getValueType();
4145   unsigned Alignment = I.getAlignment();
4146   AAMDNodes AAInfo;
4147   I.getAAMetadata(AAInfo);
4148 
4149   auto MMOFlags = MachineMemOperand::MONone;
4150   if (I.isVolatile())
4151     MMOFlags |= MachineMemOperand::MOVolatile;
4152   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4153     MMOFlags |= MachineMemOperand::MONonTemporal;
4154   MMOFlags |= TLI.getMMOFlags(I);
4155 
4156   // An aggregate load cannot wrap around the address space, so offsets to its
4157   // parts don't wrap either.
4158   SDNodeFlags Flags;
4159   Flags.setNoUnsignedWrap(true);
4160 
4161   unsigned ChainI = 0;
4162   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4163     // See visitLoad comments.
4164     if (ChainI == MaxParallelChains) {
4165       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4166                                   makeArrayRef(Chains.data(), ChainI));
4167       Root = Chain;
4168       ChainI = 0;
4169     }
4170     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4171                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4172     SDValue St = DAG.getStore(
4173         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
4174         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
4175     Chains[ChainI] = St;
4176   }
4177 
4178   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4179                                   makeArrayRef(Chains.data(), ChainI));
4180   DAG.setRoot(StoreNode);
4181 }
4182 
4183 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4184                                            bool IsCompressing) {
4185   SDLoc sdl = getCurSDLoc();
4186 
4187   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4188                            unsigned& Alignment) {
4189     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4190     Src0 = I.getArgOperand(0);
4191     Ptr = I.getArgOperand(1);
4192     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4193     Mask = I.getArgOperand(3);
4194   };
4195   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4196                            unsigned& Alignment) {
4197     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4198     Src0 = I.getArgOperand(0);
4199     Ptr = I.getArgOperand(1);
4200     Mask = I.getArgOperand(2);
4201     Alignment = 0;
4202   };
4203 
4204   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4205   unsigned Alignment;
4206   if (IsCompressing)
4207     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4208   else
4209     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4210 
4211   SDValue Ptr = getValue(PtrOperand);
4212   SDValue Src0 = getValue(Src0Operand);
4213   SDValue Mask = getValue(MaskOperand);
4214 
4215   EVT VT = Src0.getValueType();
4216   if (!Alignment)
4217     Alignment = DAG.getEVTAlignment(VT);
4218 
4219   AAMDNodes AAInfo;
4220   I.getAAMetadata(AAInfo);
4221 
4222   MachineMemOperand *MMO =
4223     DAG.getMachineFunction().
4224     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4225                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4226                           Alignment, AAInfo);
4227   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4228                                          MMO, false /* Truncating */,
4229                                          IsCompressing);
4230   DAG.setRoot(StoreNode);
4231   setValue(&I, StoreNode);
4232 }
4233 
4234 // Get a uniform base for the Gather/Scatter intrinsic.
4235 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4236 // We try to represent it as a base pointer + vector of indices.
4237 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4238 // The first operand of the GEP may be a single pointer or a vector of pointers
4239 // Example:
4240 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4241 //  or
4242 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4243 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4244 //
4245 // When the first GEP operand is a single pointer - it is the uniform base we
4246 // are looking for. If first operand of the GEP is a splat vector - we
4247 // extract the splat value and use it as a uniform base.
4248 // In all other cases the function returns 'false'.
4249 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4250                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4251   SelectionDAG& DAG = SDB->DAG;
4252   LLVMContext &Context = *DAG.getContext();
4253 
4254   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4255   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4256   if (!GEP)
4257     return false;
4258 
4259   const Value *GEPPtr = GEP->getPointerOperand();
4260   if (!GEPPtr->getType()->isVectorTy())
4261     Ptr = GEPPtr;
4262   else if (!(Ptr = getSplatValue(GEPPtr)))
4263     return false;
4264 
4265   unsigned FinalIndex = GEP->getNumOperands() - 1;
4266   Value *IndexVal = GEP->getOperand(FinalIndex);
4267 
4268   // Ensure all the other indices are 0.
4269   for (unsigned i = 1; i < FinalIndex; ++i) {
4270     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4271     if (!C || !C->isZero())
4272       return false;
4273   }
4274 
4275   // The operands of the GEP may be defined in another basic block.
4276   // In this case we'll not find nodes for the operands.
4277   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4278     return false;
4279 
4280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4281   const DataLayout &DL = DAG.getDataLayout();
4282   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4283                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4284   Base = SDB->getValue(Ptr);
4285   Index = SDB->getValue(IndexVal);
4286 
4287   if (!Index.getValueType().isVector()) {
4288     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4289     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4290     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4291   }
4292   return true;
4293 }
4294 
4295 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4296   SDLoc sdl = getCurSDLoc();
4297 
4298   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4299   const Value *Ptr = I.getArgOperand(1);
4300   SDValue Src0 = getValue(I.getArgOperand(0));
4301   SDValue Mask = getValue(I.getArgOperand(3));
4302   EVT VT = Src0.getValueType();
4303   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4304   if (!Alignment)
4305     Alignment = DAG.getEVTAlignment(VT);
4306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4307 
4308   AAMDNodes AAInfo;
4309   I.getAAMetadata(AAInfo);
4310 
4311   SDValue Base;
4312   SDValue Index;
4313   SDValue Scale;
4314   const Value *BasePtr = Ptr;
4315   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4316 
4317   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4318   MachineMemOperand *MMO = DAG.getMachineFunction().
4319     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4320                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4321                          Alignment, AAInfo);
4322   if (!UniformBase) {
4323     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4324     Index = getValue(Ptr);
4325     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4326   }
4327   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4328   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4329                                          Ops, MMO);
4330   DAG.setRoot(Scatter);
4331   setValue(&I, Scatter);
4332 }
4333 
4334 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4335   SDLoc sdl = getCurSDLoc();
4336 
4337   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4338                            unsigned& Alignment) {
4339     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4340     Ptr = I.getArgOperand(0);
4341     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4342     Mask = I.getArgOperand(2);
4343     Src0 = I.getArgOperand(3);
4344   };
4345   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4346                            unsigned& Alignment) {
4347     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4348     Ptr = I.getArgOperand(0);
4349     Alignment = 0;
4350     Mask = I.getArgOperand(1);
4351     Src0 = I.getArgOperand(2);
4352   };
4353 
4354   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4355   unsigned Alignment;
4356   if (IsExpanding)
4357     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4358   else
4359     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4360 
4361   SDValue Ptr = getValue(PtrOperand);
4362   SDValue Src0 = getValue(Src0Operand);
4363   SDValue Mask = getValue(MaskOperand);
4364 
4365   EVT VT = Src0.getValueType();
4366   if (!Alignment)
4367     Alignment = DAG.getEVTAlignment(VT);
4368 
4369   AAMDNodes AAInfo;
4370   I.getAAMetadata(AAInfo);
4371   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4372 
4373   // Do not serialize masked loads of constant memory with anything.
4374   bool AddToChain =
4375       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4376                  PtrOperand,
4377                  LocationSize::precise(
4378                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4379                  AAInfo));
4380   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4381 
4382   MachineMemOperand *MMO =
4383     DAG.getMachineFunction().
4384     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4385                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4386                           Alignment, AAInfo, Ranges);
4387 
4388   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4389                                    ISD::NON_EXTLOAD, IsExpanding);
4390   if (AddToChain)
4391     PendingLoads.push_back(Load.getValue(1));
4392   setValue(&I, Load);
4393 }
4394 
4395 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4396   SDLoc sdl = getCurSDLoc();
4397 
4398   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4399   const Value *Ptr = I.getArgOperand(0);
4400   SDValue Src0 = getValue(I.getArgOperand(3));
4401   SDValue Mask = getValue(I.getArgOperand(2));
4402 
4403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4404   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4405   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4406   if (!Alignment)
4407     Alignment = DAG.getEVTAlignment(VT);
4408 
4409   AAMDNodes AAInfo;
4410   I.getAAMetadata(AAInfo);
4411   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4412 
4413   SDValue Root = DAG.getRoot();
4414   SDValue Base;
4415   SDValue Index;
4416   SDValue Scale;
4417   const Value *BasePtr = Ptr;
4418   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4419   bool ConstantMemory = false;
4420   if (UniformBase && AA &&
4421       AA->pointsToConstantMemory(
4422           MemoryLocation(BasePtr,
4423                          LocationSize::precise(
4424                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4425                          AAInfo))) {
4426     // Do not serialize (non-volatile) loads of constant memory with anything.
4427     Root = DAG.getEntryNode();
4428     ConstantMemory = true;
4429   }
4430 
4431   MachineMemOperand *MMO =
4432     DAG.getMachineFunction().
4433     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4434                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4435                          Alignment, AAInfo, Ranges);
4436 
4437   if (!UniformBase) {
4438     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4439     Index = getValue(Ptr);
4440     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4441   }
4442   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4443   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4444                                        Ops, MMO);
4445 
4446   SDValue OutChain = Gather.getValue(1);
4447   if (!ConstantMemory)
4448     PendingLoads.push_back(OutChain);
4449   setValue(&I, Gather);
4450 }
4451 
4452 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4453   SDLoc dl = getCurSDLoc();
4454   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4455   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4456   SyncScope::ID SSID = I.getSyncScopeID();
4457 
4458   SDValue InChain = getRoot();
4459 
4460   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4461   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4462 
4463   auto Alignment = DAG.getEVTAlignment(MemVT);
4464 
4465   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4466   if (I.isVolatile())
4467     Flags |= MachineMemOperand::MOVolatile;
4468   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4469 
4470   MachineFunction &MF = DAG.getMachineFunction();
4471   MachineMemOperand *MMO =
4472     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4473                             Flags, MemVT.getStoreSize(), Alignment,
4474                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4475                             FailureOrdering);
4476 
4477   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4478                                    dl, MemVT, VTs, InChain,
4479                                    getValue(I.getPointerOperand()),
4480                                    getValue(I.getCompareOperand()),
4481                                    getValue(I.getNewValOperand()), MMO);
4482 
4483   SDValue OutChain = L.getValue(2);
4484 
4485   setValue(&I, L);
4486   DAG.setRoot(OutChain);
4487 }
4488 
4489 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4490   SDLoc dl = getCurSDLoc();
4491   ISD::NodeType NT;
4492   switch (I.getOperation()) {
4493   default: llvm_unreachable("Unknown atomicrmw operation");
4494   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4495   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4496   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4497   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4498   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4499   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4500   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4501   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4502   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4503   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4504   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4505   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4506   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4507   }
4508   AtomicOrdering Ordering = I.getOrdering();
4509   SyncScope::ID SSID = I.getSyncScopeID();
4510 
4511   SDValue InChain = getRoot();
4512 
4513   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4514   auto Alignment = DAG.getEVTAlignment(MemVT);
4515 
4516   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4517   if (I.isVolatile())
4518     Flags |= MachineMemOperand::MOVolatile;
4519   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4520 
4521   MachineFunction &MF = DAG.getMachineFunction();
4522   MachineMemOperand *MMO =
4523     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4524                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4525                             nullptr, SSID, Ordering);
4526 
4527   SDValue L =
4528     DAG.getAtomic(NT, dl, MemVT, InChain,
4529                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4530                   MMO);
4531 
4532   SDValue OutChain = L.getValue(1);
4533 
4534   setValue(&I, L);
4535   DAG.setRoot(OutChain);
4536 }
4537 
4538 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4539   SDLoc dl = getCurSDLoc();
4540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4541   SDValue Ops[3];
4542   Ops[0] = getRoot();
4543   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4544                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4545   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4546                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4547   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4548 }
4549 
4550 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4551   SDLoc dl = getCurSDLoc();
4552   AtomicOrdering Order = I.getOrdering();
4553   SyncScope::ID SSID = I.getSyncScopeID();
4554 
4555   SDValue InChain = getRoot();
4556 
4557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4558   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4559 
4560   if (!TLI.supportsUnalignedAtomics() &&
4561       I.getAlignment() < VT.getStoreSize())
4562     report_fatal_error("Cannot generate unaligned atomic load");
4563 
4564   auto Flags = MachineMemOperand::MOLoad;
4565   if (I.isVolatile())
4566     Flags |= MachineMemOperand::MOVolatile;
4567   if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
4568     Flags |= MachineMemOperand::MOInvariant;
4569   if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
4570     Flags |= MachineMemOperand::MODereferenceable;
4571 
4572   Flags |= TLI.getMMOFlags(I);
4573 
4574   MachineMemOperand *MMO =
4575       DAG.getMachineFunction().
4576       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4577                            Flags, VT.getStoreSize(),
4578                            I.getAlignment() ? I.getAlignment() :
4579                                               DAG.getEVTAlignment(VT),
4580                            AAMDNodes(), nullptr, SSID, Order);
4581 
4582   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4583   SDValue L =
4584       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4585                     getValue(I.getPointerOperand()), MMO);
4586 
4587   SDValue OutChain = L.getValue(1);
4588 
4589   setValue(&I, L);
4590   DAG.setRoot(OutChain);
4591 }
4592 
4593 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4594   SDLoc dl = getCurSDLoc();
4595 
4596   AtomicOrdering Ordering = I.getOrdering();
4597   SyncScope::ID SSID = I.getSyncScopeID();
4598 
4599   SDValue InChain = getRoot();
4600 
4601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4602   EVT VT =
4603       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4604 
4605   if (I.getAlignment() < VT.getStoreSize())
4606     report_fatal_error("Cannot generate unaligned atomic store");
4607 
4608   auto Flags = MachineMemOperand::MOStore;
4609   if (I.isVolatile())
4610     Flags |= MachineMemOperand::MOVolatile;
4611   Flags |= TLI.getMMOFlags(I);
4612 
4613   MachineFunction &MF = DAG.getMachineFunction();
4614   MachineMemOperand *MMO =
4615     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4616                             VT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4617                             nullptr, SSID, Ordering);
4618   SDValue OutChain =
4619     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain,
4620               getValue(I.getPointerOperand()), getValue(I.getValueOperand()),
4621               MMO);
4622 
4623 
4624   DAG.setRoot(OutChain);
4625 }
4626 
4627 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4628 /// node.
4629 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4630                                                unsigned Intrinsic) {
4631   // Ignore the callsite's attributes. A specific call site may be marked with
4632   // readnone, but the lowering code will expect the chain based on the
4633   // definition.
4634   const Function *F = I.getCalledFunction();
4635   bool HasChain = !F->doesNotAccessMemory();
4636   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4637 
4638   // Build the operand list.
4639   SmallVector<SDValue, 8> Ops;
4640   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4641     if (OnlyLoad) {
4642       // We don't need to serialize loads against other loads.
4643       Ops.push_back(DAG.getRoot());
4644     } else {
4645       Ops.push_back(getRoot());
4646     }
4647   }
4648 
4649   // Info is set by getTgtMemInstrinsic
4650   TargetLowering::IntrinsicInfo Info;
4651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4652   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4653                                                DAG.getMachineFunction(),
4654                                                Intrinsic);
4655 
4656   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4657   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4658       Info.opc == ISD::INTRINSIC_W_CHAIN)
4659     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4660                                         TLI.getPointerTy(DAG.getDataLayout())));
4661 
4662   // Add all operands of the call to the operand list.
4663   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4664     SDValue Op = getValue(I.getArgOperand(i));
4665     Ops.push_back(Op);
4666   }
4667 
4668   SmallVector<EVT, 4> ValueVTs;
4669   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4670 
4671   if (HasChain)
4672     ValueVTs.push_back(MVT::Other);
4673 
4674   SDVTList VTs = DAG.getVTList(ValueVTs);
4675 
4676   // Create the node.
4677   SDValue Result;
4678   if (IsTgtIntrinsic) {
4679     // This is target intrinsic that touches memory
4680     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4681       Ops, Info.memVT,
4682       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4683       Info.flags, Info.size);
4684   } else if (!HasChain) {
4685     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4686   } else if (!I.getType()->isVoidTy()) {
4687     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4688   } else {
4689     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4690   }
4691 
4692   if (HasChain) {
4693     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4694     if (OnlyLoad)
4695       PendingLoads.push_back(Chain);
4696     else
4697       DAG.setRoot(Chain);
4698   }
4699 
4700   if (!I.getType()->isVoidTy()) {
4701     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4702       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4703       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4704     } else
4705       Result = lowerRangeToAssertZExt(DAG, I, Result);
4706 
4707     setValue(&I, Result);
4708   }
4709 }
4710 
4711 /// GetSignificand - Get the significand and build it into a floating-point
4712 /// number with exponent of 1:
4713 ///
4714 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4715 ///
4716 /// where Op is the hexadecimal representation of floating point value.
4717 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4718   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4719                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4720   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4721                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4722   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4723 }
4724 
4725 /// GetExponent - Get the exponent:
4726 ///
4727 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4728 ///
4729 /// where Op is the hexadecimal representation of floating point value.
4730 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4731                            const TargetLowering &TLI, const SDLoc &dl) {
4732   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4733                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4734   SDValue t1 = DAG.getNode(
4735       ISD::SRL, dl, MVT::i32, t0,
4736       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4737   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4738                            DAG.getConstant(127, dl, MVT::i32));
4739   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4740 }
4741 
4742 /// getF32Constant - Get 32-bit floating point constant.
4743 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4744                               const SDLoc &dl) {
4745   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4746                            MVT::f32);
4747 }
4748 
4749 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4750                                        SelectionDAG &DAG) {
4751   // TODO: What fast-math-flags should be set on the floating-point nodes?
4752 
4753   //   IntegerPartOfX = ((int32_t)(t0);
4754   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4755 
4756   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4757   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4758   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4759 
4760   //   IntegerPartOfX <<= 23;
4761   IntegerPartOfX = DAG.getNode(
4762       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4763       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4764                                   DAG.getDataLayout())));
4765 
4766   SDValue TwoToFractionalPartOfX;
4767   if (LimitFloatPrecision <= 6) {
4768     // For floating-point precision of 6:
4769     //
4770     //   TwoToFractionalPartOfX =
4771     //     0.997535578f +
4772     //       (0.735607626f + 0.252464424f * x) * x;
4773     //
4774     // error 0.0144103317, which is 6 bits
4775     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4776                              getF32Constant(DAG, 0x3e814304, dl));
4777     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4778                              getF32Constant(DAG, 0x3f3c50c8, dl));
4779     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4780     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4781                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4782   } else if (LimitFloatPrecision <= 12) {
4783     // For floating-point precision of 12:
4784     //
4785     //   TwoToFractionalPartOfX =
4786     //     0.999892986f +
4787     //       (0.696457318f +
4788     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4789     //
4790     // error 0.000107046256, which is 13 to 14 bits
4791     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4792                              getF32Constant(DAG, 0x3da235e3, dl));
4793     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4794                              getF32Constant(DAG, 0x3e65b8f3, dl));
4795     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4796     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4797                              getF32Constant(DAG, 0x3f324b07, dl));
4798     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4799     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4800                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4801   } else { // LimitFloatPrecision <= 18
4802     // For floating-point precision of 18:
4803     //
4804     //   TwoToFractionalPartOfX =
4805     //     0.999999982f +
4806     //       (0.693148872f +
4807     //         (0.240227044f +
4808     //           (0.554906021e-1f +
4809     //             (0.961591928e-2f +
4810     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4811     // error 2.47208000*10^(-7), which is better than 18 bits
4812     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4813                              getF32Constant(DAG, 0x3924b03e, dl));
4814     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4815                              getF32Constant(DAG, 0x3ab24b87, dl));
4816     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4817     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4818                              getF32Constant(DAG, 0x3c1d8c17, dl));
4819     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4820     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4821                              getF32Constant(DAG, 0x3d634a1d, dl));
4822     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4823     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4824                              getF32Constant(DAG, 0x3e75fe14, dl));
4825     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4826     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4827                               getF32Constant(DAG, 0x3f317234, dl));
4828     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4829     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4830                                          getF32Constant(DAG, 0x3f800000, dl));
4831   }
4832 
4833   // Add the exponent into the result in integer domain.
4834   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4835   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4836                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4837 }
4838 
4839 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4840 /// limited-precision mode.
4841 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4842                          const TargetLowering &TLI) {
4843   if (Op.getValueType() == MVT::f32 &&
4844       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4845 
4846     // Put the exponent in the right bit position for later addition to the
4847     // final result:
4848     //
4849     //   #define LOG2OFe 1.4426950f
4850     //   t0 = Op * LOG2OFe
4851 
4852     // TODO: What fast-math-flags should be set here?
4853     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4854                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4855     return getLimitedPrecisionExp2(t0, dl, DAG);
4856   }
4857 
4858   // No special expansion.
4859   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4860 }
4861 
4862 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4863 /// limited-precision mode.
4864 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4865                          const TargetLowering &TLI) {
4866   // TODO: What fast-math-flags should be set on the floating-point nodes?
4867 
4868   if (Op.getValueType() == MVT::f32 &&
4869       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4870     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4871 
4872     // Scale the exponent by log(2) [0.69314718f].
4873     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4874     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4875                                         getF32Constant(DAG, 0x3f317218, dl));
4876 
4877     // Get the significand and build it into a floating-point number with
4878     // exponent of 1.
4879     SDValue X = GetSignificand(DAG, Op1, dl);
4880 
4881     SDValue LogOfMantissa;
4882     if (LimitFloatPrecision <= 6) {
4883       // For floating-point precision of 6:
4884       //
4885       //   LogofMantissa =
4886       //     -1.1609546f +
4887       //       (1.4034025f - 0.23903021f * x) * x;
4888       //
4889       // error 0.0034276066, which is better than 8 bits
4890       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4891                                getF32Constant(DAG, 0xbe74c456, dl));
4892       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4893                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4894       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4895       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4896                                   getF32Constant(DAG, 0x3f949a29, dl));
4897     } else if (LimitFloatPrecision <= 12) {
4898       // For floating-point precision of 12:
4899       //
4900       //   LogOfMantissa =
4901       //     -1.7417939f +
4902       //       (2.8212026f +
4903       //         (-1.4699568f +
4904       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4905       //
4906       // error 0.000061011436, which is 14 bits
4907       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4908                                getF32Constant(DAG, 0xbd67b6d6, dl));
4909       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4910                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4911       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4912       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4913                                getF32Constant(DAG, 0x3fbc278b, dl));
4914       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4915       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4916                                getF32Constant(DAG, 0x40348e95, dl));
4917       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4918       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4919                                   getF32Constant(DAG, 0x3fdef31a, dl));
4920     } else { // LimitFloatPrecision <= 18
4921       // For floating-point precision of 18:
4922       //
4923       //   LogOfMantissa =
4924       //     -2.1072184f +
4925       //       (4.2372794f +
4926       //         (-3.7029485f +
4927       //           (2.2781945f +
4928       //             (-0.87823314f +
4929       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4930       //
4931       // error 0.0000023660568, which is better than 18 bits
4932       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4933                                getF32Constant(DAG, 0xbc91e5ac, dl));
4934       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4935                                getF32Constant(DAG, 0x3e4350aa, dl));
4936       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4937       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4938                                getF32Constant(DAG, 0x3f60d3e3, dl));
4939       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4940       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4941                                getF32Constant(DAG, 0x4011cdf0, dl));
4942       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4943       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4944                                getF32Constant(DAG, 0x406cfd1c, dl));
4945       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4946       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4947                                getF32Constant(DAG, 0x408797cb, dl));
4948       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4949       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4950                                   getF32Constant(DAG, 0x4006dcab, dl));
4951     }
4952 
4953     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4954   }
4955 
4956   // No special expansion.
4957   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4958 }
4959 
4960 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4961 /// limited-precision mode.
4962 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4963                           const TargetLowering &TLI) {
4964   // TODO: What fast-math-flags should be set on the floating-point nodes?
4965 
4966   if (Op.getValueType() == MVT::f32 &&
4967       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4968     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4969 
4970     // Get the exponent.
4971     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4972 
4973     // Get the significand and build it into a floating-point number with
4974     // exponent of 1.
4975     SDValue X = GetSignificand(DAG, Op1, dl);
4976 
4977     // Different possible minimax approximations of significand in
4978     // floating-point for various degrees of accuracy over [1,2].
4979     SDValue Log2ofMantissa;
4980     if (LimitFloatPrecision <= 6) {
4981       // For floating-point precision of 6:
4982       //
4983       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4984       //
4985       // error 0.0049451742, which is more than 7 bits
4986       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4987                                getF32Constant(DAG, 0xbeb08fe0, dl));
4988       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4989                                getF32Constant(DAG, 0x40019463, dl));
4990       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4991       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4992                                    getF32Constant(DAG, 0x3fd6633d, dl));
4993     } else if (LimitFloatPrecision <= 12) {
4994       // For floating-point precision of 12:
4995       //
4996       //   Log2ofMantissa =
4997       //     -2.51285454f +
4998       //       (4.07009056f +
4999       //         (-2.12067489f +
5000       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5001       //
5002       // error 0.0000876136000, which is better than 13 bits
5003       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5004                                getF32Constant(DAG, 0xbda7262e, dl));
5005       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5006                                getF32Constant(DAG, 0x3f25280b, dl));
5007       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5008       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5009                                getF32Constant(DAG, 0x4007b923, dl));
5010       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5011       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5012                                getF32Constant(DAG, 0x40823e2f, dl));
5013       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5014       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5015                                    getF32Constant(DAG, 0x4020d29c, dl));
5016     } else { // LimitFloatPrecision <= 18
5017       // For floating-point precision of 18:
5018       //
5019       //   Log2ofMantissa =
5020       //     -3.0400495f +
5021       //       (6.1129976f +
5022       //         (-5.3420409f +
5023       //           (3.2865683f +
5024       //             (-1.2669343f +
5025       //               (0.27515199f -
5026       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5027       //
5028       // error 0.0000018516, which is better than 18 bits
5029       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5030                                getF32Constant(DAG, 0xbcd2769e, dl));
5031       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5032                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5033       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5034       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5035                                getF32Constant(DAG, 0x3fa22ae7, dl));
5036       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5037       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5038                                getF32Constant(DAG, 0x40525723, dl));
5039       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5040       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5041                                getF32Constant(DAG, 0x40aaf200, dl));
5042       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5043       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5044                                getF32Constant(DAG, 0x40c39dad, dl));
5045       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5046       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5047                                    getF32Constant(DAG, 0x4042902c, dl));
5048     }
5049 
5050     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5051   }
5052 
5053   // No special expansion.
5054   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5055 }
5056 
5057 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5058 /// limited-precision mode.
5059 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5060                            const TargetLowering &TLI) {
5061   // TODO: What fast-math-flags should be set on the floating-point nodes?
5062 
5063   if (Op.getValueType() == MVT::f32 &&
5064       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5065     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5066 
5067     // Scale the exponent by log10(2) [0.30102999f].
5068     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5069     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5070                                         getF32Constant(DAG, 0x3e9a209a, dl));
5071 
5072     // Get the significand and build it into a floating-point number with
5073     // exponent of 1.
5074     SDValue X = GetSignificand(DAG, Op1, dl);
5075 
5076     SDValue Log10ofMantissa;
5077     if (LimitFloatPrecision <= 6) {
5078       // For floating-point precision of 6:
5079       //
5080       //   Log10ofMantissa =
5081       //     -0.50419619f +
5082       //       (0.60948995f - 0.10380950f * x) * x;
5083       //
5084       // error 0.0014886165, which is 6 bits
5085       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5086                                getF32Constant(DAG, 0xbdd49a13, dl));
5087       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5088                                getF32Constant(DAG, 0x3f1c0789, dl));
5089       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5090       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5091                                     getF32Constant(DAG, 0x3f011300, dl));
5092     } else if (LimitFloatPrecision <= 12) {
5093       // For floating-point precision of 12:
5094       //
5095       //   Log10ofMantissa =
5096       //     -0.64831180f +
5097       //       (0.91751397f +
5098       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5099       //
5100       // error 0.00019228036, which is better than 12 bits
5101       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5102                                getF32Constant(DAG, 0x3d431f31, dl));
5103       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5104                                getF32Constant(DAG, 0x3ea21fb2, dl));
5105       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5106       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5107                                getF32Constant(DAG, 0x3f6ae232, dl));
5108       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5109       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5110                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5111     } else { // LimitFloatPrecision <= 18
5112       // For floating-point precision of 18:
5113       //
5114       //   Log10ofMantissa =
5115       //     -0.84299375f +
5116       //       (1.5327582f +
5117       //         (-1.0688956f +
5118       //           (0.49102474f +
5119       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5120       //
5121       // error 0.0000037995730, which is better than 18 bits
5122       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5123                                getF32Constant(DAG, 0x3c5d51ce, dl));
5124       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5125                                getF32Constant(DAG, 0x3e00685a, dl));
5126       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5127       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5128                                getF32Constant(DAG, 0x3efb6798, dl));
5129       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5130       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5131                                getF32Constant(DAG, 0x3f88d192, dl));
5132       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5133       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5134                                getF32Constant(DAG, 0x3fc4316c, dl));
5135       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5136       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5137                                     getF32Constant(DAG, 0x3f57ce70, dl));
5138     }
5139 
5140     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5141   }
5142 
5143   // No special expansion.
5144   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5145 }
5146 
5147 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5148 /// limited-precision mode.
5149 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5150                           const TargetLowering &TLI) {
5151   if (Op.getValueType() == MVT::f32 &&
5152       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5153     return getLimitedPrecisionExp2(Op, dl, DAG);
5154 
5155   // No special expansion.
5156   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5157 }
5158 
5159 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5160 /// limited-precision mode with x == 10.0f.
5161 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5162                          SelectionDAG &DAG, const TargetLowering &TLI) {
5163   bool IsExp10 = false;
5164   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5165       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5166     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5167       APFloat Ten(10.0f);
5168       IsExp10 = LHSC->isExactlyValue(Ten);
5169     }
5170   }
5171 
5172   // TODO: What fast-math-flags should be set on the FMUL node?
5173   if (IsExp10) {
5174     // Put the exponent in the right bit position for later addition to the
5175     // final result:
5176     //
5177     //   #define LOG2OF10 3.3219281f
5178     //   t0 = Op * LOG2OF10;
5179     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5180                              getF32Constant(DAG, 0x40549a78, dl));
5181     return getLimitedPrecisionExp2(t0, dl, DAG);
5182   }
5183 
5184   // No special expansion.
5185   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5186 }
5187 
5188 /// ExpandPowI - Expand a llvm.powi intrinsic.
5189 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5190                           SelectionDAG &DAG) {
5191   // If RHS is a constant, we can expand this out to a multiplication tree,
5192   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5193   // optimizing for size, we only want to do this if the expansion would produce
5194   // a small number of multiplies, otherwise we do the full expansion.
5195   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5196     // Get the exponent as a positive value.
5197     unsigned Val = RHSC->getSExtValue();
5198     if ((int)Val < 0) Val = -Val;
5199 
5200     // powi(x, 0) -> 1.0
5201     if (Val == 0)
5202       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5203 
5204     const Function &F = DAG.getMachineFunction().getFunction();
5205     if (!F.optForSize() ||
5206         // If optimizing for size, don't insert too many multiplies.
5207         // This inserts up to 5 multiplies.
5208         countPopulation(Val) + Log2_32(Val) < 7) {
5209       // We use the simple binary decomposition method to generate the multiply
5210       // sequence.  There are more optimal ways to do this (for example,
5211       // powi(x,15) generates one more multiply than it should), but this has
5212       // the benefit of being both really simple and much better than a libcall.
5213       SDValue Res;  // Logically starts equal to 1.0
5214       SDValue CurSquare = LHS;
5215       // TODO: Intrinsics should have fast-math-flags that propagate to these
5216       // nodes.
5217       while (Val) {
5218         if (Val & 1) {
5219           if (Res.getNode())
5220             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5221           else
5222             Res = CurSquare;  // 1.0*CurSquare.
5223         }
5224 
5225         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5226                                 CurSquare, CurSquare);
5227         Val >>= 1;
5228       }
5229 
5230       // If the original was negative, invert the result, producing 1/(x*x*x).
5231       if (RHSC->getSExtValue() < 0)
5232         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5233                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5234       return Res;
5235     }
5236   }
5237 
5238   // Otherwise, expand to a libcall.
5239   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5240 }
5241 
5242 // getUnderlyingArgReg - Find underlying register used for a truncated or
5243 // bitcasted argument.
5244 static unsigned getUnderlyingArgReg(const SDValue &N) {
5245   switch (N.getOpcode()) {
5246   case ISD::CopyFromReg:
5247     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5248   case ISD::BITCAST:
5249   case ISD::AssertZext:
5250   case ISD::AssertSext:
5251   case ISD::TRUNCATE:
5252     return getUnderlyingArgReg(N.getOperand(0));
5253   default:
5254     return 0;
5255   }
5256 }
5257 
5258 /// If the DbgValueInst is a dbg_value of a function argument, create the
5259 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5260 /// instruction selection, they will be inserted to the entry BB.
5261 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5262     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5263     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5264   const Argument *Arg = dyn_cast<Argument>(V);
5265   if (!Arg)
5266     return false;
5267 
5268   if (!IsDbgDeclare) {
5269     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5270     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5271     // the entry block.
5272     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5273     if (!IsInEntryBlock)
5274       return false;
5275 
5276     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5277     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5278     // variable that also is a param.
5279     //
5280     // Although, if we are at the top of the entry block already, we can still
5281     // emit using ArgDbgValue. This might catch some situations when the
5282     // dbg.value refers to an argument that isn't used in the entry block, so
5283     // any CopyToReg node would be optimized out and the only way to express
5284     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5285     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5286     // we should only emit as ArgDbgValue if the Variable is an argument to the
5287     // current function, and the dbg.value intrinsic is found in the entry
5288     // block.
5289     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5290         !DL->getInlinedAt();
5291     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5292     if (!IsInPrologue && !VariableIsFunctionInputArg)
5293       return false;
5294 
5295     // Here we assume that a function argument on IR level only can be used to
5296     // describe one input parameter on source level. If we for example have
5297     // source code like this
5298     //
5299     //    struct A { long x, y; };
5300     //    void foo(struct A a, long b) {
5301     //      ...
5302     //      b = a.x;
5303     //      ...
5304     //    }
5305     //
5306     // and IR like this
5307     //
5308     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5309     //  entry:
5310     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5311     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5312     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5313     //    ...
5314     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5315     //    ...
5316     //
5317     // then the last dbg.value is describing a parameter "b" using a value that
5318     // is an argument. But since we already has used %a1 to describe a parameter
5319     // we should not handle that last dbg.value here (that would result in an
5320     // incorrect hoisting of the DBG_VALUE to the function entry).
5321     // Notice that we allow one dbg.value per IR level argument, to accomodate
5322     // for the situation with fragments above.
5323     if (VariableIsFunctionInputArg) {
5324       unsigned ArgNo = Arg->getArgNo();
5325       if (ArgNo >= FuncInfo.DescribedArgs.size())
5326         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5327       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5328         return false;
5329       FuncInfo.DescribedArgs.set(ArgNo);
5330     }
5331   }
5332 
5333   MachineFunction &MF = DAG.getMachineFunction();
5334   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5335 
5336   bool IsIndirect = false;
5337   Optional<MachineOperand> Op;
5338   // Some arguments' frame index is recorded during argument lowering.
5339   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5340   if (FI != std::numeric_limits<int>::max())
5341     Op = MachineOperand::CreateFI(FI);
5342 
5343   if (!Op && N.getNode()) {
5344     unsigned Reg = getUnderlyingArgReg(N);
5345     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5346       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5347       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5348       if (PR)
5349         Reg = PR;
5350     }
5351     if (Reg) {
5352       Op = MachineOperand::CreateReg(Reg, false);
5353       IsIndirect = IsDbgDeclare;
5354     }
5355   }
5356 
5357   if (!Op && N.getNode()) {
5358     // Check if frame index is available.
5359     SDValue LCandidate = peekThroughBitcasts(N);
5360     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5361       if (FrameIndexSDNode *FINode =
5362           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5363         Op = MachineOperand::CreateFI(FINode->getIndex());
5364   }
5365 
5366   if (!Op) {
5367     // Check if ValueMap has reg number.
5368     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5369     if (VMI != FuncInfo.ValueMap.end()) {
5370       const auto &TLI = DAG.getTargetLoweringInfo();
5371       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5372                        V->getType(), getABIRegCopyCC(V));
5373       if (RFV.occupiesMultipleRegs()) {
5374         unsigned Offset = 0;
5375         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5376           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5377           auto FragmentExpr = DIExpression::createFragmentExpression(
5378               Expr, Offset, RegAndSize.second);
5379           if (!FragmentExpr)
5380             continue;
5381           FuncInfo.ArgDbgValues.push_back(
5382               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5383                       Op->getReg(), Variable, *FragmentExpr));
5384           Offset += RegAndSize.second;
5385         }
5386         return true;
5387       }
5388       Op = MachineOperand::CreateReg(VMI->second, false);
5389       IsIndirect = IsDbgDeclare;
5390     }
5391   }
5392 
5393   if (!Op)
5394     return false;
5395 
5396   assert(Variable->isValidLocationForIntrinsic(DL) &&
5397          "Expected inlined-at fields to agree");
5398   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5399   FuncInfo.ArgDbgValues.push_back(
5400       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5401               *Op, Variable, Expr));
5402 
5403   return true;
5404 }
5405 
5406 /// Return the appropriate SDDbgValue based on N.
5407 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5408                                              DILocalVariable *Variable,
5409                                              DIExpression *Expr,
5410                                              const DebugLoc &dl,
5411                                              unsigned DbgSDNodeOrder) {
5412   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5413     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5414     // stack slot locations.
5415     //
5416     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5417     // debug values here after optimization:
5418     //
5419     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5420     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5421     //
5422     // Both describe the direct values of their associated variables.
5423     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5424                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5425   }
5426   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5427                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5428 }
5429 
5430 // VisualStudio defines setjmp as _setjmp
5431 #if defined(_MSC_VER) && defined(setjmp) && \
5432                          !defined(setjmp_undefined_for_msvc)
5433 #  pragma push_macro("setjmp")
5434 #  undef setjmp
5435 #  define setjmp_undefined_for_msvc
5436 #endif
5437 
5438 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5439   switch (Intrinsic) {
5440   case Intrinsic::smul_fix:
5441     return ISD::SMULFIX;
5442   case Intrinsic::umul_fix:
5443     return ISD::UMULFIX;
5444   default:
5445     llvm_unreachable("Unhandled fixed point intrinsic");
5446   }
5447 }
5448 
5449 /// Lower the call to the specified intrinsic function. If we want to emit this
5450 /// as a call to a named external function, return the name. Otherwise, lower it
5451 /// and return null.
5452 const char *
5453 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5455   SDLoc sdl = getCurSDLoc();
5456   DebugLoc dl = getCurDebugLoc();
5457   SDValue Res;
5458 
5459   switch (Intrinsic) {
5460   default:
5461     // By default, turn this into a target intrinsic node.
5462     visitTargetIntrinsic(I, Intrinsic);
5463     return nullptr;
5464   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5465   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5466   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5467   case Intrinsic::returnaddress:
5468     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5469                              TLI.getPointerTy(DAG.getDataLayout()),
5470                              getValue(I.getArgOperand(0))));
5471     return nullptr;
5472   case Intrinsic::addressofreturnaddress:
5473     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5474                              TLI.getPointerTy(DAG.getDataLayout())));
5475     return nullptr;
5476   case Intrinsic::sponentry:
5477     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5478                              TLI.getPointerTy(DAG.getDataLayout())));
5479     return nullptr;
5480   case Intrinsic::frameaddress:
5481     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5482                              TLI.getPointerTy(DAG.getDataLayout()),
5483                              getValue(I.getArgOperand(0))));
5484     return nullptr;
5485   case Intrinsic::read_register: {
5486     Value *Reg = I.getArgOperand(0);
5487     SDValue Chain = getRoot();
5488     SDValue RegName =
5489         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5490     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5491     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5492       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5493     setValue(&I, Res);
5494     DAG.setRoot(Res.getValue(1));
5495     return nullptr;
5496   }
5497   case Intrinsic::write_register: {
5498     Value *Reg = I.getArgOperand(0);
5499     Value *RegValue = I.getArgOperand(1);
5500     SDValue Chain = getRoot();
5501     SDValue RegName =
5502         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5503     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5504                             RegName, getValue(RegValue)));
5505     return nullptr;
5506   }
5507   case Intrinsic::setjmp:
5508     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5509   case Intrinsic::longjmp:
5510     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5511   case Intrinsic::memcpy: {
5512     const auto &MCI = cast<MemCpyInst>(I);
5513     SDValue Op1 = getValue(I.getArgOperand(0));
5514     SDValue Op2 = getValue(I.getArgOperand(1));
5515     SDValue Op3 = getValue(I.getArgOperand(2));
5516     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5517     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5518     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5519     unsigned Align = MinAlign(DstAlign, SrcAlign);
5520     bool isVol = MCI.isVolatile();
5521     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5522     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5523     // node.
5524     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5525                                false, isTC,
5526                                MachinePointerInfo(I.getArgOperand(0)),
5527                                MachinePointerInfo(I.getArgOperand(1)));
5528     updateDAGForMaybeTailCall(MC);
5529     return nullptr;
5530   }
5531   case Intrinsic::memset: {
5532     const auto &MSI = cast<MemSetInst>(I);
5533     SDValue Op1 = getValue(I.getArgOperand(0));
5534     SDValue Op2 = getValue(I.getArgOperand(1));
5535     SDValue Op3 = getValue(I.getArgOperand(2));
5536     // @llvm.memset defines 0 and 1 to both mean no alignment.
5537     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5538     bool isVol = MSI.isVolatile();
5539     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5540     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5541                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5542     updateDAGForMaybeTailCall(MS);
5543     return nullptr;
5544   }
5545   case Intrinsic::memmove: {
5546     const auto &MMI = cast<MemMoveInst>(I);
5547     SDValue Op1 = getValue(I.getArgOperand(0));
5548     SDValue Op2 = getValue(I.getArgOperand(1));
5549     SDValue Op3 = getValue(I.getArgOperand(2));
5550     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5551     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5552     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5553     unsigned Align = MinAlign(DstAlign, SrcAlign);
5554     bool isVol = MMI.isVolatile();
5555     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5556     // FIXME: Support passing different dest/src alignments to the memmove DAG
5557     // node.
5558     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5559                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5560                                 MachinePointerInfo(I.getArgOperand(1)));
5561     updateDAGForMaybeTailCall(MM);
5562     return nullptr;
5563   }
5564   case Intrinsic::memcpy_element_unordered_atomic: {
5565     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5566     SDValue Dst = getValue(MI.getRawDest());
5567     SDValue Src = getValue(MI.getRawSource());
5568     SDValue Length = getValue(MI.getLength());
5569 
5570     unsigned DstAlign = MI.getDestAlignment();
5571     unsigned SrcAlign = MI.getSourceAlignment();
5572     Type *LengthTy = MI.getLength()->getType();
5573     unsigned ElemSz = MI.getElementSizeInBytes();
5574     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5575     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5576                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5577                                      MachinePointerInfo(MI.getRawDest()),
5578                                      MachinePointerInfo(MI.getRawSource()));
5579     updateDAGForMaybeTailCall(MC);
5580     return nullptr;
5581   }
5582   case Intrinsic::memmove_element_unordered_atomic: {
5583     auto &MI = cast<AtomicMemMoveInst>(I);
5584     SDValue Dst = getValue(MI.getRawDest());
5585     SDValue Src = getValue(MI.getRawSource());
5586     SDValue Length = getValue(MI.getLength());
5587 
5588     unsigned DstAlign = MI.getDestAlignment();
5589     unsigned SrcAlign = MI.getSourceAlignment();
5590     Type *LengthTy = MI.getLength()->getType();
5591     unsigned ElemSz = MI.getElementSizeInBytes();
5592     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5593     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5594                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5595                                       MachinePointerInfo(MI.getRawDest()),
5596                                       MachinePointerInfo(MI.getRawSource()));
5597     updateDAGForMaybeTailCall(MC);
5598     return nullptr;
5599   }
5600   case Intrinsic::memset_element_unordered_atomic: {
5601     auto &MI = cast<AtomicMemSetInst>(I);
5602     SDValue Dst = getValue(MI.getRawDest());
5603     SDValue Val = getValue(MI.getValue());
5604     SDValue Length = getValue(MI.getLength());
5605 
5606     unsigned DstAlign = MI.getDestAlignment();
5607     Type *LengthTy = MI.getLength()->getType();
5608     unsigned ElemSz = MI.getElementSizeInBytes();
5609     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5610     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5611                                      LengthTy, ElemSz, isTC,
5612                                      MachinePointerInfo(MI.getRawDest()));
5613     updateDAGForMaybeTailCall(MC);
5614     return nullptr;
5615   }
5616   case Intrinsic::dbg_addr:
5617   case Intrinsic::dbg_declare: {
5618     const auto &DI = cast<DbgVariableIntrinsic>(I);
5619     DILocalVariable *Variable = DI.getVariable();
5620     DIExpression *Expression = DI.getExpression();
5621     dropDanglingDebugInfo(Variable, Expression);
5622     assert(Variable && "Missing variable");
5623 
5624     // Check if address has undef value.
5625     const Value *Address = DI.getVariableLocation();
5626     if (!Address || isa<UndefValue>(Address) ||
5627         (Address->use_empty() && !isa<Argument>(Address))) {
5628       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5629       return nullptr;
5630     }
5631 
5632     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5633 
5634     // Check if this variable can be described by a frame index, typically
5635     // either as a static alloca or a byval parameter.
5636     int FI = std::numeric_limits<int>::max();
5637     if (const auto *AI =
5638             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5639       if (AI->isStaticAlloca()) {
5640         auto I = FuncInfo.StaticAllocaMap.find(AI);
5641         if (I != FuncInfo.StaticAllocaMap.end())
5642           FI = I->second;
5643       }
5644     } else if (const auto *Arg = dyn_cast<Argument>(
5645                    Address->stripInBoundsConstantOffsets())) {
5646       FI = FuncInfo.getArgumentFrameIndex(Arg);
5647     }
5648 
5649     // llvm.dbg.addr is control dependent and always generates indirect
5650     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5651     // the MachineFunction variable table.
5652     if (FI != std::numeric_limits<int>::max()) {
5653       if (Intrinsic == Intrinsic::dbg_addr) {
5654         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5655             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5656         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5657       }
5658       return nullptr;
5659     }
5660 
5661     SDValue &N = NodeMap[Address];
5662     if (!N.getNode() && isa<Argument>(Address))
5663       // Check unused arguments map.
5664       N = UnusedArgNodeMap[Address];
5665     SDDbgValue *SDV;
5666     if (N.getNode()) {
5667       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5668         Address = BCI->getOperand(0);
5669       // Parameters are handled specially.
5670       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5671       if (isParameter && FINode) {
5672         // Byval parameter. We have a frame index at this point.
5673         SDV =
5674             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5675                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5676       } else if (isa<Argument>(Address)) {
5677         // Address is an argument, so try to emit its dbg value using
5678         // virtual register info from the FuncInfo.ValueMap.
5679         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5680         return nullptr;
5681       } else {
5682         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5683                               true, dl, SDNodeOrder);
5684       }
5685       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5686     } else {
5687       // If Address is an argument then try to emit its dbg value using
5688       // virtual register info from the FuncInfo.ValueMap.
5689       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5690                                     N)) {
5691         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5692       }
5693     }
5694     return nullptr;
5695   }
5696   case Intrinsic::dbg_label: {
5697     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5698     DILabel *Label = DI.getLabel();
5699     assert(Label && "Missing label");
5700 
5701     SDDbgLabel *SDV;
5702     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5703     DAG.AddDbgLabel(SDV);
5704     return nullptr;
5705   }
5706   case Intrinsic::dbg_value: {
5707     const DbgValueInst &DI = cast<DbgValueInst>(I);
5708     assert(DI.getVariable() && "Missing variable");
5709 
5710     DILocalVariable *Variable = DI.getVariable();
5711     DIExpression *Expression = DI.getExpression();
5712     dropDanglingDebugInfo(Variable, Expression);
5713     const Value *V = DI.getValue();
5714     if (!V)
5715       return nullptr;
5716 
5717     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5718         SDNodeOrder))
5719       return nullptr;
5720 
5721     // TODO: Dangling debug info will eventually either be resolved or produce
5722     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5723     // between the original dbg.value location and its resolved DBG_VALUE, which
5724     // we should ideally fill with an extra Undef DBG_VALUE.
5725 
5726     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5727     return nullptr;
5728   }
5729 
5730   case Intrinsic::eh_typeid_for: {
5731     // Find the type id for the given typeinfo.
5732     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5733     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5734     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5735     setValue(&I, Res);
5736     return nullptr;
5737   }
5738 
5739   case Intrinsic::eh_return_i32:
5740   case Intrinsic::eh_return_i64:
5741     DAG.getMachineFunction().setCallsEHReturn(true);
5742     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5743                             MVT::Other,
5744                             getControlRoot(),
5745                             getValue(I.getArgOperand(0)),
5746                             getValue(I.getArgOperand(1))));
5747     return nullptr;
5748   case Intrinsic::eh_unwind_init:
5749     DAG.getMachineFunction().setCallsUnwindInit(true);
5750     return nullptr;
5751   case Intrinsic::eh_dwarf_cfa:
5752     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5753                              TLI.getPointerTy(DAG.getDataLayout()),
5754                              getValue(I.getArgOperand(0))));
5755     return nullptr;
5756   case Intrinsic::eh_sjlj_callsite: {
5757     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5758     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5759     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5760     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5761 
5762     MMI.setCurrentCallSite(CI->getZExtValue());
5763     return nullptr;
5764   }
5765   case Intrinsic::eh_sjlj_functioncontext: {
5766     // Get and store the index of the function context.
5767     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5768     AllocaInst *FnCtx =
5769       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5770     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5771     MFI.setFunctionContextIndex(FI);
5772     return nullptr;
5773   }
5774   case Intrinsic::eh_sjlj_setjmp: {
5775     SDValue Ops[2];
5776     Ops[0] = getRoot();
5777     Ops[1] = getValue(I.getArgOperand(0));
5778     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5779                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5780     setValue(&I, Op.getValue(0));
5781     DAG.setRoot(Op.getValue(1));
5782     return nullptr;
5783   }
5784   case Intrinsic::eh_sjlj_longjmp:
5785     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5786                             getRoot(), getValue(I.getArgOperand(0))));
5787     return nullptr;
5788   case Intrinsic::eh_sjlj_setup_dispatch:
5789     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5790                             getRoot()));
5791     return nullptr;
5792   case Intrinsic::masked_gather:
5793     visitMaskedGather(I);
5794     return nullptr;
5795   case Intrinsic::masked_load:
5796     visitMaskedLoad(I);
5797     return nullptr;
5798   case Intrinsic::masked_scatter:
5799     visitMaskedScatter(I);
5800     return nullptr;
5801   case Intrinsic::masked_store:
5802     visitMaskedStore(I);
5803     return nullptr;
5804   case Intrinsic::masked_expandload:
5805     visitMaskedLoad(I, true /* IsExpanding */);
5806     return nullptr;
5807   case Intrinsic::masked_compressstore:
5808     visitMaskedStore(I, true /* IsCompressing */);
5809     return nullptr;
5810   case Intrinsic::x86_mmx_pslli_w:
5811   case Intrinsic::x86_mmx_pslli_d:
5812   case Intrinsic::x86_mmx_pslli_q:
5813   case Intrinsic::x86_mmx_psrli_w:
5814   case Intrinsic::x86_mmx_psrli_d:
5815   case Intrinsic::x86_mmx_psrli_q:
5816   case Intrinsic::x86_mmx_psrai_w:
5817   case Intrinsic::x86_mmx_psrai_d: {
5818     SDValue ShAmt = getValue(I.getArgOperand(1));
5819     if (isa<ConstantSDNode>(ShAmt)) {
5820       visitTargetIntrinsic(I, Intrinsic);
5821       return nullptr;
5822     }
5823     unsigned NewIntrinsic = 0;
5824     EVT ShAmtVT = MVT::v2i32;
5825     switch (Intrinsic) {
5826     case Intrinsic::x86_mmx_pslli_w:
5827       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5828       break;
5829     case Intrinsic::x86_mmx_pslli_d:
5830       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5831       break;
5832     case Intrinsic::x86_mmx_pslli_q:
5833       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5834       break;
5835     case Intrinsic::x86_mmx_psrli_w:
5836       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5837       break;
5838     case Intrinsic::x86_mmx_psrli_d:
5839       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5840       break;
5841     case Intrinsic::x86_mmx_psrli_q:
5842       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5843       break;
5844     case Intrinsic::x86_mmx_psrai_w:
5845       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5846       break;
5847     case Intrinsic::x86_mmx_psrai_d:
5848       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5849       break;
5850     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5851     }
5852 
5853     // The vector shift intrinsics with scalars uses 32b shift amounts but
5854     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5855     // to be zero.
5856     // We must do this early because v2i32 is not a legal type.
5857     SDValue ShOps[2];
5858     ShOps[0] = ShAmt;
5859     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5860     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5861     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5862     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5863     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5864                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5865                        getValue(I.getArgOperand(0)), ShAmt);
5866     setValue(&I, Res);
5867     return nullptr;
5868   }
5869   case Intrinsic::powi:
5870     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5871                             getValue(I.getArgOperand(1)), DAG));
5872     return nullptr;
5873   case Intrinsic::log:
5874     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5875     return nullptr;
5876   case Intrinsic::log2:
5877     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5878     return nullptr;
5879   case Intrinsic::log10:
5880     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5881     return nullptr;
5882   case Intrinsic::exp:
5883     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5884     return nullptr;
5885   case Intrinsic::exp2:
5886     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5887     return nullptr;
5888   case Intrinsic::pow:
5889     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5890                            getValue(I.getArgOperand(1)), DAG, TLI));
5891     return nullptr;
5892   case Intrinsic::sqrt:
5893   case Intrinsic::fabs:
5894   case Intrinsic::sin:
5895   case Intrinsic::cos:
5896   case Intrinsic::floor:
5897   case Intrinsic::ceil:
5898   case Intrinsic::trunc:
5899   case Intrinsic::rint:
5900   case Intrinsic::nearbyint:
5901   case Intrinsic::round:
5902   case Intrinsic::canonicalize: {
5903     unsigned Opcode;
5904     switch (Intrinsic) {
5905     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5906     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5907     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5908     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5909     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5910     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5911     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5912     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5913     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5914     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5915     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5916     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5917     }
5918 
5919     setValue(&I, DAG.getNode(Opcode, sdl,
5920                              getValue(I.getArgOperand(0)).getValueType(),
5921                              getValue(I.getArgOperand(0))));
5922     return nullptr;
5923   }
5924   case Intrinsic::minnum: {
5925     auto VT = getValue(I.getArgOperand(0)).getValueType();
5926     unsigned Opc =
5927         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5928             ? ISD::FMINIMUM
5929             : ISD::FMINNUM;
5930     setValue(&I, DAG.getNode(Opc, sdl, VT,
5931                              getValue(I.getArgOperand(0)),
5932                              getValue(I.getArgOperand(1))));
5933     return nullptr;
5934   }
5935   case Intrinsic::maxnum: {
5936     auto VT = getValue(I.getArgOperand(0)).getValueType();
5937     unsigned Opc =
5938         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5939             ? ISD::FMAXIMUM
5940             : ISD::FMAXNUM;
5941     setValue(&I, DAG.getNode(Opc, sdl, VT,
5942                              getValue(I.getArgOperand(0)),
5943                              getValue(I.getArgOperand(1))));
5944     return nullptr;
5945   }
5946   case Intrinsic::minimum:
5947     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5948                              getValue(I.getArgOperand(0)).getValueType(),
5949                              getValue(I.getArgOperand(0)),
5950                              getValue(I.getArgOperand(1))));
5951     return nullptr;
5952   case Intrinsic::maximum:
5953     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5954                              getValue(I.getArgOperand(0)).getValueType(),
5955                              getValue(I.getArgOperand(0)),
5956                              getValue(I.getArgOperand(1))));
5957     return nullptr;
5958   case Intrinsic::copysign:
5959     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5960                              getValue(I.getArgOperand(0)).getValueType(),
5961                              getValue(I.getArgOperand(0)),
5962                              getValue(I.getArgOperand(1))));
5963     return nullptr;
5964   case Intrinsic::fma:
5965     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5966                              getValue(I.getArgOperand(0)).getValueType(),
5967                              getValue(I.getArgOperand(0)),
5968                              getValue(I.getArgOperand(1)),
5969                              getValue(I.getArgOperand(2))));
5970     return nullptr;
5971   case Intrinsic::experimental_constrained_fadd:
5972   case Intrinsic::experimental_constrained_fsub:
5973   case Intrinsic::experimental_constrained_fmul:
5974   case Intrinsic::experimental_constrained_fdiv:
5975   case Intrinsic::experimental_constrained_frem:
5976   case Intrinsic::experimental_constrained_fma:
5977   case Intrinsic::experimental_constrained_sqrt:
5978   case Intrinsic::experimental_constrained_pow:
5979   case Intrinsic::experimental_constrained_powi:
5980   case Intrinsic::experimental_constrained_sin:
5981   case Intrinsic::experimental_constrained_cos:
5982   case Intrinsic::experimental_constrained_exp:
5983   case Intrinsic::experimental_constrained_exp2:
5984   case Intrinsic::experimental_constrained_log:
5985   case Intrinsic::experimental_constrained_log10:
5986   case Intrinsic::experimental_constrained_log2:
5987   case Intrinsic::experimental_constrained_rint:
5988   case Intrinsic::experimental_constrained_nearbyint:
5989   case Intrinsic::experimental_constrained_maxnum:
5990   case Intrinsic::experimental_constrained_minnum:
5991   case Intrinsic::experimental_constrained_ceil:
5992   case Intrinsic::experimental_constrained_floor:
5993   case Intrinsic::experimental_constrained_round:
5994   case Intrinsic::experimental_constrained_trunc:
5995     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5996     return nullptr;
5997   case Intrinsic::fmuladd: {
5998     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5999     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6000         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6001       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6002                                getValue(I.getArgOperand(0)).getValueType(),
6003                                getValue(I.getArgOperand(0)),
6004                                getValue(I.getArgOperand(1)),
6005                                getValue(I.getArgOperand(2))));
6006     } else {
6007       // TODO: Intrinsic calls should have fast-math-flags.
6008       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6009                                 getValue(I.getArgOperand(0)).getValueType(),
6010                                 getValue(I.getArgOperand(0)),
6011                                 getValue(I.getArgOperand(1)));
6012       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6013                                 getValue(I.getArgOperand(0)).getValueType(),
6014                                 Mul,
6015                                 getValue(I.getArgOperand(2)));
6016       setValue(&I, Add);
6017     }
6018     return nullptr;
6019   }
6020   case Intrinsic::convert_to_fp16:
6021     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6022                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6023                                          getValue(I.getArgOperand(0)),
6024                                          DAG.getTargetConstant(0, sdl,
6025                                                                MVT::i32))));
6026     return nullptr;
6027   case Intrinsic::convert_from_fp16:
6028     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6029                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6030                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6031                                          getValue(I.getArgOperand(0)))));
6032     return nullptr;
6033   case Intrinsic::pcmarker: {
6034     SDValue Tmp = getValue(I.getArgOperand(0));
6035     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6036     return nullptr;
6037   }
6038   case Intrinsic::readcyclecounter: {
6039     SDValue Op = getRoot();
6040     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6041                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6042     setValue(&I, Res);
6043     DAG.setRoot(Res.getValue(1));
6044     return nullptr;
6045   }
6046   case Intrinsic::bitreverse:
6047     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6048                              getValue(I.getArgOperand(0)).getValueType(),
6049                              getValue(I.getArgOperand(0))));
6050     return nullptr;
6051   case Intrinsic::bswap:
6052     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6053                              getValue(I.getArgOperand(0)).getValueType(),
6054                              getValue(I.getArgOperand(0))));
6055     return nullptr;
6056   case Intrinsic::cttz: {
6057     SDValue Arg = getValue(I.getArgOperand(0));
6058     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6059     EVT Ty = Arg.getValueType();
6060     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6061                              sdl, Ty, Arg));
6062     return nullptr;
6063   }
6064   case Intrinsic::ctlz: {
6065     SDValue Arg = getValue(I.getArgOperand(0));
6066     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6067     EVT Ty = Arg.getValueType();
6068     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6069                              sdl, Ty, Arg));
6070     return nullptr;
6071   }
6072   case Intrinsic::ctpop: {
6073     SDValue Arg = getValue(I.getArgOperand(0));
6074     EVT Ty = Arg.getValueType();
6075     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6076     return nullptr;
6077   }
6078   case Intrinsic::fshl:
6079   case Intrinsic::fshr: {
6080     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6081     SDValue X = getValue(I.getArgOperand(0));
6082     SDValue Y = getValue(I.getArgOperand(1));
6083     SDValue Z = getValue(I.getArgOperand(2));
6084     EVT VT = X.getValueType();
6085     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6086     SDValue Zero = DAG.getConstant(0, sdl, VT);
6087     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6088 
6089     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6090     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6091       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6092       return nullptr;
6093     }
6094 
6095     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6096     // avoid the select that is necessary in the general case to filter out
6097     // the 0-shift possibility that leads to UB.
6098     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6099       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6100       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6101         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6102         return nullptr;
6103       }
6104 
6105       // Some targets only rotate one way. Try the opposite direction.
6106       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6107       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6108         // Negate the shift amount because it is safe to ignore the high bits.
6109         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6110         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6111         return nullptr;
6112       }
6113 
6114       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6115       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6116       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6117       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6118       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6119       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6120       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6121       return nullptr;
6122     }
6123 
6124     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6125     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6126     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6127     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6128     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6129     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6130 
6131     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6132     // and that is undefined. We must compare and select to avoid UB.
6133     EVT CCVT = MVT::i1;
6134     if (VT.isVector())
6135       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6136 
6137     // For fshl, 0-shift returns the 1st arg (X).
6138     // For fshr, 0-shift returns the 2nd arg (Y).
6139     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6140     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6141     return nullptr;
6142   }
6143   case Intrinsic::sadd_sat: {
6144     SDValue Op1 = getValue(I.getArgOperand(0));
6145     SDValue Op2 = getValue(I.getArgOperand(1));
6146     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6147     return nullptr;
6148   }
6149   case Intrinsic::uadd_sat: {
6150     SDValue Op1 = getValue(I.getArgOperand(0));
6151     SDValue Op2 = getValue(I.getArgOperand(1));
6152     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6153     return nullptr;
6154   }
6155   case Intrinsic::ssub_sat: {
6156     SDValue Op1 = getValue(I.getArgOperand(0));
6157     SDValue Op2 = getValue(I.getArgOperand(1));
6158     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6159     return nullptr;
6160   }
6161   case Intrinsic::usub_sat: {
6162     SDValue Op1 = getValue(I.getArgOperand(0));
6163     SDValue Op2 = getValue(I.getArgOperand(1));
6164     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6165     return nullptr;
6166   }
6167   case Intrinsic::smul_fix:
6168   case Intrinsic::umul_fix: {
6169     SDValue Op1 = getValue(I.getArgOperand(0));
6170     SDValue Op2 = getValue(I.getArgOperand(1));
6171     SDValue Op3 = getValue(I.getArgOperand(2));
6172     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6173                              Op1.getValueType(), Op1, Op2, Op3));
6174     return nullptr;
6175   }
6176   case Intrinsic::stacksave: {
6177     SDValue Op = getRoot();
6178     Res = DAG.getNode(
6179         ISD::STACKSAVE, sdl,
6180         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6181     setValue(&I, Res);
6182     DAG.setRoot(Res.getValue(1));
6183     return nullptr;
6184   }
6185   case Intrinsic::stackrestore:
6186     Res = getValue(I.getArgOperand(0));
6187     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6188     return nullptr;
6189   case Intrinsic::get_dynamic_area_offset: {
6190     SDValue Op = getRoot();
6191     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6192     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6193     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6194     // target.
6195     if (PtrTy != ResTy)
6196       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6197                          " intrinsic!");
6198     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6199                       Op);
6200     DAG.setRoot(Op);
6201     setValue(&I, Res);
6202     return nullptr;
6203   }
6204   case Intrinsic::stackguard: {
6205     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6206     MachineFunction &MF = DAG.getMachineFunction();
6207     const Module &M = *MF.getFunction().getParent();
6208     SDValue Chain = getRoot();
6209     if (TLI.useLoadStackGuardNode()) {
6210       Res = getLoadStackGuard(DAG, sdl, Chain);
6211     } else {
6212       const Value *Global = TLI.getSDagStackGuard(M);
6213       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6214       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6215                         MachinePointerInfo(Global, 0), Align,
6216                         MachineMemOperand::MOVolatile);
6217     }
6218     if (TLI.useStackGuardXorFP())
6219       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6220     DAG.setRoot(Chain);
6221     setValue(&I, Res);
6222     return nullptr;
6223   }
6224   case Intrinsic::stackprotector: {
6225     // Emit code into the DAG to store the stack guard onto the stack.
6226     MachineFunction &MF = DAG.getMachineFunction();
6227     MachineFrameInfo &MFI = MF.getFrameInfo();
6228     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6229     SDValue Src, Chain = getRoot();
6230 
6231     if (TLI.useLoadStackGuardNode())
6232       Src = getLoadStackGuard(DAG, sdl, Chain);
6233     else
6234       Src = getValue(I.getArgOperand(0));   // The guard's value.
6235 
6236     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6237 
6238     int FI = FuncInfo.StaticAllocaMap[Slot];
6239     MFI.setStackProtectorIndex(FI);
6240 
6241     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6242 
6243     // Store the stack protector onto the stack.
6244     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6245                                                  DAG.getMachineFunction(), FI),
6246                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6247     setValue(&I, Res);
6248     DAG.setRoot(Res);
6249     return nullptr;
6250   }
6251   case Intrinsic::objectsize: {
6252     // If we don't know by now, we're never going to know.
6253     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6254 
6255     assert(CI && "Non-constant type in __builtin_object_size?");
6256 
6257     SDValue Arg = getValue(I.getCalledValue());
6258     EVT Ty = Arg.getValueType();
6259 
6260     if (CI->isZero())
6261       Res = DAG.getConstant(-1ULL, sdl, Ty);
6262     else
6263       Res = DAG.getConstant(0, sdl, Ty);
6264 
6265     setValue(&I, Res);
6266     return nullptr;
6267   }
6268 
6269   case Intrinsic::is_constant:
6270     // If this wasn't constant-folded away by now, then it's not a
6271     // constant.
6272     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6273     return nullptr;
6274 
6275   case Intrinsic::annotation:
6276   case Intrinsic::ptr_annotation:
6277   case Intrinsic::launder_invariant_group:
6278   case Intrinsic::strip_invariant_group:
6279     // Drop the intrinsic, but forward the value
6280     setValue(&I, getValue(I.getOperand(0)));
6281     return nullptr;
6282   case Intrinsic::assume:
6283   case Intrinsic::var_annotation:
6284   case Intrinsic::sideeffect:
6285     // Discard annotate attributes, assumptions, and artificial side-effects.
6286     return nullptr;
6287 
6288   case Intrinsic::codeview_annotation: {
6289     // Emit a label associated with this metadata.
6290     MachineFunction &MF = DAG.getMachineFunction();
6291     MCSymbol *Label =
6292         MF.getMMI().getContext().createTempSymbol("annotation", true);
6293     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6294     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6295     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6296     DAG.setRoot(Res);
6297     return nullptr;
6298   }
6299 
6300   case Intrinsic::init_trampoline: {
6301     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6302 
6303     SDValue Ops[6];
6304     Ops[0] = getRoot();
6305     Ops[1] = getValue(I.getArgOperand(0));
6306     Ops[2] = getValue(I.getArgOperand(1));
6307     Ops[3] = getValue(I.getArgOperand(2));
6308     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6309     Ops[5] = DAG.getSrcValue(F);
6310 
6311     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6312 
6313     DAG.setRoot(Res);
6314     return nullptr;
6315   }
6316   case Intrinsic::adjust_trampoline:
6317     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6318                              TLI.getPointerTy(DAG.getDataLayout()),
6319                              getValue(I.getArgOperand(0))));
6320     return nullptr;
6321   case Intrinsic::gcroot: {
6322     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6323            "only valid in functions with gc specified, enforced by Verifier");
6324     assert(GFI && "implied by previous");
6325     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6326     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6327 
6328     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6329     GFI->addStackRoot(FI->getIndex(), TypeMap);
6330     return nullptr;
6331   }
6332   case Intrinsic::gcread:
6333   case Intrinsic::gcwrite:
6334     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6335   case Intrinsic::flt_rounds:
6336     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6337     return nullptr;
6338 
6339   case Intrinsic::expect:
6340     // Just replace __builtin_expect(exp, c) with EXP.
6341     setValue(&I, getValue(I.getArgOperand(0)));
6342     return nullptr;
6343 
6344   case Intrinsic::debugtrap:
6345   case Intrinsic::trap: {
6346     StringRef TrapFuncName =
6347         I.getAttributes()
6348             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6349             .getValueAsString();
6350     if (TrapFuncName.empty()) {
6351       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6352         ISD::TRAP : ISD::DEBUGTRAP;
6353       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6354       return nullptr;
6355     }
6356     TargetLowering::ArgListTy Args;
6357 
6358     TargetLowering::CallLoweringInfo CLI(DAG);
6359     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6360         CallingConv::C, I.getType(),
6361         DAG.getExternalSymbol(TrapFuncName.data(),
6362                               TLI.getPointerTy(DAG.getDataLayout())),
6363         std::move(Args));
6364 
6365     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6366     DAG.setRoot(Result.second);
6367     return nullptr;
6368   }
6369 
6370   case Intrinsic::uadd_with_overflow:
6371   case Intrinsic::sadd_with_overflow:
6372   case Intrinsic::usub_with_overflow:
6373   case Intrinsic::ssub_with_overflow:
6374   case Intrinsic::umul_with_overflow:
6375   case Intrinsic::smul_with_overflow: {
6376     ISD::NodeType Op;
6377     switch (Intrinsic) {
6378     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6379     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6380     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6381     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6382     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6383     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6384     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6385     }
6386     SDValue Op1 = getValue(I.getArgOperand(0));
6387     SDValue Op2 = getValue(I.getArgOperand(1));
6388 
6389     EVT ResultVT = Op1.getValueType();
6390     EVT OverflowVT = MVT::i1;
6391     if (ResultVT.isVector())
6392       OverflowVT = EVT::getVectorVT(
6393           *Context, OverflowVT, ResultVT.getVectorNumElements());
6394 
6395     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6396     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6397     return nullptr;
6398   }
6399   case Intrinsic::prefetch: {
6400     SDValue Ops[5];
6401     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6402     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6403     Ops[0] = DAG.getRoot();
6404     Ops[1] = getValue(I.getArgOperand(0));
6405     Ops[2] = getValue(I.getArgOperand(1));
6406     Ops[3] = getValue(I.getArgOperand(2));
6407     Ops[4] = getValue(I.getArgOperand(3));
6408     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6409                                              DAG.getVTList(MVT::Other), Ops,
6410                                              EVT::getIntegerVT(*Context, 8),
6411                                              MachinePointerInfo(I.getArgOperand(0)),
6412                                              0, /* align */
6413                                              Flags);
6414 
6415     // Chain the prefetch in parallell with any pending loads, to stay out of
6416     // the way of later optimizations.
6417     PendingLoads.push_back(Result);
6418     Result = getRoot();
6419     DAG.setRoot(Result);
6420     return nullptr;
6421   }
6422   case Intrinsic::lifetime_start:
6423   case Intrinsic::lifetime_end: {
6424     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6425     // Stack coloring is not enabled in O0, discard region information.
6426     if (TM.getOptLevel() == CodeGenOpt::None)
6427       return nullptr;
6428 
6429     const int64_t ObjectSize =
6430         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6431     Value *const ObjectPtr = I.getArgOperand(1);
6432     SmallVector<Value *, 4> Allocas;
6433     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6434 
6435     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6436            E = Allocas.end(); Object != E; ++Object) {
6437       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6438 
6439       // Could not find an Alloca.
6440       if (!LifetimeObject)
6441         continue;
6442 
6443       // First check that the Alloca is static, otherwise it won't have a
6444       // valid frame index.
6445       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6446       if (SI == FuncInfo.StaticAllocaMap.end())
6447         return nullptr;
6448 
6449       const int FrameIndex = SI->second;
6450       int64_t Offset;
6451       if (GetPointerBaseWithConstantOffset(
6452               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6453         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6454       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6455                                 Offset);
6456       DAG.setRoot(Res);
6457     }
6458     return nullptr;
6459   }
6460   case Intrinsic::invariant_start:
6461     // Discard region information.
6462     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6463     return nullptr;
6464   case Intrinsic::invariant_end:
6465     // Discard region information.
6466     return nullptr;
6467   case Intrinsic::clear_cache:
6468     return TLI.getClearCacheBuiltinName();
6469   case Intrinsic::donothing:
6470     // ignore
6471     return nullptr;
6472   case Intrinsic::experimental_stackmap:
6473     visitStackmap(I);
6474     return nullptr;
6475   case Intrinsic::experimental_patchpoint_void:
6476   case Intrinsic::experimental_patchpoint_i64:
6477     visitPatchpoint(&I);
6478     return nullptr;
6479   case Intrinsic::experimental_gc_statepoint:
6480     LowerStatepoint(ImmutableStatepoint(&I));
6481     return nullptr;
6482   case Intrinsic::experimental_gc_result:
6483     visitGCResult(cast<GCResultInst>(I));
6484     return nullptr;
6485   case Intrinsic::experimental_gc_relocate:
6486     visitGCRelocate(cast<GCRelocateInst>(I));
6487     return nullptr;
6488   case Intrinsic::instrprof_increment:
6489     llvm_unreachable("instrprof failed to lower an increment");
6490   case Intrinsic::instrprof_value_profile:
6491     llvm_unreachable("instrprof failed to lower a value profiling call");
6492   case Intrinsic::localescape: {
6493     MachineFunction &MF = DAG.getMachineFunction();
6494     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6495 
6496     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6497     // is the same on all targets.
6498     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6499       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6500       if (isa<ConstantPointerNull>(Arg))
6501         continue; // Skip null pointers. They represent a hole in index space.
6502       AllocaInst *Slot = cast<AllocaInst>(Arg);
6503       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6504              "can only escape static allocas");
6505       int FI = FuncInfo.StaticAllocaMap[Slot];
6506       MCSymbol *FrameAllocSym =
6507           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6508               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6509       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6510               TII->get(TargetOpcode::LOCAL_ESCAPE))
6511           .addSym(FrameAllocSym)
6512           .addFrameIndex(FI);
6513     }
6514 
6515     return nullptr;
6516   }
6517 
6518   case Intrinsic::localrecover: {
6519     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6520     MachineFunction &MF = DAG.getMachineFunction();
6521     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6522 
6523     // Get the symbol that defines the frame offset.
6524     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6525     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6526     unsigned IdxVal =
6527         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6528     MCSymbol *FrameAllocSym =
6529         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6530             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6531 
6532     // Create a MCSymbol for the label to avoid any target lowering
6533     // that would make this PC relative.
6534     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6535     SDValue OffsetVal =
6536         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6537 
6538     // Add the offset to the FP.
6539     Value *FP = I.getArgOperand(1);
6540     SDValue FPVal = getValue(FP);
6541     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6542     setValue(&I, Add);
6543 
6544     return nullptr;
6545   }
6546 
6547   case Intrinsic::eh_exceptionpointer:
6548   case Intrinsic::eh_exceptioncode: {
6549     // Get the exception pointer vreg, copy from it, and resize it to fit.
6550     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6551     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6552     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6553     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6554     SDValue N =
6555         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6556     if (Intrinsic == Intrinsic::eh_exceptioncode)
6557       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6558     setValue(&I, N);
6559     return nullptr;
6560   }
6561   case Intrinsic::xray_customevent: {
6562     // Here we want to make sure that the intrinsic behaves as if it has a
6563     // specific calling convention, and only for x86_64.
6564     // FIXME: Support other platforms later.
6565     const auto &Triple = DAG.getTarget().getTargetTriple();
6566     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6567       return nullptr;
6568 
6569     SDLoc DL = getCurSDLoc();
6570     SmallVector<SDValue, 8> Ops;
6571 
6572     // We want to say that we always want the arguments in registers.
6573     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6574     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6575     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6576     SDValue Chain = getRoot();
6577     Ops.push_back(LogEntryVal);
6578     Ops.push_back(StrSizeVal);
6579     Ops.push_back(Chain);
6580 
6581     // We need to enforce the calling convention for the callsite, so that
6582     // argument ordering is enforced correctly, and that register allocation can
6583     // see that some registers may be assumed clobbered and have to preserve
6584     // them across calls to the intrinsic.
6585     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6586                                            DL, NodeTys, Ops);
6587     SDValue patchableNode = SDValue(MN, 0);
6588     DAG.setRoot(patchableNode);
6589     setValue(&I, patchableNode);
6590     return nullptr;
6591   }
6592   case Intrinsic::xray_typedevent: {
6593     // Here we want to make sure that the intrinsic behaves as if it has a
6594     // specific calling convention, and only for x86_64.
6595     // FIXME: Support other platforms later.
6596     const auto &Triple = DAG.getTarget().getTargetTriple();
6597     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6598       return nullptr;
6599 
6600     SDLoc DL = getCurSDLoc();
6601     SmallVector<SDValue, 8> Ops;
6602 
6603     // We want to say that we always want the arguments in registers.
6604     // It's unclear to me how manipulating the selection DAG here forces callers
6605     // to provide arguments in registers instead of on the stack.
6606     SDValue LogTypeId = getValue(I.getArgOperand(0));
6607     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6608     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6609     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6610     SDValue Chain = getRoot();
6611     Ops.push_back(LogTypeId);
6612     Ops.push_back(LogEntryVal);
6613     Ops.push_back(StrSizeVal);
6614     Ops.push_back(Chain);
6615 
6616     // We need to enforce the calling convention for the callsite, so that
6617     // argument ordering is enforced correctly, and that register allocation can
6618     // see that some registers may be assumed clobbered and have to preserve
6619     // them across calls to the intrinsic.
6620     MachineSDNode *MN = DAG.getMachineNode(
6621         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6622     SDValue patchableNode = SDValue(MN, 0);
6623     DAG.setRoot(patchableNode);
6624     setValue(&I, patchableNode);
6625     return nullptr;
6626   }
6627   case Intrinsic::experimental_deoptimize:
6628     LowerDeoptimizeCall(&I);
6629     return nullptr;
6630 
6631   case Intrinsic::experimental_vector_reduce_fadd:
6632   case Intrinsic::experimental_vector_reduce_fmul:
6633   case Intrinsic::experimental_vector_reduce_add:
6634   case Intrinsic::experimental_vector_reduce_mul:
6635   case Intrinsic::experimental_vector_reduce_and:
6636   case Intrinsic::experimental_vector_reduce_or:
6637   case Intrinsic::experimental_vector_reduce_xor:
6638   case Intrinsic::experimental_vector_reduce_smax:
6639   case Intrinsic::experimental_vector_reduce_smin:
6640   case Intrinsic::experimental_vector_reduce_umax:
6641   case Intrinsic::experimental_vector_reduce_umin:
6642   case Intrinsic::experimental_vector_reduce_fmax:
6643   case Intrinsic::experimental_vector_reduce_fmin:
6644     visitVectorReduce(I, Intrinsic);
6645     return nullptr;
6646 
6647   case Intrinsic::icall_branch_funnel: {
6648     SmallVector<SDValue, 16> Ops;
6649     Ops.push_back(DAG.getRoot());
6650     Ops.push_back(getValue(I.getArgOperand(0)));
6651 
6652     int64_t Offset;
6653     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6654         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6655     if (!Base)
6656       report_fatal_error(
6657           "llvm.icall.branch.funnel operand must be a GlobalValue");
6658     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6659 
6660     struct BranchFunnelTarget {
6661       int64_t Offset;
6662       SDValue Target;
6663     };
6664     SmallVector<BranchFunnelTarget, 8> Targets;
6665 
6666     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6667       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6668           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6669       if (ElemBase != Base)
6670         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6671                            "to the same GlobalValue");
6672 
6673       SDValue Val = getValue(I.getArgOperand(Op + 1));
6674       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6675       if (!GA)
6676         report_fatal_error(
6677             "llvm.icall.branch.funnel operand must be a GlobalValue");
6678       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6679                                      GA->getGlobal(), getCurSDLoc(),
6680                                      Val.getValueType(), GA->getOffset())});
6681     }
6682     llvm::sort(Targets,
6683                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6684                  return T1.Offset < T2.Offset;
6685                });
6686 
6687     for (auto &T : Targets) {
6688       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6689       Ops.push_back(T.Target);
6690     }
6691 
6692     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6693                                  getCurSDLoc(), MVT::Other, Ops),
6694               0);
6695     DAG.setRoot(N);
6696     setValue(&I, N);
6697     HasTailCall = true;
6698     return nullptr;
6699   }
6700 
6701   case Intrinsic::wasm_landingpad_index:
6702     // Information this intrinsic contained has been transferred to
6703     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6704     // delete it now.
6705     return nullptr;
6706   }
6707 }
6708 
6709 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6710     const ConstrainedFPIntrinsic &FPI) {
6711   SDLoc sdl = getCurSDLoc();
6712   unsigned Opcode;
6713   switch (FPI.getIntrinsicID()) {
6714   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6715   case Intrinsic::experimental_constrained_fadd:
6716     Opcode = ISD::STRICT_FADD;
6717     break;
6718   case Intrinsic::experimental_constrained_fsub:
6719     Opcode = ISD::STRICT_FSUB;
6720     break;
6721   case Intrinsic::experimental_constrained_fmul:
6722     Opcode = ISD::STRICT_FMUL;
6723     break;
6724   case Intrinsic::experimental_constrained_fdiv:
6725     Opcode = ISD::STRICT_FDIV;
6726     break;
6727   case Intrinsic::experimental_constrained_frem:
6728     Opcode = ISD::STRICT_FREM;
6729     break;
6730   case Intrinsic::experimental_constrained_fma:
6731     Opcode = ISD::STRICT_FMA;
6732     break;
6733   case Intrinsic::experimental_constrained_sqrt:
6734     Opcode = ISD::STRICT_FSQRT;
6735     break;
6736   case Intrinsic::experimental_constrained_pow:
6737     Opcode = ISD::STRICT_FPOW;
6738     break;
6739   case Intrinsic::experimental_constrained_powi:
6740     Opcode = ISD::STRICT_FPOWI;
6741     break;
6742   case Intrinsic::experimental_constrained_sin:
6743     Opcode = ISD::STRICT_FSIN;
6744     break;
6745   case Intrinsic::experimental_constrained_cos:
6746     Opcode = ISD::STRICT_FCOS;
6747     break;
6748   case Intrinsic::experimental_constrained_exp:
6749     Opcode = ISD::STRICT_FEXP;
6750     break;
6751   case Intrinsic::experimental_constrained_exp2:
6752     Opcode = ISD::STRICT_FEXP2;
6753     break;
6754   case Intrinsic::experimental_constrained_log:
6755     Opcode = ISD::STRICT_FLOG;
6756     break;
6757   case Intrinsic::experimental_constrained_log10:
6758     Opcode = ISD::STRICT_FLOG10;
6759     break;
6760   case Intrinsic::experimental_constrained_log2:
6761     Opcode = ISD::STRICT_FLOG2;
6762     break;
6763   case Intrinsic::experimental_constrained_rint:
6764     Opcode = ISD::STRICT_FRINT;
6765     break;
6766   case Intrinsic::experimental_constrained_nearbyint:
6767     Opcode = ISD::STRICT_FNEARBYINT;
6768     break;
6769   case Intrinsic::experimental_constrained_maxnum:
6770     Opcode = ISD::STRICT_FMAXNUM;
6771     break;
6772   case Intrinsic::experimental_constrained_minnum:
6773     Opcode = ISD::STRICT_FMINNUM;
6774     break;
6775   case Intrinsic::experimental_constrained_ceil:
6776     Opcode = ISD::STRICT_FCEIL;
6777     break;
6778   case Intrinsic::experimental_constrained_floor:
6779     Opcode = ISD::STRICT_FFLOOR;
6780     break;
6781   case Intrinsic::experimental_constrained_round:
6782     Opcode = ISD::STRICT_FROUND;
6783     break;
6784   case Intrinsic::experimental_constrained_trunc:
6785     Opcode = ISD::STRICT_FTRUNC;
6786     break;
6787   }
6788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6789   SDValue Chain = getRoot();
6790   SmallVector<EVT, 4> ValueVTs;
6791   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6792   ValueVTs.push_back(MVT::Other); // Out chain
6793 
6794   SDVTList VTs = DAG.getVTList(ValueVTs);
6795   SDValue Result;
6796   if (FPI.isUnaryOp())
6797     Result = DAG.getNode(Opcode, sdl, VTs,
6798                          { Chain, getValue(FPI.getArgOperand(0)) });
6799   else if (FPI.isTernaryOp())
6800     Result = DAG.getNode(Opcode, sdl, VTs,
6801                          { Chain, getValue(FPI.getArgOperand(0)),
6802                                   getValue(FPI.getArgOperand(1)),
6803                                   getValue(FPI.getArgOperand(2)) });
6804   else
6805     Result = DAG.getNode(Opcode, sdl, VTs,
6806                          { Chain, getValue(FPI.getArgOperand(0)),
6807                            getValue(FPI.getArgOperand(1))  });
6808 
6809   assert(Result.getNode()->getNumValues() == 2);
6810   SDValue OutChain = Result.getValue(1);
6811   DAG.setRoot(OutChain);
6812   SDValue FPResult = Result.getValue(0);
6813   setValue(&FPI, FPResult);
6814 }
6815 
6816 std::pair<SDValue, SDValue>
6817 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6818                                     const BasicBlock *EHPadBB) {
6819   MachineFunction &MF = DAG.getMachineFunction();
6820   MachineModuleInfo &MMI = MF.getMMI();
6821   MCSymbol *BeginLabel = nullptr;
6822 
6823   if (EHPadBB) {
6824     // Insert a label before the invoke call to mark the try range.  This can be
6825     // used to detect deletion of the invoke via the MachineModuleInfo.
6826     BeginLabel = MMI.getContext().createTempSymbol();
6827 
6828     // For SjLj, keep track of which landing pads go with which invokes
6829     // so as to maintain the ordering of pads in the LSDA.
6830     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6831     if (CallSiteIndex) {
6832       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6833       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6834 
6835       // Now that the call site is handled, stop tracking it.
6836       MMI.setCurrentCallSite(0);
6837     }
6838 
6839     // Both PendingLoads and PendingExports must be flushed here;
6840     // this call might not return.
6841     (void)getRoot();
6842     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6843 
6844     CLI.setChain(getRoot());
6845   }
6846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6847   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6848 
6849   assert((CLI.IsTailCall || Result.second.getNode()) &&
6850          "Non-null chain expected with non-tail call!");
6851   assert((Result.second.getNode() || !Result.first.getNode()) &&
6852          "Null value expected with tail call!");
6853 
6854   if (!Result.second.getNode()) {
6855     // As a special case, a null chain means that a tail call has been emitted
6856     // and the DAG root is already updated.
6857     HasTailCall = true;
6858 
6859     // Since there's no actual continuation from this block, nothing can be
6860     // relying on us setting vregs for them.
6861     PendingExports.clear();
6862   } else {
6863     DAG.setRoot(Result.second);
6864   }
6865 
6866   if (EHPadBB) {
6867     // Insert a label at the end of the invoke call to mark the try range.  This
6868     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6869     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6870     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6871 
6872     // Inform MachineModuleInfo of range.
6873     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6874     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6875     // actually use outlined funclets and their LSDA info style.
6876     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6877       assert(CLI.CS);
6878       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6879       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6880                                 BeginLabel, EndLabel);
6881     } else if (!isScopedEHPersonality(Pers)) {
6882       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6883     }
6884   }
6885 
6886   return Result;
6887 }
6888 
6889 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6890                                       bool isTailCall,
6891                                       const BasicBlock *EHPadBB) {
6892   auto &DL = DAG.getDataLayout();
6893   FunctionType *FTy = CS.getFunctionType();
6894   Type *RetTy = CS.getType();
6895 
6896   TargetLowering::ArgListTy Args;
6897   Args.reserve(CS.arg_size());
6898 
6899   const Value *SwiftErrorVal = nullptr;
6900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6901 
6902   // We can't tail call inside a function with a swifterror argument. Lowering
6903   // does not support this yet. It would have to move into the swifterror
6904   // register before the call.
6905   auto *Caller = CS.getInstruction()->getParent()->getParent();
6906   if (TLI.supportSwiftError() &&
6907       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6908     isTailCall = false;
6909 
6910   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6911        i != e; ++i) {
6912     TargetLowering::ArgListEntry Entry;
6913     const Value *V = *i;
6914 
6915     // Skip empty types
6916     if (V->getType()->isEmptyTy())
6917       continue;
6918 
6919     SDValue ArgNode = getValue(V);
6920     Entry.Node = ArgNode; Entry.Ty = V->getType();
6921 
6922     Entry.setAttributes(&CS, i - CS.arg_begin());
6923 
6924     // Use swifterror virtual register as input to the call.
6925     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6926       SwiftErrorVal = V;
6927       // We find the virtual register for the actual swifterror argument.
6928       // Instead of using the Value, we use the virtual register instead.
6929       Entry.Node = DAG.getRegister(FuncInfo
6930                                        .getOrCreateSwiftErrorVRegUseAt(
6931                                            CS.getInstruction(), FuncInfo.MBB, V)
6932                                        .first,
6933                                    EVT(TLI.getPointerTy(DL)));
6934     }
6935 
6936     Args.push_back(Entry);
6937 
6938     // If we have an explicit sret argument that is an Instruction, (i.e., it
6939     // might point to function-local memory), we can't meaningfully tail-call.
6940     if (Entry.IsSRet && isa<Instruction>(V))
6941       isTailCall = false;
6942   }
6943 
6944   // Check if target-independent constraints permit a tail call here.
6945   // Target-dependent constraints are checked within TLI->LowerCallTo.
6946   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6947     isTailCall = false;
6948 
6949   // Disable tail calls if there is an swifterror argument. Targets have not
6950   // been updated to support tail calls.
6951   if (TLI.supportSwiftError() && SwiftErrorVal)
6952     isTailCall = false;
6953 
6954   TargetLowering::CallLoweringInfo CLI(DAG);
6955   CLI.setDebugLoc(getCurSDLoc())
6956       .setChain(getRoot())
6957       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6958       .setTailCall(isTailCall)
6959       .setConvergent(CS.isConvergent());
6960   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6961 
6962   if (Result.first.getNode()) {
6963     const Instruction *Inst = CS.getInstruction();
6964     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6965     setValue(Inst, Result.first);
6966   }
6967 
6968   // The last element of CLI.InVals has the SDValue for swifterror return.
6969   // Here we copy it to a virtual register and update SwiftErrorMap for
6970   // book-keeping.
6971   if (SwiftErrorVal && TLI.supportSwiftError()) {
6972     // Get the last element of InVals.
6973     SDValue Src = CLI.InVals.back();
6974     unsigned VReg; bool CreatedVReg;
6975     std::tie(VReg, CreatedVReg) =
6976         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6977     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6978     // We update the virtual register for the actual swifterror argument.
6979     if (CreatedVReg)
6980       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6981     DAG.setRoot(CopyNode);
6982   }
6983 }
6984 
6985 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6986                              SelectionDAGBuilder &Builder) {
6987   // Check to see if this load can be trivially constant folded, e.g. if the
6988   // input is from a string literal.
6989   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6990     // Cast pointer to the type we really want to load.
6991     Type *LoadTy =
6992         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6993     if (LoadVT.isVector())
6994       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6995 
6996     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6997                                          PointerType::getUnqual(LoadTy));
6998 
6999     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7000             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7001       return Builder.getValue(LoadCst);
7002   }
7003 
7004   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7005   // still constant memory, the input chain can be the entry node.
7006   SDValue Root;
7007   bool ConstantMemory = false;
7008 
7009   // Do not serialize (non-volatile) loads of constant memory with anything.
7010   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7011     Root = Builder.DAG.getEntryNode();
7012     ConstantMemory = true;
7013   } else {
7014     // Do not serialize non-volatile loads against each other.
7015     Root = Builder.DAG.getRoot();
7016   }
7017 
7018   SDValue Ptr = Builder.getValue(PtrVal);
7019   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7020                                         Ptr, MachinePointerInfo(PtrVal),
7021                                         /* Alignment = */ 1);
7022 
7023   if (!ConstantMemory)
7024     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7025   return LoadVal;
7026 }
7027 
7028 /// Record the value for an instruction that produces an integer result,
7029 /// converting the type where necessary.
7030 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7031                                                   SDValue Value,
7032                                                   bool IsSigned) {
7033   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7034                                                     I.getType(), true);
7035   if (IsSigned)
7036     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7037   else
7038     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7039   setValue(&I, Value);
7040 }
7041 
7042 /// See if we can lower a memcmp call into an optimized form. If so, return
7043 /// true and lower it. Otherwise return false, and it will be lowered like a
7044 /// normal call.
7045 /// The caller already checked that \p I calls the appropriate LibFunc with a
7046 /// correct prototype.
7047 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7048   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7049   const Value *Size = I.getArgOperand(2);
7050   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7051   if (CSize && CSize->getZExtValue() == 0) {
7052     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7053                                                           I.getType(), true);
7054     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7055     return true;
7056   }
7057 
7058   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7059   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7060       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7061       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7062   if (Res.first.getNode()) {
7063     processIntegerCallValue(I, Res.first, true);
7064     PendingLoads.push_back(Res.second);
7065     return true;
7066   }
7067 
7068   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7069   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7070   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7071     return false;
7072 
7073   // If the target has a fast compare for the given size, it will return a
7074   // preferred load type for that size. Require that the load VT is legal and
7075   // that the target supports unaligned loads of that type. Otherwise, return
7076   // INVALID.
7077   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7078     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7079     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7080     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7081       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7082       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7083       // TODO: Check alignment of src and dest ptrs.
7084       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7085       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7086       if (!TLI.isTypeLegal(LVT) ||
7087           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7088           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7089         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7090     }
7091 
7092     return LVT;
7093   };
7094 
7095   // This turns into unaligned loads. We only do this if the target natively
7096   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7097   // we'll only produce a small number of byte loads.
7098   MVT LoadVT;
7099   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7100   switch (NumBitsToCompare) {
7101   default:
7102     return false;
7103   case 16:
7104     LoadVT = MVT::i16;
7105     break;
7106   case 32:
7107     LoadVT = MVT::i32;
7108     break;
7109   case 64:
7110   case 128:
7111   case 256:
7112     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7113     break;
7114   }
7115 
7116   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7117     return false;
7118 
7119   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7120   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7121 
7122   // Bitcast to a wide integer type if the loads are vectors.
7123   if (LoadVT.isVector()) {
7124     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7125     LoadL = DAG.getBitcast(CmpVT, LoadL);
7126     LoadR = DAG.getBitcast(CmpVT, LoadR);
7127   }
7128 
7129   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7130   processIntegerCallValue(I, Cmp, false);
7131   return true;
7132 }
7133 
7134 /// See if we can lower a memchr call into an optimized form. If so, return
7135 /// true and lower it. Otherwise return false, and it will be lowered like a
7136 /// normal call.
7137 /// The caller already checked that \p I calls the appropriate LibFunc with a
7138 /// correct prototype.
7139 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7140   const Value *Src = I.getArgOperand(0);
7141   const Value *Char = I.getArgOperand(1);
7142   const Value *Length = I.getArgOperand(2);
7143 
7144   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7145   std::pair<SDValue, SDValue> Res =
7146     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7147                                 getValue(Src), getValue(Char), getValue(Length),
7148                                 MachinePointerInfo(Src));
7149   if (Res.first.getNode()) {
7150     setValue(&I, Res.first);
7151     PendingLoads.push_back(Res.second);
7152     return true;
7153   }
7154 
7155   return false;
7156 }
7157 
7158 /// See if we can lower a mempcpy call into an optimized form. If so, return
7159 /// true and lower it. Otherwise return false, and it will be lowered like a
7160 /// normal call.
7161 /// The caller already checked that \p I calls the appropriate LibFunc with a
7162 /// correct prototype.
7163 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7164   SDValue Dst = getValue(I.getArgOperand(0));
7165   SDValue Src = getValue(I.getArgOperand(1));
7166   SDValue Size = getValue(I.getArgOperand(2));
7167 
7168   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7169   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7170   unsigned Align = std::min(DstAlign, SrcAlign);
7171   if (Align == 0) // Alignment of one or both could not be inferred.
7172     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7173 
7174   bool isVol = false;
7175   SDLoc sdl = getCurSDLoc();
7176 
7177   // In the mempcpy context we need to pass in a false value for isTailCall
7178   // because the return pointer needs to be adjusted by the size of
7179   // the copied memory.
7180   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7181                              false, /*isTailCall=*/false,
7182                              MachinePointerInfo(I.getArgOperand(0)),
7183                              MachinePointerInfo(I.getArgOperand(1)));
7184   assert(MC.getNode() != nullptr &&
7185          "** memcpy should not be lowered as TailCall in mempcpy context **");
7186   DAG.setRoot(MC);
7187 
7188   // Check if Size needs to be truncated or extended.
7189   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7190 
7191   // Adjust return pointer to point just past the last dst byte.
7192   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7193                                     Dst, Size);
7194   setValue(&I, DstPlusSize);
7195   return true;
7196 }
7197 
7198 /// See if we can lower a strcpy call into an optimized form.  If so, return
7199 /// true and lower it, otherwise return false and it will be lowered like a
7200 /// normal call.
7201 /// The caller already checked that \p I calls the appropriate LibFunc with a
7202 /// correct prototype.
7203 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7204   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7205 
7206   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7207   std::pair<SDValue, SDValue> Res =
7208     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7209                                 getValue(Arg0), getValue(Arg1),
7210                                 MachinePointerInfo(Arg0),
7211                                 MachinePointerInfo(Arg1), isStpcpy);
7212   if (Res.first.getNode()) {
7213     setValue(&I, Res.first);
7214     DAG.setRoot(Res.second);
7215     return true;
7216   }
7217 
7218   return false;
7219 }
7220 
7221 /// See if we can lower a strcmp call into an optimized form.  If so, return
7222 /// true and lower it, otherwise return false and it will be lowered like a
7223 /// normal call.
7224 /// The caller already checked that \p I calls the appropriate LibFunc with a
7225 /// correct prototype.
7226 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7227   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7228 
7229   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7230   std::pair<SDValue, SDValue> Res =
7231     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7232                                 getValue(Arg0), getValue(Arg1),
7233                                 MachinePointerInfo(Arg0),
7234                                 MachinePointerInfo(Arg1));
7235   if (Res.first.getNode()) {
7236     processIntegerCallValue(I, Res.first, true);
7237     PendingLoads.push_back(Res.second);
7238     return true;
7239   }
7240 
7241   return false;
7242 }
7243 
7244 /// See if we can lower a strlen call into an optimized form.  If so, return
7245 /// true and lower it, otherwise return false and it will be lowered like a
7246 /// normal call.
7247 /// The caller already checked that \p I calls the appropriate LibFunc with a
7248 /// correct prototype.
7249 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7250   const Value *Arg0 = I.getArgOperand(0);
7251 
7252   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7253   std::pair<SDValue, SDValue> Res =
7254     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7255                                 getValue(Arg0), MachinePointerInfo(Arg0));
7256   if (Res.first.getNode()) {
7257     processIntegerCallValue(I, Res.first, false);
7258     PendingLoads.push_back(Res.second);
7259     return true;
7260   }
7261 
7262   return false;
7263 }
7264 
7265 /// See if we can lower a strnlen call into an optimized form.  If so, return
7266 /// true and lower it, otherwise return false and it will be lowered like a
7267 /// normal call.
7268 /// The caller already checked that \p I calls the appropriate LibFunc with a
7269 /// correct prototype.
7270 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7271   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7272 
7273   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7274   std::pair<SDValue, SDValue> Res =
7275     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7276                                  getValue(Arg0), getValue(Arg1),
7277                                  MachinePointerInfo(Arg0));
7278   if (Res.first.getNode()) {
7279     processIntegerCallValue(I, Res.first, false);
7280     PendingLoads.push_back(Res.second);
7281     return true;
7282   }
7283 
7284   return false;
7285 }
7286 
7287 /// See if we can lower a unary floating-point operation into an SDNode with
7288 /// the specified Opcode.  If so, return true and lower it, otherwise return
7289 /// false and it will be lowered like a normal call.
7290 /// The caller already checked that \p I calls the appropriate LibFunc with a
7291 /// correct prototype.
7292 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7293                                               unsigned Opcode) {
7294   // We already checked this call's prototype; verify it doesn't modify errno.
7295   if (!I.onlyReadsMemory())
7296     return false;
7297 
7298   SDValue Tmp = getValue(I.getArgOperand(0));
7299   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7300   return true;
7301 }
7302 
7303 /// See if we can lower a binary floating-point operation into an SDNode with
7304 /// the specified Opcode. If so, return true and lower it. Otherwise return
7305 /// false, and it will be lowered like a normal call.
7306 /// The caller already checked that \p I calls the appropriate LibFunc with a
7307 /// correct prototype.
7308 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7309                                                unsigned Opcode) {
7310   // We already checked this call's prototype; verify it doesn't modify errno.
7311   if (!I.onlyReadsMemory())
7312     return false;
7313 
7314   SDValue Tmp0 = getValue(I.getArgOperand(0));
7315   SDValue Tmp1 = getValue(I.getArgOperand(1));
7316   EVT VT = Tmp0.getValueType();
7317   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7318   return true;
7319 }
7320 
7321 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7322   // Handle inline assembly differently.
7323   if (isa<InlineAsm>(I.getCalledValue())) {
7324     visitInlineAsm(&I);
7325     return;
7326   }
7327 
7328   const char *RenameFn = nullptr;
7329   if (Function *F = I.getCalledFunction()) {
7330     if (F->isDeclaration()) {
7331       // Is this an LLVM intrinsic or a target-specific intrinsic?
7332       unsigned IID = F->getIntrinsicID();
7333       if (!IID)
7334         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7335           IID = II->getIntrinsicID(F);
7336 
7337       if (IID) {
7338         RenameFn = visitIntrinsicCall(I, IID);
7339         if (!RenameFn)
7340           return;
7341       }
7342     }
7343 
7344     // Check for well-known libc/libm calls.  If the function is internal, it
7345     // can't be a library call.  Don't do the check if marked as nobuiltin for
7346     // some reason or the call site requires strict floating point semantics.
7347     LibFunc Func;
7348     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7349         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7350         LibInfo->hasOptimizedCodeGen(Func)) {
7351       switch (Func) {
7352       default: break;
7353       case LibFunc_copysign:
7354       case LibFunc_copysignf:
7355       case LibFunc_copysignl:
7356         // We already checked this call's prototype; verify it doesn't modify
7357         // errno.
7358         if (I.onlyReadsMemory()) {
7359           SDValue LHS = getValue(I.getArgOperand(0));
7360           SDValue RHS = getValue(I.getArgOperand(1));
7361           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7362                                    LHS.getValueType(), LHS, RHS));
7363           return;
7364         }
7365         break;
7366       case LibFunc_fabs:
7367       case LibFunc_fabsf:
7368       case LibFunc_fabsl:
7369         if (visitUnaryFloatCall(I, ISD::FABS))
7370           return;
7371         break;
7372       case LibFunc_fmin:
7373       case LibFunc_fminf:
7374       case LibFunc_fminl:
7375         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7376           return;
7377         break;
7378       case LibFunc_fmax:
7379       case LibFunc_fmaxf:
7380       case LibFunc_fmaxl:
7381         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7382           return;
7383         break;
7384       case LibFunc_sin:
7385       case LibFunc_sinf:
7386       case LibFunc_sinl:
7387         if (visitUnaryFloatCall(I, ISD::FSIN))
7388           return;
7389         break;
7390       case LibFunc_cos:
7391       case LibFunc_cosf:
7392       case LibFunc_cosl:
7393         if (visitUnaryFloatCall(I, ISD::FCOS))
7394           return;
7395         break;
7396       case LibFunc_sqrt:
7397       case LibFunc_sqrtf:
7398       case LibFunc_sqrtl:
7399       case LibFunc_sqrt_finite:
7400       case LibFunc_sqrtf_finite:
7401       case LibFunc_sqrtl_finite:
7402         if (visitUnaryFloatCall(I, ISD::FSQRT))
7403           return;
7404         break;
7405       case LibFunc_floor:
7406       case LibFunc_floorf:
7407       case LibFunc_floorl:
7408         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7409           return;
7410         break;
7411       case LibFunc_nearbyint:
7412       case LibFunc_nearbyintf:
7413       case LibFunc_nearbyintl:
7414         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7415           return;
7416         break;
7417       case LibFunc_ceil:
7418       case LibFunc_ceilf:
7419       case LibFunc_ceill:
7420         if (visitUnaryFloatCall(I, ISD::FCEIL))
7421           return;
7422         break;
7423       case LibFunc_rint:
7424       case LibFunc_rintf:
7425       case LibFunc_rintl:
7426         if (visitUnaryFloatCall(I, ISD::FRINT))
7427           return;
7428         break;
7429       case LibFunc_round:
7430       case LibFunc_roundf:
7431       case LibFunc_roundl:
7432         if (visitUnaryFloatCall(I, ISD::FROUND))
7433           return;
7434         break;
7435       case LibFunc_trunc:
7436       case LibFunc_truncf:
7437       case LibFunc_truncl:
7438         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7439           return;
7440         break;
7441       case LibFunc_log2:
7442       case LibFunc_log2f:
7443       case LibFunc_log2l:
7444         if (visitUnaryFloatCall(I, ISD::FLOG2))
7445           return;
7446         break;
7447       case LibFunc_exp2:
7448       case LibFunc_exp2f:
7449       case LibFunc_exp2l:
7450         if (visitUnaryFloatCall(I, ISD::FEXP2))
7451           return;
7452         break;
7453       case LibFunc_memcmp:
7454         if (visitMemCmpCall(I))
7455           return;
7456         break;
7457       case LibFunc_mempcpy:
7458         if (visitMemPCpyCall(I))
7459           return;
7460         break;
7461       case LibFunc_memchr:
7462         if (visitMemChrCall(I))
7463           return;
7464         break;
7465       case LibFunc_strcpy:
7466         if (visitStrCpyCall(I, false))
7467           return;
7468         break;
7469       case LibFunc_stpcpy:
7470         if (visitStrCpyCall(I, true))
7471           return;
7472         break;
7473       case LibFunc_strcmp:
7474         if (visitStrCmpCall(I))
7475           return;
7476         break;
7477       case LibFunc_strlen:
7478         if (visitStrLenCall(I))
7479           return;
7480         break;
7481       case LibFunc_strnlen:
7482         if (visitStrNLenCall(I))
7483           return;
7484         break;
7485       }
7486     }
7487   }
7488 
7489   SDValue Callee;
7490   if (!RenameFn)
7491     Callee = getValue(I.getCalledValue());
7492   else
7493     Callee = DAG.getExternalSymbol(
7494         RenameFn,
7495         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7496 
7497   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7498   // have to do anything here to lower funclet bundles.
7499   assert(!I.hasOperandBundlesOtherThan(
7500              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7501          "Cannot lower calls with arbitrary operand bundles!");
7502 
7503   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7504     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7505   else
7506     // Check if we can potentially perform a tail call. More detailed checking
7507     // is be done within LowerCallTo, after more information about the call is
7508     // known.
7509     LowerCallTo(&I, Callee, I.isTailCall());
7510 }
7511 
7512 namespace {
7513 
7514 /// AsmOperandInfo - This contains information for each constraint that we are
7515 /// lowering.
7516 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7517 public:
7518   /// CallOperand - If this is the result output operand or a clobber
7519   /// this is null, otherwise it is the incoming operand to the CallInst.
7520   /// This gets modified as the asm is processed.
7521   SDValue CallOperand;
7522 
7523   /// AssignedRegs - If this is a register or register class operand, this
7524   /// contains the set of register corresponding to the operand.
7525   RegsForValue AssignedRegs;
7526 
7527   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7528     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7529   }
7530 
7531   /// Whether or not this operand accesses memory
7532   bool hasMemory(const TargetLowering &TLI) const {
7533     // Indirect operand accesses access memory.
7534     if (isIndirect)
7535       return true;
7536 
7537     for (const auto &Code : Codes)
7538       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7539         return true;
7540 
7541     return false;
7542   }
7543 
7544   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7545   /// corresponds to.  If there is no Value* for this operand, it returns
7546   /// MVT::Other.
7547   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7548                            const DataLayout &DL) const {
7549     if (!CallOperandVal) return MVT::Other;
7550 
7551     if (isa<BasicBlock>(CallOperandVal))
7552       return TLI.getPointerTy(DL);
7553 
7554     llvm::Type *OpTy = CallOperandVal->getType();
7555 
7556     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7557     // If this is an indirect operand, the operand is a pointer to the
7558     // accessed type.
7559     if (isIndirect) {
7560       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7561       if (!PtrTy)
7562         report_fatal_error("Indirect operand for inline asm not a pointer!");
7563       OpTy = PtrTy->getElementType();
7564     }
7565 
7566     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7567     if (StructType *STy = dyn_cast<StructType>(OpTy))
7568       if (STy->getNumElements() == 1)
7569         OpTy = STy->getElementType(0);
7570 
7571     // If OpTy is not a single value, it may be a struct/union that we
7572     // can tile with integers.
7573     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7574       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7575       switch (BitSize) {
7576       default: break;
7577       case 1:
7578       case 8:
7579       case 16:
7580       case 32:
7581       case 64:
7582       case 128:
7583         OpTy = IntegerType::get(Context, BitSize);
7584         break;
7585       }
7586     }
7587 
7588     return TLI.getValueType(DL, OpTy, true);
7589   }
7590 };
7591 
7592 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7593 
7594 } // end anonymous namespace
7595 
7596 /// Make sure that the output operand \p OpInfo and its corresponding input
7597 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7598 /// out).
7599 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7600                                SDISelAsmOperandInfo &MatchingOpInfo,
7601                                SelectionDAG &DAG) {
7602   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7603     return;
7604 
7605   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7606   const auto &TLI = DAG.getTargetLoweringInfo();
7607 
7608   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7609       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7610                                        OpInfo.ConstraintVT);
7611   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7612       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7613                                        MatchingOpInfo.ConstraintVT);
7614   if ((OpInfo.ConstraintVT.isInteger() !=
7615        MatchingOpInfo.ConstraintVT.isInteger()) ||
7616       (MatchRC.second != InputRC.second)) {
7617     // FIXME: error out in a more elegant fashion
7618     report_fatal_error("Unsupported asm: input constraint"
7619                        " with a matching output constraint of"
7620                        " incompatible type!");
7621   }
7622   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7623 }
7624 
7625 /// Get a direct memory input to behave well as an indirect operand.
7626 /// This may introduce stores, hence the need for a \p Chain.
7627 /// \return The (possibly updated) chain.
7628 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7629                                         SDISelAsmOperandInfo &OpInfo,
7630                                         SelectionDAG &DAG) {
7631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7632 
7633   // If we don't have an indirect input, put it in the constpool if we can,
7634   // otherwise spill it to a stack slot.
7635   // TODO: This isn't quite right. We need to handle these according to
7636   // the addressing mode that the constraint wants. Also, this may take
7637   // an additional register for the computation and we don't want that
7638   // either.
7639 
7640   // If the operand is a float, integer, or vector constant, spill to a
7641   // constant pool entry to get its address.
7642   const Value *OpVal = OpInfo.CallOperandVal;
7643   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7644       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7645     OpInfo.CallOperand = DAG.getConstantPool(
7646         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7647     return Chain;
7648   }
7649 
7650   // Otherwise, create a stack slot and emit a store to it before the asm.
7651   Type *Ty = OpVal->getType();
7652   auto &DL = DAG.getDataLayout();
7653   uint64_t TySize = DL.getTypeAllocSize(Ty);
7654   unsigned Align = DL.getPrefTypeAlignment(Ty);
7655   MachineFunction &MF = DAG.getMachineFunction();
7656   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7657   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7658   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7659                        MachinePointerInfo::getFixedStack(MF, SSFI));
7660   OpInfo.CallOperand = StackSlot;
7661 
7662   return Chain;
7663 }
7664 
7665 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7666 /// specified operand.  We prefer to assign virtual registers, to allow the
7667 /// register allocator to handle the assignment process.  However, if the asm
7668 /// uses features that we can't model on machineinstrs, we have SDISel do the
7669 /// allocation.  This produces generally horrible, but correct, code.
7670 ///
7671 ///   OpInfo describes the operand
7672 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7673 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7674                                  SDISelAsmOperandInfo &OpInfo,
7675                                  SDISelAsmOperandInfo &RefOpInfo) {
7676   LLVMContext &Context = *DAG.getContext();
7677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7678 
7679   MachineFunction &MF = DAG.getMachineFunction();
7680   SmallVector<unsigned, 4> Regs;
7681   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7682 
7683   // No work to do for memory operations.
7684   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7685     return;
7686 
7687   // If this is a constraint for a single physreg, or a constraint for a
7688   // register class, find it.
7689   unsigned AssignedReg;
7690   const TargetRegisterClass *RC;
7691   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7692       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7693   // RC is unset only on failure. Return immediately.
7694   if (!RC)
7695     return;
7696 
7697   // Get the actual register value type.  This is important, because the user
7698   // may have asked for (e.g.) the AX register in i32 type.  We need to
7699   // remember that AX is actually i16 to get the right extension.
7700   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7701 
7702   if (OpInfo.ConstraintVT != MVT::Other) {
7703     // If this is an FP operand in an integer register (or visa versa), or more
7704     // generally if the operand value disagrees with the register class we plan
7705     // to stick it in, fix the operand type.
7706     //
7707     // If this is an input value, the bitcast to the new type is done now.
7708     // Bitcast for output value is done at the end of visitInlineAsm().
7709     if ((OpInfo.Type == InlineAsm::isOutput ||
7710          OpInfo.Type == InlineAsm::isInput) &&
7711         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7712       // Try to convert to the first EVT that the reg class contains.  If the
7713       // types are identical size, use a bitcast to convert (e.g. two differing
7714       // vector types).  Note: output bitcast is done at the end of
7715       // visitInlineAsm().
7716       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7717         // Exclude indirect inputs while they are unsupported because the code
7718         // to perform the load is missing and thus OpInfo.CallOperand still
7719         // refers to the input address rather than the pointed-to value.
7720         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7721           OpInfo.CallOperand =
7722               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7723         OpInfo.ConstraintVT = RegVT;
7724         // If the operand is an FP value and we want it in integer registers,
7725         // use the corresponding integer type. This turns an f64 value into
7726         // i64, which can be passed with two i32 values on a 32-bit machine.
7727       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7728         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7729         if (OpInfo.Type == InlineAsm::isInput)
7730           OpInfo.CallOperand =
7731               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7732         OpInfo.ConstraintVT = VT;
7733       }
7734     }
7735   }
7736 
7737   // No need to allocate a matching input constraint since the constraint it's
7738   // matching to has already been allocated.
7739   if (OpInfo.isMatchingInputConstraint())
7740     return;
7741 
7742   EVT ValueVT = OpInfo.ConstraintVT;
7743   if (OpInfo.ConstraintVT == MVT::Other)
7744     ValueVT = RegVT;
7745 
7746   // Initialize NumRegs.
7747   unsigned NumRegs = 1;
7748   if (OpInfo.ConstraintVT != MVT::Other)
7749     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7750 
7751   // If this is a constraint for a specific physical register, like {r17},
7752   // assign it now.
7753 
7754   // If this associated to a specific register, initialize iterator to correct
7755   // place. If virtual, make sure we have enough registers
7756 
7757   // Initialize iterator if necessary
7758   TargetRegisterClass::iterator I = RC->begin();
7759   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7760 
7761   // Do not check for single registers.
7762   if (AssignedReg) {
7763       for (; *I != AssignedReg; ++I)
7764         assert(I != RC->end() && "AssignedReg should be member of RC");
7765   }
7766 
7767   for (; NumRegs; --NumRegs, ++I) {
7768     assert(I != RC->end() && "Ran out of registers to allocate!");
7769     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7770     Regs.push_back(R);
7771   }
7772 
7773   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7774 }
7775 
7776 static unsigned
7777 findMatchingInlineAsmOperand(unsigned OperandNo,
7778                              const std::vector<SDValue> &AsmNodeOperands) {
7779   // Scan until we find the definition we already emitted of this operand.
7780   unsigned CurOp = InlineAsm::Op_FirstOperand;
7781   for (; OperandNo; --OperandNo) {
7782     // Advance to the next operand.
7783     unsigned OpFlag =
7784         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7785     assert((InlineAsm::isRegDefKind(OpFlag) ||
7786             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7787             InlineAsm::isMemKind(OpFlag)) &&
7788            "Skipped past definitions?");
7789     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7790   }
7791   return CurOp;
7792 }
7793 
7794 namespace {
7795 
7796 class ExtraFlags {
7797   unsigned Flags = 0;
7798 
7799 public:
7800   explicit ExtraFlags(ImmutableCallSite CS) {
7801     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7802     if (IA->hasSideEffects())
7803       Flags |= InlineAsm::Extra_HasSideEffects;
7804     if (IA->isAlignStack())
7805       Flags |= InlineAsm::Extra_IsAlignStack;
7806     if (CS.isConvergent())
7807       Flags |= InlineAsm::Extra_IsConvergent;
7808     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7809   }
7810 
7811   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7812     // Ideally, we would only check against memory constraints.  However, the
7813     // meaning of an Other constraint can be target-specific and we can't easily
7814     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7815     // for Other constraints as well.
7816     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7817         OpInfo.ConstraintType == TargetLowering::C_Other) {
7818       if (OpInfo.Type == InlineAsm::isInput)
7819         Flags |= InlineAsm::Extra_MayLoad;
7820       else if (OpInfo.Type == InlineAsm::isOutput)
7821         Flags |= InlineAsm::Extra_MayStore;
7822       else if (OpInfo.Type == InlineAsm::isClobber)
7823         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7824     }
7825   }
7826 
7827   unsigned get() const { return Flags; }
7828 };
7829 
7830 } // end anonymous namespace
7831 
7832 /// visitInlineAsm - Handle a call to an InlineAsm object.
7833 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7834   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7835 
7836   /// ConstraintOperands - Information about all of the constraints.
7837   SDISelAsmOperandInfoVector ConstraintOperands;
7838 
7839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7840   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7841       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7842 
7843   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7844   // AsmDialect, MayLoad, MayStore).
7845   bool HasSideEffect = IA->hasSideEffects();
7846   ExtraFlags ExtraInfo(CS);
7847 
7848   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7849   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7850   for (auto &T : TargetConstraints) {
7851     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7852     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7853 
7854     // Compute the value type for each operand.
7855     if (OpInfo.Type == InlineAsm::isInput ||
7856         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7857       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7858 
7859       // Process the call argument. BasicBlocks are labels, currently appearing
7860       // only in asm's.
7861       const Instruction *I = CS.getInstruction();
7862       if (isa<CallBrInst>(I) &&
7863           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7864                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7865         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7866         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7867         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7868       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7869         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7870       } else {
7871         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7872       }
7873 
7874       OpInfo.ConstraintVT =
7875           OpInfo
7876               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7877               .getSimpleVT();
7878     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7879       // The return value of the call is this value.  As such, there is no
7880       // corresponding argument.
7881       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7882       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7883         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7884             DAG.getDataLayout(), STy->getElementType(ResNo));
7885       } else {
7886         assert(ResNo == 0 && "Asm only has one result!");
7887         OpInfo.ConstraintVT =
7888             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7889       }
7890       ++ResNo;
7891     } else {
7892       OpInfo.ConstraintVT = MVT::Other;
7893     }
7894 
7895     if (!HasSideEffect)
7896       HasSideEffect = OpInfo.hasMemory(TLI);
7897 
7898     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7899     // FIXME: Could we compute this on OpInfo rather than T?
7900 
7901     // Compute the constraint code and ConstraintType to use.
7902     TLI.ComputeConstraintToUse(T, SDValue());
7903 
7904     ExtraInfo.update(T);
7905   }
7906 
7907   // We won't need to flush pending loads if this asm doesn't touch
7908   // memory and is nonvolatile.
7909   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7910 
7911   // Second pass over the constraints: compute which constraint option to use.
7912   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7913     // If this is an output operand with a matching input operand, look up the
7914     // matching input. If their types mismatch, e.g. one is an integer, the
7915     // other is floating point, or their sizes are different, flag it as an
7916     // error.
7917     if (OpInfo.hasMatchingInput()) {
7918       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7919       patchMatchingInput(OpInfo, Input, DAG);
7920     }
7921 
7922     // Compute the constraint code and ConstraintType to use.
7923     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7924 
7925     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7926         OpInfo.Type == InlineAsm::isClobber)
7927       continue;
7928 
7929     // If this is a memory input, and if the operand is not indirect, do what we
7930     // need to provide an address for the memory input.
7931     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7932         !OpInfo.isIndirect) {
7933       assert((OpInfo.isMultipleAlternative ||
7934               (OpInfo.Type == InlineAsm::isInput)) &&
7935              "Can only indirectify direct input operands!");
7936 
7937       // Memory operands really want the address of the value.
7938       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7939 
7940       // There is no longer a Value* corresponding to this operand.
7941       OpInfo.CallOperandVal = nullptr;
7942 
7943       // It is now an indirect operand.
7944       OpInfo.isIndirect = true;
7945     }
7946 
7947   }
7948 
7949   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7950   std::vector<SDValue> AsmNodeOperands;
7951   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7952   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7953       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7954 
7955   // If we have a !srcloc metadata node associated with it, we want to attach
7956   // this to the ultimately generated inline asm machineinstr.  To do this, we
7957   // pass in the third operand as this (potentially null) inline asm MDNode.
7958   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7959   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7960 
7961   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7962   // bits as operand 3.
7963   AsmNodeOperands.push_back(DAG.getTargetConstant(
7964       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7965 
7966   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7967   // this, assign virtual and physical registers for inputs and otput.
7968   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7969     // Assign Registers.
7970     SDISelAsmOperandInfo &RefOpInfo =
7971         OpInfo.isMatchingInputConstraint()
7972             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7973             : OpInfo;
7974     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7975 
7976     switch (OpInfo.Type) {
7977     case InlineAsm::isOutput:
7978       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7979           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7980            OpInfo.isIndirect)) {
7981         unsigned ConstraintID =
7982             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7983         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7984                "Failed to convert memory constraint code to constraint id.");
7985 
7986         // Add information to the INLINEASM node to know about this output.
7987         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7988         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7989         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7990                                                         MVT::i32));
7991         AsmNodeOperands.push_back(OpInfo.CallOperand);
7992         break;
7993       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7994                   !OpInfo.isIndirect) ||
7995                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7996                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7997         // Otherwise, this outputs to a register (directly for C_Register /
7998         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7999         // register that we can use.
8000         if (OpInfo.AssignedRegs.Regs.empty()) {
8001           emitInlineAsmError(
8002               CS, "couldn't allocate output register for constraint '" +
8003                       Twine(OpInfo.ConstraintCode) + "'");
8004           return;
8005         }
8006 
8007         // Add information to the INLINEASM node to know that this register is
8008         // set.
8009         OpInfo.AssignedRegs.AddInlineAsmOperands(
8010             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8011                                   : InlineAsm::Kind_RegDef,
8012             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8013       }
8014       break;
8015 
8016     case InlineAsm::isInput: {
8017       SDValue InOperandVal = OpInfo.CallOperand;
8018 
8019       if (OpInfo.isMatchingInputConstraint()) {
8020         // If this is required to match an output register we have already set,
8021         // just use its register.
8022         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8023                                                   AsmNodeOperands);
8024         unsigned OpFlag =
8025           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8026         if (InlineAsm::isRegDefKind(OpFlag) ||
8027             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8028           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8029           if (OpInfo.isIndirect) {
8030             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8031             emitInlineAsmError(CS, "inline asm not supported yet:"
8032                                    " don't know how to handle tied "
8033                                    "indirect register inputs");
8034             return;
8035           }
8036 
8037           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8038           SmallVector<unsigned, 4> Regs;
8039 
8040           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8041             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8042             MachineRegisterInfo &RegInfo =
8043                 DAG.getMachineFunction().getRegInfo();
8044             for (unsigned i = 0; i != NumRegs; ++i)
8045               Regs.push_back(RegInfo.createVirtualRegister(RC));
8046           } else {
8047             emitInlineAsmError(CS, "inline asm error: This value type register "
8048                                    "class is not natively supported!");
8049             return;
8050           }
8051 
8052           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8053 
8054           SDLoc dl = getCurSDLoc();
8055           // Use the produced MatchedRegs object to
8056           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8057                                     CS.getInstruction());
8058           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8059                                            true, OpInfo.getMatchedOperand(), dl,
8060                                            DAG, AsmNodeOperands);
8061           break;
8062         }
8063 
8064         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8065         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8066                "Unexpected number of operands");
8067         // Add information to the INLINEASM node to know about this input.
8068         // See InlineAsm.h isUseOperandTiedToDef.
8069         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8070         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8071                                                     OpInfo.getMatchedOperand());
8072         AsmNodeOperands.push_back(DAG.getTargetConstant(
8073             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8074         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8075         break;
8076       }
8077 
8078       // Treat indirect 'X' constraint as memory.
8079       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8080           OpInfo.isIndirect)
8081         OpInfo.ConstraintType = TargetLowering::C_Memory;
8082 
8083       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
8084         std::vector<SDValue> Ops;
8085         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8086                                           Ops, DAG);
8087         if (Ops.empty()) {
8088           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8089                                      Twine(OpInfo.ConstraintCode) + "'");
8090           return;
8091         }
8092 
8093         // Add information to the INLINEASM node to know about this input.
8094         unsigned ResOpType =
8095           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8096         AsmNodeOperands.push_back(DAG.getTargetConstant(
8097             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8098         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8099         break;
8100       }
8101 
8102       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8103         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8104         assert(InOperandVal.getValueType() ==
8105                    TLI.getPointerTy(DAG.getDataLayout()) &&
8106                "Memory operands expect pointer values");
8107 
8108         unsigned ConstraintID =
8109             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8110         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8111                "Failed to convert memory constraint code to constraint id.");
8112 
8113         // Add information to the INLINEASM node to know about this input.
8114         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8115         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8116         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8117                                                         getCurSDLoc(),
8118                                                         MVT::i32));
8119         AsmNodeOperands.push_back(InOperandVal);
8120         break;
8121       }
8122 
8123       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8124               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8125              "Unknown constraint type!");
8126 
8127       // TODO: Support this.
8128       if (OpInfo.isIndirect) {
8129         emitInlineAsmError(
8130             CS, "Don't know how to handle indirect register inputs yet "
8131                 "for constraint '" +
8132                     Twine(OpInfo.ConstraintCode) + "'");
8133         return;
8134       }
8135 
8136       // Copy the input into the appropriate registers.
8137       if (OpInfo.AssignedRegs.Regs.empty()) {
8138         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8139                                    Twine(OpInfo.ConstraintCode) + "'");
8140         return;
8141       }
8142 
8143       SDLoc dl = getCurSDLoc();
8144 
8145       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8146                                         Chain, &Flag, CS.getInstruction());
8147 
8148       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8149                                                dl, DAG, AsmNodeOperands);
8150       break;
8151     }
8152     case InlineAsm::isClobber:
8153       // Add the clobbered value to the operand list, so that the register
8154       // allocator is aware that the physreg got clobbered.
8155       if (!OpInfo.AssignedRegs.Regs.empty())
8156         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8157                                                  false, 0, getCurSDLoc(), DAG,
8158                                                  AsmNodeOperands);
8159       break;
8160     }
8161   }
8162 
8163   // Finish up input operands.  Set the input chain and add the flag last.
8164   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8165   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8166 
8167   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM;
8168   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8169                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8170   Flag = Chain.getValue(1);
8171 
8172   // Do additional work to generate outputs.
8173 
8174   SmallVector<EVT, 1> ResultVTs;
8175   SmallVector<SDValue, 1> ResultValues;
8176   SmallVector<SDValue, 8> OutChains;
8177 
8178   llvm::Type *CSResultType = CS.getType();
8179   ArrayRef<Type *> ResultTypes;
8180   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8181     ResultTypes = StructResult->elements();
8182   else if (!CSResultType->isVoidTy())
8183     ResultTypes = makeArrayRef(CSResultType);
8184 
8185   auto CurResultType = ResultTypes.begin();
8186   auto handleRegAssign = [&](SDValue V) {
8187     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8188     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8189     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8190     ++CurResultType;
8191     // If the type of the inline asm call site return value is different but has
8192     // same size as the type of the asm output bitcast it.  One example of this
8193     // is for vectors with different width / number of elements.  This can
8194     // happen for register classes that can contain multiple different value
8195     // types.  The preg or vreg allocated may not have the same VT as was
8196     // expected.
8197     //
8198     // This can also happen for a return value that disagrees with the register
8199     // class it is put in, eg. a double in a general-purpose register on a
8200     // 32-bit machine.
8201     if (ResultVT != V.getValueType() &&
8202         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8203       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8204     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8205              V.getValueType().isInteger()) {
8206       // If a result value was tied to an input value, the computed result
8207       // may have a wider width than the expected result.  Extract the
8208       // relevant portion.
8209       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8210     }
8211     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8212     ResultVTs.push_back(ResultVT);
8213     ResultValues.push_back(V);
8214   };
8215 
8216   // Deal with output operands.
8217   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8218     if (OpInfo.Type == InlineAsm::isOutput) {
8219       SDValue Val;
8220       // Skip trivial output operands.
8221       if (OpInfo.AssignedRegs.Regs.empty())
8222         continue;
8223 
8224       switch (OpInfo.ConstraintType) {
8225       case TargetLowering::C_Register:
8226       case TargetLowering::C_RegisterClass:
8227         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8228             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8229         break;
8230       case TargetLowering::C_Other:
8231         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8232                                               OpInfo, DAG);
8233         break;
8234       case TargetLowering::C_Memory:
8235         break; // Already handled.
8236       case TargetLowering::C_Unknown:
8237         assert(false && "Unexpected unknown constraint");
8238       }
8239 
8240       // Indirect output manifest as stores. Record output chains.
8241       if (OpInfo.isIndirect) {
8242         const Value *Ptr = OpInfo.CallOperandVal;
8243         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8244         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8245                                      MachinePointerInfo(Ptr));
8246         OutChains.push_back(Store);
8247       } else {
8248         // generate CopyFromRegs to associated registers.
8249         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8250         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8251           for (const SDValue &V : Val->op_values())
8252             handleRegAssign(V);
8253         } else
8254           handleRegAssign(Val);
8255       }
8256     }
8257   }
8258 
8259   // Set results.
8260   if (!ResultValues.empty()) {
8261     assert(CurResultType == ResultTypes.end() &&
8262            "Mismatch in number of ResultTypes");
8263     assert(ResultValues.size() == ResultTypes.size() &&
8264            "Mismatch in number of output operands in asm result");
8265 
8266     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8267                             DAG.getVTList(ResultVTs), ResultValues);
8268     setValue(CS.getInstruction(), V);
8269   }
8270 
8271   // Collect store chains.
8272   if (!OutChains.empty())
8273     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8274 
8275   // Only Update Root if inline assembly has a memory effect.
8276   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8277     DAG.setRoot(Chain);
8278 }
8279 
8280 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8281                                              const Twine &Message) {
8282   LLVMContext &Ctx = *DAG.getContext();
8283   Ctx.emitError(CS.getInstruction(), Message);
8284 
8285   // Make sure we leave the DAG in a valid state
8286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8287   SmallVector<EVT, 1> ValueVTs;
8288   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8289 
8290   if (ValueVTs.empty())
8291     return;
8292 
8293   SmallVector<SDValue, 1> Ops;
8294   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8295     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8296 
8297   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8298 }
8299 
8300 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8301   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8302                           MVT::Other, getRoot(),
8303                           getValue(I.getArgOperand(0)),
8304                           DAG.getSrcValue(I.getArgOperand(0))));
8305 }
8306 
8307 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8309   const DataLayout &DL = DAG.getDataLayout();
8310   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8311                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8312                            DAG.getSrcValue(I.getOperand(0)),
8313                            DL.getABITypeAlignment(I.getType()));
8314   setValue(&I, V);
8315   DAG.setRoot(V.getValue(1));
8316 }
8317 
8318 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8319   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8320                           MVT::Other, getRoot(),
8321                           getValue(I.getArgOperand(0)),
8322                           DAG.getSrcValue(I.getArgOperand(0))));
8323 }
8324 
8325 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8326   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8327                           MVT::Other, getRoot(),
8328                           getValue(I.getArgOperand(0)),
8329                           getValue(I.getArgOperand(1)),
8330                           DAG.getSrcValue(I.getArgOperand(0)),
8331                           DAG.getSrcValue(I.getArgOperand(1))));
8332 }
8333 
8334 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8335                                                     const Instruction &I,
8336                                                     SDValue Op) {
8337   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8338   if (!Range)
8339     return Op;
8340 
8341   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8342   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8343     return Op;
8344 
8345   APInt Lo = CR.getUnsignedMin();
8346   if (!Lo.isMinValue())
8347     return Op;
8348 
8349   APInt Hi = CR.getUnsignedMax();
8350   unsigned Bits = std::max(Hi.getActiveBits(),
8351                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8352 
8353   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8354 
8355   SDLoc SL = getCurSDLoc();
8356 
8357   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8358                              DAG.getValueType(SmallVT));
8359   unsigned NumVals = Op.getNode()->getNumValues();
8360   if (NumVals == 1)
8361     return ZExt;
8362 
8363   SmallVector<SDValue, 4> Ops;
8364 
8365   Ops.push_back(ZExt);
8366   for (unsigned I = 1; I != NumVals; ++I)
8367     Ops.push_back(Op.getValue(I));
8368 
8369   return DAG.getMergeValues(Ops, SL);
8370 }
8371 
8372 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8373 /// the call being lowered.
8374 ///
8375 /// This is a helper for lowering intrinsics that follow a target calling
8376 /// convention or require stack pointer adjustment. Only a subset of the
8377 /// intrinsic's operands need to participate in the calling convention.
8378 void SelectionDAGBuilder::populateCallLoweringInfo(
8379     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8380     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8381     bool IsPatchPoint) {
8382   TargetLowering::ArgListTy Args;
8383   Args.reserve(NumArgs);
8384 
8385   // Populate the argument list.
8386   // Attributes for args start at offset 1, after the return attribute.
8387   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8388        ArgI != ArgE; ++ArgI) {
8389     const Value *V = Call->getOperand(ArgI);
8390 
8391     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8392 
8393     TargetLowering::ArgListEntry Entry;
8394     Entry.Node = getValue(V);
8395     Entry.Ty = V->getType();
8396     Entry.setAttributes(Call, ArgI);
8397     Args.push_back(Entry);
8398   }
8399 
8400   CLI.setDebugLoc(getCurSDLoc())
8401       .setChain(getRoot())
8402       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8403       .setDiscardResult(Call->use_empty())
8404       .setIsPatchPoint(IsPatchPoint);
8405 }
8406 
8407 /// Add a stack map intrinsic call's live variable operands to a stackmap
8408 /// or patchpoint target node's operand list.
8409 ///
8410 /// Constants are converted to TargetConstants purely as an optimization to
8411 /// avoid constant materialization and register allocation.
8412 ///
8413 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8414 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8415 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8416 /// address materialization and register allocation, but may also be required
8417 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8418 /// alloca in the entry block, then the runtime may assume that the alloca's
8419 /// StackMap location can be read immediately after compilation and that the
8420 /// location is valid at any point during execution (this is similar to the
8421 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8422 /// only available in a register, then the runtime would need to trap when
8423 /// execution reaches the StackMap in order to read the alloca's location.
8424 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8425                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8426                                 SelectionDAGBuilder &Builder) {
8427   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8428     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8429     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8430       Ops.push_back(
8431         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8432       Ops.push_back(
8433         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8434     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8435       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8436       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8437           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8438     } else
8439       Ops.push_back(OpVal);
8440   }
8441 }
8442 
8443 /// Lower llvm.experimental.stackmap directly to its target opcode.
8444 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8445   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8446   //                                  [live variables...])
8447 
8448   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8449 
8450   SDValue Chain, InFlag, Callee, NullPtr;
8451   SmallVector<SDValue, 32> Ops;
8452 
8453   SDLoc DL = getCurSDLoc();
8454   Callee = getValue(CI.getCalledValue());
8455   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8456 
8457   // The stackmap intrinsic only records the live variables (the arguemnts
8458   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8459   // intrinsic, this won't be lowered to a function call. This means we don't
8460   // have to worry about calling conventions and target specific lowering code.
8461   // Instead we perform the call lowering right here.
8462   //
8463   // chain, flag = CALLSEQ_START(chain, 0, 0)
8464   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8465   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8466   //
8467   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8468   InFlag = Chain.getValue(1);
8469 
8470   // Add the <id> and <numBytes> constants.
8471   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8472   Ops.push_back(DAG.getTargetConstant(
8473                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8474   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8475   Ops.push_back(DAG.getTargetConstant(
8476                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8477                   MVT::i32));
8478 
8479   // Push live variables for the stack map.
8480   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8481 
8482   // We are not pushing any register mask info here on the operands list,
8483   // because the stackmap doesn't clobber anything.
8484 
8485   // Push the chain and the glue flag.
8486   Ops.push_back(Chain);
8487   Ops.push_back(InFlag);
8488 
8489   // Create the STACKMAP node.
8490   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8491   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8492   Chain = SDValue(SM, 0);
8493   InFlag = Chain.getValue(1);
8494 
8495   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8496 
8497   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8498 
8499   // Set the root to the target-lowered call chain.
8500   DAG.setRoot(Chain);
8501 
8502   // Inform the Frame Information that we have a stackmap in this function.
8503   FuncInfo.MF->getFrameInfo().setHasStackMap();
8504 }
8505 
8506 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8507 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8508                                           const BasicBlock *EHPadBB) {
8509   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8510   //                                                 i32 <numBytes>,
8511   //                                                 i8* <target>,
8512   //                                                 i32 <numArgs>,
8513   //                                                 [Args...],
8514   //                                                 [live variables...])
8515 
8516   CallingConv::ID CC = CS.getCallingConv();
8517   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8518   bool HasDef = !CS->getType()->isVoidTy();
8519   SDLoc dl = getCurSDLoc();
8520   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8521 
8522   // Handle immediate and symbolic callees.
8523   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8524     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8525                                    /*isTarget=*/true);
8526   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8527     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8528                                          SDLoc(SymbolicCallee),
8529                                          SymbolicCallee->getValueType(0));
8530 
8531   // Get the real number of arguments participating in the call <numArgs>
8532   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8533   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8534 
8535   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8536   // Intrinsics include all meta-operands up to but not including CC.
8537   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8538   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8539          "Not enough arguments provided to the patchpoint intrinsic");
8540 
8541   // For AnyRegCC the arguments are lowered later on manually.
8542   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8543   Type *ReturnTy =
8544     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8545 
8546   TargetLowering::CallLoweringInfo CLI(DAG);
8547   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8548                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8549   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8550 
8551   SDNode *CallEnd = Result.second.getNode();
8552   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8553     CallEnd = CallEnd->getOperand(0).getNode();
8554 
8555   /// Get a call instruction from the call sequence chain.
8556   /// Tail calls are not allowed.
8557   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8558          "Expected a callseq node.");
8559   SDNode *Call = CallEnd->getOperand(0).getNode();
8560   bool HasGlue = Call->getGluedNode();
8561 
8562   // Replace the target specific call node with the patchable intrinsic.
8563   SmallVector<SDValue, 8> Ops;
8564 
8565   // Add the <id> and <numBytes> constants.
8566   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8567   Ops.push_back(DAG.getTargetConstant(
8568                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8569   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8570   Ops.push_back(DAG.getTargetConstant(
8571                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8572                   MVT::i32));
8573 
8574   // Add the callee.
8575   Ops.push_back(Callee);
8576 
8577   // Adjust <numArgs> to account for any arguments that have been passed on the
8578   // stack instead.
8579   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8580   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8581   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8582   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8583 
8584   // Add the calling convention
8585   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8586 
8587   // Add the arguments we omitted previously. The register allocator should
8588   // place these in any free register.
8589   if (IsAnyRegCC)
8590     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8591       Ops.push_back(getValue(CS.getArgument(i)));
8592 
8593   // Push the arguments from the call instruction up to the register mask.
8594   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8595   Ops.append(Call->op_begin() + 2, e);
8596 
8597   // Push live variables for the stack map.
8598   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8599 
8600   // Push the register mask info.
8601   if (HasGlue)
8602     Ops.push_back(*(Call->op_end()-2));
8603   else
8604     Ops.push_back(*(Call->op_end()-1));
8605 
8606   // Push the chain (this is originally the first operand of the call, but
8607   // becomes now the last or second to last operand).
8608   Ops.push_back(*(Call->op_begin()));
8609 
8610   // Push the glue flag (last operand).
8611   if (HasGlue)
8612     Ops.push_back(*(Call->op_end()-1));
8613 
8614   SDVTList NodeTys;
8615   if (IsAnyRegCC && HasDef) {
8616     // Create the return types based on the intrinsic definition
8617     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8618     SmallVector<EVT, 3> ValueVTs;
8619     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8620     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8621 
8622     // There is always a chain and a glue type at the end
8623     ValueVTs.push_back(MVT::Other);
8624     ValueVTs.push_back(MVT::Glue);
8625     NodeTys = DAG.getVTList(ValueVTs);
8626   } else
8627     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8628 
8629   // Replace the target specific call node with a PATCHPOINT node.
8630   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8631                                          dl, NodeTys, Ops);
8632 
8633   // Update the NodeMap.
8634   if (HasDef) {
8635     if (IsAnyRegCC)
8636       setValue(CS.getInstruction(), SDValue(MN, 0));
8637     else
8638       setValue(CS.getInstruction(), Result.first);
8639   }
8640 
8641   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8642   // call sequence. Furthermore the location of the chain and glue can change
8643   // when the AnyReg calling convention is used and the intrinsic returns a
8644   // value.
8645   if (IsAnyRegCC && HasDef) {
8646     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8647     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8648     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8649   } else
8650     DAG.ReplaceAllUsesWith(Call, MN);
8651   DAG.DeleteNode(Call);
8652 
8653   // Inform the Frame Information that we have a patchpoint in this function.
8654   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8655 }
8656 
8657 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8658                                             unsigned Intrinsic) {
8659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8660   SDValue Op1 = getValue(I.getArgOperand(0));
8661   SDValue Op2;
8662   if (I.getNumArgOperands() > 1)
8663     Op2 = getValue(I.getArgOperand(1));
8664   SDLoc dl = getCurSDLoc();
8665   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8666   SDValue Res;
8667   FastMathFlags FMF;
8668   if (isa<FPMathOperator>(I))
8669     FMF = I.getFastMathFlags();
8670 
8671   switch (Intrinsic) {
8672   case Intrinsic::experimental_vector_reduce_fadd:
8673     if (FMF.isFast())
8674       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8675     else
8676       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8677     break;
8678   case Intrinsic::experimental_vector_reduce_fmul:
8679     if (FMF.isFast())
8680       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8681     else
8682       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8683     break;
8684   case Intrinsic::experimental_vector_reduce_add:
8685     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8686     break;
8687   case Intrinsic::experimental_vector_reduce_mul:
8688     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8689     break;
8690   case Intrinsic::experimental_vector_reduce_and:
8691     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8692     break;
8693   case Intrinsic::experimental_vector_reduce_or:
8694     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8695     break;
8696   case Intrinsic::experimental_vector_reduce_xor:
8697     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8698     break;
8699   case Intrinsic::experimental_vector_reduce_smax:
8700     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8701     break;
8702   case Intrinsic::experimental_vector_reduce_smin:
8703     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8704     break;
8705   case Intrinsic::experimental_vector_reduce_umax:
8706     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8707     break;
8708   case Intrinsic::experimental_vector_reduce_umin:
8709     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8710     break;
8711   case Intrinsic::experimental_vector_reduce_fmax:
8712     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8713     break;
8714   case Intrinsic::experimental_vector_reduce_fmin:
8715     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8716     break;
8717   default:
8718     llvm_unreachable("Unhandled vector reduce intrinsic");
8719   }
8720   setValue(&I, Res);
8721 }
8722 
8723 /// Returns an AttributeList representing the attributes applied to the return
8724 /// value of the given call.
8725 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8726   SmallVector<Attribute::AttrKind, 2> Attrs;
8727   if (CLI.RetSExt)
8728     Attrs.push_back(Attribute::SExt);
8729   if (CLI.RetZExt)
8730     Attrs.push_back(Attribute::ZExt);
8731   if (CLI.IsInReg)
8732     Attrs.push_back(Attribute::InReg);
8733 
8734   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8735                             Attrs);
8736 }
8737 
8738 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8739 /// implementation, which just calls LowerCall.
8740 /// FIXME: When all targets are
8741 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8742 std::pair<SDValue, SDValue>
8743 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8744   // Handle the incoming return values from the call.
8745   CLI.Ins.clear();
8746   Type *OrigRetTy = CLI.RetTy;
8747   SmallVector<EVT, 4> RetTys;
8748   SmallVector<uint64_t, 4> Offsets;
8749   auto &DL = CLI.DAG.getDataLayout();
8750   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8751 
8752   if (CLI.IsPostTypeLegalization) {
8753     // If we are lowering a libcall after legalization, split the return type.
8754     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8755     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8756     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8757       EVT RetVT = OldRetTys[i];
8758       uint64_t Offset = OldOffsets[i];
8759       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8760       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8761       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8762       RetTys.append(NumRegs, RegisterVT);
8763       for (unsigned j = 0; j != NumRegs; ++j)
8764         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8765     }
8766   }
8767 
8768   SmallVector<ISD::OutputArg, 4> Outs;
8769   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8770 
8771   bool CanLowerReturn =
8772       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8773                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8774 
8775   SDValue DemoteStackSlot;
8776   int DemoteStackIdx = -100;
8777   if (!CanLowerReturn) {
8778     // FIXME: equivalent assert?
8779     // assert(!CS.hasInAllocaArgument() &&
8780     //        "sret demotion is incompatible with inalloca");
8781     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8782     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8783     MachineFunction &MF = CLI.DAG.getMachineFunction();
8784     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8785     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8786                                               DL.getAllocaAddrSpace());
8787 
8788     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8789     ArgListEntry Entry;
8790     Entry.Node = DemoteStackSlot;
8791     Entry.Ty = StackSlotPtrType;
8792     Entry.IsSExt = false;
8793     Entry.IsZExt = false;
8794     Entry.IsInReg = false;
8795     Entry.IsSRet = true;
8796     Entry.IsNest = false;
8797     Entry.IsByVal = false;
8798     Entry.IsReturned = false;
8799     Entry.IsSwiftSelf = false;
8800     Entry.IsSwiftError = false;
8801     Entry.Alignment = Align;
8802     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8803     CLI.NumFixedArgs += 1;
8804     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8805 
8806     // sret demotion isn't compatible with tail-calls, since the sret argument
8807     // points into the callers stack frame.
8808     CLI.IsTailCall = false;
8809   } else {
8810     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8811       EVT VT = RetTys[I];
8812       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8813                                                      CLI.CallConv, VT);
8814       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8815                                                        CLI.CallConv, VT);
8816       for (unsigned i = 0; i != NumRegs; ++i) {
8817         ISD::InputArg MyFlags;
8818         MyFlags.VT = RegisterVT;
8819         MyFlags.ArgVT = VT;
8820         MyFlags.Used = CLI.IsReturnValueUsed;
8821         if (CLI.RetSExt)
8822           MyFlags.Flags.setSExt();
8823         if (CLI.RetZExt)
8824           MyFlags.Flags.setZExt();
8825         if (CLI.IsInReg)
8826           MyFlags.Flags.setInReg();
8827         CLI.Ins.push_back(MyFlags);
8828       }
8829     }
8830   }
8831 
8832   // We push in swifterror return as the last element of CLI.Ins.
8833   ArgListTy &Args = CLI.getArgs();
8834   if (supportSwiftError()) {
8835     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8836       if (Args[i].IsSwiftError) {
8837         ISD::InputArg MyFlags;
8838         MyFlags.VT = getPointerTy(DL);
8839         MyFlags.ArgVT = EVT(getPointerTy(DL));
8840         MyFlags.Flags.setSwiftError();
8841         CLI.Ins.push_back(MyFlags);
8842       }
8843     }
8844   }
8845 
8846   // Handle all of the outgoing arguments.
8847   CLI.Outs.clear();
8848   CLI.OutVals.clear();
8849   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8850     SmallVector<EVT, 4> ValueVTs;
8851     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8852     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8853     Type *FinalType = Args[i].Ty;
8854     if (Args[i].IsByVal)
8855       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8856     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8857         FinalType, CLI.CallConv, CLI.IsVarArg);
8858     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8859          ++Value) {
8860       EVT VT = ValueVTs[Value];
8861       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8862       SDValue Op = SDValue(Args[i].Node.getNode(),
8863                            Args[i].Node.getResNo() + Value);
8864       ISD::ArgFlagsTy Flags;
8865 
8866       // Certain targets (such as MIPS), may have a different ABI alignment
8867       // for a type depending on the context. Give the target a chance to
8868       // specify the alignment it wants.
8869       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8870 
8871       if (Args[i].IsZExt)
8872         Flags.setZExt();
8873       if (Args[i].IsSExt)
8874         Flags.setSExt();
8875       if (Args[i].IsInReg) {
8876         // If we are using vectorcall calling convention, a structure that is
8877         // passed InReg - is surely an HVA
8878         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8879             isa<StructType>(FinalType)) {
8880           // The first value of a structure is marked
8881           if (0 == Value)
8882             Flags.setHvaStart();
8883           Flags.setHva();
8884         }
8885         // Set InReg Flag
8886         Flags.setInReg();
8887       }
8888       if (Args[i].IsSRet)
8889         Flags.setSRet();
8890       if (Args[i].IsSwiftSelf)
8891         Flags.setSwiftSelf();
8892       if (Args[i].IsSwiftError)
8893         Flags.setSwiftError();
8894       if (Args[i].IsByVal)
8895         Flags.setByVal();
8896       if (Args[i].IsInAlloca) {
8897         Flags.setInAlloca();
8898         // Set the byval flag for CCAssignFn callbacks that don't know about
8899         // inalloca.  This way we can know how many bytes we should've allocated
8900         // and how many bytes a callee cleanup function will pop.  If we port
8901         // inalloca to more targets, we'll have to add custom inalloca handling
8902         // in the various CC lowering callbacks.
8903         Flags.setByVal();
8904       }
8905       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8906         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8907         Type *ElementTy = Ty->getElementType();
8908         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8909         // For ByVal, alignment should come from FE.  BE will guess if this
8910         // info is not there but there are cases it cannot get right.
8911         unsigned FrameAlign;
8912         if (Args[i].Alignment)
8913           FrameAlign = Args[i].Alignment;
8914         else
8915           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8916         Flags.setByValAlign(FrameAlign);
8917       }
8918       if (Args[i].IsNest)
8919         Flags.setNest();
8920       if (NeedsRegBlock)
8921         Flags.setInConsecutiveRegs();
8922       Flags.setOrigAlign(OriginalAlignment);
8923 
8924       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8925                                                  CLI.CallConv, VT);
8926       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8927                                                         CLI.CallConv, VT);
8928       SmallVector<SDValue, 4> Parts(NumParts);
8929       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8930 
8931       if (Args[i].IsSExt)
8932         ExtendKind = ISD::SIGN_EXTEND;
8933       else if (Args[i].IsZExt)
8934         ExtendKind = ISD::ZERO_EXTEND;
8935 
8936       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8937       // for now.
8938       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8939           CanLowerReturn) {
8940         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8941                "unexpected use of 'returned'");
8942         // Before passing 'returned' to the target lowering code, ensure that
8943         // either the register MVT and the actual EVT are the same size or that
8944         // the return value and argument are extended in the same way; in these
8945         // cases it's safe to pass the argument register value unchanged as the
8946         // return register value (although it's at the target's option whether
8947         // to do so)
8948         // TODO: allow code generation to take advantage of partially preserved
8949         // registers rather than clobbering the entire register when the
8950         // parameter extension method is not compatible with the return
8951         // extension method
8952         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8953             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8954              CLI.RetZExt == Args[i].IsZExt))
8955           Flags.setReturned();
8956       }
8957 
8958       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8959                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8960 
8961       for (unsigned j = 0; j != NumParts; ++j) {
8962         // if it isn't first piece, alignment must be 1
8963         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8964                                i < CLI.NumFixedArgs,
8965                                i, j*Parts[j].getValueType().getStoreSize());
8966         if (NumParts > 1 && j == 0)
8967           MyFlags.Flags.setSplit();
8968         else if (j != 0) {
8969           MyFlags.Flags.setOrigAlign(1);
8970           if (j == NumParts - 1)
8971             MyFlags.Flags.setSplitEnd();
8972         }
8973 
8974         CLI.Outs.push_back(MyFlags);
8975         CLI.OutVals.push_back(Parts[j]);
8976       }
8977 
8978       if (NeedsRegBlock && Value == NumValues - 1)
8979         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8980     }
8981   }
8982 
8983   SmallVector<SDValue, 4> InVals;
8984   CLI.Chain = LowerCall(CLI, InVals);
8985 
8986   // Update CLI.InVals to use outside of this function.
8987   CLI.InVals = InVals;
8988 
8989   // Verify that the target's LowerCall behaved as expected.
8990   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8991          "LowerCall didn't return a valid chain!");
8992   assert((!CLI.IsTailCall || InVals.empty()) &&
8993          "LowerCall emitted a return value for a tail call!");
8994   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8995          "LowerCall didn't emit the correct number of values!");
8996 
8997   // For a tail call, the return value is merely live-out and there aren't
8998   // any nodes in the DAG representing it. Return a special value to
8999   // indicate that a tail call has been emitted and no more Instructions
9000   // should be processed in the current block.
9001   if (CLI.IsTailCall) {
9002     CLI.DAG.setRoot(CLI.Chain);
9003     return std::make_pair(SDValue(), SDValue());
9004   }
9005 
9006 #ifndef NDEBUG
9007   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9008     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9009     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9010            "LowerCall emitted a value with the wrong type!");
9011   }
9012 #endif
9013 
9014   SmallVector<SDValue, 4> ReturnValues;
9015   if (!CanLowerReturn) {
9016     // The instruction result is the result of loading from the
9017     // hidden sret parameter.
9018     SmallVector<EVT, 1> PVTs;
9019     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9020 
9021     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9022     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9023     EVT PtrVT = PVTs[0];
9024 
9025     unsigned NumValues = RetTys.size();
9026     ReturnValues.resize(NumValues);
9027     SmallVector<SDValue, 4> Chains(NumValues);
9028 
9029     // An aggregate return value cannot wrap around the address space, so
9030     // offsets to its parts don't wrap either.
9031     SDNodeFlags Flags;
9032     Flags.setNoUnsignedWrap(true);
9033 
9034     for (unsigned i = 0; i < NumValues; ++i) {
9035       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9036                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9037                                                         PtrVT), Flags);
9038       SDValue L = CLI.DAG.getLoad(
9039           RetTys[i], CLI.DL, CLI.Chain, Add,
9040           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9041                                             DemoteStackIdx, Offsets[i]),
9042           /* Alignment = */ 1);
9043       ReturnValues[i] = L;
9044       Chains[i] = L.getValue(1);
9045     }
9046 
9047     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9048   } else {
9049     // Collect the legal value parts into potentially illegal values
9050     // that correspond to the original function's return values.
9051     Optional<ISD::NodeType> AssertOp;
9052     if (CLI.RetSExt)
9053       AssertOp = ISD::AssertSext;
9054     else if (CLI.RetZExt)
9055       AssertOp = ISD::AssertZext;
9056     unsigned CurReg = 0;
9057     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9058       EVT VT = RetTys[I];
9059       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9060                                                      CLI.CallConv, VT);
9061       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9062                                                        CLI.CallConv, VT);
9063 
9064       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9065                                               NumRegs, RegisterVT, VT, nullptr,
9066                                               CLI.CallConv, AssertOp));
9067       CurReg += NumRegs;
9068     }
9069 
9070     // For a function returning void, there is no return value. We can't create
9071     // such a node, so we just return a null return value in that case. In
9072     // that case, nothing will actually look at the value.
9073     if (ReturnValues.empty())
9074       return std::make_pair(SDValue(), CLI.Chain);
9075   }
9076 
9077   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9078                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9079   return std::make_pair(Res, CLI.Chain);
9080 }
9081 
9082 void TargetLowering::LowerOperationWrapper(SDNode *N,
9083                                            SmallVectorImpl<SDValue> &Results,
9084                                            SelectionDAG &DAG) const {
9085   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9086     Results.push_back(Res);
9087 }
9088 
9089 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9090   llvm_unreachable("LowerOperation not implemented for this target!");
9091 }
9092 
9093 void
9094 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9095   SDValue Op = getNonRegisterValue(V);
9096   assert((Op.getOpcode() != ISD::CopyFromReg ||
9097           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9098          "Copy from a reg to the same reg!");
9099   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9100 
9101   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9102   // If this is an InlineAsm we have to match the registers required, not the
9103   // notional registers required by the type.
9104 
9105   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9106                    None); // This is not an ABI copy.
9107   SDValue Chain = DAG.getEntryNode();
9108 
9109   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9110                               FuncInfo.PreferredExtendType.end())
9111                                  ? ISD::ANY_EXTEND
9112                                  : FuncInfo.PreferredExtendType[V];
9113   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9114   PendingExports.push_back(Chain);
9115 }
9116 
9117 #include "llvm/CodeGen/SelectionDAGISel.h"
9118 
9119 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9120 /// entry block, return true.  This includes arguments used by switches, since
9121 /// the switch may expand into multiple basic blocks.
9122 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9123   // With FastISel active, we may be splitting blocks, so force creation
9124   // of virtual registers for all non-dead arguments.
9125   if (FastISel)
9126     return A->use_empty();
9127 
9128   const BasicBlock &Entry = A->getParent()->front();
9129   for (const User *U : A->users())
9130     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9131       return false;  // Use not in entry block.
9132 
9133   return true;
9134 }
9135 
9136 using ArgCopyElisionMapTy =
9137     DenseMap<const Argument *,
9138              std::pair<const AllocaInst *, const StoreInst *>>;
9139 
9140 /// Scan the entry block of the function in FuncInfo for arguments that look
9141 /// like copies into a local alloca. Record any copied arguments in
9142 /// ArgCopyElisionCandidates.
9143 static void
9144 findArgumentCopyElisionCandidates(const DataLayout &DL,
9145                                   FunctionLoweringInfo *FuncInfo,
9146                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9147   // Record the state of every static alloca used in the entry block. Argument
9148   // allocas are all used in the entry block, so we need approximately as many
9149   // entries as we have arguments.
9150   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9151   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9152   unsigned NumArgs = FuncInfo->Fn->arg_size();
9153   StaticAllocas.reserve(NumArgs * 2);
9154 
9155   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9156     if (!V)
9157       return nullptr;
9158     V = V->stripPointerCasts();
9159     const auto *AI = dyn_cast<AllocaInst>(V);
9160     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9161       return nullptr;
9162     auto Iter = StaticAllocas.insert({AI, Unknown});
9163     return &Iter.first->second;
9164   };
9165 
9166   // Look for stores of arguments to static allocas. Look through bitcasts and
9167   // GEPs to handle type coercions, as long as the alloca is fully initialized
9168   // by the store. Any non-store use of an alloca escapes it and any subsequent
9169   // unanalyzed store might write it.
9170   // FIXME: Handle structs initialized with multiple stores.
9171   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9172     // Look for stores, and handle non-store uses conservatively.
9173     const auto *SI = dyn_cast<StoreInst>(&I);
9174     if (!SI) {
9175       // We will look through cast uses, so ignore them completely.
9176       if (I.isCast())
9177         continue;
9178       // Ignore debug info intrinsics, they don't escape or store to allocas.
9179       if (isa<DbgInfoIntrinsic>(I))
9180         continue;
9181       // This is an unknown instruction. Assume it escapes or writes to all
9182       // static alloca operands.
9183       for (const Use &U : I.operands()) {
9184         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9185           *Info = StaticAllocaInfo::Clobbered;
9186       }
9187       continue;
9188     }
9189 
9190     // If the stored value is a static alloca, mark it as escaped.
9191     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9192       *Info = StaticAllocaInfo::Clobbered;
9193 
9194     // Check if the destination is a static alloca.
9195     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9196     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9197     if (!Info)
9198       continue;
9199     const AllocaInst *AI = cast<AllocaInst>(Dst);
9200 
9201     // Skip allocas that have been initialized or clobbered.
9202     if (*Info != StaticAllocaInfo::Unknown)
9203       continue;
9204 
9205     // Check if the stored value is an argument, and that this store fully
9206     // initializes the alloca. Don't elide copies from the same argument twice.
9207     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9208     const auto *Arg = dyn_cast<Argument>(Val);
9209     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9210         Arg->getType()->isEmptyTy() ||
9211         DL.getTypeStoreSize(Arg->getType()) !=
9212             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9213         ArgCopyElisionCandidates.count(Arg)) {
9214       *Info = StaticAllocaInfo::Clobbered;
9215       continue;
9216     }
9217 
9218     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9219                       << '\n');
9220 
9221     // Mark this alloca and store for argument copy elision.
9222     *Info = StaticAllocaInfo::Elidable;
9223     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9224 
9225     // Stop scanning if we've seen all arguments. This will happen early in -O0
9226     // builds, which is useful, because -O0 builds have large entry blocks and
9227     // many allocas.
9228     if (ArgCopyElisionCandidates.size() == NumArgs)
9229       break;
9230   }
9231 }
9232 
9233 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9234 /// ArgVal is a load from a suitable fixed stack object.
9235 static void tryToElideArgumentCopy(
9236     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9237     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9238     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9239     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9240     SDValue ArgVal, bool &ArgHasUses) {
9241   // Check if this is a load from a fixed stack object.
9242   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9243   if (!LNode)
9244     return;
9245   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9246   if (!FINode)
9247     return;
9248 
9249   // Check that the fixed stack object is the right size and alignment.
9250   // Look at the alignment that the user wrote on the alloca instead of looking
9251   // at the stack object.
9252   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9253   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9254   const AllocaInst *AI = ArgCopyIter->second.first;
9255   int FixedIndex = FINode->getIndex();
9256   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9257   int OldIndex = AllocaIndex;
9258   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9259   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9260     LLVM_DEBUG(
9261         dbgs() << "  argument copy elision failed due to bad fixed stack "
9262                   "object size\n");
9263     return;
9264   }
9265   unsigned RequiredAlignment = AI->getAlignment();
9266   if (!RequiredAlignment) {
9267     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9268         AI->getAllocatedType());
9269   }
9270   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9271     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9272                          "greater than stack argument alignment ("
9273                       << RequiredAlignment << " vs "
9274                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9275     return;
9276   }
9277 
9278   // Perform the elision. Delete the old stack object and replace its only use
9279   // in the variable info map. Mark the stack object as mutable.
9280   LLVM_DEBUG({
9281     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9282            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9283            << '\n';
9284   });
9285   MFI.RemoveStackObject(OldIndex);
9286   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9287   AllocaIndex = FixedIndex;
9288   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9289   Chains.push_back(ArgVal.getValue(1));
9290 
9291   // Avoid emitting code for the store implementing the copy.
9292   const StoreInst *SI = ArgCopyIter->second.second;
9293   ElidedArgCopyInstrs.insert(SI);
9294 
9295   // Check for uses of the argument again so that we can avoid exporting ArgVal
9296   // if it is't used by anything other than the store.
9297   for (const Value *U : Arg.users()) {
9298     if (U != SI) {
9299       ArgHasUses = true;
9300       break;
9301     }
9302   }
9303 }
9304 
9305 void SelectionDAGISel::LowerArguments(const Function &F) {
9306   SelectionDAG &DAG = SDB->DAG;
9307   SDLoc dl = SDB->getCurSDLoc();
9308   const DataLayout &DL = DAG.getDataLayout();
9309   SmallVector<ISD::InputArg, 16> Ins;
9310 
9311   if (!FuncInfo->CanLowerReturn) {
9312     // Put in an sret pointer parameter before all the other parameters.
9313     SmallVector<EVT, 1> ValueVTs;
9314     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9315                     F.getReturnType()->getPointerTo(
9316                         DAG.getDataLayout().getAllocaAddrSpace()),
9317                     ValueVTs);
9318 
9319     // NOTE: Assuming that a pointer will never break down to more than one VT
9320     // or one register.
9321     ISD::ArgFlagsTy Flags;
9322     Flags.setSRet();
9323     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9324     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9325                          ISD::InputArg::NoArgIndex, 0);
9326     Ins.push_back(RetArg);
9327   }
9328 
9329   // Look for stores of arguments to static allocas. Mark such arguments with a
9330   // flag to ask the target to give us the memory location of that argument if
9331   // available.
9332   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9333   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9334 
9335   // Set up the incoming argument description vector.
9336   for (const Argument &Arg : F.args()) {
9337     unsigned ArgNo = Arg.getArgNo();
9338     SmallVector<EVT, 4> ValueVTs;
9339     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9340     bool isArgValueUsed = !Arg.use_empty();
9341     unsigned PartBase = 0;
9342     Type *FinalType = Arg.getType();
9343     if (Arg.hasAttribute(Attribute::ByVal))
9344       FinalType = cast<PointerType>(FinalType)->getElementType();
9345     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9346         FinalType, F.getCallingConv(), F.isVarArg());
9347     for (unsigned Value = 0, NumValues = ValueVTs.size();
9348          Value != NumValues; ++Value) {
9349       EVT VT = ValueVTs[Value];
9350       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9351       ISD::ArgFlagsTy Flags;
9352 
9353       // Certain targets (such as MIPS), may have a different ABI alignment
9354       // for a type depending on the context. Give the target a chance to
9355       // specify the alignment it wants.
9356       unsigned OriginalAlignment =
9357           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9358 
9359       if (Arg.hasAttribute(Attribute::ZExt))
9360         Flags.setZExt();
9361       if (Arg.hasAttribute(Attribute::SExt))
9362         Flags.setSExt();
9363       if (Arg.hasAttribute(Attribute::InReg)) {
9364         // If we are using vectorcall calling convention, a structure that is
9365         // passed InReg - is surely an HVA
9366         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9367             isa<StructType>(Arg.getType())) {
9368           // The first value of a structure is marked
9369           if (0 == Value)
9370             Flags.setHvaStart();
9371           Flags.setHva();
9372         }
9373         // Set InReg Flag
9374         Flags.setInReg();
9375       }
9376       if (Arg.hasAttribute(Attribute::StructRet))
9377         Flags.setSRet();
9378       if (Arg.hasAttribute(Attribute::SwiftSelf))
9379         Flags.setSwiftSelf();
9380       if (Arg.hasAttribute(Attribute::SwiftError))
9381         Flags.setSwiftError();
9382       if (Arg.hasAttribute(Attribute::ByVal))
9383         Flags.setByVal();
9384       if (Arg.hasAttribute(Attribute::InAlloca)) {
9385         Flags.setInAlloca();
9386         // Set the byval flag for CCAssignFn callbacks that don't know about
9387         // inalloca.  This way we can know how many bytes we should've allocated
9388         // and how many bytes a callee cleanup function will pop.  If we port
9389         // inalloca to more targets, we'll have to add custom inalloca handling
9390         // in the various CC lowering callbacks.
9391         Flags.setByVal();
9392       }
9393       if (F.getCallingConv() == CallingConv::X86_INTR) {
9394         // IA Interrupt passes frame (1st parameter) by value in the stack.
9395         if (ArgNo == 0)
9396           Flags.setByVal();
9397       }
9398       if (Flags.isByVal() || Flags.isInAlloca()) {
9399         PointerType *Ty = cast<PointerType>(Arg.getType());
9400         Type *ElementTy = Ty->getElementType();
9401         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9402         // For ByVal, alignment should be passed from FE.  BE will guess if
9403         // this info is not there but there are cases it cannot get right.
9404         unsigned FrameAlign;
9405         if (Arg.getParamAlignment())
9406           FrameAlign = Arg.getParamAlignment();
9407         else
9408           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9409         Flags.setByValAlign(FrameAlign);
9410       }
9411       if (Arg.hasAttribute(Attribute::Nest))
9412         Flags.setNest();
9413       if (NeedsRegBlock)
9414         Flags.setInConsecutiveRegs();
9415       Flags.setOrigAlign(OriginalAlignment);
9416       if (ArgCopyElisionCandidates.count(&Arg))
9417         Flags.setCopyElisionCandidate();
9418 
9419       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9420           *CurDAG->getContext(), F.getCallingConv(), VT);
9421       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9422           *CurDAG->getContext(), F.getCallingConv(), VT);
9423       for (unsigned i = 0; i != NumRegs; ++i) {
9424         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9425                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9426         if (NumRegs > 1 && i == 0)
9427           MyFlags.Flags.setSplit();
9428         // if it isn't first piece, alignment must be 1
9429         else if (i > 0) {
9430           MyFlags.Flags.setOrigAlign(1);
9431           if (i == NumRegs - 1)
9432             MyFlags.Flags.setSplitEnd();
9433         }
9434         Ins.push_back(MyFlags);
9435       }
9436       if (NeedsRegBlock && Value == NumValues - 1)
9437         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9438       PartBase += VT.getStoreSize();
9439     }
9440   }
9441 
9442   // Call the target to set up the argument values.
9443   SmallVector<SDValue, 8> InVals;
9444   SDValue NewRoot = TLI->LowerFormalArguments(
9445       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9446 
9447   // Verify that the target's LowerFormalArguments behaved as expected.
9448   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9449          "LowerFormalArguments didn't return a valid chain!");
9450   assert(InVals.size() == Ins.size() &&
9451          "LowerFormalArguments didn't emit the correct number of values!");
9452   LLVM_DEBUG({
9453     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9454       assert(InVals[i].getNode() &&
9455              "LowerFormalArguments emitted a null value!");
9456       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9457              "LowerFormalArguments emitted a value with the wrong type!");
9458     }
9459   });
9460 
9461   // Update the DAG with the new chain value resulting from argument lowering.
9462   DAG.setRoot(NewRoot);
9463 
9464   // Set up the argument values.
9465   unsigned i = 0;
9466   if (!FuncInfo->CanLowerReturn) {
9467     // Create a virtual register for the sret pointer, and put in a copy
9468     // from the sret argument into it.
9469     SmallVector<EVT, 1> ValueVTs;
9470     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9471                     F.getReturnType()->getPointerTo(
9472                         DAG.getDataLayout().getAllocaAddrSpace()),
9473                     ValueVTs);
9474     MVT VT = ValueVTs[0].getSimpleVT();
9475     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9476     Optional<ISD::NodeType> AssertOp = None;
9477     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9478                                         nullptr, F.getCallingConv(), AssertOp);
9479 
9480     MachineFunction& MF = SDB->DAG.getMachineFunction();
9481     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9482     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9483     FuncInfo->DemoteRegister = SRetReg;
9484     NewRoot =
9485         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9486     DAG.setRoot(NewRoot);
9487 
9488     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9489     ++i;
9490   }
9491 
9492   SmallVector<SDValue, 4> Chains;
9493   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9494   for (const Argument &Arg : F.args()) {
9495     SmallVector<SDValue, 4> ArgValues;
9496     SmallVector<EVT, 4> ValueVTs;
9497     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9498     unsigned NumValues = ValueVTs.size();
9499     if (NumValues == 0)
9500       continue;
9501 
9502     bool ArgHasUses = !Arg.use_empty();
9503 
9504     // Elide the copying store if the target loaded this argument from a
9505     // suitable fixed stack object.
9506     if (Ins[i].Flags.isCopyElisionCandidate()) {
9507       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9508                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9509                              InVals[i], ArgHasUses);
9510     }
9511 
9512     // If this argument is unused then remember its value. It is used to generate
9513     // debugging information.
9514     bool isSwiftErrorArg =
9515         TLI->supportSwiftError() &&
9516         Arg.hasAttribute(Attribute::SwiftError);
9517     if (!ArgHasUses && !isSwiftErrorArg) {
9518       SDB->setUnusedArgValue(&Arg, InVals[i]);
9519 
9520       // Also remember any frame index for use in FastISel.
9521       if (FrameIndexSDNode *FI =
9522           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9523         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9524     }
9525 
9526     for (unsigned Val = 0; Val != NumValues; ++Val) {
9527       EVT VT = ValueVTs[Val];
9528       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9529                                                       F.getCallingConv(), VT);
9530       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9531           *CurDAG->getContext(), F.getCallingConv(), VT);
9532 
9533       // Even an apparant 'unused' swifterror argument needs to be returned. So
9534       // we do generate a copy for it that can be used on return from the
9535       // function.
9536       if (ArgHasUses || isSwiftErrorArg) {
9537         Optional<ISD::NodeType> AssertOp;
9538         if (Arg.hasAttribute(Attribute::SExt))
9539           AssertOp = ISD::AssertSext;
9540         else if (Arg.hasAttribute(Attribute::ZExt))
9541           AssertOp = ISD::AssertZext;
9542 
9543         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9544                                              PartVT, VT, nullptr,
9545                                              F.getCallingConv(), AssertOp));
9546       }
9547 
9548       i += NumParts;
9549     }
9550 
9551     // We don't need to do anything else for unused arguments.
9552     if (ArgValues.empty())
9553       continue;
9554 
9555     // Note down frame index.
9556     if (FrameIndexSDNode *FI =
9557         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9558       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9559 
9560     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9561                                      SDB->getCurSDLoc());
9562 
9563     SDB->setValue(&Arg, Res);
9564     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9565       // We want to associate the argument with the frame index, among
9566       // involved operands, that correspond to the lowest address. The
9567       // getCopyFromParts function, called earlier, is swapping the order of
9568       // the operands to BUILD_PAIR depending on endianness. The result of
9569       // that swapping is that the least significant bits of the argument will
9570       // be in the first operand of the BUILD_PAIR node, and the most
9571       // significant bits will be in the second operand.
9572       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9573       if (LoadSDNode *LNode =
9574           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9575         if (FrameIndexSDNode *FI =
9576             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9577           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9578     }
9579 
9580     // Update the SwiftErrorVRegDefMap.
9581     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9582       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9583       if (TargetRegisterInfo::isVirtualRegister(Reg))
9584         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9585                                            FuncInfo->SwiftErrorArg, Reg);
9586     }
9587 
9588     // If this argument is live outside of the entry block, insert a copy from
9589     // wherever we got it to the vreg that other BB's will reference it as.
9590     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9591       // If we can, though, try to skip creating an unnecessary vreg.
9592       // FIXME: This isn't very clean... it would be nice to make this more
9593       // general.  It's also subtly incompatible with the hacks FastISel
9594       // uses with vregs.
9595       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9596       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9597         FuncInfo->ValueMap[&Arg] = Reg;
9598         continue;
9599       }
9600     }
9601     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9602       FuncInfo->InitializeRegForValue(&Arg);
9603       SDB->CopyToExportRegsIfNeeded(&Arg);
9604     }
9605   }
9606 
9607   if (!Chains.empty()) {
9608     Chains.push_back(NewRoot);
9609     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9610   }
9611 
9612   DAG.setRoot(NewRoot);
9613 
9614   assert(i == InVals.size() && "Argument register count mismatch!");
9615 
9616   // If any argument copy elisions occurred and we have debug info, update the
9617   // stale frame indices used in the dbg.declare variable info table.
9618   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9619   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9620     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9621       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9622       if (I != ArgCopyElisionFrameIndexMap.end())
9623         VI.Slot = I->second;
9624     }
9625   }
9626 
9627   // Finally, if the target has anything special to do, allow it to do so.
9628   EmitFunctionEntryCode();
9629 }
9630 
9631 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9632 /// ensure constants are generated when needed.  Remember the virtual registers
9633 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9634 /// directly add them, because expansion might result in multiple MBB's for one
9635 /// BB.  As such, the start of the BB might correspond to a different MBB than
9636 /// the end.
9637 void
9638 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9639   const Instruction *TI = LLVMBB->getTerminator();
9640 
9641   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9642 
9643   // Check PHI nodes in successors that expect a value to be available from this
9644   // block.
9645   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9646     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9647     if (!isa<PHINode>(SuccBB->begin())) continue;
9648     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9649 
9650     // If this terminator has multiple identical successors (common for
9651     // switches), only handle each succ once.
9652     if (!SuccsHandled.insert(SuccMBB).second)
9653       continue;
9654 
9655     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9656 
9657     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9658     // nodes and Machine PHI nodes, but the incoming operands have not been
9659     // emitted yet.
9660     for (const PHINode &PN : SuccBB->phis()) {
9661       // Ignore dead phi's.
9662       if (PN.use_empty())
9663         continue;
9664 
9665       // Skip empty types
9666       if (PN.getType()->isEmptyTy())
9667         continue;
9668 
9669       unsigned Reg;
9670       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9671 
9672       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9673         unsigned &RegOut = ConstantsOut[C];
9674         if (RegOut == 0) {
9675           RegOut = FuncInfo.CreateRegs(C->getType());
9676           CopyValueToVirtualRegister(C, RegOut);
9677         }
9678         Reg = RegOut;
9679       } else {
9680         DenseMap<const Value *, unsigned>::iterator I =
9681           FuncInfo.ValueMap.find(PHIOp);
9682         if (I != FuncInfo.ValueMap.end())
9683           Reg = I->second;
9684         else {
9685           assert(isa<AllocaInst>(PHIOp) &&
9686                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9687                  "Didn't codegen value into a register!??");
9688           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9689           CopyValueToVirtualRegister(PHIOp, Reg);
9690         }
9691       }
9692 
9693       // Remember that this register needs to added to the machine PHI node as
9694       // the input for this MBB.
9695       SmallVector<EVT, 4> ValueVTs;
9696       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9697       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9698       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9699         EVT VT = ValueVTs[vti];
9700         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9701         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9702           FuncInfo.PHINodesToUpdate.push_back(
9703               std::make_pair(&*MBBI++, Reg + i));
9704         Reg += NumRegisters;
9705       }
9706     }
9707   }
9708 
9709   ConstantsOut.clear();
9710 }
9711 
9712 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9713 /// is 0.
9714 MachineBasicBlock *
9715 SelectionDAGBuilder::StackProtectorDescriptor::
9716 AddSuccessorMBB(const BasicBlock *BB,
9717                 MachineBasicBlock *ParentMBB,
9718                 bool IsLikely,
9719                 MachineBasicBlock *SuccMBB) {
9720   // If SuccBB has not been created yet, create it.
9721   if (!SuccMBB) {
9722     MachineFunction *MF = ParentMBB->getParent();
9723     MachineFunction::iterator BBI(ParentMBB);
9724     SuccMBB = MF->CreateMachineBasicBlock(BB);
9725     MF->insert(++BBI, SuccMBB);
9726   }
9727   // Add it as a successor of ParentMBB.
9728   ParentMBB->addSuccessor(
9729       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9730   return SuccMBB;
9731 }
9732 
9733 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9734   MachineFunction::iterator I(MBB);
9735   if (++I == FuncInfo.MF->end())
9736     return nullptr;
9737   return &*I;
9738 }
9739 
9740 /// During lowering new call nodes can be created (such as memset, etc.).
9741 /// Those will become new roots of the current DAG, but complications arise
9742 /// when they are tail calls. In such cases, the call lowering will update
9743 /// the root, but the builder still needs to know that a tail call has been
9744 /// lowered in order to avoid generating an additional return.
9745 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9746   // If the node is null, we do have a tail call.
9747   if (MaybeTC.getNode() != nullptr)
9748     DAG.setRoot(MaybeTC);
9749   else
9750     HasTailCall = true;
9751 }
9752 
9753 uint64_t
9754 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9755                                        unsigned First, unsigned Last) const {
9756   assert(Last >= First);
9757   const APInt &LowCase = Clusters[First].Low->getValue();
9758   const APInt &HighCase = Clusters[Last].High->getValue();
9759   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9760 
9761   // FIXME: A range of consecutive cases has 100% density, but only requires one
9762   // comparison to lower. We should discriminate against such consecutive ranges
9763   // in jump tables.
9764 
9765   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9766 }
9767 
9768 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9769     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9770     unsigned Last) const {
9771   assert(Last >= First);
9772   assert(TotalCases[Last] >= TotalCases[First]);
9773   uint64_t NumCases =
9774       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9775   return NumCases;
9776 }
9777 
9778 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9779                                          unsigned First, unsigned Last,
9780                                          const SwitchInst *SI,
9781                                          MachineBasicBlock *DefaultMBB,
9782                                          CaseCluster &JTCluster) {
9783   assert(First <= Last);
9784 
9785   auto Prob = BranchProbability::getZero();
9786   unsigned NumCmps = 0;
9787   std::vector<MachineBasicBlock*> Table;
9788   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9789 
9790   // Initialize probabilities in JTProbs.
9791   for (unsigned I = First; I <= Last; ++I)
9792     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9793 
9794   for (unsigned I = First; I <= Last; ++I) {
9795     assert(Clusters[I].Kind == CC_Range);
9796     Prob += Clusters[I].Prob;
9797     const APInt &Low = Clusters[I].Low->getValue();
9798     const APInt &High = Clusters[I].High->getValue();
9799     NumCmps += (Low == High) ? 1 : 2;
9800     if (I != First) {
9801       // Fill the gap between this and the previous cluster.
9802       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9803       assert(PreviousHigh.slt(Low));
9804       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9805       for (uint64_t J = 0; J < Gap; J++)
9806         Table.push_back(DefaultMBB);
9807     }
9808     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9809     for (uint64_t J = 0; J < ClusterSize; ++J)
9810       Table.push_back(Clusters[I].MBB);
9811     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9812   }
9813 
9814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9815   unsigned NumDests = JTProbs.size();
9816   if (TLI.isSuitableForBitTests(
9817           NumDests, NumCmps, Clusters[First].Low->getValue(),
9818           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9819     // Clusters[First..Last] should be lowered as bit tests instead.
9820     return false;
9821   }
9822 
9823   // Create the MBB that will load from and jump through the table.
9824   // Note: We create it here, but it's not inserted into the function yet.
9825   MachineFunction *CurMF = FuncInfo.MF;
9826   MachineBasicBlock *JumpTableMBB =
9827       CurMF->CreateMachineBasicBlock(SI->getParent());
9828 
9829   // Add successors. Note: use table order for determinism.
9830   SmallPtrSet<MachineBasicBlock *, 8> Done;
9831   for (MachineBasicBlock *Succ : Table) {
9832     if (Done.count(Succ))
9833       continue;
9834     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9835     Done.insert(Succ);
9836   }
9837   JumpTableMBB->normalizeSuccProbs();
9838 
9839   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9840                      ->createJumpTableIndex(Table);
9841 
9842   // Set up the jump table info.
9843   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9844   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9845                       Clusters[Last].High->getValue(), SI->getCondition(),
9846                       nullptr, false);
9847   JTCases.emplace_back(std::move(JTH), std::move(JT));
9848 
9849   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9850                                      JTCases.size() - 1, Prob);
9851   return true;
9852 }
9853 
9854 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9855                                          const SwitchInst *SI,
9856                                          MachineBasicBlock *DefaultMBB) {
9857 #ifndef NDEBUG
9858   // Clusters must be non-empty, sorted, and only contain Range clusters.
9859   assert(!Clusters.empty());
9860   for (CaseCluster &C : Clusters)
9861     assert(C.Kind == CC_Range);
9862   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9863     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9864 #endif
9865 
9866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9867   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9868     return;
9869 
9870   const int64_t N = Clusters.size();
9871   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9872   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9873 
9874   if (N < 2 || N < MinJumpTableEntries)
9875     return;
9876 
9877   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9878   SmallVector<unsigned, 8> TotalCases(N);
9879   for (unsigned i = 0; i < N; ++i) {
9880     const APInt &Hi = Clusters[i].High->getValue();
9881     const APInt &Lo = Clusters[i].Low->getValue();
9882     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9883     if (i != 0)
9884       TotalCases[i] += TotalCases[i - 1];
9885   }
9886 
9887   // Cheap case: the whole range may be suitable for jump table.
9888   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9889   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9890   assert(NumCases < UINT64_MAX / 100);
9891   assert(Range >= NumCases);
9892   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9893     CaseCluster JTCluster;
9894     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9895       Clusters[0] = JTCluster;
9896       Clusters.resize(1);
9897       return;
9898     }
9899   }
9900 
9901   // The algorithm below is not suitable for -O0.
9902   if (TM.getOptLevel() == CodeGenOpt::None)
9903     return;
9904 
9905   // Split Clusters into minimum number of dense partitions. The algorithm uses
9906   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9907   // for the Case Statement'" (1994), but builds the MinPartitions array in
9908   // reverse order to make it easier to reconstruct the partitions in ascending
9909   // order. In the choice between two optimal partitionings, it picks the one
9910   // which yields more jump tables.
9911 
9912   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9913   SmallVector<unsigned, 8> MinPartitions(N);
9914   // LastElement[i] is the last element of the partition starting at i.
9915   SmallVector<unsigned, 8> LastElement(N);
9916   // PartitionsScore[i] is used to break ties when choosing between two
9917   // partitionings resulting in the same number of partitions.
9918   SmallVector<unsigned, 8> PartitionsScore(N);
9919   // For PartitionsScore, a small number of comparisons is considered as good as
9920   // a jump table and a single comparison is considered better than a jump
9921   // table.
9922   enum PartitionScores : unsigned {
9923     NoTable = 0,
9924     Table = 1,
9925     FewCases = 1,
9926     SingleCase = 2
9927   };
9928 
9929   // Base case: There is only one way to partition Clusters[N-1].
9930   MinPartitions[N - 1] = 1;
9931   LastElement[N - 1] = N - 1;
9932   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9933 
9934   // Note: loop indexes are signed to avoid underflow.
9935   for (int64_t i = N - 2; i >= 0; i--) {
9936     // Find optimal partitioning of Clusters[i..N-1].
9937     // Baseline: Put Clusters[i] into a partition on its own.
9938     MinPartitions[i] = MinPartitions[i + 1] + 1;
9939     LastElement[i] = i;
9940     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9941 
9942     // Search for a solution that results in fewer partitions.
9943     for (int64_t j = N - 1; j > i; j--) {
9944       // Try building a partition from Clusters[i..j].
9945       uint64_t Range = getJumpTableRange(Clusters, i, j);
9946       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9947       assert(NumCases < UINT64_MAX / 100);
9948       assert(Range >= NumCases);
9949       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9950         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9951         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9952         int64_t NumEntries = j - i + 1;
9953 
9954         if (NumEntries == 1)
9955           Score += PartitionScores::SingleCase;
9956         else if (NumEntries <= SmallNumberOfEntries)
9957           Score += PartitionScores::FewCases;
9958         else if (NumEntries >= MinJumpTableEntries)
9959           Score += PartitionScores::Table;
9960 
9961         // If this leads to fewer partitions, or to the same number of
9962         // partitions with better score, it is a better partitioning.
9963         if (NumPartitions < MinPartitions[i] ||
9964             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9965           MinPartitions[i] = NumPartitions;
9966           LastElement[i] = j;
9967           PartitionsScore[i] = Score;
9968         }
9969       }
9970     }
9971   }
9972 
9973   // Iterate over the partitions, replacing some with jump tables in-place.
9974   unsigned DstIndex = 0;
9975   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9976     Last = LastElement[First];
9977     assert(Last >= First);
9978     assert(DstIndex <= First);
9979     unsigned NumClusters = Last - First + 1;
9980 
9981     CaseCluster JTCluster;
9982     if (NumClusters >= MinJumpTableEntries &&
9983         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9984       Clusters[DstIndex++] = JTCluster;
9985     } else {
9986       for (unsigned I = First; I <= Last; ++I)
9987         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9988     }
9989   }
9990   Clusters.resize(DstIndex);
9991 }
9992 
9993 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9994                                         unsigned First, unsigned Last,
9995                                         const SwitchInst *SI,
9996                                         CaseCluster &BTCluster) {
9997   assert(First <= Last);
9998   if (First == Last)
9999     return false;
10000 
10001   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10002   unsigned NumCmps = 0;
10003   for (int64_t I = First; I <= Last; ++I) {
10004     assert(Clusters[I].Kind == CC_Range);
10005     Dests.set(Clusters[I].MBB->getNumber());
10006     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
10007   }
10008   unsigned NumDests = Dests.count();
10009 
10010   APInt Low = Clusters[First].Low->getValue();
10011   APInt High = Clusters[Last].High->getValue();
10012   assert(Low.slt(High));
10013 
10014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10015   const DataLayout &DL = DAG.getDataLayout();
10016   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
10017     return false;
10018 
10019   APInt LowBound;
10020   APInt CmpRange;
10021 
10022   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
10023   assert(TLI.rangeFitsInWord(Low, High, DL) &&
10024          "Case range must fit in bit mask!");
10025 
10026   // Check if the clusters cover a contiguous range such that no value in the
10027   // range will jump to the default statement.
10028   bool ContiguousRange = true;
10029   for (int64_t I = First + 1; I <= Last; ++I) {
10030     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
10031       ContiguousRange = false;
10032       break;
10033     }
10034   }
10035 
10036   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
10037     // Optimize the case where all the case values fit in a word without having
10038     // to subtract minValue. In this case, we can optimize away the subtraction.
10039     LowBound = APInt::getNullValue(Low.getBitWidth());
10040     CmpRange = High;
10041     ContiguousRange = false;
10042   } else {
10043     LowBound = Low;
10044     CmpRange = High - Low;
10045   }
10046 
10047   CaseBitsVector CBV;
10048   auto TotalProb = BranchProbability::getZero();
10049   for (unsigned i = First; i <= Last; ++i) {
10050     // Find the CaseBits for this destination.
10051     unsigned j;
10052     for (j = 0; j < CBV.size(); ++j)
10053       if (CBV[j].BB == Clusters[i].MBB)
10054         break;
10055     if (j == CBV.size())
10056       CBV.push_back(
10057           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
10058     CaseBits *CB = &CBV[j];
10059 
10060     // Update Mask, Bits and ExtraProb.
10061     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
10062     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
10063     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
10064     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
10065     CB->Bits += Hi - Lo + 1;
10066     CB->ExtraProb += Clusters[i].Prob;
10067     TotalProb += Clusters[i].Prob;
10068   }
10069 
10070   BitTestInfo BTI;
10071   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
10072     // Sort by probability first, number of bits second, bit mask third.
10073     if (a.ExtraProb != b.ExtraProb)
10074       return a.ExtraProb > b.ExtraProb;
10075     if (a.Bits != b.Bits)
10076       return a.Bits > b.Bits;
10077     return a.Mask < b.Mask;
10078   });
10079 
10080   for (auto &CB : CBV) {
10081     MachineBasicBlock *BitTestBB =
10082         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
10083     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
10084   }
10085   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
10086                             SI->getCondition(), -1U, MVT::Other, false,
10087                             ContiguousRange, nullptr, nullptr, std::move(BTI),
10088                             TotalProb);
10089 
10090   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
10091                                     BitTestCases.size() - 1, TotalProb);
10092   return true;
10093 }
10094 
10095 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
10096                                               const SwitchInst *SI) {
10097 // Partition Clusters into as few subsets as possible, where each subset has a
10098 // range that fits in a machine word and has <= 3 unique destinations.
10099 
10100 #ifndef NDEBUG
10101   // Clusters must be sorted and contain Range or JumpTable clusters.
10102   assert(!Clusters.empty());
10103   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
10104   for (const CaseCluster &C : Clusters)
10105     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
10106   for (unsigned i = 1; i < Clusters.size(); ++i)
10107     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
10108 #endif
10109 
10110   // The algorithm below is not suitable for -O0.
10111   if (TM.getOptLevel() == CodeGenOpt::None)
10112     return;
10113 
10114   // If target does not have legal shift left, do not emit bit tests at all.
10115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10116   const DataLayout &DL = DAG.getDataLayout();
10117 
10118   EVT PTy = TLI.getPointerTy(DL);
10119   if (!TLI.isOperationLegal(ISD::SHL, PTy))
10120     return;
10121 
10122   int BitWidth = PTy.getSizeInBits();
10123   const int64_t N = Clusters.size();
10124 
10125   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10126   SmallVector<unsigned, 8> MinPartitions(N);
10127   // LastElement[i] is the last element of the partition starting at i.
10128   SmallVector<unsigned, 8> LastElement(N);
10129 
10130   // FIXME: This might not be the best algorithm for finding bit test clusters.
10131 
10132   // Base case: There is only one way to partition Clusters[N-1].
10133   MinPartitions[N - 1] = 1;
10134   LastElement[N - 1] = N - 1;
10135 
10136   // Note: loop indexes are signed to avoid underflow.
10137   for (int64_t i = N - 2; i >= 0; --i) {
10138     // Find optimal partitioning of Clusters[i..N-1].
10139     // Baseline: Put Clusters[i] into a partition on its own.
10140     MinPartitions[i] = MinPartitions[i + 1] + 1;
10141     LastElement[i] = i;
10142 
10143     // Search for a solution that results in fewer partitions.
10144     // Note: the search is limited by BitWidth, reducing time complexity.
10145     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
10146       // Try building a partition from Clusters[i..j].
10147 
10148       // Check the range.
10149       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
10150                                Clusters[j].High->getValue(), DL))
10151         continue;
10152 
10153       // Check nbr of destinations and cluster types.
10154       // FIXME: This works, but doesn't seem very efficient.
10155       bool RangesOnly = true;
10156       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10157       for (int64_t k = i; k <= j; k++) {
10158         if (Clusters[k].Kind != CC_Range) {
10159           RangesOnly = false;
10160           break;
10161         }
10162         Dests.set(Clusters[k].MBB->getNumber());
10163       }
10164       if (!RangesOnly || Dests.count() > 3)
10165         break;
10166 
10167       // Check if it's a better partition.
10168       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10169       if (NumPartitions < MinPartitions[i]) {
10170         // Found a better partition.
10171         MinPartitions[i] = NumPartitions;
10172         LastElement[i] = j;
10173       }
10174     }
10175   }
10176 
10177   // Iterate over the partitions, replacing with bit-test clusters in-place.
10178   unsigned DstIndex = 0;
10179   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10180     Last = LastElement[First];
10181     assert(First <= Last);
10182     assert(DstIndex <= First);
10183 
10184     CaseCluster BitTestCluster;
10185     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10186       Clusters[DstIndex++] = BitTestCluster;
10187     } else {
10188       size_t NumClusters = Last - First + 1;
10189       std::memmove(&Clusters[DstIndex], &Clusters[First],
10190                    sizeof(Clusters[0]) * NumClusters);
10191       DstIndex += NumClusters;
10192     }
10193   }
10194   Clusters.resize(DstIndex);
10195 }
10196 
10197 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10198                                         MachineBasicBlock *SwitchMBB,
10199                                         MachineBasicBlock *DefaultMBB) {
10200   MachineFunction *CurMF = FuncInfo.MF;
10201   MachineBasicBlock *NextMBB = nullptr;
10202   MachineFunction::iterator BBI(W.MBB);
10203   if (++BBI != FuncInfo.MF->end())
10204     NextMBB = &*BBI;
10205 
10206   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10207 
10208   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10209 
10210   if (Size == 2 && W.MBB == SwitchMBB) {
10211     // If any two of the cases has the same destination, and if one value
10212     // is the same as the other, but has one bit unset that the other has set,
10213     // use bit manipulation to do two compares at once.  For example:
10214     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10215     // TODO: This could be extended to merge any 2 cases in switches with 3
10216     // cases.
10217     // TODO: Handle cases where W.CaseBB != SwitchBB.
10218     CaseCluster &Small = *W.FirstCluster;
10219     CaseCluster &Big = *W.LastCluster;
10220 
10221     if (Small.Low == Small.High && Big.Low == Big.High &&
10222         Small.MBB == Big.MBB) {
10223       const APInt &SmallValue = Small.Low->getValue();
10224       const APInt &BigValue = Big.Low->getValue();
10225 
10226       // Check that there is only one bit different.
10227       APInt CommonBit = BigValue ^ SmallValue;
10228       if (CommonBit.isPowerOf2()) {
10229         SDValue CondLHS = getValue(Cond);
10230         EVT VT = CondLHS.getValueType();
10231         SDLoc DL = getCurSDLoc();
10232 
10233         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10234                                  DAG.getConstant(CommonBit, DL, VT));
10235         SDValue Cond = DAG.getSetCC(
10236             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10237             ISD::SETEQ);
10238 
10239         // Update successor info.
10240         // Both Small and Big will jump to Small.BB, so we sum up the
10241         // probabilities.
10242         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10243         if (BPI)
10244           addSuccessorWithProb(
10245               SwitchMBB, DefaultMBB,
10246               // The default destination is the first successor in IR.
10247               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10248         else
10249           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10250 
10251         // Insert the true branch.
10252         SDValue BrCond =
10253             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10254                         DAG.getBasicBlock(Small.MBB));
10255         // Insert the false branch.
10256         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10257                              DAG.getBasicBlock(DefaultMBB));
10258 
10259         DAG.setRoot(BrCond);
10260         return;
10261       }
10262     }
10263   }
10264 
10265   if (TM.getOptLevel() != CodeGenOpt::None) {
10266     // Here, we order cases by probability so the most likely case will be
10267     // checked first. However, two clusters can have the same probability in
10268     // which case their relative ordering is non-deterministic. So we use Low
10269     // as a tie-breaker as clusters are guaranteed to never overlap.
10270     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10271                [](const CaseCluster &a, const CaseCluster &b) {
10272       return a.Prob != b.Prob ?
10273              a.Prob > b.Prob :
10274              a.Low->getValue().slt(b.Low->getValue());
10275     });
10276 
10277     // Rearrange the case blocks so that the last one falls through if possible
10278     // without changing the order of probabilities.
10279     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10280       --I;
10281       if (I->Prob > W.LastCluster->Prob)
10282         break;
10283       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10284         std::swap(*I, *W.LastCluster);
10285         break;
10286       }
10287     }
10288   }
10289 
10290   // Compute total probability.
10291   BranchProbability DefaultProb = W.DefaultProb;
10292   BranchProbability UnhandledProbs = DefaultProb;
10293   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10294     UnhandledProbs += I->Prob;
10295 
10296   MachineBasicBlock *CurMBB = W.MBB;
10297   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10298     MachineBasicBlock *Fallthrough;
10299     if (I == W.LastCluster) {
10300       // For the last cluster, fall through to the default destination.
10301       Fallthrough = DefaultMBB;
10302     } else {
10303       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10304       CurMF->insert(BBI, Fallthrough);
10305       // Put Cond in a virtual register to make it available from the new blocks.
10306       ExportFromCurrentBlock(Cond);
10307     }
10308     UnhandledProbs -= I->Prob;
10309 
10310     switch (I->Kind) {
10311       case CC_JumpTable: {
10312         // FIXME: Optimize away range check based on pivot comparisons.
10313         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10314         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10315 
10316         // The jump block hasn't been inserted yet; insert it here.
10317         MachineBasicBlock *JumpMBB = JT->MBB;
10318         CurMF->insert(BBI, JumpMBB);
10319 
10320         auto JumpProb = I->Prob;
10321         auto FallthroughProb = UnhandledProbs;
10322 
10323         // If the default statement is a target of the jump table, we evenly
10324         // distribute the default probability to successors of CurMBB. Also
10325         // update the probability on the edge from JumpMBB to Fallthrough.
10326         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10327                                               SE = JumpMBB->succ_end();
10328              SI != SE; ++SI) {
10329           if (*SI == DefaultMBB) {
10330             JumpProb += DefaultProb / 2;
10331             FallthroughProb -= DefaultProb / 2;
10332             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10333             JumpMBB->normalizeSuccProbs();
10334             break;
10335           }
10336         }
10337 
10338         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10339         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10340         CurMBB->normalizeSuccProbs();
10341 
10342         // The jump table header will be inserted in our current block, do the
10343         // range check, and fall through to our fallthrough block.
10344         JTH->HeaderBB = CurMBB;
10345         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10346 
10347         // If we're in the right place, emit the jump table header right now.
10348         if (CurMBB == SwitchMBB) {
10349           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10350           JTH->Emitted = true;
10351         }
10352         break;
10353       }
10354       case CC_BitTests: {
10355         // FIXME: Optimize away range check based on pivot comparisons.
10356         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10357 
10358         // The bit test blocks haven't been inserted yet; insert them here.
10359         for (BitTestCase &BTC : BTB->Cases)
10360           CurMF->insert(BBI, BTC.ThisBB);
10361 
10362         // Fill in fields of the BitTestBlock.
10363         BTB->Parent = CurMBB;
10364         BTB->Default = Fallthrough;
10365 
10366         BTB->DefaultProb = UnhandledProbs;
10367         // If the cases in bit test don't form a contiguous range, we evenly
10368         // distribute the probability on the edge to Fallthrough to two
10369         // successors of CurMBB.
10370         if (!BTB->ContiguousRange) {
10371           BTB->Prob += DefaultProb / 2;
10372           BTB->DefaultProb -= DefaultProb / 2;
10373         }
10374 
10375         // If we're in the right place, emit the bit test header right now.
10376         if (CurMBB == SwitchMBB) {
10377           visitBitTestHeader(*BTB, SwitchMBB);
10378           BTB->Emitted = true;
10379         }
10380         break;
10381       }
10382       case CC_Range: {
10383         const Value *RHS, *LHS, *MHS;
10384         ISD::CondCode CC;
10385         if (I->Low == I->High) {
10386           // Check Cond == I->Low.
10387           CC = ISD::SETEQ;
10388           LHS = Cond;
10389           RHS=I->Low;
10390           MHS = nullptr;
10391         } else {
10392           // Check I->Low <= Cond <= I->High.
10393           CC = ISD::SETLE;
10394           LHS = I->Low;
10395           MHS = Cond;
10396           RHS = I->High;
10397         }
10398 
10399         // The false probability is the sum of all unhandled cases.
10400         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10401                      getCurSDLoc(), I->Prob, UnhandledProbs);
10402 
10403         if (CurMBB == SwitchMBB)
10404           visitSwitchCase(CB, SwitchMBB);
10405         else
10406           SwitchCases.push_back(CB);
10407 
10408         break;
10409       }
10410     }
10411     CurMBB = Fallthrough;
10412   }
10413 }
10414 
10415 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10416                                               CaseClusterIt First,
10417                                               CaseClusterIt Last) {
10418   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10419     if (X.Prob != CC.Prob)
10420       return X.Prob > CC.Prob;
10421 
10422     // Ties are broken by comparing the case value.
10423     return X.Low->getValue().slt(CC.Low->getValue());
10424   });
10425 }
10426 
10427 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10428                                         const SwitchWorkListItem &W,
10429                                         Value *Cond,
10430                                         MachineBasicBlock *SwitchMBB) {
10431   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10432          "Clusters not sorted?");
10433 
10434   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10435 
10436   // Balance the tree based on branch probabilities to create a near-optimal (in
10437   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10438   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10439   CaseClusterIt LastLeft = W.FirstCluster;
10440   CaseClusterIt FirstRight = W.LastCluster;
10441   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10442   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10443 
10444   // Move LastLeft and FirstRight towards each other from opposite directions to
10445   // find a partitioning of the clusters which balances the probability on both
10446   // sides. If LeftProb and RightProb are equal, alternate which side is
10447   // taken to ensure 0-probability nodes are distributed evenly.
10448   unsigned I = 0;
10449   while (LastLeft + 1 < FirstRight) {
10450     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10451       LeftProb += (++LastLeft)->Prob;
10452     else
10453       RightProb += (--FirstRight)->Prob;
10454     I++;
10455   }
10456 
10457   while (true) {
10458     // Our binary search tree differs from a typical BST in that ours can have up
10459     // to three values in each leaf. The pivot selection above doesn't take that
10460     // into account, which means the tree might require more nodes and be less
10461     // efficient. We compensate for this here.
10462 
10463     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10464     unsigned NumRight = W.LastCluster - FirstRight + 1;
10465 
10466     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10467       // If one side has less than 3 clusters, and the other has more than 3,
10468       // consider taking a cluster from the other side.
10469 
10470       if (NumLeft < NumRight) {
10471         // Consider moving the first cluster on the right to the left side.
10472         CaseCluster &CC = *FirstRight;
10473         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10474         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10475         if (LeftSideRank <= RightSideRank) {
10476           // Moving the cluster to the left does not demote it.
10477           ++LastLeft;
10478           ++FirstRight;
10479           continue;
10480         }
10481       } else {
10482         assert(NumRight < NumLeft);
10483         // Consider moving the last element on the left to the right side.
10484         CaseCluster &CC = *LastLeft;
10485         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10486         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10487         if (RightSideRank <= LeftSideRank) {
10488           // Moving the cluster to the right does not demot it.
10489           --LastLeft;
10490           --FirstRight;
10491           continue;
10492         }
10493       }
10494     }
10495     break;
10496   }
10497 
10498   assert(LastLeft + 1 == FirstRight);
10499   assert(LastLeft >= W.FirstCluster);
10500   assert(FirstRight <= W.LastCluster);
10501 
10502   // Use the first element on the right as pivot since we will make less-than
10503   // comparisons against it.
10504   CaseClusterIt PivotCluster = FirstRight;
10505   assert(PivotCluster > W.FirstCluster);
10506   assert(PivotCluster <= W.LastCluster);
10507 
10508   CaseClusterIt FirstLeft = W.FirstCluster;
10509   CaseClusterIt LastRight = W.LastCluster;
10510 
10511   const ConstantInt *Pivot = PivotCluster->Low;
10512 
10513   // New blocks will be inserted immediately after the current one.
10514   MachineFunction::iterator BBI(W.MBB);
10515   ++BBI;
10516 
10517   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10518   // we can branch to its destination directly if it's squeezed exactly in
10519   // between the known lower bound and Pivot - 1.
10520   MachineBasicBlock *LeftMBB;
10521   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10522       FirstLeft->Low == W.GE &&
10523       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10524     LeftMBB = FirstLeft->MBB;
10525   } else {
10526     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10527     FuncInfo.MF->insert(BBI, LeftMBB);
10528     WorkList.push_back(
10529         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10530     // Put Cond in a virtual register to make it available from the new blocks.
10531     ExportFromCurrentBlock(Cond);
10532   }
10533 
10534   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10535   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10536   // directly if RHS.High equals the current upper bound.
10537   MachineBasicBlock *RightMBB;
10538   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10539       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10540     RightMBB = FirstRight->MBB;
10541   } else {
10542     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10543     FuncInfo.MF->insert(BBI, RightMBB);
10544     WorkList.push_back(
10545         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10546     // Put Cond in a virtual register to make it available from the new blocks.
10547     ExportFromCurrentBlock(Cond);
10548   }
10549 
10550   // Create the CaseBlock record that will be used to lower the branch.
10551   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10552                getCurSDLoc(), LeftProb, RightProb);
10553 
10554   if (W.MBB == SwitchMBB)
10555     visitSwitchCase(CB, SwitchMBB);
10556   else
10557     SwitchCases.push_back(CB);
10558 }
10559 
10560 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10561 // from the swith statement.
10562 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10563                                             BranchProbability PeeledCaseProb) {
10564   if (PeeledCaseProb == BranchProbability::getOne())
10565     return BranchProbability::getZero();
10566   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10567 
10568   uint32_t Numerator = CaseProb.getNumerator();
10569   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10570   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10571 }
10572 
10573 // Try to peel the top probability case if it exceeds the threshold.
10574 // Return current MachineBasicBlock for the switch statement if the peeling
10575 // does not occur.
10576 // If the peeling is performed, return the newly created MachineBasicBlock
10577 // for the peeled switch statement. Also update Clusters to remove the peeled
10578 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10579 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10580     const SwitchInst &SI, CaseClusterVector &Clusters,
10581     BranchProbability &PeeledCaseProb) {
10582   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10583   // Don't perform if there is only one cluster or optimizing for size.
10584   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10585       TM.getOptLevel() == CodeGenOpt::None ||
10586       SwitchMBB->getParent()->getFunction().optForMinSize())
10587     return SwitchMBB;
10588 
10589   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10590   unsigned PeeledCaseIndex = 0;
10591   bool SwitchPeeled = false;
10592   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10593     CaseCluster &CC = Clusters[Index];
10594     if (CC.Prob < TopCaseProb)
10595       continue;
10596     TopCaseProb = CC.Prob;
10597     PeeledCaseIndex = Index;
10598     SwitchPeeled = true;
10599   }
10600   if (!SwitchPeeled)
10601     return SwitchMBB;
10602 
10603   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10604                     << TopCaseProb << "\n");
10605 
10606   // Record the MBB for the peeled switch statement.
10607   MachineFunction::iterator BBI(SwitchMBB);
10608   ++BBI;
10609   MachineBasicBlock *PeeledSwitchMBB =
10610       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10611   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10612 
10613   ExportFromCurrentBlock(SI.getCondition());
10614   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10615   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10616                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10617   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10618 
10619   Clusters.erase(PeeledCaseIt);
10620   for (CaseCluster &CC : Clusters) {
10621     LLVM_DEBUG(
10622         dbgs() << "Scale the probablity for one cluster, before scaling: "
10623                << CC.Prob << "\n");
10624     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10625     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10626   }
10627   PeeledCaseProb = TopCaseProb;
10628   return PeeledSwitchMBB;
10629 }
10630 
10631 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10632   // Extract cases from the switch.
10633   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10634   CaseClusterVector Clusters;
10635   Clusters.reserve(SI.getNumCases());
10636   for (auto I : SI.cases()) {
10637     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10638     const ConstantInt *CaseVal = I.getCaseValue();
10639     BranchProbability Prob =
10640         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10641             : BranchProbability(1, SI.getNumCases() + 1);
10642     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10643   }
10644 
10645   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10646 
10647   // Cluster adjacent cases with the same destination. We do this at all
10648   // optimization levels because it's cheap to do and will make codegen faster
10649   // if there are many clusters.
10650   sortAndRangeify(Clusters);
10651 
10652   if (TM.getOptLevel() != CodeGenOpt::None) {
10653     // Replace an unreachable default with the most popular destination.
10654     // FIXME: Exploit unreachable default more aggressively.
10655     bool UnreachableDefault =
10656         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10657     if (UnreachableDefault && !Clusters.empty()) {
10658       DenseMap<const BasicBlock *, unsigned> Popularity;
10659       unsigned MaxPop = 0;
10660       const BasicBlock *MaxBB = nullptr;
10661       for (auto I : SI.cases()) {
10662         const BasicBlock *BB = I.getCaseSuccessor();
10663         if (++Popularity[BB] > MaxPop) {
10664           MaxPop = Popularity[BB];
10665           MaxBB = BB;
10666         }
10667       }
10668       // Set new default.
10669       assert(MaxPop > 0 && MaxBB);
10670       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10671 
10672       // Remove cases that were pointing to the destination that is now the
10673       // default.
10674       CaseClusterVector New;
10675       New.reserve(Clusters.size());
10676       for (CaseCluster &CC : Clusters) {
10677         if (CC.MBB != DefaultMBB)
10678           New.push_back(CC);
10679       }
10680       Clusters = std::move(New);
10681     }
10682   }
10683 
10684   // The branch probablity of the peeled case.
10685   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10686   MachineBasicBlock *PeeledSwitchMBB =
10687       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10688 
10689   // If there is only the default destination, jump there directly.
10690   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10691   if (Clusters.empty()) {
10692     assert(PeeledSwitchMBB == SwitchMBB);
10693     SwitchMBB->addSuccessor(DefaultMBB);
10694     if (DefaultMBB != NextBlock(SwitchMBB)) {
10695       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10696                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10697     }
10698     return;
10699   }
10700 
10701   findJumpTables(Clusters, &SI, DefaultMBB);
10702   findBitTestClusters(Clusters, &SI);
10703 
10704   LLVM_DEBUG({
10705     dbgs() << "Case clusters: ";
10706     for (const CaseCluster &C : Clusters) {
10707       if (C.Kind == CC_JumpTable)
10708         dbgs() << "JT:";
10709       if (C.Kind == CC_BitTests)
10710         dbgs() << "BT:";
10711 
10712       C.Low->getValue().print(dbgs(), true);
10713       if (C.Low != C.High) {
10714         dbgs() << '-';
10715         C.High->getValue().print(dbgs(), true);
10716       }
10717       dbgs() << ' ';
10718     }
10719     dbgs() << '\n';
10720   });
10721 
10722   assert(!Clusters.empty());
10723   SwitchWorkList WorkList;
10724   CaseClusterIt First = Clusters.begin();
10725   CaseClusterIt Last = Clusters.end() - 1;
10726   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10727   // Scale the branchprobability for DefaultMBB if the peel occurs and
10728   // DefaultMBB is not replaced.
10729   if (PeeledCaseProb != BranchProbability::getZero() &&
10730       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10731     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10732   WorkList.push_back(
10733       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10734 
10735   while (!WorkList.empty()) {
10736     SwitchWorkListItem W = WorkList.back();
10737     WorkList.pop_back();
10738     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10739 
10740     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10741         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10742       // For optimized builds, lower large range as a balanced binary tree.
10743       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10744       continue;
10745     }
10746 
10747     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10748   }
10749 }
10750