xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision f46262e0b7a183c22b9384cd729c5fb0f05e5d38)
1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/Loads.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Analysis/VectorUtils.h"
27 #include "llvm/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/FunctionLoweringInfo.h"
29 #include "llvm/CodeGen/GCMetadata.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
39 #include "llvm/CodeGen/StackMaps.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfo.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GetElementPtrTypeIterator.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/Statepoint.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Target/TargetFrameLowering.h"
63 #include "llvm/Target/TargetInstrInfo.h"
64 #include "llvm/Target/TargetIntrinsicInfo.h"
65 #include "llvm/Target/TargetLowering.h"
66 #include "llvm/Target/TargetOptions.h"
67 #include "llvm/Target/TargetSubtargetInfo.h"
68 #include <algorithm>
69 #include <utility>
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "isel"
73 
74 /// LimitFloatPrecision - Generate low-precision inline sequences for
75 /// some float libcalls (6, 8 or 12 bits).
76 static unsigned LimitFloatPrecision;
77 
78 static cl::opt<unsigned, true>
79 LimitFPPrecision("limit-float-precision",
80                  cl::desc("Generate low-precision inline sequences "
81                           "for some float libcalls"),
82                  cl::location(LimitFloatPrecision),
83                  cl::init(0));
84 
85 static cl::opt<bool>
86 EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden,
87                 cl::desc("Enable fast-math-flags for DAG nodes"));
88 
89 /// Minimum jump table density for normal functions.
90 static cl::opt<unsigned>
91 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
92                  cl::desc("Minimum density for building a jump table in "
93                           "a normal function"));
94 
95 /// Minimum jump table density for -Os or -Oz functions.
96 static cl::opt<unsigned>
97 OptsizeJumpTableDensity("optsize-jump-table-density", cl::init(40), cl::Hidden,
98                         cl::desc("Minimum density for building a jump table in "
99                                  "an optsize function"));
100 
101 
102 // Limit the width of DAG chains. This is important in general to prevent
103 // DAG-based analysis from blowing up. For example, alias analysis and
104 // load clustering may not complete in reasonable time. It is difficult to
105 // recognize and avoid this situation within each individual analysis, and
106 // future analyses are likely to have the same behavior. Limiting DAG width is
107 // the safe approach and will be especially important with global DAGs.
108 //
109 // MaxParallelChains default is arbitrarily high to avoid affecting
110 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
111 // sequence over this should have been converted to llvm.memcpy by the
112 // frontend. It easy to induce this behavior with .ll code such as:
113 // %buffer = alloca [4096 x i8]
114 // %data = load [4096 x i8]* %argPtr
115 // store [4096 x i8] %data, [4096 x i8]* %buffer
116 static const unsigned MaxParallelChains = 64;
117 
118 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
119                                       const SDValue *Parts, unsigned NumParts,
120                                       MVT PartVT, EVT ValueVT, const Value *V);
121 
122 /// getCopyFromParts - Create a value that contains the specified legal parts
123 /// combined into the value they represent.  If the parts combine to a type
124 /// larger then ValueVT then AssertOp can be used to specify whether the extra
125 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
126 /// (ISD::AssertSext).
127 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
128                                 const SDValue *Parts,
129                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
130                                 const Value *V,
131                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
132   if (ValueVT.isVector())
133     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
134                                   PartVT, ValueVT, V);
135 
136   assert(NumParts > 0 && "No parts to assemble!");
137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
138   SDValue Val = Parts[0];
139 
140   if (NumParts > 1) {
141     // Assemble the value from multiple parts.
142     if (ValueVT.isInteger()) {
143       unsigned PartBits = PartVT.getSizeInBits();
144       unsigned ValueBits = ValueVT.getSizeInBits();
145 
146       // Assemble the power of 2 part.
147       unsigned RoundParts = NumParts & (NumParts - 1) ?
148         1 << Log2_32(NumParts) : NumParts;
149       unsigned RoundBits = PartBits * RoundParts;
150       EVT RoundVT = RoundBits == ValueBits ?
151         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
152       SDValue Lo, Hi;
153 
154       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
155 
156       if (RoundParts > 2) {
157         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
158                               PartVT, HalfVT, V);
159         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
160                               RoundParts / 2, PartVT, HalfVT, V);
161       } else {
162         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
163         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
164       }
165 
166       if (DAG.getDataLayout().isBigEndian())
167         std::swap(Lo, Hi);
168 
169       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
170 
171       if (RoundParts < NumParts) {
172         // Assemble the trailing non-power-of-2 part.
173         unsigned OddParts = NumParts - RoundParts;
174         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
175         Hi = getCopyFromParts(DAG, DL,
176                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
177 
178         // Combine the round and odd parts.
179         Lo = Val;
180         if (DAG.getDataLayout().isBigEndian())
181           std::swap(Lo, Hi);
182         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
183         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
184         Hi =
185             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
186                         DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
187                                         TLI.getPointerTy(DAG.getDataLayout())));
188         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
189         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
190       }
191     } else if (PartVT.isFloatingPoint()) {
192       // FP split into multiple FP parts (for ppcf128)
193       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
194              "Unexpected split");
195       SDValue Lo, Hi;
196       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
197       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
198       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
199         std::swap(Lo, Hi);
200       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
201     } else {
202       // FP split into integer parts (soft fp)
203       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
204              !PartVT.isVector() && "Unexpected split");
205       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
206       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
207     }
208   }
209 
210   // There is now one part, held in Val.  Correct it to match ValueVT.
211   // PartEVT is the type of the register class that holds the value.
212   // ValueVT is the type of the inline asm operation.
213   EVT PartEVT = Val.getValueType();
214 
215   if (PartEVT == ValueVT)
216     return Val;
217 
218   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
219       ValueVT.bitsLT(PartEVT)) {
220     // For an FP value in an integer part, we need to truncate to the right
221     // width first.
222     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
223     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
224   }
225 
226   // Handle types that have the same size.
227   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
228     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
229 
230   // Handle types with different sizes.
231   if (PartEVT.isInteger() && ValueVT.isInteger()) {
232     if (ValueVT.bitsLT(PartEVT)) {
233       // For a truncate, see if we have any information to
234       // indicate whether the truncated bits will always be
235       // zero or sign-extension.
236       if (AssertOp != ISD::DELETED_NODE)
237         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
238                           DAG.getValueType(ValueVT));
239       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
240     }
241     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
242   }
243 
244   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
245     // FP_ROUND's are always exact here.
246     if (ValueVT.bitsLT(Val.getValueType()))
247       return DAG.getNode(
248           ISD::FP_ROUND, DL, ValueVT, Val,
249           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
250 
251     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
252   }
253 
254   llvm_unreachable("Unknown mismatch!");
255 }
256 
257 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
258                                               const Twine &ErrMsg) {
259   const Instruction *I = dyn_cast_or_null<Instruction>(V);
260   if (!V)
261     return Ctx.emitError(ErrMsg);
262 
263   const char *AsmError = ", possible invalid constraint for vector type";
264   if (const CallInst *CI = dyn_cast<CallInst>(I))
265     if (isa<InlineAsm>(CI->getCalledValue()))
266       return Ctx.emitError(I, ErrMsg + AsmError);
267 
268   return Ctx.emitError(I, ErrMsg);
269 }
270 
271 /// getCopyFromPartsVector - Create a value that contains the specified legal
272 /// parts combined into the value they represent.  If the parts combine to a
273 /// type larger then ValueVT then AssertOp can be used to specify whether the
274 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
275 /// ValueVT (ISD::AssertSext).
276 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
277                                       const SDValue *Parts, unsigned NumParts,
278                                       MVT PartVT, EVT ValueVT, const Value *V) {
279   assert(ValueVT.isVector() && "Not a vector value");
280   assert(NumParts > 0 && "No parts to assemble!");
281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
282   SDValue Val = Parts[0];
283 
284   // Handle a multi-element vector.
285   if (NumParts > 1) {
286     EVT IntermediateVT;
287     MVT RegisterVT;
288     unsigned NumIntermediates;
289     unsigned NumRegs =
290     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
291                                NumIntermediates, RegisterVT);
292     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
293     NumParts = NumRegs; // Silence a compiler warning.
294     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
295     assert(RegisterVT.getSizeInBits() ==
296            Parts[0].getSimpleValueType().getSizeInBits() &&
297            "Part type sizes don't match!");
298 
299     // Assemble the parts into intermediate operands.
300     SmallVector<SDValue, 8> Ops(NumIntermediates);
301     if (NumIntermediates == NumParts) {
302       // If the register was not expanded, truncate or copy the value,
303       // as appropriate.
304       for (unsigned i = 0; i != NumParts; ++i)
305         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
306                                   PartVT, IntermediateVT, V);
307     } else if (NumParts > 0) {
308       // If the intermediate type was expanded, build the intermediate
309       // operands from the parts.
310       assert(NumParts % NumIntermediates == 0 &&
311              "Must expand into a divisible number of parts!");
312       unsigned Factor = NumParts / NumIntermediates;
313       for (unsigned i = 0; i != NumIntermediates; ++i)
314         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
315                                   PartVT, IntermediateVT, V);
316     }
317 
318     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
319     // intermediate operands.
320     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
321                                                 : ISD::BUILD_VECTOR,
322                       DL, ValueVT, Ops);
323   }
324 
325   // There is now one part, held in Val.  Correct it to match ValueVT.
326   EVT PartEVT = Val.getValueType();
327 
328   if (PartEVT == ValueVT)
329     return Val;
330 
331   if (PartEVT.isVector()) {
332     // If the element type of the source/dest vectors are the same, but the
333     // parts vector has more elements than the value vector, then we have a
334     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
335     // elements we want.
336     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
337       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
338              "Cannot narrow, it would be a lossy transformation");
339       return DAG.getNode(
340           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
341           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
342     }
343 
344     // Vector/Vector bitcast.
345     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
346       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
347 
348     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
349       "Cannot handle this kind of promotion");
350     // Promoted vector extract
351     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
352 
353   }
354 
355   // Trivial bitcast if the types are the same size and the destination
356   // vector type is legal.
357   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
358       TLI.isTypeLegal(ValueVT))
359     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
360 
361   // Handle cases such as i8 -> <1 x i1>
362   if (ValueVT.getVectorNumElements() != 1) {
363     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
364                                       "non-trivial scalar-to-vector conversion");
365     return DAG.getUNDEF(ValueVT);
366   }
367 
368   if (ValueVT.getVectorNumElements() == 1 &&
369       ValueVT.getVectorElementType() != PartEVT)
370     Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType());
371 
372   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
373 }
374 
375 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
376                                  SDValue Val, SDValue *Parts, unsigned NumParts,
377                                  MVT PartVT, const Value *V);
378 
379 /// getCopyToParts - Create a series of nodes that contain the specified value
380 /// split into legal parts.  If the parts contain more bits than Val, then, for
381 /// integers, ExtendKind can be used to specify how to generate the extra bits.
382 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
383                            SDValue Val, SDValue *Parts, unsigned NumParts,
384                            MVT PartVT, const Value *V,
385                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
386   EVT ValueVT = Val.getValueType();
387 
388   // Handle the vector case separately.
389   if (ValueVT.isVector())
390     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
391 
392   unsigned PartBits = PartVT.getSizeInBits();
393   unsigned OrigNumParts = NumParts;
394   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
395          "Copying to an illegal type!");
396 
397   if (NumParts == 0)
398     return;
399 
400   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
401   EVT PartEVT = PartVT;
402   if (PartEVT == ValueVT) {
403     assert(NumParts == 1 && "No-op copy with multiple parts!");
404     Parts[0] = Val;
405     return;
406   }
407 
408   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
409     // If the parts cover more bits than the value has, promote the value.
410     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
411       assert(NumParts == 1 && "Do not know what to promote to!");
412       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
413     } else {
414       if (ValueVT.isFloatingPoint()) {
415         // FP values need to be bitcast, then extended if they are being put
416         // into a larger container.
417         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
418         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419       }
420       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
421              ValueVT.isInteger() &&
422              "Unknown mismatch!");
423       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
424       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
425       if (PartVT == MVT::x86mmx)
426         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
427     }
428   } else if (PartBits == ValueVT.getSizeInBits()) {
429     // Different types of the same size.
430     assert(NumParts == 1 && PartEVT != ValueVT);
431     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
432   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
433     // If the parts cover less bits than value has, truncate the value.
434     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
435            ValueVT.isInteger() &&
436            "Unknown mismatch!");
437     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
438     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
439     if (PartVT == MVT::x86mmx)
440       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
441   }
442 
443   // The value may have changed - recompute ValueVT.
444   ValueVT = Val.getValueType();
445   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
446          "Failed to tile the value with PartVT!");
447 
448   if (NumParts == 1) {
449     if (PartEVT != ValueVT)
450       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
451                                         "scalar-to-vector conversion failed");
452 
453     Parts[0] = Val;
454     return;
455   }
456 
457   // Expand the value into multiple parts.
458   if (NumParts & (NumParts - 1)) {
459     // The number of parts is not a power of 2.  Split off and copy the tail.
460     assert(PartVT.isInteger() && ValueVT.isInteger() &&
461            "Do not know what to expand to!");
462     unsigned RoundParts = 1 << Log2_32(NumParts);
463     unsigned RoundBits = RoundParts * PartBits;
464     unsigned OddParts = NumParts - RoundParts;
465     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
466                                  DAG.getIntPtrConstant(RoundBits, DL));
467     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
468 
469     if (DAG.getDataLayout().isBigEndian())
470       // The odd parts were reversed by getCopyToParts - unreverse them.
471       std::reverse(Parts + RoundParts, Parts + NumParts);
472 
473     NumParts = RoundParts;
474     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
475     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
476   }
477 
478   // The number of parts is a power of 2.  Repeatedly bisect the value using
479   // EXTRACT_ELEMENT.
480   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
481                          EVT::getIntegerVT(*DAG.getContext(),
482                                            ValueVT.getSizeInBits()),
483                          Val);
484 
485   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
486     for (unsigned i = 0; i < NumParts; i += StepSize) {
487       unsigned ThisBits = StepSize * PartBits / 2;
488       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
489       SDValue &Part0 = Parts[i];
490       SDValue &Part1 = Parts[i+StepSize/2];
491 
492       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
493                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
494       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
495                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
496 
497       if (ThisBits == PartBits && ThisVT != PartVT) {
498         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
499         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
500       }
501     }
502   }
503 
504   if (DAG.getDataLayout().isBigEndian())
505     std::reverse(Parts, Parts + OrigNumParts);
506 }
507 
508 
509 /// getCopyToPartsVector - Create a series of nodes that contain the specified
510 /// value split into legal parts.
511 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
512                                  SDValue Val, SDValue *Parts, unsigned NumParts,
513                                  MVT PartVT, const Value *V) {
514   EVT ValueVT = Val.getValueType();
515   assert(ValueVT.isVector() && "Not a vector");
516   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
517 
518   if (NumParts == 1) {
519     EVT PartEVT = PartVT;
520     if (PartEVT == ValueVT) {
521       // Nothing to do.
522     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
523       // Bitconvert vector->vector case.
524       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     } else if (PartVT.isVector() &&
526                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
527                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
528       EVT ElementVT = PartVT.getVectorElementType();
529       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
530       // undef elements.
531       SmallVector<SDValue, 16> Ops;
532       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
533         Ops.push_back(DAG.getNode(
534             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
535             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
536 
537       for (unsigned i = ValueVT.getVectorNumElements(),
538            e = PartVT.getVectorNumElements(); i != e; ++i)
539         Ops.push_back(DAG.getUNDEF(ElementVT));
540 
541       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
542 
543       // FIXME: Use CONCAT for 2x -> 4x.
544 
545       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
546       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
547     } else if (PartVT.isVector() &&
548                PartEVT.getVectorElementType().bitsGE(
549                  ValueVT.getVectorElementType()) &&
550                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
551 
552       // Promoted vector extract
553       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
554     } else{
555       // Vector -> scalar conversion.
556       assert(ValueVT.getVectorNumElements() == 1 &&
557              "Only trivial vector-to-scalar conversions should get here!");
558       Val = DAG.getNode(
559           ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
560           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
561 
562       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
563     }
564 
565     Parts[0] = Val;
566     return;
567   }
568 
569   // Handle a multi-element vector.
570   EVT IntermediateVT;
571   MVT RegisterVT;
572   unsigned NumIntermediates;
573   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
574                                                 IntermediateVT,
575                                                 NumIntermediates, RegisterVT);
576   unsigned NumElements = ValueVT.getVectorNumElements();
577 
578   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
579   NumParts = NumRegs; // Silence a compiler warning.
580   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
581 
582   // Split the vector into intermediate operands.
583   SmallVector<SDValue, 8> Ops(NumIntermediates);
584   for (unsigned i = 0; i != NumIntermediates; ++i) {
585     if (IntermediateVT.isVector())
586       Ops[i] =
587           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
588                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
589                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
590     else
591       Ops[i] = DAG.getNode(
592           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
593           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
594   }
595 
596   // Split the intermediate operands into legal parts.
597   if (NumParts == NumIntermediates) {
598     // If the register was not expanded, promote or copy the value,
599     // as appropriate.
600     for (unsigned i = 0; i != NumParts; ++i)
601       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
602   } else if (NumParts > 0) {
603     // If the intermediate type was expanded, split each the value into
604     // legal parts.
605     assert(NumIntermediates != 0 && "division by zero");
606     assert(NumParts % NumIntermediates == 0 &&
607            "Must expand into a divisible number of parts!");
608     unsigned Factor = NumParts / NumIntermediates;
609     for (unsigned i = 0; i != NumIntermediates; ++i)
610       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
611   }
612 }
613 
614 RegsForValue::RegsForValue() {}
615 
616 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
617                            EVT valuevt)
618     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
619 
620 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
621                            const DataLayout &DL, unsigned Reg, Type *Ty) {
622   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
623 
624   for (EVT ValueVT : ValueVTs) {
625     unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
626     MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
627     for (unsigned i = 0; i != NumRegs; ++i)
628       Regs.push_back(Reg + i);
629     RegVTs.push_back(RegisterVT);
630     Reg += NumRegs;
631   }
632 }
633 
634 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
635 /// this value and returns the result as a ValueVT value.  This uses
636 /// Chain/Flag as the input and updates them for the output Chain/Flag.
637 /// If the Flag pointer is NULL, no flag is used.
638 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
639                                       FunctionLoweringInfo &FuncInfo,
640                                       SDLoc dl,
641                                       SDValue &Chain, SDValue *Flag,
642                                       const Value *V) const {
643   // A Value with type {} or [0 x %t] needs no registers.
644   if (ValueVTs.empty())
645     return SDValue();
646 
647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
648 
649   // Assemble the legal parts into the final values.
650   SmallVector<SDValue, 4> Values(ValueVTs.size());
651   SmallVector<SDValue, 8> Parts;
652   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
653     // Copy the legal parts from the registers.
654     EVT ValueVT = ValueVTs[Value];
655     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
656     MVT RegisterVT = RegVTs[Value];
657 
658     Parts.resize(NumRegs);
659     for (unsigned i = 0; i != NumRegs; ++i) {
660       SDValue P;
661       if (!Flag) {
662         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
663       } else {
664         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
665         *Flag = P.getValue(2);
666       }
667 
668       Chain = P.getValue(1);
669       Parts[i] = P;
670 
671       // If the source register was virtual and if we know something about it,
672       // add an assert node.
673       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
674           !RegisterVT.isInteger() || RegisterVT.isVector())
675         continue;
676 
677       const FunctionLoweringInfo::LiveOutInfo *LOI =
678         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
679       if (!LOI)
680         continue;
681 
682       unsigned RegSize = RegisterVT.getSizeInBits();
683       unsigned NumSignBits = LOI->NumSignBits;
684       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
685 
686       if (NumZeroBits == RegSize) {
687         // The current value is a zero.
688         // Explicitly express that as it would be easier for
689         // optimizations to kick in.
690         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
691         continue;
692       }
693 
694       // FIXME: We capture more information than the dag can represent.  For
695       // now, just use the tightest assertzext/assertsext possible.
696       bool isSExt = true;
697       EVT FromVT(MVT::Other);
698       if (NumSignBits == RegSize) {
699         isSExt = true;   // ASSERT SEXT 1
700         FromVT = MVT::i1;
701       } else if (NumZeroBits >= RegSize - 1) {
702         isSExt = false;  // ASSERT ZEXT 1
703         FromVT = MVT::i1;
704       } else if (NumSignBits > RegSize - 8) {
705         isSExt = true;   // ASSERT SEXT 8
706         FromVT = MVT::i8;
707       } else if (NumZeroBits >= RegSize - 8) {
708         isSExt = false;  // ASSERT ZEXT 8
709         FromVT = MVT::i8;
710       } else if (NumSignBits > RegSize - 16) {
711         isSExt = true;   // ASSERT SEXT 16
712         FromVT = MVT::i16;
713       } else if (NumZeroBits >= RegSize - 16) {
714         isSExt = false;  // ASSERT ZEXT 16
715         FromVT = MVT::i16;
716       } else if (NumSignBits > RegSize - 32) {
717         isSExt = true;   // ASSERT SEXT 32
718         FromVT = MVT::i32;
719       } else if (NumZeroBits >= RegSize - 32) {
720         isSExt = false;  // ASSERT ZEXT 32
721         FromVT = MVT::i32;
722       } else {
723         continue;
724       }
725       // Add an assertion node.
726       assert(FromVT != MVT::Other);
727       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
728                              RegisterVT, P, DAG.getValueType(FromVT));
729     }
730 
731     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
732                                      NumRegs, RegisterVT, ValueVT, V);
733     Part += NumRegs;
734     Parts.clear();
735   }
736 
737   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
738 }
739 
740 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
741 /// specified value into the registers specified by this object.  This uses
742 /// Chain/Flag as the input and updates them for the output Chain/Flag.
743 /// If the Flag pointer is NULL, no flag is used.
744 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
745                                  SDValue &Chain, SDValue *Flag, const Value *V,
746                                  ISD::NodeType PreferredExtendType) const {
747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
748   ISD::NodeType ExtendKind = PreferredExtendType;
749 
750   // Get the list of the values's legal parts.
751   unsigned NumRegs = Regs.size();
752   SmallVector<SDValue, 8> Parts(NumRegs);
753   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
754     EVT ValueVT = ValueVTs[Value];
755     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
756     MVT RegisterVT = RegVTs[Value];
757 
758     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
759       ExtendKind = ISD::ZERO_EXTEND;
760 
761     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
762                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
763     Part += NumParts;
764   }
765 
766   // Copy the parts into the registers.
767   SmallVector<SDValue, 8> Chains(NumRegs);
768   for (unsigned i = 0; i != NumRegs; ++i) {
769     SDValue Part;
770     if (!Flag) {
771       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
772     } else {
773       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
774       *Flag = Part.getValue(1);
775     }
776 
777     Chains[i] = Part.getValue(0);
778   }
779 
780   if (NumRegs == 1 || Flag)
781     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
782     // flagged to it. That is the CopyToReg nodes and the user are considered
783     // a single scheduling unit. If we create a TokenFactor and return it as
784     // chain, then the TokenFactor is both a predecessor (operand) of the
785     // user as well as a successor (the TF operands are flagged to the user).
786     // c1, f1 = CopyToReg
787     // c2, f2 = CopyToReg
788     // c3     = TokenFactor c1, c2
789     // ...
790     //        = op c3, ..., f2
791     Chain = Chains[NumRegs-1];
792   else
793     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
794 }
795 
796 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
797 /// operand list.  This adds the code marker and includes the number of
798 /// values added into it.
799 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
800                                         unsigned MatchingIdx, SDLoc dl,
801                                         SelectionDAG &DAG,
802                                         std::vector<SDValue> &Ops) const {
803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
804 
805   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
806   if (HasMatching)
807     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
808   else if (!Regs.empty() &&
809            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
810     // Put the register class of the virtual registers in the flag word.  That
811     // way, later passes can recompute register class constraints for inline
812     // assembly as well as normal instructions.
813     // Don't do this for tied operands that can use the regclass information
814     // from the def.
815     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
816     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
817     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
818   }
819 
820   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
821   Ops.push_back(Res);
822 
823   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
824   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
825     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
826     MVT RegisterVT = RegVTs[Value];
827     for (unsigned i = 0; i != NumRegs; ++i) {
828       assert(Reg < Regs.size() && "Mismatch in # registers expected");
829       unsigned TheReg = Regs[Reg++];
830       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
831 
832       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
833         // If we clobbered the stack pointer, MFI should know about it.
834         assert(DAG.getMachineFunction().getFrameInfo()->
835             hasOpaqueSPAdjustment());
836       }
837     }
838   }
839 }
840 
841 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
842                                const TargetLibraryInfo *li) {
843   AA = &aa;
844   GFI = gfi;
845   LibInfo = li;
846   DL = &DAG.getDataLayout();
847   Context = DAG.getContext();
848   LPadToCallSiteMap.clear();
849 }
850 
851 /// clear - Clear out the current SelectionDAG and the associated
852 /// state and prepare this SelectionDAGBuilder object to be used
853 /// for a new block. This doesn't clear out information about
854 /// additional blocks that are needed to complete switch lowering
855 /// or PHI node updating; that information is cleared out as it is
856 /// consumed.
857 void SelectionDAGBuilder::clear() {
858   NodeMap.clear();
859   UnusedArgNodeMap.clear();
860   PendingLoads.clear();
861   PendingExports.clear();
862   CurInst = nullptr;
863   HasTailCall = false;
864   SDNodeOrder = LowestSDNodeOrder;
865   StatepointLowering.clear();
866 }
867 
868 /// clearDanglingDebugInfo - Clear the dangling debug information
869 /// map. This function is separated from the clear so that debug
870 /// information that is dangling in a basic block can be properly
871 /// resolved in a different basic block. This allows the
872 /// SelectionDAG to resolve dangling debug information attached
873 /// to PHI nodes.
874 void SelectionDAGBuilder::clearDanglingDebugInfo() {
875   DanglingDebugInfoMap.clear();
876 }
877 
878 /// getRoot - Return the current virtual root of the Selection DAG,
879 /// flushing any PendingLoad items. This must be done before emitting
880 /// a store or any other node that may need to be ordered after any
881 /// prior load instructions.
882 ///
883 SDValue SelectionDAGBuilder::getRoot() {
884   if (PendingLoads.empty())
885     return DAG.getRoot();
886 
887   if (PendingLoads.size() == 1) {
888     SDValue Root = PendingLoads[0];
889     DAG.setRoot(Root);
890     PendingLoads.clear();
891     return Root;
892   }
893 
894   // Otherwise, we have to make a token factor node.
895   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
896                              PendingLoads);
897   PendingLoads.clear();
898   DAG.setRoot(Root);
899   return Root;
900 }
901 
902 /// getControlRoot - Similar to getRoot, but instead of flushing all the
903 /// PendingLoad items, flush all the PendingExports items. It is necessary
904 /// to do this before emitting a terminator instruction.
905 ///
906 SDValue SelectionDAGBuilder::getControlRoot() {
907   SDValue Root = DAG.getRoot();
908 
909   if (PendingExports.empty())
910     return Root;
911 
912   // Turn all of the CopyToReg chains into one factored node.
913   if (Root.getOpcode() != ISD::EntryToken) {
914     unsigned i = 0, e = PendingExports.size();
915     for (; i != e; ++i) {
916       assert(PendingExports[i].getNode()->getNumOperands() > 1);
917       if (PendingExports[i].getNode()->getOperand(0) == Root)
918         break;  // Don't add the root if we already indirectly depend on it.
919     }
920 
921     if (i == e)
922       PendingExports.push_back(Root);
923   }
924 
925   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
926                      PendingExports);
927   PendingExports.clear();
928   DAG.setRoot(Root);
929   return Root;
930 }
931 
932 void SelectionDAGBuilder::visit(const Instruction &I) {
933   // Set up outgoing PHI node register values before emitting the terminator.
934   if (isa<TerminatorInst>(&I))
935     HandlePHINodesInSuccessorBlocks(I.getParent());
936 
937   ++SDNodeOrder;
938 
939   CurInst = &I;
940 
941   visit(I.getOpcode(), I);
942 
943   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
944       !isStatepoint(&I)) // statepoints handle their exports internally
945     CopyToExportRegsIfNeeded(&I);
946 
947   CurInst = nullptr;
948 }
949 
950 void SelectionDAGBuilder::visitPHI(const PHINode &) {
951   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
952 }
953 
954 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
955   // Note: this doesn't use InstVisitor, because it has to work with
956   // ConstantExpr's in addition to instructions.
957   switch (Opcode) {
958   default: llvm_unreachable("Unknown instruction type encountered!");
959     // Build the switch statement using the Instruction.def file.
960 #define HANDLE_INST(NUM, OPCODE, CLASS) \
961     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
962 #include "llvm/IR/Instruction.def"
963   }
964 }
965 
966 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
967 // generate the debug data structures now that we've seen its definition.
968 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
969                                                    SDValue Val) {
970   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
971   if (DDI.getDI()) {
972     const DbgValueInst *DI = DDI.getDI();
973     DebugLoc dl = DDI.getdl();
974     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
975     DILocalVariable *Variable = DI->getVariable();
976     DIExpression *Expr = DI->getExpression();
977     assert(Variable->isValidLocationForIntrinsic(dl) &&
978            "Expected inlined-at fields to agree");
979     uint64_t Offset = DI->getOffset();
980     SDDbgValue *SDV;
981     if (Val.getNode()) {
982       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false,
983                                     Val)) {
984         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
985                               false, Offset, dl, DbgSDNodeOrder);
986         DAG.AddDbgValue(SDV, Val.getNode(), false);
987       }
988     } else
989       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
990     DanglingDebugInfoMap[V] = DanglingDebugInfo();
991   }
992 }
993 
994 /// getCopyFromRegs - If there was virtual register allocated for the value V
995 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
996 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
997   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
998   SDValue Result;
999 
1000   if (It != FuncInfo.ValueMap.end()) {
1001     unsigned InReg = It->second;
1002     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1003                      DAG.getDataLayout(), InReg, Ty);
1004     SDValue Chain = DAG.getEntryNode();
1005     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1006     resolveDanglingDebugInfo(V, Result);
1007   }
1008 
1009   return Result;
1010 }
1011 
1012 /// getValue - Return an SDValue for the given Value.
1013 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1014   // If we already have an SDValue for this value, use it. It's important
1015   // to do this first, so that we don't create a CopyFromReg if we already
1016   // have a regular SDValue.
1017   SDValue &N = NodeMap[V];
1018   if (N.getNode()) return N;
1019 
1020   // If there's a virtual register allocated and initialized for this
1021   // value, use it.
1022   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1023     return copyFromReg;
1024 
1025   // Otherwise create a new SDValue and remember it.
1026   SDValue Val = getValueImpl(V);
1027   NodeMap[V] = Val;
1028   resolveDanglingDebugInfo(V, Val);
1029   return Val;
1030 }
1031 
1032 // Return true if SDValue exists for the given Value
1033 bool SelectionDAGBuilder::findValue(const Value *V) const {
1034   return (NodeMap.find(V) != NodeMap.end()) ||
1035     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1036 }
1037 
1038 /// getNonRegisterValue - Return an SDValue for the given Value, but
1039 /// don't look in FuncInfo.ValueMap for a virtual register.
1040 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1041   // If we already have an SDValue for this value, use it.
1042   SDValue &N = NodeMap[V];
1043   if (N.getNode()) {
1044     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1045       // Remove the debug location from the node as the node is about to be used
1046       // in a location which may differ from the original debug location.  This
1047       // is relevant to Constant and ConstantFP nodes because they can appear
1048       // as constant expressions inside PHI nodes.
1049       N->setDebugLoc(DebugLoc());
1050     }
1051     return N;
1052   }
1053 
1054   // Otherwise create a new SDValue and remember it.
1055   SDValue Val = getValueImpl(V);
1056   NodeMap[V] = Val;
1057   resolveDanglingDebugInfo(V, Val);
1058   return Val;
1059 }
1060 
1061 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1062 /// Create an SDValue for the given value.
1063 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1065 
1066   if (const Constant *C = dyn_cast<Constant>(V)) {
1067     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1068 
1069     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1070       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1071 
1072     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1073       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1074 
1075     if (isa<ConstantPointerNull>(C)) {
1076       unsigned AS = V->getType()->getPointerAddressSpace();
1077       return DAG.getConstant(0, getCurSDLoc(),
1078                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1079     }
1080 
1081     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1082       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1083 
1084     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1085       return DAG.getUNDEF(VT);
1086 
1087     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1088       visit(CE->getOpcode(), *CE);
1089       SDValue N1 = NodeMap[V];
1090       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1091       return N1;
1092     }
1093 
1094     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1095       SmallVector<SDValue, 4> Constants;
1096       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1097            OI != OE; ++OI) {
1098         SDNode *Val = getValue(*OI).getNode();
1099         // If the operand is an empty aggregate, there are no values.
1100         if (!Val) continue;
1101         // Add each leaf value from the operand to the Constants list
1102         // to form a flattened list of all the values.
1103         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1104           Constants.push_back(SDValue(Val, i));
1105       }
1106 
1107       return DAG.getMergeValues(Constants, getCurSDLoc());
1108     }
1109 
1110     if (const ConstantDataSequential *CDS =
1111           dyn_cast<ConstantDataSequential>(C)) {
1112       SmallVector<SDValue, 4> Ops;
1113       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1114         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1115         // Add each leaf value from the operand to the Constants list
1116         // to form a flattened list of all the values.
1117         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1118           Ops.push_back(SDValue(Val, i));
1119       }
1120 
1121       if (isa<ArrayType>(CDS->getType()))
1122         return DAG.getMergeValues(Ops, getCurSDLoc());
1123       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1124                                       VT, Ops);
1125     }
1126 
1127     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1128       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1129              "Unknown struct or array constant!");
1130 
1131       SmallVector<EVT, 4> ValueVTs;
1132       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1133       unsigned NumElts = ValueVTs.size();
1134       if (NumElts == 0)
1135         return SDValue(); // empty struct
1136       SmallVector<SDValue, 4> Constants(NumElts);
1137       for (unsigned i = 0; i != NumElts; ++i) {
1138         EVT EltVT = ValueVTs[i];
1139         if (isa<UndefValue>(C))
1140           Constants[i] = DAG.getUNDEF(EltVT);
1141         else if (EltVT.isFloatingPoint())
1142           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1143         else
1144           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1145       }
1146 
1147       return DAG.getMergeValues(Constants, getCurSDLoc());
1148     }
1149 
1150     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1151       return DAG.getBlockAddress(BA, VT);
1152 
1153     VectorType *VecTy = cast<VectorType>(V->getType());
1154     unsigned NumElements = VecTy->getNumElements();
1155 
1156     // Now that we know the number and type of the elements, get that number of
1157     // elements into the Ops array based on what kind of constant it is.
1158     SmallVector<SDValue, 16> Ops;
1159     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1160       for (unsigned i = 0; i != NumElements; ++i)
1161         Ops.push_back(getValue(CV->getOperand(i)));
1162     } else {
1163       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1164       EVT EltVT =
1165           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1166 
1167       SDValue Op;
1168       if (EltVT.isFloatingPoint())
1169         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1170       else
1171         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1172       Ops.assign(NumElements, Op);
1173     }
1174 
1175     // Create a BUILD_VECTOR node.
1176     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1177   }
1178 
1179   // If this is a static alloca, generate it as the frameindex instead of
1180   // computation.
1181   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1182     DenseMap<const AllocaInst*, int>::iterator SI =
1183       FuncInfo.StaticAllocaMap.find(AI);
1184     if (SI != FuncInfo.StaticAllocaMap.end())
1185       return DAG.getFrameIndex(SI->second,
1186                                TLI.getPointerTy(DAG.getDataLayout()));
1187   }
1188 
1189   // If this is an instruction which fast-isel has deferred, select it now.
1190   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1191     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1192     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1193                      Inst->getType());
1194     SDValue Chain = DAG.getEntryNode();
1195     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1196   }
1197 
1198   llvm_unreachable("Can't get register for value!");
1199 }
1200 
1201 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1202   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1203   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1204   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1205   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1206   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1207   if (IsMSVCCXX || IsCoreCLR)
1208     CatchPadMBB->setIsEHFuncletEntry();
1209 
1210   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1211 }
1212 
1213 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1214   // Update machine-CFG edge.
1215   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1216   FuncInfo.MBB->addSuccessor(TargetMBB);
1217 
1218   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1219   bool IsSEH = isAsynchronousEHPersonality(Pers);
1220   if (IsSEH) {
1221     // If this is not a fall-through branch or optimizations are switched off,
1222     // emit the branch.
1223     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1224         TM.getOptLevel() == CodeGenOpt::None)
1225       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1226                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1227     return;
1228   }
1229 
1230   // Figure out the funclet membership for the catchret's successor.
1231   // This will be used by the FuncletLayout pass to determine how to order the
1232   // BB's.
1233   // A 'catchret' returns to the outer scope's color.
1234   Value *ParentPad = I.getCatchSwitchParentPad();
1235   const BasicBlock *SuccessorColor;
1236   if (isa<ConstantTokenNone>(ParentPad))
1237     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1238   else
1239     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1240   assert(SuccessorColor && "No parent funclet for catchret!");
1241   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1242   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1243 
1244   // Create the terminator node.
1245   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1246                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1247                             DAG.getBasicBlock(SuccessorColorMBB));
1248   DAG.setRoot(Ret);
1249 }
1250 
1251 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1252   // Don't emit any special code for the cleanuppad instruction. It just marks
1253   // the start of a funclet.
1254   FuncInfo.MBB->setIsEHFuncletEntry();
1255   FuncInfo.MBB->setIsCleanupFuncletEntry();
1256 }
1257 
1258 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1259 /// many places it could ultimately go. In the IR, we have a single unwind
1260 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1261 /// This function skips over imaginary basic blocks that hold catchswitch
1262 /// instructions, and finds all the "real" machine
1263 /// basic block destinations. As those destinations may not be successors of
1264 /// EHPadBB, here we also calculate the edge probability to those destinations.
1265 /// The passed-in Prob is the edge probability to EHPadBB.
1266 static void findUnwindDestinations(
1267     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1268     BranchProbability Prob,
1269     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1270         &UnwindDests) {
1271   EHPersonality Personality =
1272     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1273   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1274   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1275 
1276   while (EHPadBB) {
1277     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1278     BasicBlock *NewEHPadBB = nullptr;
1279     if (isa<LandingPadInst>(Pad)) {
1280       // Stop on landingpads. They are not funclets.
1281       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1282       break;
1283     } else if (isa<CleanupPadInst>(Pad)) {
1284       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1285       // personalities.
1286       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1287       UnwindDests.back().first->setIsEHFuncletEntry();
1288       break;
1289     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1290       // Add the catchpad handlers to the possible destinations.
1291       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1292         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1293         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1294         if (IsMSVCCXX || IsCoreCLR)
1295           UnwindDests.back().first->setIsEHFuncletEntry();
1296       }
1297       NewEHPadBB = CatchSwitch->getUnwindDest();
1298     } else {
1299       continue;
1300     }
1301 
1302     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1303     if (BPI && NewEHPadBB)
1304       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1305     EHPadBB = NewEHPadBB;
1306   }
1307 }
1308 
1309 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1310   // Update successor info.
1311   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1312   auto UnwindDest = I.getUnwindDest();
1313   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1314   BranchProbability UnwindDestProb =
1315       (BPI && UnwindDest)
1316           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1317           : BranchProbability::getZero();
1318   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1319   for (auto &UnwindDest : UnwindDests) {
1320     UnwindDest.first->setIsEHPad();
1321     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1322   }
1323   FuncInfo.MBB->normalizeSuccProbs();
1324 
1325   // Create the terminator node.
1326   SDValue Ret =
1327       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1328   DAG.setRoot(Ret);
1329 }
1330 
1331 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1332   report_fatal_error("visitCatchSwitch not yet implemented!");
1333 }
1334 
1335 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1337   auto &DL = DAG.getDataLayout();
1338   SDValue Chain = getControlRoot();
1339   SmallVector<ISD::OutputArg, 8> Outs;
1340   SmallVector<SDValue, 8> OutVals;
1341 
1342   if (!FuncInfo.CanLowerReturn) {
1343     unsigned DemoteReg = FuncInfo.DemoteRegister;
1344     const Function *F = I.getParent()->getParent();
1345 
1346     // Emit a store of the return value through the virtual register.
1347     // Leave Outs empty so that LowerReturn won't try to load return
1348     // registers the usual way.
1349     SmallVector<EVT, 1> PtrValueVTs;
1350     ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1351                     PtrValueVTs);
1352 
1353     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1354                                         DemoteReg, PtrValueVTs[0]);
1355     SDValue RetOp = getValue(I.getOperand(0));
1356 
1357     SmallVector<EVT, 4> ValueVTs;
1358     SmallVector<uint64_t, 4> Offsets;
1359     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1360     unsigned NumValues = ValueVTs.size();
1361 
1362     // An aggregate return value cannot wrap around the address space, so
1363     // offsets to its parts don't wrap either.
1364     SDNodeFlags Flags;
1365     Flags.setNoUnsignedWrap(true);
1366 
1367     SmallVector<SDValue, 4> Chains(NumValues);
1368     for (unsigned i = 0; i != NumValues; ++i) {
1369       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1370                                 RetPtr.getValueType(), RetPtr,
1371                                 DAG.getIntPtrConstant(Offsets[i],
1372                                                       getCurSDLoc()),
1373                                 &Flags);
1374       Chains[i] =
1375         DAG.getStore(Chain, getCurSDLoc(),
1376                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1377                      // FIXME: better loc info would be nice.
1378                      Add, MachinePointerInfo(), false, false, 0);
1379     }
1380 
1381     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1382                         MVT::Other, Chains);
1383   } else if (I.getNumOperands() != 0) {
1384     SmallVector<EVT, 4> ValueVTs;
1385     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1386     unsigned NumValues = ValueVTs.size();
1387     if (NumValues) {
1388       SDValue RetOp = getValue(I.getOperand(0));
1389 
1390       const Function *F = I.getParent()->getParent();
1391 
1392       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1393       if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1394                                           Attribute::SExt))
1395         ExtendKind = ISD::SIGN_EXTEND;
1396       else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1397                                                Attribute::ZExt))
1398         ExtendKind = ISD::ZERO_EXTEND;
1399 
1400       LLVMContext &Context = F->getContext();
1401       bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1402                                                       Attribute::InReg);
1403 
1404       for (unsigned j = 0; j != NumValues; ++j) {
1405         EVT VT = ValueVTs[j];
1406 
1407         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1408           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1409 
1410         unsigned NumParts = TLI.getNumRegisters(Context, VT);
1411         MVT PartVT = TLI.getRegisterType(Context, VT);
1412         SmallVector<SDValue, 4> Parts(NumParts);
1413         getCopyToParts(DAG, getCurSDLoc(),
1414                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1415                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
1416 
1417         // 'inreg' on function refers to return value
1418         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1419         if (RetInReg)
1420           Flags.setInReg();
1421 
1422         // Propagate extension type if any
1423         if (ExtendKind == ISD::SIGN_EXTEND)
1424           Flags.setSExt();
1425         else if (ExtendKind == ISD::ZERO_EXTEND)
1426           Flags.setZExt();
1427 
1428         for (unsigned i = 0; i < NumParts; ++i) {
1429           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1430                                         VT, /*isfixed=*/true, 0, 0));
1431           OutVals.push_back(Parts[i]);
1432         }
1433       }
1434     }
1435   }
1436 
1437   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1438   CallingConv::ID CallConv =
1439     DAG.getMachineFunction().getFunction()->getCallingConv();
1440   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1441       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1442 
1443   // Verify that the target's LowerReturn behaved as expected.
1444   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1445          "LowerReturn didn't return a valid chain!");
1446 
1447   // Update the DAG with the new chain value resulting from return lowering.
1448   DAG.setRoot(Chain);
1449 }
1450 
1451 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1452 /// created for it, emit nodes to copy the value into the virtual
1453 /// registers.
1454 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1455   // Skip empty types
1456   if (V->getType()->isEmptyTy())
1457     return;
1458 
1459   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1460   if (VMI != FuncInfo.ValueMap.end()) {
1461     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1462     CopyValueToVirtualRegister(V, VMI->second);
1463   }
1464 }
1465 
1466 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1467 /// the current basic block, add it to ValueMap now so that we'll get a
1468 /// CopyTo/FromReg.
1469 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1470   // No need to export constants.
1471   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1472 
1473   // Already exported?
1474   if (FuncInfo.isExportedInst(V)) return;
1475 
1476   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1477   CopyValueToVirtualRegister(V, Reg);
1478 }
1479 
1480 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1481                                                      const BasicBlock *FromBB) {
1482   // The operands of the setcc have to be in this block.  We don't know
1483   // how to export them from some other block.
1484   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1485     // Can export from current BB.
1486     if (VI->getParent() == FromBB)
1487       return true;
1488 
1489     // Is already exported, noop.
1490     return FuncInfo.isExportedInst(V);
1491   }
1492 
1493   // If this is an argument, we can export it if the BB is the entry block or
1494   // if it is already exported.
1495   if (isa<Argument>(V)) {
1496     if (FromBB == &FromBB->getParent()->getEntryBlock())
1497       return true;
1498 
1499     // Otherwise, can only export this if it is already exported.
1500     return FuncInfo.isExportedInst(V);
1501   }
1502 
1503   // Otherwise, constants can always be exported.
1504   return true;
1505 }
1506 
1507 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1508 BranchProbability
1509 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1510                                         const MachineBasicBlock *Dst) const {
1511   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1512   const BasicBlock *SrcBB = Src->getBasicBlock();
1513   const BasicBlock *DstBB = Dst->getBasicBlock();
1514   if (!BPI) {
1515     // If BPI is not available, set the default probability as 1 / N, where N is
1516     // the number of successors.
1517     auto SuccSize = std::max<uint32_t>(
1518         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1519     return BranchProbability(1, SuccSize);
1520   }
1521   return BPI->getEdgeProbability(SrcBB, DstBB);
1522 }
1523 
1524 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1525                                                MachineBasicBlock *Dst,
1526                                                BranchProbability Prob) {
1527   if (!FuncInfo.BPI)
1528     Src->addSuccessorWithoutProb(Dst);
1529   else {
1530     if (Prob.isUnknown())
1531       Prob = getEdgeProbability(Src, Dst);
1532     Src->addSuccessor(Dst, Prob);
1533   }
1534 }
1535 
1536 static bool InBlock(const Value *V, const BasicBlock *BB) {
1537   if (const Instruction *I = dyn_cast<Instruction>(V))
1538     return I->getParent() == BB;
1539   return true;
1540 }
1541 
1542 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1543 /// This function emits a branch and is used at the leaves of an OR or an
1544 /// AND operator tree.
1545 ///
1546 void
1547 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1548                                                   MachineBasicBlock *TBB,
1549                                                   MachineBasicBlock *FBB,
1550                                                   MachineBasicBlock *CurBB,
1551                                                   MachineBasicBlock *SwitchBB,
1552                                                   BranchProbability TProb,
1553                                                   BranchProbability FProb) {
1554   const BasicBlock *BB = CurBB->getBasicBlock();
1555 
1556   // If the leaf of the tree is a comparison, merge the condition into
1557   // the caseblock.
1558   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1559     // The operands of the cmp have to be in this block.  We don't know
1560     // how to export them from some other block.  If this is the first block
1561     // of the sequence, no exporting is needed.
1562     if (CurBB == SwitchBB ||
1563         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1564          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1565       ISD::CondCode Condition;
1566       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1567         Condition = getICmpCondCode(IC->getPredicate());
1568       } else {
1569         const FCmpInst *FC = cast<FCmpInst>(Cond);
1570         Condition = getFCmpCondCode(FC->getPredicate());
1571         if (TM.Options.NoNaNsFPMath)
1572           Condition = getFCmpCodeWithoutNaN(Condition);
1573       }
1574 
1575       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1576                    TBB, FBB, CurBB, TProb, FProb);
1577       SwitchCases.push_back(CB);
1578       return;
1579     }
1580   }
1581 
1582   // Create a CaseBlock record representing this branch.
1583   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1584                nullptr, TBB, FBB, CurBB, TProb, FProb);
1585   SwitchCases.push_back(CB);
1586 }
1587 
1588 /// FindMergedConditions - If Cond is an expression like
1589 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1590                                                MachineBasicBlock *TBB,
1591                                                MachineBasicBlock *FBB,
1592                                                MachineBasicBlock *CurBB,
1593                                                MachineBasicBlock *SwitchBB,
1594                                                Instruction::BinaryOps Opc,
1595                                                BranchProbability TProb,
1596                                                BranchProbability FProb) {
1597   // If this node is not part of the or/and tree, emit it as a branch.
1598   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1599   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1600       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1601       BOp->getParent() != CurBB->getBasicBlock() ||
1602       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1603       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1604     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1605                                  TProb, FProb);
1606     return;
1607   }
1608 
1609   //  Create TmpBB after CurBB.
1610   MachineFunction::iterator BBI(CurBB);
1611   MachineFunction &MF = DAG.getMachineFunction();
1612   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1613   CurBB->getParent()->insert(++BBI, TmpBB);
1614 
1615   if (Opc == Instruction::Or) {
1616     // Codegen X | Y as:
1617     // BB1:
1618     //   jmp_if_X TBB
1619     //   jmp TmpBB
1620     // TmpBB:
1621     //   jmp_if_Y TBB
1622     //   jmp FBB
1623     //
1624 
1625     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1626     // The requirement is that
1627     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1628     //     = TrueProb for original BB.
1629     // Assuming the original probabilities are A and B, one choice is to set
1630     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1631     // A/(1+B) and 2B/(1+B). This choice assumes that
1632     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1633     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1634     // TmpBB, but the math is more complicated.
1635 
1636     auto NewTrueProb = TProb / 2;
1637     auto NewFalseProb = TProb / 2 + FProb;
1638     // Emit the LHS condition.
1639     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1640                          NewTrueProb, NewFalseProb);
1641 
1642     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1643     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1644     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1645     // Emit the RHS condition into TmpBB.
1646     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1647                          Probs[0], Probs[1]);
1648   } else {
1649     assert(Opc == Instruction::And && "Unknown merge op!");
1650     // Codegen X & Y as:
1651     // BB1:
1652     //   jmp_if_X TmpBB
1653     //   jmp FBB
1654     // TmpBB:
1655     //   jmp_if_Y TBB
1656     //   jmp FBB
1657     //
1658     //  This requires creation of TmpBB after CurBB.
1659 
1660     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1661     // The requirement is that
1662     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1663     //     = FalseProb for original BB.
1664     // Assuming the original probabilities are A and B, one choice is to set
1665     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1666     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1667     // TrueProb for BB1 * FalseProb for TmpBB.
1668 
1669     auto NewTrueProb = TProb + FProb / 2;
1670     auto NewFalseProb = FProb / 2;
1671     // Emit the LHS condition.
1672     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1673                          NewTrueProb, NewFalseProb);
1674 
1675     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1676     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1677     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1678     // Emit the RHS condition into TmpBB.
1679     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1680                          Probs[0], Probs[1]);
1681   }
1682 }
1683 
1684 /// If the set of cases should be emitted as a series of branches, return true.
1685 /// If we should emit this as a bunch of and/or'd together conditions, return
1686 /// false.
1687 bool
1688 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1689   if (Cases.size() != 2) return true;
1690 
1691   // If this is two comparisons of the same values or'd or and'd together, they
1692   // will get folded into a single comparison, so don't emit two blocks.
1693   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1694        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1695       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1696        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1697     return false;
1698   }
1699 
1700   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1701   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1702   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1703       Cases[0].CC == Cases[1].CC &&
1704       isa<Constant>(Cases[0].CmpRHS) &&
1705       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1706     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1707       return false;
1708     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1709       return false;
1710   }
1711 
1712   return true;
1713 }
1714 
1715 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1716   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1717 
1718   // Update machine-CFG edges.
1719   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1720 
1721   if (I.isUnconditional()) {
1722     // Update machine-CFG edges.
1723     BrMBB->addSuccessor(Succ0MBB);
1724 
1725     // If this is not a fall-through branch or optimizations are switched off,
1726     // emit the branch.
1727     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1728       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1729                               MVT::Other, getControlRoot(),
1730                               DAG.getBasicBlock(Succ0MBB)));
1731 
1732     return;
1733   }
1734 
1735   // If this condition is one of the special cases we handle, do special stuff
1736   // now.
1737   const Value *CondVal = I.getCondition();
1738   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1739 
1740   // If this is a series of conditions that are or'd or and'd together, emit
1741   // this as a sequence of branches instead of setcc's with and/or operations.
1742   // As long as jumps are not expensive, this should improve performance.
1743   // For example, instead of something like:
1744   //     cmp A, B
1745   //     C = seteq
1746   //     cmp D, E
1747   //     F = setle
1748   //     or C, F
1749   //     jnz foo
1750   // Emit:
1751   //     cmp A, B
1752   //     je foo
1753   //     cmp D, E
1754   //     jle foo
1755   //
1756   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1757     Instruction::BinaryOps Opcode = BOp->getOpcode();
1758     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1759         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1760         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1761       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1762                            Opcode,
1763                            getEdgeProbability(BrMBB, Succ0MBB),
1764                            getEdgeProbability(BrMBB, Succ1MBB));
1765       // If the compares in later blocks need to use values not currently
1766       // exported from this block, export them now.  This block should always
1767       // be the first entry.
1768       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1769 
1770       // Allow some cases to be rejected.
1771       if (ShouldEmitAsBranches(SwitchCases)) {
1772         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1773           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1774           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1775         }
1776 
1777         // Emit the branch for this block.
1778         visitSwitchCase(SwitchCases[0], BrMBB);
1779         SwitchCases.erase(SwitchCases.begin());
1780         return;
1781       }
1782 
1783       // Okay, we decided not to do this, remove any inserted MBB's and clear
1784       // SwitchCases.
1785       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1786         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1787 
1788       SwitchCases.clear();
1789     }
1790   }
1791 
1792   // Create a CaseBlock record representing this branch.
1793   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1794                nullptr, Succ0MBB, Succ1MBB, BrMBB);
1795 
1796   // Use visitSwitchCase to actually insert the fast branch sequence for this
1797   // cond branch.
1798   visitSwitchCase(CB, BrMBB);
1799 }
1800 
1801 /// visitSwitchCase - Emits the necessary code to represent a single node in
1802 /// the binary search tree resulting from lowering a switch instruction.
1803 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1804                                           MachineBasicBlock *SwitchBB) {
1805   SDValue Cond;
1806   SDValue CondLHS = getValue(CB.CmpLHS);
1807   SDLoc dl = getCurSDLoc();
1808 
1809   // Build the setcc now.
1810   if (!CB.CmpMHS) {
1811     // Fold "(X == true)" to X and "(X == false)" to !X to
1812     // handle common cases produced by branch lowering.
1813     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1814         CB.CC == ISD::SETEQ)
1815       Cond = CondLHS;
1816     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1817              CB.CC == ISD::SETEQ) {
1818       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1819       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1820     } else
1821       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1822   } else {
1823     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1824 
1825     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1826     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1827 
1828     SDValue CmpOp = getValue(CB.CmpMHS);
1829     EVT VT = CmpOp.getValueType();
1830 
1831     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1832       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1833                           ISD::SETLE);
1834     } else {
1835       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1836                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1837       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1838                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1839     }
1840   }
1841 
1842   // Update successor info
1843   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
1844   // TrueBB and FalseBB are always different unless the incoming IR is
1845   // degenerate. This only happens when running llc on weird IR.
1846   if (CB.TrueBB != CB.FalseBB)
1847     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
1848   SwitchBB->normalizeSuccProbs();
1849 
1850   // If the lhs block is the next block, invert the condition so that we can
1851   // fall through to the lhs instead of the rhs block.
1852   if (CB.TrueBB == NextBlock(SwitchBB)) {
1853     std::swap(CB.TrueBB, CB.FalseBB);
1854     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1855     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1856   }
1857 
1858   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1859                                MVT::Other, getControlRoot(), Cond,
1860                                DAG.getBasicBlock(CB.TrueBB));
1861 
1862   // Insert the false branch. Do this even if it's a fall through branch,
1863   // this makes it easier to do DAG optimizations which require inverting
1864   // the branch condition.
1865   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1866                        DAG.getBasicBlock(CB.FalseBB));
1867 
1868   DAG.setRoot(BrCond);
1869 }
1870 
1871 /// visitJumpTable - Emit JumpTable node in the current MBB
1872 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1873   // Emit the code for the jump table
1874   assert(JT.Reg != -1U && "Should lower JT Header first!");
1875   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1876   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1877                                      JT.Reg, PTy);
1878   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1879   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1880                                     MVT::Other, Index.getValue(1),
1881                                     Table, Index);
1882   DAG.setRoot(BrJumpTable);
1883 }
1884 
1885 /// visitJumpTableHeader - This function emits necessary code to produce index
1886 /// in the JumpTable from switch case.
1887 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1888                                                JumpTableHeader &JTH,
1889                                                MachineBasicBlock *SwitchBB) {
1890   SDLoc dl = getCurSDLoc();
1891 
1892   // Subtract the lowest switch case value from the value being switched on and
1893   // conditional branch to default mbb if the result is greater than the
1894   // difference between smallest and largest cases.
1895   SDValue SwitchOp = getValue(JTH.SValue);
1896   EVT VT = SwitchOp.getValueType();
1897   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1898                             DAG.getConstant(JTH.First, dl, VT));
1899 
1900   // The SDNode we just created, which holds the value being switched on minus
1901   // the smallest case value, needs to be copied to a virtual register so it
1902   // can be used as an index into the jump table in a subsequent basic block.
1903   // This value may be smaller or larger than the target's pointer type, and
1904   // therefore require extension or truncating.
1905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1906   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
1907 
1908   unsigned JumpTableReg =
1909       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
1910   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1911                                     JumpTableReg, SwitchOp);
1912   JT.Reg = JumpTableReg;
1913 
1914   // Emit the range check for the jump table, and branch to the default block
1915   // for the switch statement if the value being switched on exceeds the largest
1916   // case in the switch.
1917   SDValue CMP = DAG.getSetCC(
1918       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1919                                  Sub.getValueType()),
1920       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
1921 
1922   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1923                                MVT::Other, CopyTo, CMP,
1924                                DAG.getBasicBlock(JT.Default));
1925 
1926   // Avoid emitting unnecessary branches to the next block.
1927   if (JT.MBB != NextBlock(SwitchBB))
1928     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1929                          DAG.getBasicBlock(JT.MBB));
1930 
1931   DAG.setRoot(BrCond);
1932 }
1933 
1934 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1935 /// tail spliced into a stack protector check success bb.
1936 ///
1937 /// For a high level explanation of how this fits into the stack protector
1938 /// generation see the comment on the declaration of class
1939 /// StackProtectorDescriptor.
1940 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1941                                                   MachineBasicBlock *ParentBB) {
1942 
1943   // First create the loads to the guard/stack slot for the comparison.
1944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1945   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
1946 
1947   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1948   int FI = MFI->getStackProtectorIndex();
1949 
1950   const Value *IRGuard = SPD.getGuard();
1951   SDValue GuardPtr = getValue(IRGuard);
1952   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1953 
1954   unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType());
1955 
1956   SDValue Guard;
1957   SDLoc dl = getCurSDLoc();
1958 
1959   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1960   // guard value from the virtual register holding the value. Otherwise, emit a
1961   // volatile load to retrieve the stack guard value.
1962   unsigned GuardReg = SPD.getGuardReg();
1963 
1964   if (GuardReg && TLI.useLoadStackGuardNode())
1965     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
1966                                PtrTy);
1967   else
1968     Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1969                         GuardPtr, MachinePointerInfo(IRGuard, 0),
1970                         true, false, false, Align);
1971 
1972   SDValue StackSlot = DAG.getLoad(
1973       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
1974       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), true,
1975       false, false, Align);
1976 
1977   // Perform the comparison via a subtract/getsetcc.
1978   EVT VT = Guard.getValueType();
1979   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
1980 
1981   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
1982                                                         *DAG.getContext(),
1983                                                         Sub.getValueType()),
1984                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
1985 
1986   // If the sub is not 0, then we know the guard/stackslot do not equal, so
1987   // branch to failure MBB.
1988   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1989                                MVT::Other, StackSlot.getOperand(0),
1990                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1991   // Otherwise branch to success MBB.
1992   SDValue Br = DAG.getNode(ISD::BR, dl,
1993                            MVT::Other, BrCond,
1994                            DAG.getBasicBlock(SPD.getSuccessMBB()));
1995 
1996   DAG.setRoot(Br);
1997 }
1998 
1999 /// Codegen the failure basic block for a stack protector check.
2000 ///
2001 /// A failure stack protector machine basic block consists simply of a call to
2002 /// __stack_chk_fail().
2003 ///
2004 /// For a high level explanation of how this fits into the stack protector
2005 /// generation see the comment on the declaration of class
2006 /// StackProtectorDescriptor.
2007 void
2008 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2010   SDValue Chain =
2011       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2012                       None, false, getCurSDLoc(), false, false).second;
2013   DAG.setRoot(Chain);
2014 }
2015 
2016 /// visitBitTestHeader - This function emits necessary code to produce value
2017 /// suitable for "bit tests"
2018 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2019                                              MachineBasicBlock *SwitchBB) {
2020   SDLoc dl = getCurSDLoc();
2021 
2022   // Subtract the minimum value
2023   SDValue SwitchOp = getValue(B.SValue);
2024   EVT VT = SwitchOp.getValueType();
2025   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2026                             DAG.getConstant(B.First, dl, VT));
2027 
2028   // Check range
2029   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2030   SDValue RangeCmp = DAG.getSetCC(
2031       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2032                                  Sub.getValueType()),
2033       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2034 
2035   // Determine the type of the test operands.
2036   bool UsePtrType = false;
2037   if (!TLI.isTypeLegal(VT))
2038     UsePtrType = true;
2039   else {
2040     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2041       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2042         // Switch table case range are encoded into series of masks.
2043         // Just use pointer type, it's guaranteed to fit.
2044         UsePtrType = true;
2045         break;
2046       }
2047   }
2048   if (UsePtrType) {
2049     VT = TLI.getPointerTy(DAG.getDataLayout());
2050     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2051   }
2052 
2053   B.RegVT = VT.getSimpleVT();
2054   B.Reg = FuncInfo.CreateReg(B.RegVT);
2055   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2056 
2057   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2058 
2059   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2060   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2061   SwitchBB->normalizeSuccProbs();
2062 
2063   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2064                                 MVT::Other, CopyTo, RangeCmp,
2065                                 DAG.getBasicBlock(B.Default));
2066 
2067   // Avoid emitting unnecessary branches to the next block.
2068   if (MBB != NextBlock(SwitchBB))
2069     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2070                           DAG.getBasicBlock(MBB));
2071 
2072   DAG.setRoot(BrRange);
2073 }
2074 
2075 /// visitBitTestCase - this function produces one "bit test"
2076 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2077                                            MachineBasicBlock* NextMBB,
2078                                            BranchProbability BranchProbToNext,
2079                                            unsigned Reg,
2080                                            BitTestCase &B,
2081                                            MachineBasicBlock *SwitchBB) {
2082   SDLoc dl = getCurSDLoc();
2083   MVT VT = BB.RegVT;
2084   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2085   SDValue Cmp;
2086   unsigned PopCount = countPopulation(B.Mask);
2087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2088   if (PopCount == 1) {
2089     // Testing for a single bit; just compare the shift count with what it
2090     // would need to be to shift a 1 bit in that position.
2091     Cmp = DAG.getSetCC(
2092         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2093         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2094         ISD::SETEQ);
2095   } else if (PopCount == BB.Range) {
2096     // There is only one zero bit in the range, test for it directly.
2097     Cmp = DAG.getSetCC(
2098         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2099         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2100         ISD::SETNE);
2101   } else {
2102     // Make desired shift
2103     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2104                                     DAG.getConstant(1, dl, VT), ShiftOp);
2105 
2106     // Emit bit tests and jumps
2107     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2108                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2109     Cmp = DAG.getSetCC(
2110         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2111         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2112   }
2113 
2114   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2115   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2116   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2117   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2118   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2119   // one as they are relative probabilities (and thus work more like weights),
2120   // and hence we need to normalize them to let the sum of them become one.
2121   SwitchBB->normalizeSuccProbs();
2122 
2123   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2124                               MVT::Other, getControlRoot(),
2125                               Cmp, DAG.getBasicBlock(B.TargetBB));
2126 
2127   // Avoid emitting unnecessary branches to the next block.
2128   if (NextMBB != NextBlock(SwitchBB))
2129     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2130                         DAG.getBasicBlock(NextMBB));
2131 
2132   DAG.setRoot(BrAnd);
2133 }
2134 
2135 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2136   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2137 
2138   // Retrieve successors. Look through artificial IR level blocks like
2139   // catchswitch for successors.
2140   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2141   const BasicBlock *EHPadBB = I.getSuccessor(1);
2142 
2143   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2144   // have to do anything here to lower funclet bundles.
2145   assert(!I.hasOperandBundlesOtherThan(
2146              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2147          "Cannot lower invokes with arbitrary operand bundles yet!");
2148 
2149   const Value *Callee(I.getCalledValue());
2150   const Function *Fn = dyn_cast<Function>(Callee);
2151   if (isa<InlineAsm>(Callee))
2152     visitInlineAsm(&I);
2153   else if (Fn && Fn->isIntrinsic()) {
2154     switch (Fn->getIntrinsicID()) {
2155     default:
2156       llvm_unreachable("Cannot invoke this intrinsic");
2157     case Intrinsic::donothing:
2158       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2159       break;
2160     case Intrinsic::experimental_patchpoint_void:
2161     case Intrinsic::experimental_patchpoint_i64:
2162       visitPatchpoint(&I, EHPadBB);
2163       break;
2164     case Intrinsic::experimental_gc_statepoint:
2165       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2166       break;
2167     }
2168   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2169     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2170     // Eventually we will support lowering the @llvm.experimental.deoptimize
2171     // intrinsic, and right now there are no plans to support other intrinsics
2172     // with deopt state.
2173     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2174   } else {
2175     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2176   }
2177 
2178   // If the value of the invoke is used outside of its defining block, make it
2179   // available as a virtual register.
2180   // We already took care of the exported value for the statepoint instruction
2181   // during call to the LowerStatepoint.
2182   if (!isStatepoint(I)) {
2183     CopyToExportRegsIfNeeded(&I);
2184   }
2185 
2186   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2187   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2188   BranchProbability EHPadBBProb =
2189       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2190           : BranchProbability::getZero();
2191   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2192 
2193   // Update successor info.
2194   addSuccessorWithProb(InvokeMBB, Return);
2195   for (auto &UnwindDest : UnwindDests) {
2196     UnwindDest.first->setIsEHPad();
2197     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2198   }
2199   InvokeMBB->normalizeSuccProbs();
2200 
2201   // Drop into normal successor.
2202   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2203                           MVT::Other, getControlRoot(),
2204                           DAG.getBasicBlock(Return)));
2205 }
2206 
2207 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2208   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2209 }
2210 
2211 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2212   assert(FuncInfo.MBB->isEHPad() &&
2213          "Call to landingpad not in landing pad!");
2214 
2215   MachineBasicBlock *MBB = FuncInfo.MBB;
2216   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2217   AddLandingPadInfo(LP, MMI, MBB);
2218 
2219   // If there aren't registers to copy the values into (e.g., during SjLj
2220   // exceptions), then don't bother to create these DAG nodes.
2221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2222   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2223   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2224       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2225     return;
2226 
2227   // If landingpad's return type is token type, we don't create DAG nodes
2228   // for its exception pointer and selector value. The extraction of exception
2229   // pointer or selector value from token type landingpads is not currently
2230   // supported.
2231   if (LP.getType()->isTokenTy())
2232     return;
2233 
2234   SmallVector<EVT, 2> ValueVTs;
2235   SDLoc dl = getCurSDLoc();
2236   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2237   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2238 
2239   // Get the two live-in registers as SDValues. The physregs have already been
2240   // copied into virtual registers.
2241   SDValue Ops[2];
2242   if (FuncInfo.ExceptionPointerVirtReg) {
2243     Ops[0] = DAG.getZExtOrTrunc(
2244         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2245                            FuncInfo.ExceptionPointerVirtReg,
2246                            TLI.getPointerTy(DAG.getDataLayout())),
2247         dl, ValueVTs[0]);
2248   } else {
2249     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2250   }
2251   Ops[1] = DAG.getZExtOrTrunc(
2252       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2253                          FuncInfo.ExceptionSelectorVirtReg,
2254                          TLI.getPointerTy(DAG.getDataLayout())),
2255       dl, ValueVTs[1]);
2256 
2257   // Merge into one.
2258   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2259                             DAG.getVTList(ValueVTs), Ops);
2260   setValue(&LP, Res);
2261 }
2262 
2263 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2264 #ifndef NDEBUG
2265   for (const CaseCluster &CC : Clusters)
2266     assert(CC.Low == CC.High && "Input clusters must be single-case");
2267 #endif
2268 
2269   std::sort(Clusters.begin(), Clusters.end(),
2270             [](const CaseCluster &a, const CaseCluster &b) {
2271     return a.Low->getValue().slt(b.Low->getValue());
2272   });
2273 
2274   // Merge adjacent clusters with the same destination.
2275   const unsigned N = Clusters.size();
2276   unsigned DstIndex = 0;
2277   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2278     CaseCluster &CC = Clusters[SrcIndex];
2279     const ConstantInt *CaseVal = CC.Low;
2280     MachineBasicBlock *Succ = CC.MBB;
2281 
2282     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2283         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2284       // If this case has the same successor and is a neighbour, merge it into
2285       // the previous cluster.
2286       Clusters[DstIndex - 1].High = CaseVal;
2287       Clusters[DstIndex - 1].Prob += CC.Prob;
2288     } else {
2289       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2290                    sizeof(Clusters[SrcIndex]));
2291     }
2292   }
2293   Clusters.resize(DstIndex);
2294 }
2295 
2296 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2297                                            MachineBasicBlock *Last) {
2298   // Update JTCases.
2299   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2300     if (JTCases[i].first.HeaderBB == First)
2301       JTCases[i].first.HeaderBB = Last;
2302 
2303   // Update BitTestCases.
2304   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2305     if (BitTestCases[i].Parent == First)
2306       BitTestCases[i].Parent = Last;
2307 }
2308 
2309 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2310   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2311 
2312   // Update machine-CFG edges with unique successors.
2313   SmallSet<BasicBlock*, 32> Done;
2314   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2315     BasicBlock *BB = I.getSuccessor(i);
2316     bool Inserted = Done.insert(BB).second;
2317     if (!Inserted)
2318         continue;
2319 
2320     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2321     addSuccessorWithProb(IndirectBrMBB, Succ);
2322   }
2323   IndirectBrMBB->normalizeSuccProbs();
2324 
2325   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2326                           MVT::Other, getControlRoot(),
2327                           getValue(I.getAddress())));
2328 }
2329 
2330 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2331   if (DAG.getTarget().Options.TrapUnreachable)
2332     DAG.setRoot(
2333         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2334 }
2335 
2336 void SelectionDAGBuilder::visitFSub(const User &I) {
2337   // -0.0 - X --> fneg
2338   Type *Ty = I.getType();
2339   if (isa<Constant>(I.getOperand(0)) &&
2340       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2341     SDValue Op2 = getValue(I.getOperand(1));
2342     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2343                              Op2.getValueType(), Op2));
2344     return;
2345   }
2346 
2347   visitBinary(I, ISD::FSUB);
2348 }
2349 
2350 /// Checks if the given instruction performs a vector reduction, in which case
2351 /// we have the freedom to alter the elements in the result as long as the
2352 /// reduction of them stays unchanged.
2353 static bool isVectorReductionOp(const User *I) {
2354   const Instruction *Inst = dyn_cast<Instruction>(I);
2355   if (!Inst || !Inst->getType()->isVectorTy())
2356     return false;
2357 
2358   auto OpCode = Inst->getOpcode();
2359   switch (OpCode) {
2360   case Instruction::Add:
2361   case Instruction::Mul:
2362   case Instruction::And:
2363   case Instruction::Or:
2364   case Instruction::Xor:
2365     break;
2366   case Instruction::FAdd:
2367   case Instruction::FMul:
2368     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2369       if (FPOp->getFastMathFlags().unsafeAlgebra())
2370         break;
2371     // Fall through.
2372   default:
2373     return false;
2374   }
2375 
2376   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2377   unsigned ElemNumToReduce = ElemNum;
2378 
2379   // Do DFS search on the def-use chain from the given instruction. We only
2380   // allow four kinds of operations during the search until we reach the
2381   // instruction that extracts the first element from the vector:
2382   //
2383   //   1. The reduction operation of the same opcode as the given instruction.
2384   //
2385   //   2. PHI node.
2386   //
2387   //   3. ShuffleVector instruction together with a reduction operation that
2388   //      does a partial reduction.
2389   //
2390   //   4. ExtractElement that extracts the first element from the vector, and we
2391   //      stop searching the def-use chain here.
2392   //
2393   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2394   // from 1-3 to the stack to continue the DFS. The given instruction is not
2395   // a reduction operation if we meet any other instructions other than those
2396   // listed above.
2397 
2398   SmallVector<const User *, 16> UsersToVisit{Inst};
2399   SmallPtrSet<const User *, 16> Visited;
2400   bool ReduxExtracted = false;
2401 
2402   while (!UsersToVisit.empty()) {
2403     auto User = UsersToVisit.back();
2404     UsersToVisit.pop_back();
2405     if (!Visited.insert(User).second)
2406       continue;
2407 
2408     for (const auto &U : User->users()) {
2409       auto Inst = dyn_cast<Instruction>(U);
2410       if (!Inst)
2411         return false;
2412 
2413       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2414         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2415           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
2416             return false;
2417         UsersToVisit.push_back(U);
2418       } else if (const ShuffleVectorInst *ShufInst =
2419                      dyn_cast<ShuffleVectorInst>(U)) {
2420         // Detect the following pattern: A ShuffleVector instruction together
2421         // with a reduction that do partial reduction on the first and second
2422         // ElemNumToReduce / 2 elements, and store the result in
2423         // ElemNumToReduce / 2 elements in another vector.
2424 
2425         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2426         if (ResultElements < ElemNum)
2427           return false;
2428 
2429         if (ElemNumToReduce == 1)
2430           return false;
2431         if (!isa<UndefValue>(U->getOperand(1)))
2432           return false;
2433         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2434           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2435             return false;
2436         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2437           if (ShufInst->getMaskValue(i) != -1)
2438             return false;
2439 
2440         // There is only one user of this ShuffleVector instruction, which
2441         // must be a reduction operation.
2442         if (!U->hasOneUse())
2443           return false;
2444 
2445         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2446         if (!U2 || U2->getOpcode() != OpCode)
2447           return false;
2448 
2449         // Check operands of the reduction operation.
2450         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2451             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2452           UsersToVisit.push_back(U2);
2453           ElemNumToReduce /= 2;
2454         } else
2455           return false;
2456       } else if (isa<ExtractElementInst>(U)) {
2457         // At this moment we should have reduced all elements in the vector.
2458         if (ElemNumToReduce != 1)
2459           return false;
2460 
2461         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2462         if (!Val || Val->getZExtValue() != 0)
2463           return false;
2464 
2465         ReduxExtracted = true;
2466       } else
2467         return false;
2468     }
2469   }
2470   return ReduxExtracted;
2471 }
2472 
2473 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2474   SDValue Op1 = getValue(I.getOperand(0));
2475   SDValue Op2 = getValue(I.getOperand(1));
2476 
2477   bool nuw = false;
2478   bool nsw = false;
2479   bool exact = false;
2480   bool vec_redux = false;
2481   FastMathFlags FMF;
2482 
2483   if (const OverflowingBinaryOperator *OFBinOp =
2484           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2485     nuw = OFBinOp->hasNoUnsignedWrap();
2486     nsw = OFBinOp->hasNoSignedWrap();
2487   }
2488   if (const PossiblyExactOperator *ExactOp =
2489           dyn_cast<const PossiblyExactOperator>(&I))
2490     exact = ExactOp->isExact();
2491   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2492     FMF = FPOp->getFastMathFlags();
2493 
2494   if (isVectorReductionOp(&I)) {
2495     vec_redux = true;
2496     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2497   }
2498 
2499   SDNodeFlags Flags;
2500   Flags.setExact(exact);
2501   Flags.setNoSignedWrap(nsw);
2502   Flags.setNoUnsignedWrap(nuw);
2503   Flags.setVectorReduction(vec_redux);
2504   if (EnableFMFInDAG) {
2505     Flags.setAllowReciprocal(FMF.allowReciprocal());
2506     Flags.setNoInfs(FMF.noInfs());
2507     Flags.setNoNaNs(FMF.noNaNs());
2508     Flags.setNoSignedZeros(FMF.noSignedZeros());
2509     Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2510   }
2511   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2512                                      Op1, Op2, &Flags);
2513   setValue(&I, BinNodeValue);
2514 }
2515 
2516 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2517   SDValue Op1 = getValue(I.getOperand(0));
2518   SDValue Op2 = getValue(I.getOperand(1));
2519 
2520   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2521       Op2.getValueType(), DAG.getDataLayout());
2522 
2523   // Coerce the shift amount to the right type if we can.
2524   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2525     unsigned ShiftSize = ShiftTy.getSizeInBits();
2526     unsigned Op2Size = Op2.getValueType().getSizeInBits();
2527     SDLoc DL = getCurSDLoc();
2528 
2529     // If the operand is smaller than the shift count type, promote it.
2530     if (ShiftSize > Op2Size)
2531       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2532 
2533     // If the operand is larger than the shift count type but the shift
2534     // count type has enough bits to represent any shift value, truncate
2535     // it now. This is a common case and it exposes the truncate to
2536     // optimization early.
2537     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2538       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2539     // Otherwise we'll need to temporarily settle for some other convenient
2540     // type.  Type legalization will make adjustments once the shiftee is split.
2541     else
2542       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2543   }
2544 
2545   bool nuw = false;
2546   bool nsw = false;
2547   bool exact = false;
2548 
2549   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2550 
2551     if (const OverflowingBinaryOperator *OFBinOp =
2552             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2553       nuw = OFBinOp->hasNoUnsignedWrap();
2554       nsw = OFBinOp->hasNoSignedWrap();
2555     }
2556     if (const PossiblyExactOperator *ExactOp =
2557             dyn_cast<const PossiblyExactOperator>(&I))
2558       exact = ExactOp->isExact();
2559   }
2560   SDNodeFlags Flags;
2561   Flags.setExact(exact);
2562   Flags.setNoSignedWrap(nsw);
2563   Flags.setNoUnsignedWrap(nuw);
2564   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2565                             &Flags);
2566   setValue(&I, Res);
2567 }
2568 
2569 void SelectionDAGBuilder::visitSDiv(const User &I) {
2570   SDValue Op1 = getValue(I.getOperand(0));
2571   SDValue Op2 = getValue(I.getOperand(1));
2572 
2573   SDNodeFlags Flags;
2574   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2575                  cast<PossiblyExactOperator>(&I)->isExact());
2576   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2577                            Op2, &Flags));
2578 }
2579 
2580 void SelectionDAGBuilder::visitICmp(const User &I) {
2581   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2582   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2583     predicate = IC->getPredicate();
2584   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2585     predicate = ICmpInst::Predicate(IC->getPredicate());
2586   SDValue Op1 = getValue(I.getOperand(0));
2587   SDValue Op2 = getValue(I.getOperand(1));
2588   ISD::CondCode Opcode = getICmpCondCode(predicate);
2589 
2590   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2591                                                         I.getType());
2592   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2593 }
2594 
2595 void SelectionDAGBuilder::visitFCmp(const User &I) {
2596   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2597   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2598     predicate = FC->getPredicate();
2599   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2600     predicate = FCmpInst::Predicate(FC->getPredicate());
2601   SDValue Op1 = getValue(I.getOperand(0));
2602   SDValue Op2 = getValue(I.getOperand(1));
2603   ISD::CondCode Condition = getFCmpCondCode(predicate);
2604 
2605   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2606   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2607   // further optimization, but currently FMF is only applicable to binary nodes.
2608   if (TM.Options.NoNaNsFPMath)
2609     Condition = getFCmpCodeWithoutNaN(Condition);
2610   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2611                                                         I.getType());
2612   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2613 }
2614 
2615 void SelectionDAGBuilder::visitSelect(const User &I) {
2616   SmallVector<EVT, 4> ValueVTs;
2617   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2618                   ValueVTs);
2619   unsigned NumValues = ValueVTs.size();
2620   if (NumValues == 0) return;
2621 
2622   SmallVector<SDValue, 4> Values(NumValues);
2623   SDValue Cond     = getValue(I.getOperand(0));
2624   SDValue LHSVal   = getValue(I.getOperand(1));
2625   SDValue RHSVal   = getValue(I.getOperand(2));
2626   auto BaseOps = {Cond};
2627   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2628     ISD::VSELECT : ISD::SELECT;
2629 
2630   // Min/max matching is only viable if all output VTs are the same.
2631   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2632     EVT VT = ValueVTs[0];
2633     LLVMContext &Ctx = *DAG.getContext();
2634     auto &TLI = DAG.getTargetLoweringInfo();
2635 
2636     // We care about the legality of the operation after it has been type
2637     // legalized.
2638     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2639            VT != TLI.getTypeToTransformTo(Ctx, VT))
2640       VT = TLI.getTypeToTransformTo(Ctx, VT);
2641 
2642     // If the vselect is legal, assume we want to leave this as a vector setcc +
2643     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2644     // min/max is legal on the scalar type.
2645     bool UseScalarMinMax = VT.isVector() &&
2646       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2647 
2648     Value *LHS, *RHS;
2649     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2650     ISD::NodeType Opc = ISD::DELETED_NODE;
2651     switch (SPR.Flavor) {
2652     case SPF_UMAX:    Opc = ISD::UMAX; break;
2653     case SPF_UMIN:    Opc = ISD::UMIN; break;
2654     case SPF_SMAX:    Opc = ISD::SMAX; break;
2655     case SPF_SMIN:    Opc = ISD::SMIN; break;
2656     case SPF_FMINNUM:
2657       switch (SPR.NaNBehavior) {
2658       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2659       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2660       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2661       case SPNB_RETURNS_ANY: {
2662         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2663           Opc = ISD::FMINNUM;
2664         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2665           Opc = ISD::FMINNAN;
2666         else if (UseScalarMinMax)
2667           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2668             ISD::FMINNUM : ISD::FMINNAN;
2669         break;
2670       }
2671       }
2672       break;
2673     case SPF_FMAXNUM:
2674       switch (SPR.NaNBehavior) {
2675       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2676       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2677       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2678       case SPNB_RETURNS_ANY:
2679 
2680         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2681           Opc = ISD::FMAXNUM;
2682         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2683           Opc = ISD::FMAXNAN;
2684         else if (UseScalarMinMax)
2685           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2686             ISD::FMAXNUM : ISD::FMAXNAN;
2687         break;
2688       }
2689       break;
2690     default: break;
2691     }
2692 
2693     if (Opc != ISD::DELETED_NODE &&
2694         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2695          (UseScalarMinMax &&
2696           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2697         // If the underlying comparison instruction is used by any other
2698         // instruction, the consumed instructions won't be destroyed, so it is
2699         // not profitable to convert to a min/max.
2700         cast<SelectInst>(&I)->getCondition()->hasOneUse()) {
2701       OpCode = Opc;
2702       LHSVal = getValue(LHS);
2703       RHSVal = getValue(RHS);
2704       BaseOps = {};
2705     }
2706   }
2707 
2708   for (unsigned i = 0; i != NumValues; ++i) {
2709     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2710     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2711     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2712     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2713                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2714                             Ops);
2715   }
2716 
2717   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2718                            DAG.getVTList(ValueVTs), Values));
2719 }
2720 
2721 void SelectionDAGBuilder::visitTrunc(const User &I) {
2722   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2723   SDValue N = getValue(I.getOperand(0));
2724   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2725                                                         I.getType());
2726   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2727 }
2728 
2729 void SelectionDAGBuilder::visitZExt(const User &I) {
2730   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2731   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2732   SDValue N = getValue(I.getOperand(0));
2733   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2734                                                         I.getType());
2735   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2736 }
2737 
2738 void SelectionDAGBuilder::visitSExt(const User &I) {
2739   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2740   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2741   SDValue N = getValue(I.getOperand(0));
2742   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2743                                                         I.getType());
2744   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2745 }
2746 
2747 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2748   // FPTrunc is never a no-op cast, no need to check
2749   SDValue N = getValue(I.getOperand(0));
2750   SDLoc dl = getCurSDLoc();
2751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2752   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2753   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2754                            DAG.getTargetConstant(
2755                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2756 }
2757 
2758 void SelectionDAGBuilder::visitFPExt(const User &I) {
2759   // FPExt is never a no-op cast, no need to check
2760   SDValue N = getValue(I.getOperand(0));
2761   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2762                                                         I.getType());
2763   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2764 }
2765 
2766 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2767   // FPToUI is never a no-op cast, no need to check
2768   SDValue N = getValue(I.getOperand(0));
2769   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2770                                                         I.getType());
2771   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2772 }
2773 
2774 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2775   // FPToSI is never a no-op cast, no need to check
2776   SDValue N = getValue(I.getOperand(0));
2777   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2778                                                         I.getType());
2779   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2780 }
2781 
2782 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2783   // UIToFP is never a no-op cast, no need to check
2784   SDValue N = getValue(I.getOperand(0));
2785   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2786                                                         I.getType());
2787   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2788 }
2789 
2790 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2791   // SIToFP is never a no-op cast, no need to check
2792   SDValue N = getValue(I.getOperand(0));
2793   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2794                                                         I.getType());
2795   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2796 }
2797 
2798 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2799   // What to do depends on the size of the integer and the size of the pointer.
2800   // We can either truncate, zero extend, or no-op, accordingly.
2801   SDValue N = getValue(I.getOperand(0));
2802   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2803                                                         I.getType());
2804   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2805 }
2806 
2807 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2808   // What to do depends on the size of the integer and the size of the pointer.
2809   // We can either truncate, zero extend, or no-op, accordingly.
2810   SDValue N = getValue(I.getOperand(0));
2811   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2812                                                         I.getType());
2813   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2814 }
2815 
2816 void SelectionDAGBuilder::visitBitCast(const User &I) {
2817   SDValue N = getValue(I.getOperand(0));
2818   SDLoc dl = getCurSDLoc();
2819   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2820                                                         I.getType());
2821 
2822   // BitCast assures us that source and destination are the same size so this is
2823   // either a BITCAST or a no-op.
2824   if (DestVT != N.getValueType())
2825     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2826                              DestVT, N)); // convert types.
2827   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2828   // might fold any kind of constant expression to an integer constant and that
2829   // is not what we are looking for. Only regcognize a bitcast of a genuine
2830   // constant integer as an opaque constant.
2831   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2832     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2833                                  /*isOpaque*/true));
2834   else
2835     setValue(&I, N);            // noop cast.
2836 }
2837 
2838 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2840   const Value *SV = I.getOperand(0);
2841   SDValue N = getValue(SV);
2842   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2843 
2844   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2845   unsigned DestAS = I.getType()->getPointerAddressSpace();
2846 
2847   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2848     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2849 
2850   setValue(&I, N);
2851 }
2852 
2853 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2855   SDValue InVec = getValue(I.getOperand(0));
2856   SDValue InVal = getValue(I.getOperand(1));
2857   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
2858                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
2859   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2860                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
2861                            InVec, InVal, InIdx));
2862 }
2863 
2864 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2866   SDValue InVec = getValue(I.getOperand(0));
2867   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
2868                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
2869   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2870                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
2871                            InVec, InIdx));
2872 }
2873 
2874 // Utility for visitShuffleVector - Return true if every element in Mask,
2875 // beginning from position Pos and ending in Pos+Size, falls within the
2876 // specified sequential range [L, L+Pos). or is undef.
2877 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2878                                 unsigned Pos, unsigned Size, int Low) {
2879   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2880     if (Mask[i] >= 0 && Mask[i] != Low)
2881       return false;
2882   return true;
2883 }
2884 
2885 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2886   SDValue Src1 = getValue(I.getOperand(0));
2887   SDValue Src2 = getValue(I.getOperand(1));
2888 
2889   SmallVector<int, 8> Mask;
2890   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2891   unsigned MaskNumElts = Mask.size();
2892 
2893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2894   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2895   EVT SrcVT = Src1.getValueType();
2896   unsigned SrcNumElts = SrcVT.getVectorNumElements();
2897 
2898   if (SrcNumElts == MaskNumElts) {
2899     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2900                                       &Mask[0]));
2901     return;
2902   }
2903 
2904   // Normalize the shuffle vector since mask and vector length don't match.
2905   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2906     // Mask is longer than the source vectors and is a multiple of the source
2907     // vectors.  We can use concatenate vector to make the mask and vectors
2908     // lengths match.
2909     if (SrcNumElts*2 == MaskNumElts) {
2910       // First check for Src1 in low and Src2 in high
2911       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2912           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2913         // The shuffle is concatenating two vectors together.
2914         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2915                                  VT, Src1, Src2));
2916         return;
2917       }
2918       // Then check for Src2 in low and Src1 in high
2919       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2920           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2921         // The shuffle is concatenating two vectors together.
2922         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2923                                  VT, Src2, Src1));
2924         return;
2925       }
2926     }
2927 
2928     // Pad both vectors with undefs to make them the same length as the mask.
2929     unsigned NumConcat = MaskNumElts / SrcNumElts;
2930     bool Src1U = Src1.isUndef();
2931     bool Src2U = Src2.isUndef();
2932     SDValue UndefVal = DAG.getUNDEF(SrcVT);
2933 
2934     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2935     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2936     MOps1[0] = Src1;
2937     MOps2[0] = Src2;
2938 
2939     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2940                                                   getCurSDLoc(), VT, MOps1);
2941     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2942                                                   getCurSDLoc(), VT, MOps2);
2943 
2944     // Readjust mask for new input vector length.
2945     SmallVector<int, 8> MappedOps;
2946     for (unsigned i = 0; i != MaskNumElts; ++i) {
2947       int Idx = Mask[i];
2948       if (Idx >= (int)SrcNumElts)
2949         Idx -= SrcNumElts - MaskNumElts;
2950       MappedOps.push_back(Idx);
2951     }
2952 
2953     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2954                                       &MappedOps[0]));
2955     return;
2956   }
2957 
2958   if (SrcNumElts > MaskNumElts) {
2959     // Analyze the access pattern of the vector to see if we can extract
2960     // two subvectors and do the shuffle. The analysis is done by calculating
2961     // the range of elements the mask access on both vectors.
2962     int MinRange[2] = { static_cast<int>(SrcNumElts),
2963                         static_cast<int>(SrcNumElts)};
2964     int MaxRange[2] = {-1, -1};
2965 
2966     for (unsigned i = 0; i != MaskNumElts; ++i) {
2967       int Idx = Mask[i];
2968       unsigned Input = 0;
2969       if (Idx < 0)
2970         continue;
2971 
2972       if (Idx >= (int)SrcNumElts) {
2973         Input = 1;
2974         Idx -= SrcNumElts;
2975       }
2976       if (Idx > MaxRange[Input])
2977         MaxRange[Input] = Idx;
2978       if (Idx < MinRange[Input])
2979         MinRange[Input] = Idx;
2980     }
2981 
2982     // Check if the access is smaller than the vector size and can we find
2983     // a reasonable extract index.
2984     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
2985                                    // Extract.
2986     int StartIdx[2];  // StartIdx to extract from
2987     for (unsigned Input = 0; Input < 2; ++Input) {
2988       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
2989         RangeUse[Input] = 0; // Unused
2990         StartIdx[Input] = 0;
2991         continue;
2992       }
2993 
2994       // Find a good start index that is a multiple of the mask length. Then
2995       // see if the rest of the elements are in range.
2996       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2997       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2998           StartIdx[Input] + MaskNumElts <= SrcNumElts)
2999         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3000     }
3001 
3002     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3003       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3004       return;
3005     }
3006     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3007       // Extract appropriate subvector and generate a vector shuffle
3008       for (unsigned Input = 0; Input < 2; ++Input) {
3009         SDValue &Src = Input == 0 ? Src1 : Src2;
3010         if (RangeUse[Input] == 0)
3011           Src = DAG.getUNDEF(VT);
3012         else {
3013           SDLoc dl = getCurSDLoc();
3014           Src = DAG.getNode(
3015               ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
3016               DAG.getConstant(StartIdx[Input], dl,
3017                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3018         }
3019       }
3020 
3021       // Calculate new mask.
3022       SmallVector<int, 8> MappedOps;
3023       for (unsigned i = 0; i != MaskNumElts; ++i) {
3024         int Idx = Mask[i];
3025         if (Idx >= 0) {
3026           if (Idx < (int)SrcNumElts)
3027             Idx -= StartIdx[0];
3028           else
3029             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3030         }
3031         MappedOps.push_back(Idx);
3032       }
3033 
3034       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3035                                         &MappedOps[0]));
3036       return;
3037     }
3038   }
3039 
3040   // We can't use either concat vectors or extract subvectors so fall back to
3041   // replacing the shuffle with extract and build vector.
3042   // to insert and build vector.
3043   EVT EltVT = VT.getVectorElementType();
3044   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3045   SDLoc dl = getCurSDLoc();
3046   SmallVector<SDValue,8> Ops;
3047   for (unsigned i = 0; i != MaskNumElts; ++i) {
3048     int Idx = Mask[i];
3049     SDValue Res;
3050 
3051     if (Idx < 0) {
3052       Res = DAG.getUNDEF(EltVT);
3053     } else {
3054       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3055       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3056 
3057       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3058                         EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
3059     }
3060 
3061     Ops.push_back(Res);
3062   }
3063 
3064   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
3065 }
3066 
3067 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3068   const Value *Op0 = I.getOperand(0);
3069   const Value *Op1 = I.getOperand(1);
3070   Type *AggTy = I.getType();
3071   Type *ValTy = Op1->getType();
3072   bool IntoUndef = isa<UndefValue>(Op0);
3073   bool FromUndef = isa<UndefValue>(Op1);
3074 
3075   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3076 
3077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3078   SmallVector<EVT, 4> AggValueVTs;
3079   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3080   SmallVector<EVT, 4> ValValueVTs;
3081   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3082 
3083   unsigned NumAggValues = AggValueVTs.size();
3084   unsigned NumValValues = ValValueVTs.size();
3085   SmallVector<SDValue, 4> Values(NumAggValues);
3086 
3087   // Ignore an insertvalue that produces an empty object
3088   if (!NumAggValues) {
3089     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3090     return;
3091   }
3092 
3093   SDValue Agg = getValue(Op0);
3094   unsigned i = 0;
3095   // Copy the beginning value(s) from the original aggregate.
3096   for (; i != LinearIndex; ++i)
3097     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3098                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3099   // Copy values from the inserted value(s).
3100   if (NumValValues) {
3101     SDValue Val = getValue(Op1);
3102     for (; i != LinearIndex + NumValValues; ++i)
3103       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3104                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3105   }
3106   // Copy remaining value(s) from the original aggregate.
3107   for (; i != NumAggValues; ++i)
3108     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3109                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3110 
3111   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3112                            DAG.getVTList(AggValueVTs), Values));
3113 }
3114 
3115 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3116   const Value *Op0 = I.getOperand(0);
3117   Type *AggTy = Op0->getType();
3118   Type *ValTy = I.getType();
3119   bool OutOfUndef = isa<UndefValue>(Op0);
3120 
3121   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3122 
3123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3124   SmallVector<EVT, 4> ValValueVTs;
3125   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3126 
3127   unsigned NumValValues = ValValueVTs.size();
3128 
3129   // Ignore a extractvalue that produces an empty object
3130   if (!NumValValues) {
3131     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3132     return;
3133   }
3134 
3135   SmallVector<SDValue, 4> Values(NumValValues);
3136 
3137   SDValue Agg = getValue(Op0);
3138   // Copy out the selected value(s).
3139   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3140     Values[i - LinearIndex] =
3141       OutOfUndef ?
3142         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3143         SDValue(Agg.getNode(), Agg.getResNo() + i);
3144 
3145   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3146                            DAG.getVTList(ValValueVTs), Values));
3147 }
3148 
3149 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3150   Value *Op0 = I.getOperand(0);
3151   // Note that the pointer operand may be a vector of pointers. Take the scalar
3152   // element which holds a pointer.
3153   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3154   SDValue N = getValue(Op0);
3155   SDLoc dl = getCurSDLoc();
3156 
3157   // Normalize Vector GEP - all scalar operands should be converted to the
3158   // splat vector.
3159   unsigned VectorWidth = I.getType()->isVectorTy() ?
3160     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3161 
3162   if (VectorWidth && !N.getValueType().isVector()) {
3163     MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth);
3164     SmallVector<SDValue, 16> Ops(VectorWidth, N);
3165     N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3166   }
3167   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3168        GTI != E; ++GTI) {
3169     const Value *Idx = GTI.getOperand();
3170     if (StructType *StTy = dyn_cast<StructType>(*GTI)) {
3171       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3172       if (Field) {
3173         // N = N + Offset
3174         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3175 
3176         // In an inbouds GEP with an offset that is nonnegative even when
3177         // interpreted as signed, assume there is no unsigned overflow.
3178         SDNodeFlags Flags;
3179         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3180           Flags.setNoUnsignedWrap(true);
3181 
3182         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3183                         DAG.getConstant(Offset, dl, N.getValueType()), &Flags);
3184       }
3185     } else {
3186       MVT PtrTy =
3187           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
3188       unsigned PtrSize = PtrTy.getSizeInBits();
3189       APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3190 
3191       // If this is a scalar constant or a splat vector of constants,
3192       // handle it quickly.
3193       const auto *CI = dyn_cast<ConstantInt>(Idx);
3194       if (!CI && isa<ConstantDataVector>(Idx) &&
3195           cast<ConstantDataVector>(Idx)->getSplatValue())
3196         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3197 
3198       if (CI) {
3199         if (CI->isZero())
3200           continue;
3201         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
3202         SDValue OffsVal = VectorWidth ?
3203           DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) :
3204           DAG.getConstant(Offs, dl, PtrTy);
3205 
3206         // In an inbouds GEP with an offset that is nonnegative even when
3207         // interpreted as signed, assume there is no unsigned overflow.
3208         SDNodeFlags Flags;
3209         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3210           Flags.setNoUnsignedWrap(true);
3211 
3212         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, &Flags);
3213         continue;
3214       }
3215 
3216       // N = N + Idx * ElementSize;
3217       SDValue IdxN = getValue(Idx);
3218 
3219       if (!IdxN.getValueType().isVector() && VectorWidth) {
3220         MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
3221         SmallVector<SDValue, 16> Ops(VectorWidth, IdxN);
3222         IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3223       }
3224       // If the index is smaller or larger than intptr_t, truncate or extend
3225       // it.
3226       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3227 
3228       // If this is a multiply by a power of two, turn it into a shl
3229       // immediately.  This is a very common case.
3230       if (ElementSize != 1) {
3231         if (ElementSize.isPowerOf2()) {
3232           unsigned Amt = ElementSize.logBase2();
3233           IdxN = DAG.getNode(ISD::SHL, dl,
3234                              N.getValueType(), IdxN,
3235                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3236         } else {
3237           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3238           IdxN = DAG.getNode(ISD::MUL, dl,
3239                              N.getValueType(), IdxN, Scale);
3240         }
3241       }
3242 
3243       N = DAG.getNode(ISD::ADD, dl,
3244                       N.getValueType(), N, IdxN);
3245     }
3246   }
3247 
3248   setValue(&I, N);
3249 }
3250 
3251 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3252   // If this is a fixed sized alloca in the entry block of the function,
3253   // allocate it statically on the stack.
3254   if (FuncInfo.StaticAllocaMap.count(&I))
3255     return;   // getValue will auto-populate this.
3256 
3257   SDLoc dl = getCurSDLoc();
3258   Type *Ty = I.getAllocatedType();
3259   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3260   auto &DL = DAG.getDataLayout();
3261   uint64_t TySize = DL.getTypeAllocSize(Ty);
3262   unsigned Align =
3263       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3264 
3265   SDValue AllocSize = getValue(I.getArraySize());
3266 
3267   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
3268   if (AllocSize.getValueType() != IntPtr)
3269     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3270 
3271   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3272                           AllocSize,
3273                           DAG.getConstant(TySize, dl, IntPtr));
3274 
3275   // Handle alignment.  If the requested alignment is less than or equal to
3276   // the stack alignment, ignore it.  If the size is greater than or equal to
3277   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3278   unsigned StackAlign =
3279       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3280   if (Align <= StackAlign)
3281     Align = 0;
3282 
3283   // Round the size of the allocation up to the stack alignment size
3284   // by add SA-1 to the size. This doesn't overflow because we're computing
3285   // an address inside an alloca.
3286   SDNodeFlags Flags;
3287   Flags.setNoUnsignedWrap(true);
3288   AllocSize = DAG.getNode(ISD::ADD, dl,
3289                           AllocSize.getValueType(), AllocSize,
3290                           DAG.getIntPtrConstant(StackAlign - 1, dl), &Flags);
3291 
3292   // Mask out the low bits for alignment purposes.
3293   AllocSize = DAG.getNode(ISD::AND, dl,
3294                           AllocSize.getValueType(), AllocSize,
3295                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
3296                                                 dl));
3297 
3298   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
3299   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3300   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3301   setValue(&I, DSA);
3302   DAG.setRoot(DSA.getValue(1));
3303 
3304   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3305 }
3306 
3307 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3308   if (I.isAtomic())
3309     return visitAtomicLoad(I);
3310 
3311   const Value *SV = I.getOperand(0);
3312   SDValue Ptr = getValue(SV);
3313 
3314   Type *Ty = I.getType();
3315 
3316   bool isVolatile = I.isVolatile();
3317   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3318 
3319   // The IR notion of invariant_load only guarantees that all *non-faulting*
3320   // invariant loads result in the same value.  The MI notion of invariant load
3321   // guarantees that the load can be legally moved to any location within its
3322   // containing function.  The MI notion of invariant_load is stronger than the
3323   // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load
3324   // with a guarantee that the location being loaded from is dereferenceable
3325   // throughout the function's lifetime.
3326 
3327   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr &&
3328                      isDereferenceablePointer(SV, DAG.getDataLayout());
3329   unsigned Alignment = I.getAlignment();
3330 
3331   AAMDNodes AAInfo;
3332   I.getAAMetadata(AAInfo);
3333   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3334 
3335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3336   SmallVector<EVT, 4> ValueVTs;
3337   SmallVector<uint64_t, 4> Offsets;
3338   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3339   unsigned NumValues = ValueVTs.size();
3340   if (NumValues == 0)
3341     return;
3342 
3343   SDValue Root;
3344   bool ConstantMemory = false;
3345   if (isVolatile || NumValues > MaxParallelChains)
3346     // Serialize volatile loads with other side effects.
3347     Root = getRoot();
3348   else if (AA->pointsToConstantMemory(MemoryLocation(
3349                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3350     // Do not serialize (non-volatile) loads of constant memory with anything.
3351     Root = DAG.getEntryNode();
3352     ConstantMemory = true;
3353   } else {
3354     // Do not serialize non-volatile loads against each other.
3355     Root = DAG.getRoot();
3356   }
3357 
3358   SDLoc dl = getCurSDLoc();
3359 
3360   if (isVolatile)
3361     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3362 
3363   // An aggregate load cannot wrap around the address space, so offsets to its
3364   // parts don't wrap either.
3365   SDNodeFlags Flags;
3366   Flags.setNoUnsignedWrap(true);
3367 
3368   SmallVector<SDValue, 4> Values(NumValues);
3369   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3370   EVT PtrVT = Ptr.getValueType();
3371   unsigned ChainI = 0;
3372   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3373     // Serializing loads here may result in excessive register pressure, and
3374     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3375     // could recover a bit by hoisting nodes upward in the chain by recognizing
3376     // they are side-effect free or do not alias. The optimizer should really
3377     // avoid this case by converting large object/array copies to llvm.memcpy
3378     // (MaxParallelChains should always remain as failsafe).
3379     if (ChainI == MaxParallelChains) {
3380       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3381       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3382                                   makeArrayRef(Chains.data(), ChainI));
3383       Root = Chain;
3384       ChainI = 0;
3385     }
3386     SDValue A = DAG.getNode(ISD::ADD, dl,
3387                             PtrVT, Ptr,
3388                             DAG.getConstant(Offsets[i], dl, PtrVT),
3389                             &Flags);
3390     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
3391                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3392                             isNonTemporal, isInvariant, Alignment, AAInfo,
3393                             Ranges);
3394 
3395     Values[i] = L;
3396     Chains[ChainI] = L.getValue(1);
3397   }
3398 
3399   if (!ConstantMemory) {
3400     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3401                                 makeArrayRef(Chains.data(), ChainI));
3402     if (isVolatile)
3403       DAG.setRoot(Chain);
3404     else
3405       PendingLoads.push_back(Chain);
3406   }
3407 
3408   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3409                            DAG.getVTList(ValueVTs), Values));
3410 }
3411 
3412 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3413   if (I.isAtomic())
3414     return visitAtomicStore(I);
3415 
3416   const Value *SrcV = I.getOperand(0);
3417   const Value *PtrV = I.getOperand(1);
3418 
3419   SmallVector<EVT, 4> ValueVTs;
3420   SmallVector<uint64_t, 4> Offsets;
3421   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3422                   SrcV->getType(), ValueVTs, &Offsets);
3423   unsigned NumValues = ValueVTs.size();
3424   if (NumValues == 0)
3425     return;
3426 
3427   // Get the lowered operands. Note that we do this after
3428   // checking if NumResults is zero, because with zero results
3429   // the operands won't have values in the map.
3430   SDValue Src = getValue(SrcV);
3431   SDValue Ptr = getValue(PtrV);
3432 
3433   SDValue Root = getRoot();
3434   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3435   EVT PtrVT = Ptr.getValueType();
3436   bool isVolatile = I.isVolatile();
3437   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3438   unsigned Alignment = I.getAlignment();
3439   SDLoc dl = getCurSDLoc();
3440 
3441   AAMDNodes AAInfo;
3442   I.getAAMetadata(AAInfo);
3443 
3444   // An aggregate load cannot wrap around the address space, so offsets to its
3445   // parts don't wrap either.
3446   SDNodeFlags Flags;
3447   Flags.setNoUnsignedWrap(true);
3448 
3449   unsigned ChainI = 0;
3450   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3451     // See visitLoad comments.
3452     if (ChainI == MaxParallelChains) {
3453       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3454                                   makeArrayRef(Chains.data(), ChainI));
3455       Root = Chain;
3456       ChainI = 0;
3457     }
3458     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3459                               DAG.getConstant(Offsets[i], dl, PtrVT), &Flags);
3460     SDValue St = DAG.getStore(Root, dl,
3461                               SDValue(Src.getNode(), Src.getResNo() + i),
3462                               Add, MachinePointerInfo(PtrV, Offsets[i]),
3463                               isVolatile, isNonTemporal, Alignment, AAInfo);
3464     Chains[ChainI] = St;
3465   }
3466 
3467   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3468                                   makeArrayRef(Chains.data(), ChainI));
3469   DAG.setRoot(StoreNode);
3470 }
3471 
3472 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3473   SDLoc sdl = getCurSDLoc();
3474 
3475   // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3476   Value  *PtrOperand = I.getArgOperand(1);
3477   SDValue Ptr = getValue(PtrOperand);
3478   SDValue Src0 = getValue(I.getArgOperand(0));
3479   SDValue Mask = getValue(I.getArgOperand(3));
3480   EVT VT = Src0.getValueType();
3481   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3482   if (!Alignment)
3483     Alignment = DAG.getEVTAlignment(VT);
3484 
3485   AAMDNodes AAInfo;
3486   I.getAAMetadata(AAInfo);
3487 
3488   MachineMemOperand *MMO =
3489     DAG.getMachineFunction().
3490     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3491                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3492                           Alignment, AAInfo);
3493   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3494                                          MMO, false);
3495   DAG.setRoot(StoreNode);
3496   setValue(&I, StoreNode);
3497 }
3498 
3499 // Get a uniform base for the Gather/Scatter intrinsic.
3500 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3501 // We try to represent it as a base pointer + vector of indices.
3502 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3503 // The first operand of the GEP may be a single pointer or a vector of pointers
3504 // Example:
3505 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3506 //  or
3507 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3508 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3509 //
3510 // When the first GEP operand is a single pointer - it is the uniform base we
3511 // are looking for. If first operand of the GEP is a splat vector - we
3512 // extract the spalt value and use it as a uniform base.
3513 // In all other cases the function returns 'false'.
3514 //
3515 static bool getUniformBase(const Value *& Ptr, SDValue& Base, SDValue& Index,
3516                            SelectionDAGBuilder* SDB) {
3517 
3518   SelectionDAG& DAG = SDB->DAG;
3519   LLVMContext &Context = *DAG.getContext();
3520 
3521   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3522   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3523   if (!GEP || GEP->getNumOperands() > 2)
3524     return false;
3525 
3526   const Value *GEPPtr = GEP->getPointerOperand();
3527   if (!GEPPtr->getType()->isVectorTy())
3528     Ptr = GEPPtr;
3529   else if (!(Ptr = getSplatValue(GEPPtr)))
3530     return false;
3531 
3532   Value *IndexVal = GEP->getOperand(1);
3533 
3534   // The operands of the GEP may be defined in another basic block.
3535   // In this case we'll not find nodes for the operands.
3536   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3537     return false;
3538 
3539   Base = SDB->getValue(Ptr);
3540   Index = SDB->getValue(IndexVal);
3541 
3542   // Suppress sign extension.
3543   if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3544     if (SDB->findValue(Sext->getOperand(0))) {
3545       IndexVal = Sext->getOperand(0);
3546       Index = SDB->getValue(IndexVal);
3547     }
3548   }
3549   if (!Index.getValueType().isVector()) {
3550     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3551     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3552     SmallVector<SDValue, 16> Ops(GEPWidth, Index);
3553     Index = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Index), VT, Ops);
3554   }
3555   return true;
3556 }
3557 
3558 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3559   SDLoc sdl = getCurSDLoc();
3560 
3561   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3562   const Value *Ptr = I.getArgOperand(1);
3563   SDValue Src0 = getValue(I.getArgOperand(0));
3564   SDValue Mask = getValue(I.getArgOperand(3));
3565   EVT VT = Src0.getValueType();
3566   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3567   if (!Alignment)
3568     Alignment = DAG.getEVTAlignment(VT);
3569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3570 
3571   AAMDNodes AAInfo;
3572   I.getAAMetadata(AAInfo);
3573 
3574   SDValue Base;
3575   SDValue Index;
3576   const Value *BasePtr = Ptr;
3577   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3578 
3579   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3580   MachineMemOperand *MMO = DAG.getMachineFunction().
3581     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3582                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3583                          Alignment, AAInfo);
3584   if (!UniformBase) {
3585     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3586     Index = getValue(Ptr);
3587   }
3588   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3589   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3590                                          Ops, MMO);
3591   DAG.setRoot(Scatter);
3592   setValue(&I, Scatter);
3593 }
3594 
3595 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3596   SDLoc sdl = getCurSDLoc();
3597 
3598   // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3599   Value  *PtrOperand = I.getArgOperand(0);
3600   SDValue Ptr = getValue(PtrOperand);
3601   SDValue Src0 = getValue(I.getArgOperand(3));
3602   SDValue Mask = getValue(I.getArgOperand(2));
3603 
3604   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3605   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3606   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3607   if (!Alignment)
3608     Alignment = DAG.getEVTAlignment(VT);
3609 
3610   AAMDNodes AAInfo;
3611   I.getAAMetadata(AAInfo);
3612   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3613 
3614   SDValue InChain = DAG.getRoot();
3615   if (AA->pointsToConstantMemory(MemoryLocation(
3616           PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3617           AAInfo))) {
3618     // Do not serialize (non-volatile) loads of constant memory with anything.
3619     InChain = DAG.getEntryNode();
3620   }
3621 
3622   MachineMemOperand *MMO =
3623     DAG.getMachineFunction().
3624     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3625                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
3626                           Alignment, AAInfo, Ranges);
3627 
3628   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3629                                    ISD::NON_EXTLOAD);
3630   SDValue OutChain = Load.getValue(1);
3631   DAG.setRoot(OutChain);
3632   setValue(&I, Load);
3633 }
3634 
3635 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3636   SDLoc sdl = getCurSDLoc();
3637 
3638   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3639   const Value *Ptr = I.getArgOperand(0);
3640   SDValue Src0 = getValue(I.getArgOperand(3));
3641   SDValue Mask = getValue(I.getArgOperand(2));
3642 
3643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3644   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3645   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3646   if (!Alignment)
3647     Alignment = DAG.getEVTAlignment(VT);
3648 
3649   AAMDNodes AAInfo;
3650   I.getAAMetadata(AAInfo);
3651   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3652 
3653   SDValue Root = DAG.getRoot();
3654   SDValue Base;
3655   SDValue Index;
3656   const Value *BasePtr = Ptr;
3657   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3658   bool ConstantMemory = false;
3659   if (UniformBase &&
3660       AA->pointsToConstantMemory(MemoryLocation(
3661           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3662           AAInfo))) {
3663     // Do not serialize (non-volatile) loads of constant memory with anything.
3664     Root = DAG.getEntryNode();
3665     ConstantMemory = true;
3666   }
3667 
3668   MachineMemOperand *MMO =
3669     DAG.getMachineFunction().
3670     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3671                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
3672                          Alignment, AAInfo, Ranges);
3673 
3674   if (!UniformBase) {
3675     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3676     Index = getValue(Ptr);
3677   }
3678   SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3679   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3680                                        Ops, MMO);
3681 
3682   SDValue OutChain = Gather.getValue(1);
3683   if (!ConstantMemory)
3684     PendingLoads.push_back(OutChain);
3685   setValue(&I, Gather);
3686 }
3687 
3688 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3689   SDLoc dl = getCurSDLoc();
3690   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3691   AtomicOrdering FailureOrder = I.getFailureOrdering();
3692   SynchronizationScope Scope = I.getSynchScope();
3693 
3694   SDValue InChain = getRoot();
3695 
3696   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3697   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3698   SDValue L = DAG.getAtomicCmpSwap(
3699       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3700       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3701       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3702       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3703 
3704   SDValue OutChain = L.getValue(2);
3705 
3706   setValue(&I, L);
3707   DAG.setRoot(OutChain);
3708 }
3709 
3710 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3711   SDLoc dl = getCurSDLoc();
3712   ISD::NodeType NT;
3713   switch (I.getOperation()) {
3714   default: llvm_unreachable("Unknown atomicrmw operation");
3715   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3716   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
3717   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
3718   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
3719   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3720   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
3721   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
3722   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
3723   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
3724   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3725   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3726   }
3727   AtomicOrdering Order = I.getOrdering();
3728   SynchronizationScope Scope = I.getSynchScope();
3729 
3730   SDValue InChain = getRoot();
3731 
3732   SDValue L =
3733     DAG.getAtomic(NT, dl,
3734                   getValue(I.getValOperand()).getSimpleValueType(),
3735                   InChain,
3736                   getValue(I.getPointerOperand()),
3737                   getValue(I.getValOperand()),
3738                   I.getPointerOperand(),
3739                   /* Alignment=*/ 0, Order, Scope);
3740 
3741   SDValue OutChain = L.getValue(1);
3742 
3743   setValue(&I, L);
3744   DAG.setRoot(OutChain);
3745 }
3746 
3747 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3748   SDLoc dl = getCurSDLoc();
3749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3750   SDValue Ops[3];
3751   Ops[0] = getRoot();
3752   Ops[1] = DAG.getConstant(I.getOrdering(), dl,
3753                            TLI.getPointerTy(DAG.getDataLayout()));
3754   Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
3755                            TLI.getPointerTy(DAG.getDataLayout()));
3756   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3757 }
3758 
3759 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3760   SDLoc dl = getCurSDLoc();
3761   AtomicOrdering Order = I.getOrdering();
3762   SynchronizationScope Scope = I.getSynchScope();
3763 
3764   SDValue InChain = getRoot();
3765 
3766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3767   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3768 
3769   if (I.getAlignment() < VT.getSizeInBits() / 8)
3770     report_fatal_error("Cannot generate unaligned atomic load");
3771 
3772   MachineMemOperand *MMO =
3773       DAG.getMachineFunction().
3774       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3775                            MachineMemOperand::MOVolatile |
3776                            MachineMemOperand::MOLoad,
3777                            VT.getStoreSize(),
3778                            I.getAlignment() ? I.getAlignment() :
3779                                               DAG.getEVTAlignment(VT));
3780 
3781   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3782   SDValue L =
3783       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3784                     getValue(I.getPointerOperand()), MMO,
3785                     Order, Scope);
3786 
3787   SDValue OutChain = L.getValue(1);
3788 
3789   setValue(&I, L);
3790   DAG.setRoot(OutChain);
3791 }
3792 
3793 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3794   SDLoc dl = getCurSDLoc();
3795 
3796   AtomicOrdering Order = I.getOrdering();
3797   SynchronizationScope Scope = I.getSynchScope();
3798 
3799   SDValue InChain = getRoot();
3800 
3801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3802   EVT VT =
3803       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
3804 
3805   if (I.getAlignment() < VT.getSizeInBits() / 8)
3806     report_fatal_error("Cannot generate unaligned atomic store");
3807 
3808   SDValue OutChain =
3809     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3810                   InChain,
3811                   getValue(I.getPointerOperand()),
3812                   getValue(I.getValueOperand()),
3813                   I.getPointerOperand(), I.getAlignment(),
3814                   Order, Scope);
3815 
3816   DAG.setRoot(OutChain);
3817 }
3818 
3819 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3820 /// node.
3821 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3822                                                unsigned Intrinsic) {
3823   bool HasChain = !I.doesNotAccessMemory();
3824   bool OnlyLoad = HasChain && I.onlyReadsMemory();
3825 
3826   // Build the operand list.
3827   SmallVector<SDValue, 8> Ops;
3828   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3829     if (OnlyLoad) {
3830       // We don't need to serialize loads against other loads.
3831       Ops.push_back(DAG.getRoot());
3832     } else {
3833       Ops.push_back(getRoot());
3834     }
3835   }
3836 
3837   // Info is set by getTgtMemInstrinsic
3838   TargetLowering::IntrinsicInfo Info;
3839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3840   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3841 
3842   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3843   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3844       Info.opc == ISD::INTRINSIC_W_CHAIN)
3845     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3846                                         TLI.getPointerTy(DAG.getDataLayout())));
3847 
3848   // Add all operands of the call to the operand list.
3849   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3850     SDValue Op = getValue(I.getArgOperand(i));
3851     Ops.push_back(Op);
3852   }
3853 
3854   SmallVector<EVT, 4> ValueVTs;
3855   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
3856 
3857   if (HasChain)
3858     ValueVTs.push_back(MVT::Other);
3859 
3860   SDVTList VTs = DAG.getVTList(ValueVTs);
3861 
3862   // Create the node.
3863   SDValue Result;
3864   if (IsTgtIntrinsic) {
3865     // This is target intrinsic that touches memory
3866     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3867                                      VTs, Ops, Info.memVT,
3868                                    MachinePointerInfo(Info.ptrVal, Info.offset),
3869                                      Info.align, Info.vol,
3870                                      Info.readMem, Info.writeMem, Info.size);
3871   } else if (!HasChain) {
3872     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3873   } else if (!I.getType()->isVoidTy()) {
3874     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3875   } else {
3876     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3877   }
3878 
3879   if (HasChain) {
3880     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3881     if (OnlyLoad)
3882       PendingLoads.push_back(Chain);
3883     else
3884       DAG.setRoot(Chain);
3885   }
3886 
3887   if (!I.getType()->isVoidTy()) {
3888     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3889       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
3890       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3891     } else
3892       Result = lowerRangeToAssertZExt(DAG, I, Result);
3893 
3894     setValue(&I, Result);
3895   }
3896 }
3897 
3898 /// GetSignificand - Get the significand and build it into a floating-point
3899 /// number with exponent of 1:
3900 ///
3901 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3902 ///
3903 /// where Op is the hexadecimal representation of floating point value.
3904 static SDValue
3905 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3906   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3907                            DAG.getConstant(0x007fffff, dl, MVT::i32));
3908   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3909                            DAG.getConstant(0x3f800000, dl, MVT::i32));
3910   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3911 }
3912 
3913 /// GetExponent - Get the exponent:
3914 ///
3915 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3916 ///
3917 /// where Op is the hexadecimal representation of floating point value.
3918 static SDValue
3919 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3920             SDLoc dl) {
3921   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3922                            DAG.getConstant(0x7f800000, dl, MVT::i32));
3923   SDValue t1 = DAG.getNode(
3924       ISD::SRL, dl, MVT::i32, t0,
3925       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
3926   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3927                            DAG.getConstant(127, dl, MVT::i32));
3928   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3929 }
3930 
3931 /// getF32Constant - Get 32-bit floating point constant.
3932 static SDValue
3933 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3934   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3935                            MVT::f32);
3936 }
3937 
3938 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3939                                        SelectionDAG &DAG) {
3940   // TODO: What fast-math-flags should be set on the floating-point nodes?
3941 
3942   //   IntegerPartOfX = ((int32_t)(t0);
3943   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3944 
3945   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
3946   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3947   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3948 
3949   //   IntegerPartOfX <<= 23;
3950   IntegerPartOfX = DAG.getNode(
3951       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3952       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
3953                                   DAG.getDataLayout())));
3954 
3955   SDValue TwoToFractionalPartOfX;
3956   if (LimitFloatPrecision <= 6) {
3957     // For floating-point precision of 6:
3958     //
3959     //   TwoToFractionalPartOfX =
3960     //     0.997535578f +
3961     //       (0.735607626f + 0.252464424f * x) * x;
3962     //
3963     // error 0.0144103317, which is 6 bits
3964     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3965                              getF32Constant(DAG, 0x3e814304, dl));
3966     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3967                              getF32Constant(DAG, 0x3f3c50c8, dl));
3968     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3969     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3970                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
3971   } else if (LimitFloatPrecision <= 12) {
3972     // For floating-point precision of 12:
3973     //
3974     //   TwoToFractionalPartOfX =
3975     //     0.999892986f +
3976     //       (0.696457318f +
3977     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3978     //
3979     // error 0.000107046256, which is 13 to 14 bits
3980     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3981                              getF32Constant(DAG, 0x3da235e3, dl));
3982     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3983                              getF32Constant(DAG, 0x3e65b8f3, dl));
3984     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3985     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3986                              getF32Constant(DAG, 0x3f324b07, dl));
3987     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3988     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3989                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
3990   } else { // LimitFloatPrecision <= 18
3991     // For floating-point precision of 18:
3992     //
3993     //   TwoToFractionalPartOfX =
3994     //     0.999999982f +
3995     //       (0.693148872f +
3996     //         (0.240227044f +
3997     //           (0.554906021e-1f +
3998     //             (0.961591928e-2f +
3999     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4000     // error 2.47208000*10^(-7), which is better than 18 bits
4001     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4002                              getF32Constant(DAG, 0x3924b03e, dl));
4003     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4004                              getF32Constant(DAG, 0x3ab24b87, dl));
4005     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4006     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4007                              getF32Constant(DAG, 0x3c1d8c17, dl));
4008     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4009     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4010                              getF32Constant(DAG, 0x3d634a1d, dl));
4011     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4012     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4013                              getF32Constant(DAG, 0x3e75fe14, dl));
4014     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4015     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4016                               getF32Constant(DAG, 0x3f317234, dl));
4017     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4018     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4019                                          getF32Constant(DAG, 0x3f800000, dl));
4020   }
4021 
4022   // Add the exponent into the result in integer domain.
4023   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4024   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4025                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4026 }
4027 
4028 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4029 /// limited-precision mode.
4030 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4031                          const TargetLowering &TLI) {
4032   if (Op.getValueType() == MVT::f32 &&
4033       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4034 
4035     // Put the exponent in the right bit position for later addition to the
4036     // final result:
4037     //
4038     //   #define LOG2OFe 1.4426950f
4039     //   t0 = Op * LOG2OFe
4040 
4041     // TODO: What fast-math-flags should be set here?
4042     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4043                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4044     return getLimitedPrecisionExp2(t0, dl, DAG);
4045   }
4046 
4047   // No special expansion.
4048   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4049 }
4050 
4051 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4052 /// limited-precision mode.
4053 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4054                          const TargetLowering &TLI) {
4055 
4056   // TODO: What fast-math-flags should be set on the floating-point nodes?
4057 
4058   if (Op.getValueType() == MVT::f32 &&
4059       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4060     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4061 
4062     // Scale the exponent by log(2) [0.69314718f].
4063     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4064     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4065                                         getF32Constant(DAG, 0x3f317218, dl));
4066 
4067     // Get the significand and build it into a floating-point number with
4068     // exponent of 1.
4069     SDValue X = GetSignificand(DAG, Op1, dl);
4070 
4071     SDValue LogOfMantissa;
4072     if (LimitFloatPrecision <= 6) {
4073       // For floating-point precision of 6:
4074       //
4075       //   LogofMantissa =
4076       //     -1.1609546f +
4077       //       (1.4034025f - 0.23903021f * x) * x;
4078       //
4079       // error 0.0034276066, which is better than 8 bits
4080       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4081                                getF32Constant(DAG, 0xbe74c456, dl));
4082       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4083                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4084       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4085       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4086                                   getF32Constant(DAG, 0x3f949a29, dl));
4087     } else if (LimitFloatPrecision <= 12) {
4088       // For floating-point precision of 12:
4089       //
4090       //   LogOfMantissa =
4091       //     -1.7417939f +
4092       //       (2.8212026f +
4093       //         (-1.4699568f +
4094       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4095       //
4096       // error 0.000061011436, which is 14 bits
4097       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4098                                getF32Constant(DAG, 0xbd67b6d6, dl));
4099       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4100                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4101       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4102       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4103                                getF32Constant(DAG, 0x3fbc278b, dl));
4104       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4105       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4106                                getF32Constant(DAG, 0x40348e95, dl));
4107       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4108       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4109                                   getF32Constant(DAG, 0x3fdef31a, dl));
4110     } else { // LimitFloatPrecision <= 18
4111       // For floating-point precision of 18:
4112       //
4113       //   LogOfMantissa =
4114       //     -2.1072184f +
4115       //       (4.2372794f +
4116       //         (-3.7029485f +
4117       //           (2.2781945f +
4118       //             (-0.87823314f +
4119       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4120       //
4121       // error 0.0000023660568, which is better than 18 bits
4122       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4123                                getF32Constant(DAG, 0xbc91e5ac, dl));
4124       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4125                                getF32Constant(DAG, 0x3e4350aa, dl));
4126       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4127       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4128                                getF32Constant(DAG, 0x3f60d3e3, dl));
4129       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4130       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4131                                getF32Constant(DAG, 0x4011cdf0, dl));
4132       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4133       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4134                                getF32Constant(DAG, 0x406cfd1c, dl));
4135       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4136       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4137                                getF32Constant(DAG, 0x408797cb, dl));
4138       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4139       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4140                                   getF32Constant(DAG, 0x4006dcab, dl));
4141     }
4142 
4143     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4144   }
4145 
4146   // No special expansion.
4147   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4148 }
4149 
4150 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4151 /// limited-precision mode.
4152 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4153                           const TargetLowering &TLI) {
4154 
4155   // TODO: What fast-math-flags should be set on the floating-point nodes?
4156 
4157   if (Op.getValueType() == MVT::f32 &&
4158       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4159     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4160 
4161     // Get the exponent.
4162     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4163 
4164     // Get the significand and build it into a floating-point number with
4165     // exponent of 1.
4166     SDValue X = GetSignificand(DAG, Op1, dl);
4167 
4168     // Different possible minimax approximations of significand in
4169     // floating-point for various degrees of accuracy over [1,2].
4170     SDValue Log2ofMantissa;
4171     if (LimitFloatPrecision <= 6) {
4172       // For floating-point precision of 6:
4173       //
4174       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4175       //
4176       // error 0.0049451742, which is more than 7 bits
4177       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4178                                getF32Constant(DAG, 0xbeb08fe0, dl));
4179       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4180                                getF32Constant(DAG, 0x40019463, dl));
4181       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4182       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4183                                    getF32Constant(DAG, 0x3fd6633d, dl));
4184     } else if (LimitFloatPrecision <= 12) {
4185       // For floating-point precision of 12:
4186       //
4187       //   Log2ofMantissa =
4188       //     -2.51285454f +
4189       //       (4.07009056f +
4190       //         (-2.12067489f +
4191       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4192       //
4193       // error 0.0000876136000, which is better than 13 bits
4194       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4195                                getF32Constant(DAG, 0xbda7262e, dl));
4196       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4197                                getF32Constant(DAG, 0x3f25280b, dl));
4198       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4199       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4200                                getF32Constant(DAG, 0x4007b923, dl));
4201       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4202       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4203                                getF32Constant(DAG, 0x40823e2f, dl));
4204       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4205       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4206                                    getF32Constant(DAG, 0x4020d29c, dl));
4207     } else { // LimitFloatPrecision <= 18
4208       // For floating-point precision of 18:
4209       //
4210       //   Log2ofMantissa =
4211       //     -3.0400495f +
4212       //       (6.1129976f +
4213       //         (-5.3420409f +
4214       //           (3.2865683f +
4215       //             (-1.2669343f +
4216       //               (0.27515199f -
4217       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4218       //
4219       // error 0.0000018516, which is better than 18 bits
4220       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4221                                getF32Constant(DAG, 0xbcd2769e, dl));
4222       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4223                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4224       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4225       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4226                                getF32Constant(DAG, 0x3fa22ae7, dl));
4227       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4228       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4229                                getF32Constant(DAG, 0x40525723, dl));
4230       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4231       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4232                                getF32Constant(DAG, 0x40aaf200, dl));
4233       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4234       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4235                                getF32Constant(DAG, 0x40c39dad, dl));
4236       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4237       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4238                                    getF32Constant(DAG, 0x4042902c, dl));
4239     }
4240 
4241     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4242   }
4243 
4244   // No special expansion.
4245   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4246 }
4247 
4248 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4249 /// limited-precision mode.
4250 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4251                            const TargetLowering &TLI) {
4252 
4253   // TODO: What fast-math-flags should be set on the floating-point nodes?
4254 
4255   if (Op.getValueType() == MVT::f32 &&
4256       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4257     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4258 
4259     // Scale the exponent by log10(2) [0.30102999f].
4260     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4261     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4262                                         getF32Constant(DAG, 0x3e9a209a, dl));
4263 
4264     // Get the significand and build it into a floating-point number with
4265     // exponent of 1.
4266     SDValue X = GetSignificand(DAG, Op1, dl);
4267 
4268     SDValue Log10ofMantissa;
4269     if (LimitFloatPrecision <= 6) {
4270       // For floating-point precision of 6:
4271       //
4272       //   Log10ofMantissa =
4273       //     -0.50419619f +
4274       //       (0.60948995f - 0.10380950f * x) * x;
4275       //
4276       // error 0.0014886165, which is 6 bits
4277       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4278                                getF32Constant(DAG, 0xbdd49a13, dl));
4279       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4280                                getF32Constant(DAG, 0x3f1c0789, dl));
4281       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4282       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4283                                     getF32Constant(DAG, 0x3f011300, dl));
4284     } else if (LimitFloatPrecision <= 12) {
4285       // For floating-point precision of 12:
4286       //
4287       //   Log10ofMantissa =
4288       //     -0.64831180f +
4289       //       (0.91751397f +
4290       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4291       //
4292       // error 0.00019228036, which is better than 12 bits
4293       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4294                                getF32Constant(DAG, 0x3d431f31, dl));
4295       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4296                                getF32Constant(DAG, 0x3ea21fb2, dl));
4297       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4298       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4299                                getF32Constant(DAG, 0x3f6ae232, dl));
4300       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4301       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4302                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4303     } else { // LimitFloatPrecision <= 18
4304       // For floating-point precision of 18:
4305       //
4306       //   Log10ofMantissa =
4307       //     -0.84299375f +
4308       //       (1.5327582f +
4309       //         (-1.0688956f +
4310       //           (0.49102474f +
4311       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4312       //
4313       // error 0.0000037995730, which is better than 18 bits
4314       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4315                                getF32Constant(DAG, 0x3c5d51ce, dl));
4316       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4317                                getF32Constant(DAG, 0x3e00685a, dl));
4318       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4319       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4320                                getF32Constant(DAG, 0x3efb6798, dl));
4321       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4322       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4323                                getF32Constant(DAG, 0x3f88d192, dl));
4324       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4325       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4326                                getF32Constant(DAG, 0x3fc4316c, dl));
4327       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4328       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4329                                     getF32Constant(DAG, 0x3f57ce70, dl));
4330     }
4331 
4332     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4333   }
4334 
4335   // No special expansion.
4336   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4337 }
4338 
4339 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4340 /// limited-precision mode.
4341 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4342                           const TargetLowering &TLI) {
4343   if (Op.getValueType() == MVT::f32 &&
4344       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4345     return getLimitedPrecisionExp2(Op, dl, DAG);
4346 
4347   // No special expansion.
4348   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4349 }
4350 
4351 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4352 /// limited-precision mode with x == 10.0f.
4353 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4354                          SelectionDAG &DAG, const TargetLowering &TLI) {
4355   bool IsExp10 = false;
4356   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4357       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4358     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4359       APFloat Ten(10.0f);
4360       IsExp10 = LHSC->isExactlyValue(Ten);
4361     }
4362   }
4363 
4364   // TODO: What fast-math-flags should be set on the FMUL node?
4365   if (IsExp10) {
4366     // Put the exponent in the right bit position for later addition to the
4367     // final result:
4368     //
4369     //   #define LOG2OF10 3.3219281f
4370     //   t0 = Op * LOG2OF10;
4371     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4372                              getF32Constant(DAG, 0x40549a78, dl));
4373     return getLimitedPrecisionExp2(t0, dl, DAG);
4374   }
4375 
4376   // No special expansion.
4377   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4378 }
4379 
4380 
4381 /// ExpandPowI - Expand a llvm.powi intrinsic.
4382 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4383                           SelectionDAG &DAG) {
4384   // If RHS is a constant, we can expand this out to a multiplication tree,
4385   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4386   // optimizing for size, we only want to do this if the expansion would produce
4387   // a small number of multiplies, otherwise we do the full expansion.
4388   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4389     // Get the exponent as a positive value.
4390     unsigned Val = RHSC->getSExtValue();
4391     if ((int)Val < 0) Val = -Val;
4392 
4393     // powi(x, 0) -> 1.0
4394     if (Val == 0)
4395       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4396 
4397     const Function *F = DAG.getMachineFunction().getFunction();
4398     if (!F->optForSize() ||
4399         // If optimizing for size, don't insert too many multiplies.
4400         // This inserts up to 5 multiplies.
4401         countPopulation(Val) + Log2_32(Val) < 7) {
4402       // We use the simple binary decomposition method to generate the multiply
4403       // sequence.  There are more optimal ways to do this (for example,
4404       // powi(x,15) generates one more multiply than it should), but this has
4405       // the benefit of being both really simple and much better than a libcall.
4406       SDValue Res;  // Logically starts equal to 1.0
4407       SDValue CurSquare = LHS;
4408       // TODO: Intrinsics should have fast-math-flags that propagate to these
4409       // nodes.
4410       while (Val) {
4411         if (Val & 1) {
4412           if (Res.getNode())
4413             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4414           else
4415             Res = CurSquare;  // 1.0*CurSquare.
4416         }
4417 
4418         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4419                                 CurSquare, CurSquare);
4420         Val >>= 1;
4421       }
4422 
4423       // If the original was negative, invert the result, producing 1/(x*x*x).
4424       if (RHSC->getSExtValue() < 0)
4425         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4426                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4427       return Res;
4428     }
4429   }
4430 
4431   // Otherwise, expand to a libcall.
4432   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4433 }
4434 
4435 // getUnderlyingArgReg - Find underlying register used for a truncated or
4436 // bitcasted argument.
4437 static unsigned getUnderlyingArgReg(const SDValue &N) {
4438   switch (N.getOpcode()) {
4439   case ISD::CopyFromReg:
4440     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4441   case ISD::BITCAST:
4442   case ISD::AssertZext:
4443   case ISD::AssertSext:
4444   case ISD::TRUNCATE:
4445     return getUnderlyingArgReg(N.getOperand(0));
4446   default:
4447     return 0;
4448   }
4449 }
4450 
4451 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4452 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4453 /// At the end of instruction selection, they will be inserted to the entry BB.
4454 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4455     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4456     DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
4457   const Argument *Arg = dyn_cast<Argument>(V);
4458   if (!Arg)
4459     return false;
4460 
4461   MachineFunction &MF = DAG.getMachineFunction();
4462   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4463 
4464   // Ignore inlined function arguments here.
4465   //
4466   // FIXME: Should we be checking DL->inlinedAt() to determine this?
4467   if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
4468     return false;
4469 
4470   Optional<MachineOperand> Op;
4471   // Some arguments' frame index is recorded during argument lowering.
4472   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4473     Op = MachineOperand::CreateFI(FI);
4474 
4475   if (!Op && N.getNode()) {
4476     unsigned Reg = getUnderlyingArgReg(N);
4477     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4478       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4479       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4480       if (PR)
4481         Reg = PR;
4482     }
4483     if (Reg)
4484       Op = MachineOperand::CreateReg(Reg, false);
4485   }
4486 
4487   if (!Op) {
4488     // Check if ValueMap has reg number.
4489     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4490     if (VMI != FuncInfo.ValueMap.end())
4491       Op = MachineOperand::CreateReg(VMI->second, false);
4492   }
4493 
4494   if (!Op && N.getNode())
4495     // Check if frame index is available.
4496     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4497       if (FrameIndexSDNode *FINode =
4498           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4499         Op = MachineOperand::CreateFI(FINode->getIndex());
4500 
4501   if (!Op)
4502     return false;
4503 
4504   assert(Variable->isValidLocationForIntrinsic(DL) &&
4505          "Expected inlined-at fields to agree");
4506   if (Op->isReg())
4507     FuncInfo.ArgDbgValues.push_back(
4508         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4509                 Op->getReg(), Offset, Variable, Expr));
4510   else
4511     FuncInfo.ArgDbgValues.push_back(
4512         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4513             .addOperand(*Op)
4514             .addImm(Offset)
4515             .addMetadata(Variable)
4516             .addMetadata(Expr));
4517 
4518   return true;
4519 }
4520 
4521 // VisualStudio defines setjmp as _setjmp
4522 #if defined(_MSC_VER) && defined(setjmp) && \
4523                          !defined(setjmp_undefined_for_msvc)
4524 #  pragma push_macro("setjmp")
4525 #  undef setjmp
4526 #  define setjmp_undefined_for_msvc
4527 #endif
4528 
4529 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
4530 /// we want to emit this as a call to a named external function, return the name
4531 /// otherwise lower it and return null.
4532 const char *
4533 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4535   SDLoc sdl = getCurSDLoc();
4536   DebugLoc dl = getCurDebugLoc();
4537   SDValue Res;
4538 
4539   switch (Intrinsic) {
4540   default:
4541     // By default, turn this into a target intrinsic node.
4542     visitTargetIntrinsic(I, Intrinsic);
4543     return nullptr;
4544   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
4545   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
4546   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
4547   case Intrinsic::returnaddress:
4548     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4549                              TLI.getPointerTy(DAG.getDataLayout()),
4550                              getValue(I.getArgOperand(0))));
4551     return nullptr;
4552   case Intrinsic::frameaddress:
4553     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4554                              TLI.getPointerTy(DAG.getDataLayout()),
4555                              getValue(I.getArgOperand(0))));
4556     return nullptr;
4557   case Intrinsic::read_register: {
4558     Value *Reg = I.getArgOperand(0);
4559     SDValue Chain = getRoot();
4560     SDValue RegName =
4561         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4562     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4563     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4564       DAG.getVTList(VT, MVT::Other), Chain, RegName);
4565     setValue(&I, Res);
4566     DAG.setRoot(Res.getValue(1));
4567     return nullptr;
4568   }
4569   case Intrinsic::write_register: {
4570     Value *Reg = I.getArgOperand(0);
4571     Value *RegValue = I.getArgOperand(1);
4572     SDValue Chain = getRoot();
4573     SDValue RegName =
4574         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4575     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4576                             RegName, getValue(RegValue)));
4577     return nullptr;
4578   }
4579   case Intrinsic::setjmp:
4580     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4581   case Intrinsic::longjmp:
4582     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4583   case Intrinsic::memcpy: {
4584     SDValue Op1 = getValue(I.getArgOperand(0));
4585     SDValue Op2 = getValue(I.getArgOperand(1));
4586     SDValue Op3 = getValue(I.getArgOperand(2));
4587     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4588     if (!Align)
4589       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4590     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4591     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4592     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4593                                false, isTC,
4594                                MachinePointerInfo(I.getArgOperand(0)),
4595                                MachinePointerInfo(I.getArgOperand(1)));
4596     updateDAGForMaybeTailCall(MC);
4597     return nullptr;
4598   }
4599   case Intrinsic::memset: {
4600     SDValue Op1 = getValue(I.getArgOperand(0));
4601     SDValue Op2 = getValue(I.getArgOperand(1));
4602     SDValue Op3 = getValue(I.getArgOperand(2));
4603     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4604     if (!Align)
4605       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4606     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4607     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4608     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4609                                isTC, MachinePointerInfo(I.getArgOperand(0)));
4610     updateDAGForMaybeTailCall(MS);
4611     return nullptr;
4612   }
4613   case Intrinsic::memmove: {
4614     SDValue Op1 = getValue(I.getArgOperand(0));
4615     SDValue Op2 = getValue(I.getArgOperand(1));
4616     SDValue Op3 = getValue(I.getArgOperand(2));
4617     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4618     if (!Align)
4619       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4620     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4621     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4622     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4623                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
4624                                 MachinePointerInfo(I.getArgOperand(1)));
4625     updateDAGForMaybeTailCall(MM);
4626     return nullptr;
4627   }
4628   case Intrinsic::dbg_declare: {
4629     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4630     DILocalVariable *Variable = DI.getVariable();
4631     DIExpression *Expression = DI.getExpression();
4632     const Value *Address = DI.getAddress();
4633     assert(Variable && "Missing variable");
4634     if (!Address) {
4635       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4636       return nullptr;
4637     }
4638 
4639     // Check if address has undef value.
4640     if (isa<UndefValue>(Address) ||
4641         (Address->use_empty() && !isa<Argument>(Address))) {
4642       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4643       return nullptr;
4644     }
4645 
4646     SDValue &N = NodeMap[Address];
4647     if (!N.getNode() && isa<Argument>(Address))
4648       // Check unused arguments map.
4649       N = UnusedArgNodeMap[Address];
4650     SDDbgValue *SDV;
4651     if (N.getNode()) {
4652       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4653         Address = BCI->getOperand(0);
4654       // Parameters are handled specially.
4655       bool isParameter = Variable->isParameter() || isa<Argument>(Address);
4656       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4657       if (isParameter && FINode) {
4658         // Byval parameter. We have a frame index at this point.
4659         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
4660                                         FINode->getIndex(), 0, dl, SDNodeOrder);
4661       } else if (isa<Argument>(Address)) {
4662         // Address is an argument, so try to emit its dbg value using
4663         // virtual register info from the FuncInfo.ValueMap.
4664         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4665                                  N);
4666         return nullptr;
4667       } else {
4668         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4669                               true, 0, dl, SDNodeOrder);
4670       }
4671       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4672     } else {
4673       // If Address is an argument then try to emit its dbg value using
4674       // virtual register info from the FuncInfo.ValueMap.
4675       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4676                                     N)) {
4677         // If variable is pinned by a alloca in dominating bb then
4678         // use StaticAllocaMap.
4679         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4680           if (AI->getParent() != DI.getParent()) {
4681             DenseMap<const AllocaInst*, int>::iterator SI =
4682               FuncInfo.StaticAllocaMap.find(AI);
4683             if (SI != FuncInfo.StaticAllocaMap.end()) {
4684               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4685                                               0, dl, SDNodeOrder);
4686               DAG.AddDbgValue(SDV, nullptr, false);
4687               return nullptr;
4688             }
4689           }
4690         }
4691         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4692       }
4693     }
4694     return nullptr;
4695   }
4696   case Intrinsic::dbg_value: {
4697     const DbgValueInst &DI = cast<DbgValueInst>(I);
4698     assert(DI.getVariable() && "Missing variable");
4699 
4700     DILocalVariable *Variable = DI.getVariable();
4701     DIExpression *Expression = DI.getExpression();
4702     uint64_t Offset = DI.getOffset();
4703     const Value *V = DI.getValue();
4704     if (!V)
4705       return nullptr;
4706 
4707     SDDbgValue *SDV;
4708     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4709       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4710                                     SDNodeOrder);
4711       DAG.AddDbgValue(SDV, nullptr, false);
4712     } else {
4713       // Do not use getValue() in here; we don't want to generate code at
4714       // this point if it hasn't been done yet.
4715       SDValue N = NodeMap[V];
4716       if (!N.getNode() && isa<Argument>(V))
4717         // Check unused arguments map.
4718         N = UnusedArgNodeMap[V];
4719       if (N.getNode()) {
4720         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4721                                       false, N)) {
4722           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4723                                 false, Offset, dl, SDNodeOrder);
4724           DAG.AddDbgValue(SDV, N.getNode(), false);
4725         }
4726       } else if (!V->use_empty() ) {
4727         // Do not call getValue(V) yet, as we don't want to generate code.
4728         // Remember it for later.
4729         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4730         DanglingDebugInfoMap[V] = DDI;
4731       } else {
4732         // We may expand this to cover more cases.  One case where we have no
4733         // data available is an unreferenced parameter.
4734         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4735       }
4736     }
4737 
4738     // Build a debug info table entry.
4739     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4740       V = BCI->getOperand(0);
4741     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4742     // Don't handle byval struct arguments or VLAs, for example.
4743     if (!AI) {
4744       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
4745       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
4746       return nullptr;
4747     }
4748     DenseMap<const AllocaInst*, int>::iterator SI =
4749       FuncInfo.StaticAllocaMap.find(AI);
4750     if (SI == FuncInfo.StaticAllocaMap.end())
4751       return nullptr; // VLAs.
4752     return nullptr;
4753   }
4754 
4755   case Intrinsic::eh_typeid_for: {
4756     // Find the type id for the given typeinfo.
4757     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4758     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4759     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4760     setValue(&I, Res);
4761     return nullptr;
4762   }
4763 
4764   case Intrinsic::eh_return_i32:
4765   case Intrinsic::eh_return_i64:
4766     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4767     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4768                             MVT::Other,
4769                             getControlRoot(),
4770                             getValue(I.getArgOperand(0)),
4771                             getValue(I.getArgOperand(1))));
4772     return nullptr;
4773   case Intrinsic::eh_unwind_init:
4774     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4775     return nullptr;
4776   case Intrinsic::eh_dwarf_cfa: {
4777     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4778                                         TLI.getPointerTy(DAG.getDataLayout()));
4779     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4780                                  CfaArg.getValueType(),
4781                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4782                                              CfaArg.getValueType()),
4783                                  CfaArg);
4784     SDValue FA = DAG.getNode(
4785         ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()),
4786         DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
4787     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4788                              FA, Offset));
4789     return nullptr;
4790   }
4791   case Intrinsic::eh_sjlj_callsite: {
4792     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4793     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4794     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4795     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4796 
4797     MMI.setCurrentCallSite(CI->getZExtValue());
4798     return nullptr;
4799   }
4800   case Intrinsic::eh_sjlj_functioncontext: {
4801     // Get and store the index of the function context.
4802     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4803     AllocaInst *FnCtx =
4804       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4805     int FI = FuncInfo.StaticAllocaMap[FnCtx];
4806     MFI->setFunctionContextIndex(FI);
4807     return nullptr;
4808   }
4809   case Intrinsic::eh_sjlj_setjmp: {
4810     SDValue Ops[2];
4811     Ops[0] = getRoot();
4812     Ops[1] = getValue(I.getArgOperand(0));
4813     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4814                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
4815     setValue(&I, Op.getValue(0));
4816     DAG.setRoot(Op.getValue(1));
4817     return nullptr;
4818   }
4819   case Intrinsic::eh_sjlj_longjmp: {
4820     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4821                             getRoot(), getValue(I.getArgOperand(0))));
4822     return nullptr;
4823   }
4824   case Intrinsic::eh_sjlj_setup_dispatch: {
4825     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
4826                             getRoot()));
4827     return nullptr;
4828   }
4829 
4830   case Intrinsic::masked_gather:
4831     visitMaskedGather(I);
4832     return nullptr;
4833   case Intrinsic::masked_load:
4834     visitMaskedLoad(I);
4835     return nullptr;
4836   case Intrinsic::masked_scatter:
4837     visitMaskedScatter(I);
4838     return nullptr;
4839   case Intrinsic::masked_store:
4840     visitMaskedStore(I);
4841     return nullptr;
4842   case Intrinsic::x86_mmx_pslli_w:
4843   case Intrinsic::x86_mmx_pslli_d:
4844   case Intrinsic::x86_mmx_pslli_q:
4845   case Intrinsic::x86_mmx_psrli_w:
4846   case Intrinsic::x86_mmx_psrli_d:
4847   case Intrinsic::x86_mmx_psrli_q:
4848   case Intrinsic::x86_mmx_psrai_w:
4849   case Intrinsic::x86_mmx_psrai_d: {
4850     SDValue ShAmt = getValue(I.getArgOperand(1));
4851     if (isa<ConstantSDNode>(ShAmt)) {
4852       visitTargetIntrinsic(I, Intrinsic);
4853       return nullptr;
4854     }
4855     unsigned NewIntrinsic = 0;
4856     EVT ShAmtVT = MVT::v2i32;
4857     switch (Intrinsic) {
4858     case Intrinsic::x86_mmx_pslli_w:
4859       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4860       break;
4861     case Intrinsic::x86_mmx_pslli_d:
4862       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4863       break;
4864     case Intrinsic::x86_mmx_pslli_q:
4865       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4866       break;
4867     case Intrinsic::x86_mmx_psrli_w:
4868       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4869       break;
4870     case Intrinsic::x86_mmx_psrli_d:
4871       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4872       break;
4873     case Intrinsic::x86_mmx_psrli_q:
4874       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4875       break;
4876     case Intrinsic::x86_mmx_psrai_w:
4877       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4878       break;
4879     case Intrinsic::x86_mmx_psrai_d:
4880       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4881       break;
4882     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4883     }
4884 
4885     // The vector shift intrinsics with scalars uses 32b shift amounts but
4886     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4887     // to be zero.
4888     // We must do this early because v2i32 is not a legal type.
4889     SDValue ShOps[2];
4890     ShOps[0] = ShAmt;
4891     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4892     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4893     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4894     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4895     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4896                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4897                        getValue(I.getArgOperand(0)), ShAmt);
4898     setValue(&I, Res);
4899     return nullptr;
4900   }
4901   case Intrinsic::convertff:
4902   case Intrinsic::convertfsi:
4903   case Intrinsic::convertfui:
4904   case Intrinsic::convertsif:
4905   case Intrinsic::convertuif:
4906   case Intrinsic::convertss:
4907   case Intrinsic::convertsu:
4908   case Intrinsic::convertus:
4909   case Intrinsic::convertuu: {
4910     ISD::CvtCode Code = ISD::CVT_INVALID;
4911     switch (Intrinsic) {
4912     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4913     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4914     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4915     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4916     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4917     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4918     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4919     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4920     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4921     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4922     }
4923     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4924     const Value *Op1 = I.getArgOperand(0);
4925     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4926                                DAG.getValueType(DestVT),
4927                                DAG.getValueType(getValue(Op1).getValueType()),
4928                                getValue(I.getArgOperand(1)),
4929                                getValue(I.getArgOperand(2)),
4930                                Code);
4931     setValue(&I, Res);
4932     return nullptr;
4933   }
4934   case Intrinsic::powi:
4935     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4936                             getValue(I.getArgOperand(1)), DAG));
4937     return nullptr;
4938   case Intrinsic::log:
4939     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4940     return nullptr;
4941   case Intrinsic::log2:
4942     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4943     return nullptr;
4944   case Intrinsic::log10:
4945     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4946     return nullptr;
4947   case Intrinsic::exp:
4948     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4949     return nullptr;
4950   case Intrinsic::exp2:
4951     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4952     return nullptr;
4953   case Intrinsic::pow:
4954     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4955                            getValue(I.getArgOperand(1)), DAG, TLI));
4956     return nullptr;
4957   case Intrinsic::sqrt:
4958   case Intrinsic::fabs:
4959   case Intrinsic::sin:
4960   case Intrinsic::cos:
4961   case Intrinsic::floor:
4962   case Intrinsic::ceil:
4963   case Intrinsic::trunc:
4964   case Intrinsic::rint:
4965   case Intrinsic::nearbyint:
4966   case Intrinsic::round: {
4967     unsigned Opcode;
4968     switch (Intrinsic) {
4969     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4970     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
4971     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
4972     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
4973     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
4974     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
4975     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
4976     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
4977     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
4978     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4979     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
4980     }
4981 
4982     setValue(&I, DAG.getNode(Opcode, sdl,
4983                              getValue(I.getArgOperand(0)).getValueType(),
4984                              getValue(I.getArgOperand(0))));
4985     return nullptr;
4986   }
4987   case Intrinsic::minnum:
4988     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4989                              getValue(I.getArgOperand(0)).getValueType(),
4990                              getValue(I.getArgOperand(0)),
4991                              getValue(I.getArgOperand(1))));
4992     return nullptr;
4993   case Intrinsic::maxnum:
4994     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4995                              getValue(I.getArgOperand(0)).getValueType(),
4996                              getValue(I.getArgOperand(0)),
4997                              getValue(I.getArgOperand(1))));
4998     return nullptr;
4999   case Intrinsic::copysign:
5000     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5001                              getValue(I.getArgOperand(0)).getValueType(),
5002                              getValue(I.getArgOperand(0)),
5003                              getValue(I.getArgOperand(1))));
5004     return nullptr;
5005   case Intrinsic::fma:
5006     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5007                              getValue(I.getArgOperand(0)).getValueType(),
5008                              getValue(I.getArgOperand(0)),
5009                              getValue(I.getArgOperand(1)),
5010                              getValue(I.getArgOperand(2))));
5011     return nullptr;
5012   case Intrinsic::fmuladd: {
5013     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5014     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5015         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5016       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5017                                getValue(I.getArgOperand(0)).getValueType(),
5018                                getValue(I.getArgOperand(0)),
5019                                getValue(I.getArgOperand(1)),
5020                                getValue(I.getArgOperand(2))));
5021     } else {
5022       // TODO: Intrinsic calls should have fast-math-flags.
5023       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5024                                 getValue(I.getArgOperand(0)).getValueType(),
5025                                 getValue(I.getArgOperand(0)),
5026                                 getValue(I.getArgOperand(1)));
5027       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5028                                 getValue(I.getArgOperand(0)).getValueType(),
5029                                 Mul,
5030                                 getValue(I.getArgOperand(2)));
5031       setValue(&I, Add);
5032     }
5033     return nullptr;
5034   }
5035   case Intrinsic::convert_to_fp16:
5036     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5037                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5038                                          getValue(I.getArgOperand(0)),
5039                                          DAG.getTargetConstant(0, sdl,
5040                                                                MVT::i32))));
5041     return nullptr;
5042   case Intrinsic::convert_from_fp16:
5043     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5044                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5045                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5046                                          getValue(I.getArgOperand(0)))));
5047     return nullptr;
5048   case Intrinsic::pcmarker: {
5049     SDValue Tmp = getValue(I.getArgOperand(0));
5050     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5051     return nullptr;
5052   }
5053   case Intrinsic::readcyclecounter: {
5054     SDValue Op = getRoot();
5055     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5056                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5057     setValue(&I, Res);
5058     DAG.setRoot(Res.getValue(1));
5059     return nullptr;
5060   }
5061   case Intrinsic::bitreverse:
5062     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5063                              getValue(I.getArgOperand(0)).getValueType(),
5064                              getValue(I.getArgOperand(0))));
5065     return nullptr;
5066   case Intrinsic::bswap:
5067     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5068                              getValue(I.getArgOperand(0)).getValueType(),
5069                              getValue(I.getArgOperand(0))));
5070     return nullptr;
5071   case Intrinsic::cttz: {
5072     SDValue Arg = getValue(I.getArgOperand(0));
5073     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5074     EVT Ty = Arg.getValueType();
5075     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5076                              sdl, Ty, Arg));
5077     return nullptr;
5078   }
5079   case Intrinsic::ctlz: {
5080     SDValue Arg = getValue(I.getArgOperand(0));
5081     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5082     EVT Ty = Arg.getValueType();
5083     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5084                              sdl, Ty, Arg));
5085     return nullptr;
5086   }
5087   case Intrinsic::ctpop: {
5088     SDValue Arg = getValue(I.getArgOperand(0));
5089     EVT Ty = Arg.getValueType();
5090     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5091     return nullptr;
5092   }
5093   case Intrinsic::stacksave: {
5094     SDValue Op = getRoot();
5095     Res = DAG.getNode(
5096         ISD::STACKSAVE, sdl,
5097         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5098     setValue(&I, Res);
5099     DAG.setRoot(Res.getValue(1));
5100     return nullptr;
5101   }
5102   case Intrinsic::stackrestore: {
5103     Res = getValue(I.getArgOperand(0));
5104     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5105     return nullptr;
5106   }
5107   case Intrinsic::get_dynamic_area_offset: {
5108     SDValue Op = getRoot();
5109     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5110     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5111     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5112     // target.
5113     if (PtrTy != ResTy)
5114       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5115                          " intrinsic!");
5116     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5117                       Op);
5118     DAG.setRoot(Op);
5119     setValue(&I, Res);
5120     return nullptr;
5121   }
5122   case Intrinsic::stackprotector: {
5123     // Emit code into the DAG to store the stack guard onto the stack.
5124     MachineFunction &MF = DAG.getMachineFunction();
5125     MachineFrameInfo *MFI = MF.getFrameInfo();
5126     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5127     SDValue Src, Chain = getRoot();
5128     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5129     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5130 
5131     // See if Ptr is a bitcast. If it is, look through it and see if we can get
5132     // global variable __stack_chk_guard.
5133     if (!GV)
5134       if (const Operator *BC = dyn_cast<Operator>(Ptr))
5135         if (BC->getOpcode() == Instruction::BitCast)
5136           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5137 
5138     if (GV && TLI.useLoadStackGuardNode()) {
5139       // Emit a LOAD_STACK_GUARD node.
5140       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5141                                                sdl, PtrTy, Chain);
5142       MachinePointerInfo MPInfo(GV);
5143       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5144       unsigned Flags = MachineMemOperand::MOLoad |
5145                        MachineMemOperand::MOInvariant;
5146       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5147                                          PtrTy.getSizeInBits() / 8,
5148                                          DAG.getEVTAlignment(PtrTy));
5149       Node->setMemRefs(MemRefs, MemRefs + 1);
5150 
5151       // Copy the guard value to a virtual register so that it can be
5152       // retrieved in the epilogue.
5153       Src = SDValue(Node, 0);
5154       const TargetRegisterClass *RC =
5155           TLI.getRegClassFor(Src.getSimpleValueType());
5156       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5157 
5158       SPDescriptor.setGuardReg(Reg);
5159       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5160     } else {
5161       Src = getValue(I.getArgOperand(0));   // The guard's value.
5162     }
5163 
5164     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5165 
5166     int FI = FuncInfo.StaticAllocaMap[Slot];
5167     MFI->setStackProtectorIndex(FI);
5168 
5169     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5170 
5171     // Store the stack protector onto the stack.
5172     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5173                                                  DAG.getMachineFunction(), FI),
5174                        true, false, 0);
5175     setValue(&I, Res);
5176     DAG.setRoot(Res);
5177     return nullptr;
5178   }
5179   case Intrinsic::objectsize: {
5180     // If we don't know by now, we're never going to know.
5181     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5182 
5183     assert(CI && "Non-constant type in __builtin_object_size?");
5184 
5185     SDValue Arg = getValue(I.getCalledValue());
5186     EVT Ty = Arg.getValueType();
5187 
5188     if (CI->isZero())
5189       Res = DAG.getConstant(-1ULL, sdl, Ty);
5190     else
5191       Res = DAG.getConstant(0, sdl, Ty);
5192 
5193     setValue(&I, Res);
5194     return nullptr;
5195   }
5196   case Intrinsic::annotation:
5197   case Intrinsic::ptr_annotation:
5198     // Drop the intrinsic, but forward the value
5199     setValue(&I, getValue(I.getOperand(0)));
5200     return nullptr;
5201   case Intrinsic::assume:
5202   case Intrinsic::var_annotation:
5203     // Discard annotate attributes and assumptions
5204     return nullptr;
5205 
5206   case Intrinsic::init_trampoline: {
5207     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5208 
5209     SDValue Ops[6];
5210     Ops[0] = getRoot();
5211     Ops[1] = getValue(I.getArgOperand(0));
5212     Ops[2] = getValue(I.getArgOperand(1));
5213     Ops[3] = getValue(I.getArgOperand(2));
5214     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5215     Ops[5] = DAG.getSrcValue(F);
5216 
5217     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5218 
5219     DAG.setRoot(Res);
5220     return nullptr;
5221   }
5222   case Intrinsic::adjust_trampoline: {
5223     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5224                              TLI.getPointerTy(DAG.getDataLayout()),
5225                              getValue(I.getArgOperand(0))));
5226     return nullptr;
5227   }
5228   case Intrinsic::gcroot: {
5229     MachineFunction &MF = DAG.getMachineFunction();
5230     const Function *F = MF.getFunction();
5231     (void)F;
5232     assert(F->hasGC() &&
5233            "only valid in functions with gc specified, enforced by Verifier");
5234     assert(GFI && "implied by previous");
5235     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5236     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5237 
5238     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5239     GFI->addStackRoot(FI->getIndex(), TypeMap);
5240     return nullptr;
5241   }
5242   case Intrinsic::gcread:
5243   case Intrinsic::gcwrite:
5244     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5245   case Intrinsic::flt_rounds:
5246     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5247     return nullptr;
5248 
5249   case Intrinsic::expect: {
5250     // Just replace __builtin_expect(exp, c) with EXP.
5251     setValue(&I, getValue(I.getArgOperand(0)));
5252     return nullptr;
5253   }
5254 
5255   case Intrinsic::debugtrap:
5256   case Intrinsic::trap: {
5257     StringRef TrapFuncName =
5258         I.getAttributes()
5259             .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
5260             .getValueAsString();
5261     if (TrapFuncName.empty()) {
5262       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5263         ISD::TRAP : ISD::DEBUGTRAP;
5264       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5265       return nullptr;
5266     }
5267     TargetLowering::ArgListTy Args;
5268 
5269     TargetLowering::CallLoweringInfo CLI(DAG);
5270     CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
5271         CallingConv::C, I.getType(),
5272         DAG.getExternalSymbol(TrapFuncName.data(),
5273                               TLI.getPointerTy(DAG.getDataLayout())),
5274         std::move(Args), 0);
5275 
5276     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5277     DAG.setRoot(Result.second);
5278     return nullptr;
5279   }
5280 
5281   case Intrinsic::uadd_with_overflow:
5282   case Intrinsic::sadd_with_overflow:
5283   case Intrinsic::usub_with_overflow:
5284   case Intrinsic::ssub_with_overflow:
5285   case Intrinsic::umul_with_overflow:
5286   case Intrinsic::smul_with_overflow: {
5287     ISD::NodeType Op;
5288     switch (Intrinsic) {
5289     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5290     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5291     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5292     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5293     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5294     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5295     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5296     }
5297     SDValue Op1 = getValue(I.getArgOperand(0));
5298     SDValue Op2 = getValue(I.getArgOperand(1));
5299 
5300     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5301     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5302     return nullptr;
5303   }
5304   case Intrinsic::prefetch: {
5305     SDValue Ops[5];
5306     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5307     Ops[0] = getRoot();
5308     Ops[1] = getValue(I.getArgOperand(0));
5309     Ops[2] = getValue(I.getArgOperand(1));
5310     Ops[3] = getValue(I.getArgOperand(2));
5311     Ops[4] = getValue(I.getArgOperand(3));
5312     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5313                                         DAG.getVTList(MVT::Other), Ops,
5314                                         EVT::getIntegerVT(*Context, 8),
5315                                         MachinePointerInfo(I.getArgOperand(0)),
5316                                         0, /* align */
5317                                         false, /* volatile */
5318                                         rw==0, /* read */
5319                                         rw==1)); /* write */
5320     return nullptr;
5321   }
5322   case Intrinsic::lifetime_start:
5323   case Intrinsic::lifetime_end: {
5324     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5325     // Stack coloring is not enabled in O0, discard region information.
5326     if (TM.getOptLevel() == CodeGenOpt::None)
5327       return nullptr;
5328 
5329     SmallVector<Value *, 4> Allocas;
5330     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5331 
5332     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5333            E = Allocas.end(); Object != E; ++Object) {
5334       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5335 
5336       // Could not find an Alloca.
5337       if (!LifetimeObject)
5338         continue;
5339 
5340       // First check that the Alloca is static, otherwise it won't have a
5341       // valid frame index.
5342       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5343       if (SI == FuncInfo.StaticAllocaMap.end())
5344         return nullptr;
5345 
5346       int FI = SI->second;
5347 
5348       SDValue Ops[2];
5349       Ops[0] = getRoot();
5350       Ops[1] =
5351           DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
5352       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5353 
5354       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5355       DAG.setRoot(Res);
5356     }
5357     return nullptr;
5358   }
5359   case Intrinsic::invariant_start:
5360     // Discard region information.
5361     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5362     return nullptr;
5363   case Intrinsic::invariant_end:
5364     // Discard region information.
5365     return nullptr;
5366   case Intrinsic::stackprotectorcheck: {
5367     // Do not actually emit anything for this basic block. Instead we initialize
5368     // the stack protector descriptor and export the guard variable so we can
5369     // access it in FinishBasicBlock.
5370     const BasicBlock *BB = I.getParent();
5371     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5372     ExportFromCurrentBlock(SPDescriptor.getGuard());
5373 
5374     // Flush our exports since we are going to process a terminator.
5375     (void)getControlRoot();
5376     return nullptr;
5377   }
5378   case Intrinsic::clear_cache:
5379     return TLI.getClearCacheBuiltinName();
5380   case Intrinsic::donothing:
5381     // ignore
5382     return nullptr;
5383   case Intrinsic::experimental_stackmap: {
5384     visitStackmap(I);
5385     return nullptr;
5386   }
5387   case Intrinsic::experimental_patchpoint_void:
5388   case Intrinsic::experimental_patchpoint_i64: {
5389     visitPatchpoint(&I);
5390     return nullptr;
5391   }
5392   case Intrinsic::experimental_gc_statepoint: {
5393     LowerStatepoint(ImmutableStatepoint(&I));
5394     return nullptr;
5395   }
5396   case Intrinsic::experimental_gc_result: {
5397     visitGCResult(I);
5398     return nullptr;
5399   }
5400   case Intrinsic::experimental_gc_relocate: {
5401     visitGCRelocate(cast<GCRelocateInst>(I));
5402     return nullptr;
5403   }
5404   case Intrinsic::instrprof_increment:
5405     llvm_unreachable("instrprof failed to lower an increment");
5406   case Intrinsic::instrprof_value_profile:
5407     llvm_unreachable("instrprof failed to lower a value profiling call");
5408   case Intrinsic::localescape: {
5409     MachineFunction &MF = DAG.getMachineFunction();
5410     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5411 
5412     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5413     // is the same on all targets.
5414     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5415       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5416       if (isa<ConstantPointerNull>(Arg))
5417         continue; // Skip null pointers. They represent a hole in index space.
5418       AllocaInst *Slot = cast<AllocaInst>(Arg);
5419       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5420              "can only escape static allocas");
5421       int FI = FuncInfo.StaticAllocaMap[Slot];
5422       MCSymbol *FrameAllocSym =
5423           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5424               GlobalValue::getRealLinkageName(MF.getName()), Idx);
5425       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5426               TII->get(TargetOpcode::LOCAL_ESCAPE))
5427           .addSym(FrameAllocSym)
5428           .addFrameIndex(FI);
5429     }
5430 
5431     return nullptr;
5432   }
5433 
5434   case Intrinsic::localrecover: {
5435     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5436     MachineFunction &MF = DAG.getMachineFunction();
5437     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5438 
5439     // Get the symbol that defines the frame offset.
5440     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5441     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5442     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5443     MCSymbol *FrameAllocSym =
5444         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5445             GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
5446 
5447     // Create a MCSymbol for the label to avoid any target lowering
5448     // that would make this PC relative.
5449     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5450     SDValue OffsetVal =
5451         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5452 
5453     // Add the offset to the FP.
5454     Value *FP = I.getArgOperand(1);
5455     SDValue FPVal = getValue(FP);
5456     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5457     setValue(&I, Add);
5458 
5459     return nullptr;
5460   }
5461 
5462   case Intrinsic::eh_exceptionpointer:
5463   case Intrinsic::eh_exceptioncode: {
5464     // Get the exception pointer vreg, copy from it, and resize it to fit.
5465     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5466     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5467     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5468     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5469     SDValue N =
5470         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5471     if (Intrinsic == Intrinsic::eh_exceptioncode)
5472       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5473     setValue(&I, N);
5474     return nullptr;
5475   }
5476 
5477   case Intrinsic::experimental_deoptimize:
5478     LowerDeoptimizeCall(&I);
5479     return nullptr;
5480   }
5481 }
5482 
5483 std::pair<SDValue, SDValue>
5484 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5485                                     const BasicBlock *EHPadBB) {
5486   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5487   MCSymbol *BeginLabel = nullptr;
5488 
5489   if (EHPadBB) {
5490     // Insert a label before the invoke call to mark the try range.  This can be
5491     // used to detect deletion of the invoke via the MachineModuleInfo.
5492     BeginLabel = MMI.getContext().createTempSymbol();
5493 
5494     // For SjLj, keep track of which landing pads go with which invokes
5495     // so as to maintain the ordering of pads in the LSDA.
5496     unsigned CallSiteIndex = MMI.getCurrentCallSite();
5497     if (CallSiteIndex) {
5498       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5499       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5500 
5501       // Now that the call site is handled, stop tracking it.
5502       MMI.setCurrentCallSite(0);
5503     }
5504 
5505     // Both PendingLoads and PendingExports must be flushed here;
5506     // this call might not return.
5507     (void)getRoot();
5508     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5509 
5510     CLI.setChain(getRoot());
5511   }
5512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5513   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5514 
5515   assert((CLI.IsTailCall || Result.second.getNode()) &&
5516          "Non-null chain expected with non-tail call!");
5517   assert((Result.second.getNode() || !Result.first.getNode()) &&
5518          "Null value expected with tail call!");
5519 
5520   if (!Result.second.getNode()) {
5521     // As a special case, a null chain means that a tail call has been emitted
5522     // and the DAG root is already updated.
5523     HasTailCall = true;
5524 
5525     // Since there's no actual continuation from this block, nothing can be
5526     // relying on us setting vregs for them.
5527     PendingExports.clear();
5528   } else {
5529     DAG.setRoot(Result.second);
5530   }
5531 
5532   if (EHPadBB) {
5533     // Insert a label at the end of the invoke call to mark the try range.  This
5534     // can be used to detect deletion of the invoke via the MachineModuleInfo.
5535     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5536     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5537 
5538     // Inform MachineModuleInfo of range.
5539     if (MMI.hasEHFunclets()) {
5540       assert(CLI.CS);
5541       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
5542       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
5543                                 BeginLabel, EndLabel);
5544     } else {
5545       MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5546     }
5547   }
5548 
5549   return Result;
5550 }
5551 
5552 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5553                                       bool isTailCall,
5554                                       const BasicBlock *EHPadBB) {
5555   FunctionType *FTy = CS.getFunctionType();
5556   Type *RetTy = CS.getType();
5557 
5558   TargetLowering::ArgListTy Args;
5559   TargetLowering::ArgListEntry Entry;
5560   Args.reserve(CS.arg_size());
5561 
5562   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5563        i != e; ++i) {
5564     const Value *V = *i;
5565 
5566     // Skip empty types
5567     if (V->getType()->isEmptyTy())
5568       continue;
5569 
5570     SDValue ArgNode = getValue(V);
5571     Entry.Node = ArgNode; Entry.Ty = V->getType();
5572 
5573     // Skip the first return-type Attribute to get to params.
5574     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5575     Args.push_back(Entry);
5576 
5577     // If we have an explicit sret argument that is an Instruction, (i.e., it
5578     // might point to function-local memory), we can't meaningfully tail-call.
5579     if (Entry.isSRet && isa<Instruction>(V))
5580       isTailCall = false;
5581   }
5582 
5583   // Check if target-independent constraints permit a tail call here.
5584   // Target-dependent constraints are checked within TLI->LowerCallTo.
5585   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5586     isTailCall = false;
5587 
5588   TargetLowering::CallLoweringInfo CLI(DAG);
5589   CLI.setDebugLoc(getCurSDLoc())
5590       .setChain(getRoot())
5591       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5592       .setTailCall(isTailCall)
5593       .setConvergent(CS.isConvergent());
5594   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5595 
5596   if (Result.first.getNode()) {
5597     const Instruction *Inst = CS.getInstruction();
5598     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
5599     setValue(Inst, Result.first);
5600   }
5601 }
5602 
5603 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5604 /// value is equal or not-equal to zero.
5605 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5606   for (const User *U : V->users()) {
5607     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5608       if (IC->isEquality())
5609         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5610           if (C->isNullValue())
5611             continue;
5612     // Unknown instruction.
5613     return false;
5614   }
5615   return true;
5616 }
5617 
5618 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5619                              Type *LoadTy,
5620                              SelectionDAGBuilder &Builder) {
5621 
5622   // Check to see if this load can be trivially constant folded, e.g. if the
5623   // input is from a string literal.
5624   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5625     // Cast pointer to the type we really want to load.
5626     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5627                                          PointerType::getUnqual(LoadTy));
5628 
5629     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5630             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
5631       return Builder.getValue(LoadCst);
5632   }
5633 
5634   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5635   // still constant memory, the input chain can be the entry node.
5636   SDValue Root;
5637   bool ConstantMemory = false;
5638 
5639   // Do not serialize (non-volatile) loads of constant memory with anything.
5640   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5641     Root = Builder.DAG.getEntryNode();
5642     ConstantMemory = true;
5643   } else {
5644     // Do not serialize non-volatile loads against each other.
5645     Root = Builder.DAG.getRoot();
5646   }
5647 
5648   SDValue Ptr = Builder.getValue(PtrVal);
5649   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5650                                         Ptr, MachinePointerInfo(PtrVal),
5651                                         false /*volatile*/,
5652                                         false /*nontemporal*/,
5653                                         false /*isinvariant*/, 1 /* align=1 */);
5654 
5655   if (!ConstantMemory)
5656     Builder.PendingLoads.push_back(LoadVal.getValue(1));
5657   return LoadVal;
5658 }
5659 
5660 /// processIntegerCallValue - Record the value for an instruction that
5661 /// produces an integer result, converting the type where necessary.
5662 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5663                                                   SDValue Value,
5664                                                   bool IsSigned) {
5665   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5666                                                     I.getType(), true);
5667   if (IsSigned)
5668     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5669   else
5670     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5671   setValue(&I, Value);
5672 }
5673 
5674 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5675 /// If so, return true and lower it, otherwise return false and it will be
5676 /// lowered like a normal call.
5677 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5678   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5679   if (I.getNumArgOperands() != 3)
5680     return false;
5681 
5682   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5683   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5684       !I.getArgOperand(2)->getType()->isIntegerTy() ||
5685       !I.getType()->isIntegerTy())
5686     return false;
5687 
5688   const Value *Size = I.getArgOperand(2);
5689   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5690   if (CSize && CSize->getZExtValue() == 0) {
5691     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5692                                                           I.getType(), true);
5693     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5694     return true;
5695   }
5696 
5697   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5698   std::pair<SDValue, SDValue> Res =
5699     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5700                                 getValue(LHS), getValue(RHS), getValue(Size),
5701                                 MachinePointerInfo(LHS),
5702                                 MachinePointerInfo(RHS));
5703   if (Res.first.getNode()) {
5704     processIntegerCallValue(I, Res.first, true);
5705     PendingLoads.push_back(Res.second);
5706     return true;
5707   }
5708 
5709   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5710   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5711   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5712     bool ActuallyDoIt = true;
5713     MVT LoadVT;
5714     Type *LoadTy;
5715     switch (CSize->getZExtValue()) {
5716     default:
5717       LoadVT = MVT::Other;
5718       LoadTy = nullptr;
5719       ActuallyDoIt = false;
5720       break;
5721     case 2:
5722       LoadVT = MVT::i16;
5723       LoadTy = Type::getInt16Ty(CSize->getContext());
5724       break;
5725     case 4:
5726       LoadVT = MVT::i32;
5727       LoadTy = Type::getInt32Ty(CSize->getContext());
5728       break;
5729     case 8:
5730       LoadVT = MVT::i64;
5731       LoadTy = Type::getInt64Ty(CSize->getContext());
5732       break;
5733         /*
5734     case 16:
5735       LoadVT = MVT::v4i32;
5736       LoadTy = Type::getInt32Ty(CSize->getContext());
5737       LoadTy = VectorType::get(LoadTy, 4);
5738       break;
5739          */
5740     }
5741 
5742     // This turns into unaligned loads.  We only do this if the target natively
5743     // supports the MVT we'll be loading or if it is small enough (<= 4) that
5744     // we'll only produce a small number of byte loads.
5745 
5746     // Require that we can find a legal MVT, and only do this if the target
5747     // supports unaligned loads of that type.  Expanding into byte loads would
5748     // bloat the code.
5749     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5750     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5751       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5752       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5753       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5754       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5755       // TODO: Check alignment of src and dest ptrs.
5756       if (!TLI.isTypeLegal(LoadVT) ||
5757           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5758           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5759         ActuallyDoIt = false;
5760     }
5761 
5762     if (ActuallyDoIt) {
5763       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5764       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5765 
5766       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5767                                  ISD::SETNE);
5768       processIntegerCallValue(I, Res, false);
5769       return true;
5770     }
5771   }
5772 
5773 
5774   return false;
5775 }
5776 
5777 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5778 /// form.  If so, return true and lower it, otherwise return false and it
5779 /// will be lowered like a normal call.
5780 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5781   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
5782   if (I.getNumArgOperands() != 3)
5783     return false;
5784 
5785   const Value *Src = I.getArgOperand(0);
5786   const Value *Char = I.getArgOperand(1);
5787   const Value *Length = I.getArgOperand(2);
5788   if (!Src->getType()->isPointerTy() ||
5789       !Char->getType()->isIntegerTy() ||
5790       !Length->getType()->isIntegerTy() ||
5791       !I.getType()->isPointerTy())
5792     return false;
5793 
5794   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5795   std::pair<SDValue, SDValue> Res =
5796     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5797                                 getValue(Src), getValue(Char), getValue(Length),
5798                                 MachinePointerInfo(Src));
5799   if (Res.first.getNode()) {
5800     setValue(&I, Res.first);
5801     PendingLoads.push_back(Res.second);
5802     return true;
5803   }
5804 
5805   return false;
5806 }
5807 
5808 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5809 /// optimized form.  If so, return true and lower it, otherwise return false
5810 /// and it will be lowered like a normal call.
5811 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5812   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
5813   if (I.getNumArgOperands() != 2)
5814     return false;
5815 
5816   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5817   if (!Arg0->getType()->isPointerTy() ||
5818       !Arg1->getType()->isPointerTy() ||
5819       !I.getType()->isPointerTy())
5820     return false;
5821 
5822   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5823   std::pair<SDValue, SDValue> Res =
5824     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5825                                 getValue(Arg0), getValue(Arg1),
5826                                 MachinePointerInfo(Arg0),
5827                                 MachinePointerInfo(Arg1), isStpcpy);
5828   if (Res.first.getNode()) {
5829     setValue(&I, Res.first);
5830     DAG.setRoot(Res.second);
5831     return true;
5832   }
5833 
5834   return false;
5835 }
5836 
5837 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5838 /// If so, return true and lower it, otherwise return false and it will be
5839 /// lowered like a normal call.
5840 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5841   // Verify that the prototype makes sense.  int strcmp(void*,void*)
5842   if (I.getNumArgOperands() != 2)
5843     return false;
5844 
5845   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5846   if (!Arg0->getType()->isPointerTy() ||
5847       !Arg1->getType()->isPointerTy() ||
5848       !I.getType()->isIntegerTy())
5849     return false;
5850 
5851   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5852   std::pair<SDValue, SDValue> Res =
5853     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5854                                 getValue(Arg0), getValue(Arg1),
5855                                 MachinePointerInfo(Arg0),
5856                                 MachinePointerInfo(Arg1));
5857   if (Res.first.getNode()) {
5858     processIntegerCallValue(I, Res.first, true);
5859     PendingLoads.push_back(Res.second);
5860     return true;
5861   }
5862 
5863   return false;
5864 }
5865 
5866 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5867 /// form.  If so, return true and lower it, otherwise return false and it
5868 /// will be lowered like a normal call.
5869 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5870   // Verify that the prototype makes sense.  size_t strlen(char *)
5871   if (I.getNumArgOperands() != 1)
5872     return false;
5873 
5874   const Value *Arg0 = I.getArgOperand(0);
5875   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5876     return false;
5877 
5878   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5879   std::pair<SDValue, SDValue> Res =
5880     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5881                                 getValue(Arg0), MachinePointerInfo(Arg0));
5882   if (Res.first.getNode()) {
5883     processIntegerCallValue(I, Res.first, false);
5884     PendingLoads.push_back(Res.second);
5885     return true;
5886   }
5887 
5888   return false;
5889 }
5890 
5891 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5892 /// form.  If so, return true and lower it, otherwise return false and it
5893 /// will be lowered like a normal call.
5894 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5895   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
5896   if (I.getNumArgOperands() != 2)
5897     return false;
5898 
5899   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5900   if (!Arg0->getType()->isPointerTy() ||
5901       !Arg1->getType()->isIntegerTy() ||
5902       !I.getType()->isIntegerTy())
5903     return false;
5904 
5905   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5906   std::pair<SDValue, SDValue> Res =
5907     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5908                                  getValue(Arg0), getValue(Arg1),
5909                                  MachinePointerInfo(Arg0));
5910   if (Res.first.getNode()) {
5911     processIntegerCallValue(I, Res.first, false);
5912     PendingLoads.push_back(Res.second);
5913     return true;
5914   }
5915 
5916   return false;
5917 }
5918 
5919 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5920 /// operation (as expected), translate it to an SDNode with the specified opcode
5921 /// and return true.
5922 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5923                                               unsigned Opcode) {
5924   // Sanity check that it really is a unary floating-point call.
5925   if (I.getNumArgOperands() != 1 ||
5926       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5927       I.getType() != I.getArgOperand(0)->getType() ||
5928       !I.onlyReadsMemory())
5929     return false;
5930 
5931   SDValue Tmp = getValue(I.getArgOperand(0));
5932   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5933   return true;
5934 }
5935 
5936 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5937 /// operation (as expected), translate it to an SDNode with the specified opcode
5938 /// and return true.
5939 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5940                                                unsigned Opcode) {
5941   // Sanity check that it really is a binary floating-point call.
5942   if (I.getNumArgOperands() != 2 ||
5943       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5944       I.getType() != I.getArgOperand(0)->getType() ||
5945       I.getType() != I.getArgOperand(1)->getType() ||
5946       !I.onlyReadsMemory())
5947     return false;
5948 
5949   SDValue Tmp0 = getValue(I.getArgOperand(0));
5950   SDValue Tmp1 = getValue(I.getArgOperand(1));
5951   EVT VT = Tmp0.getValueType();
5952   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5953   return true;
5954 }
5955 
5956 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5957   // Handle inline assembly differently.
5958   if (isa<InlineAsm>(I.getCalledValue())) {
5959     visitInlineAsm(&I);
5960     return;
5961   }
5962 
5963   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5964   ComputeUsesVAFloatArgument(I, &MMI);
5965 
5966   const char *RenameFn = nullptr;
5967   if (Function *F = I.getCalledFunction()) {
5968     if (F->isDeclaration()) {
5969       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5970         if (unsigned IID = II->getIntrinsicID(F)) {
5971           RenameFn = visitIntrinsicCall(I, IID);
5972           if (!RenameFn)
5973             return;
5974         }
5975       }
5976       if (Intrinsic::ID IID = F->getIntrinsicID()) {
5977         RenameFn = visitIntrinsicCall(I, IID);
5978         if (!RenameFn)
5979           return;
5980       }
5981     }
5982 
5983     // Check for well-known libc/libm calls.  If the function is internal, it
5984     // can't be a library call.
5985     LibFunc::Func Func;
5986     if (!F->hasLocalLinkage() && F->hasName() &&
5987         LibInfo->getLibFunc(F->getName(), Func) &&
5988         LibInfo->hasOptimizedCodeGen(Func)) {
5989       switch (Func) {
5990       default: break;
5991       case LibFunc::copysign:
5992       case LibFunc::copysignf:
5993       case LibFunc::copysignl:
5994         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
5995             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5996             I.getType() == I.getArgOperand(0)->getType() &&
5997             I.getType() == I.getArgOperand(1)->getType() &&
5998             I.onlyReadsMemory()) {
5999           SDValue LHS = getValue(I.getArgOperand(0));
6000           SDValue RHS = getValue(I.getArgOperand(1));
6001           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6002                                    LHS.getValueType(), LHS, RHS));
6003           return;
6004         }
6005         break;
6006       case LibFunc::fabs:
6007       case LibFunc::fabsf:
6008       case LibFunc::fabsl:
6009         if (visitUnaryFloatCall(I, ISD::FABS))
6010           return;
6011         break;
6012       case LibFunc::fmin:
6013       case LibFunc::fminf:
6014       case LibFunc::fminl:
6015         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6016           return;
6017         break;
6018       case LibFunc::fmax:
6019       case LibFunc::fmaxf:
6020       case LibFunc::fmaxl:
6021         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6022           return;
6023         break;
6024       case LibFunc::sin:
6025       case LibFunc::sinf:
6026       case LibFunc::sinl:
6027         if (visitUnaryFloatCall(I, ISD::FSIN))
6028           return;
6029         break;
6030       case LibFunc::cos:
6031       case LibFunc::cosf:
6032       case LibFunc::cosl:
6033         if (visitUnaryFloatCall(I, ISD::FCOS))
6034           return;
6035         break;
6036       case LibFunc::sqrt:
6037       case LibFunc::sqrtf:
6038       case LibFunc::sqrtl:
6039       case LibFunc::sqrt_finite:
6040       case LibFunc::sqrtf_finite:
6041       case LibFunc::sqrtl_finite:
6042         if (visitUnaryFloatCall(I, ISD::FSQRT))
6043           return;
6044         break;
6045       case LibFunc::floor:
6046       case LibFunc::floorf:
6047       case LibFunc::floorl:
6048         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6049           return;
6050         break;
6051       case LibFunc::nearbyint:
6052       case LibFunc::nearbyintf:
6053       case LibFunc::nearbyintl:
6054         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6055           return;
6056         break;
6057       case LibFunc::ceil:
6058       case LibFunc::ceilf:
6059       case LibFunc::ceill:
6060         if (visitUnaryFloatCall(I, ISD::FCEIL))
6061           return;
6062         break;
6063       case LibFunc::rint:
6064       case LibFunc::rintf:
6065       case LibFunc::rintl:
6066         if (visitUnaryFloatCall(I, ISD::FRINT))
6067           return;
6068         break;
6069       case LibFunc::round:
6070       case LibFunc::roundf:
6071       case LibFunc::roundl:
6072         if (visitUnaryFloatCall(I, ISD::FROUND))
6073           return;
6074         break;
6075       case LibFunc::trunc:
6076       case LibFunc::truncf:
6077       case LibFunc::truncl:
6078         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6079           return;
6080         break;
6081       case LibFunc::log2:
6082       case LibFunc::log2f:
6083       case LibFunc::log2l:
6084         if (visitUnaryFloatCall(I, ISD::FLOG2))
6085           return;
6086         break;
6087       case LibFunc::exp2:
6088       case LibFunc::exp2f:
6089       case LibFunc::exp2l:
6090         if (visitUnaryFloatCall(I, ISD::FEXP2))
6091           return;
6092         break;
6093       case LibFunc::memcmp:
6094         if (visitMemCmpCall(I))
6095           return;
6096         break;
6097       case LibFunc::memchr:
6098         if (visitMemChrCall(I))
6099           return;
6100         break;
6101       case LibFunc::strcpy:
6102         if (visitStrCpyCall(I, false))
6103           return;
6104         break;
6105       case LibFunc::stpcpy:
6106         if (visitStrCpyCall(I, true))
6107           return;
6108         break;
6109       case LibFunc::strcmp:
6110         if (visitStrCmpCall(I))
6111           return;
6112         break;
6113       case LibFunc::strlen:
6114         if (visitStrLenCall(I))
6115           return;
6116         break;
6117       case LibFunc::strnlen:
6118         if (visitStrNLenCall(I))
6119           return;
6120         break;
6121       }
6122     }
6123   }
6124 
6125   SDValue Callee;
6126   if (!RenameFn)
6127     Callee = getValue(I.getCalledValue());
6128   else
6129     Callee = DAG.getExternalSymbol(
6130         RenameFn,
6131         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6132 
6133   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6134   // have to do anything here to lower funclet bundles.
6135   assert(!I.hasOperandBundlesOtherThan(
6136              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6137          "Cannot lower calls with arbitrary operand bundles!");
6138 
6139   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6140     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6141   else
6142     // Check if we can potentially perform a tail call. More detailed checking
6143     // is be done within LowerCallTo, after more information about the call is
6144     // known.
6145     LowerCallTo(&I, Callee, I.isTailCall());
6146 }
6147 
6148 namespace {
6149 
6150 /// AsmOperandInfo - This contains information for each constraint that we are
6151 /// lowering.
6152 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6153 public:
6154   /// CallOperand - If this is the result output operand or a clobber
6155   /// this is null, otherwise it is the incoming operand to the CallInst.
6156   /// This gets modified as the asm is processed.
6157   SDValue CallOperand;
6158 
6159   /// AssignedRegs - If this is a register or register class operand, this
6160   /// contains the set of register corresponding to the operand.
6161   RegsForValue AssignedRegs;
6162 
6163   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6164     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6165   }
6166 
6167   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6168   /// corresponds to.  If there is no Value* for this operand, it returns
6169   /// MVT::Other.
6170   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6171                            const DataLayout &DL) const {
6172     if (!CallOperandVal) return MVT::Other;
6173 
6174     if (isa<BasicBlock>(CallOperandVal))
6175       return TLI.getPointerTy(DL);
6176 
6177     llvm::Type *OpTy = CallOperandVal->getType();
6178 
6179     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6180     // If this is an indirect operand, the operand is a pointer to the
6181     // accessed type.
6182     if (isIndirect) {
6183       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6184       if (!PtrTy)
6185         report_fatal_error("Indirect operand for inline asm not a pointer!");
6186       OpTy = PtrTy->getElementType();
6187     }
6188 
6189     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6190     if (StructType *STy = dyn_cast<StructType>(OpTy))
6191       if (STy->getNumElements() == 1)
6192         OpTy = STy->getElementType(0);
6193 
6194     // If OpTy is not a single value, it may be a struct/union that we
6195     // can tile with integers.
6196     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6197       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6198       switch (BitSize) {
6199       default: break;
6200       case 1:
6201       case 8:
6202       case 16:
6203       case 32:
6204       case 64:
6205       case 128:
6206         OpTy = IntegerType::get(Context, BitSize);
6207         break;
6208       }
6209     }
6210 
6211     return TLI.getValueType(DL, OpTy, true);
6212   }
6213 };
6214 
6215 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6216 
6217 } // end anonymous namespace
6218 
6219 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6220 /// specified operand.  We prefer to assign virtual registers, to allow the
6221 /// register allocator to handle the assignment process.  However, if the asm
6222 /// uses features that we can't model on machineinstrs, we have SDISel do the
6223 /// allocation.  This produces generally horrible, but correct, code.
6224 ///
6225 ///   OpInfo describes the operand.
6226 ///
6227 static void GetRegistersForValue(SelectionDAG &DAG,
6228                                  const TargetLowering &TLI,
6229                                  SDLoc DL,
6230                                  SDISelAsmOperandInfo &OpInfo) {
6231   LLVMContext &Context = *DAG.getContext();
6232 
6233   MachineFunction &MF = DAG.getMachineFunction();
6234   SmallVector<unsigned, 4> Regs;
6235 
6236   // If this is a constraint for a single physreg, or a constraint for a
6237   // register class, find it.
6238   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6239       TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
6240                                        OpInfo.ConstraintCode,
6241                                        OpInfo.ConstraintVT);
6242 
6243   unsigned NumRegs = 1;
6244   if (OpInfo.ConstraintVT != MVT::Other) {
6245     // If this is a FP input in an integer register (or visa versa) insert a bit
6246     // cast of the input value.  More generally, handle any case where the input
6247     // value disagrees with the register class we plan to stick this in.
6248     if (OpInfo.Type == InlineAsm::isInput &&
6249         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6250       // Try to convert to the first EVT that the reg class contains.  If the
6251       // types are identical size, use a bitcast to convert (e.g. two differing
6252       // vector types).
6253       MVT RegVT = *PhysReg.second->vt_begin();
6254       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6255         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6256                                          RegVT, OpInfo.CallOperand);
6257         OpInfo.ConstraintVT = RegVT;
6258       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6259         // If the input is a FP value and we want it in FP registers, do a
6260         // bitcast to the corresponding integer type.  This turns an f64 value
6261         // into i64, which can be passed with two i32 values on a 32-bit
6262         // machine.
6263         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6264         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6265                                          RegVT, OpInfo.CallOperand);
6266         OpInfo.ConstraintVT = RegVT;
6267       }
6268     }
6269 
6270     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6271   }
6272 
6273   MVT RegVT;
6274   EVT ValueVT = OpInfo.ConstraintVT;
6275 
6276   // If this is a constraint for a specific physical register, like {r17},
6277   // assign it now.
6278   if (unsigned AssignedReg = PhysReg.first) {
6279     const TargetRegisterClass *RC = PhysReg.second;
6280     if (OpInfo.ConstraintVT == MVT::Other)
6281       ValueVT = *RC->vt_begin();
6282 
6283     // Get the actual register value type.  This is important, because the user
6284     // may have asked for (e.g.) the AX register in i32 type.  We need to
6285     // remember that AX is actually i16 to get the right extension.
6286     RegVT = *RC->vt_begin();
6287 
6288     // This is a explicit reference to a physical register.
6289     Regs.push_back(AssignedReg);
6290 
6291     // If this is an expanded reference, add the rest of the regs to Regs.
6292     if (NumRegs != 1) {
6293       TargetRegisterClass::iterator I = RC->begin();
6294       for (; *I != AssignedReg; ++I)
6295         assert(I != RC->end() && "Didn't find reg!");
6296 
6297       // Already added the first reg.
6298       --NumRegs; ++I;
6299       for (; NumRegs; --NumRegs, ++I) {
6300         assert(I != RC->end() && "Ran out of registers to allocate!");
6301         Regs.push_back(*I);
6302       }
6303     }
6304 
6305     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6306     return;
6307   }
6308 
6309   // Otherwise, if this was a reference to an LLVM register class, create vregs
6310   // for this reference.
6311   if (const TargetRegisterClass *RC = PhysReg.second) {
6312     RegVT = *RC->vt_begin();
6313     if (OpInfo.ConstraintVT == MVT::Other)
6314       ValueVT = RegVT;
6315 
6316     // Create the appropriate number of virtual registers.
6317     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6318     for (; NumRegs; --NumRegs)
6319       Regs.push_back(RegInfo.createVirtualRegister(RC));
6320 
6321     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6322     return;
6323   }
6324 
6325   // Otherwise, we couldn't allocate enough registers for this.
6326 }
6327 
6328 /// visitInlineAsm - Handle a call to an InlineAsm object.
6329 ///
6330 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6331   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6332 
6333   /// ConstraintOperands - Information about all of the constraints.
6334   SDISelAsmOperandInfoVector ConstraintOperands;
6335 
6336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6337   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6338       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6339 
6340   bool hasMemory = false;
6341 
6342   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
6343   unsigned ResNo = 0;   // ResNo - The result number of the next output.
6344   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6345     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6346     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6347 
6348     MVT OpVT = MVT::Other;
6349 
6350     // Compute the value type for each operand.
6351     switch (OpInfo.Type) {
6352     case InlineAsm::isOutput:
6353       // Indirect outputs just consume an argument.
6354       if (OpInfo.isIndirect) {
6355         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6356         break;
6357       }
6358 
6359       // The return value of the call is this value.  As such, there is no
6360       // corresponding argument.
6361       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6362       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6363         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6364                                       STy->getElementType(ResNo));
6365       } else {
6366         assert(ResNo == 0 && "Asm only has one result!");
6367         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6368       }
6369       ++ResNo;
6370       break;
6371     case InlineAsm::isInput:
6372       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6373       break;
6374     case InlineAsm::isClobber:
6375       // Nothing to do.
6376       break;
6377     }
6378 
6379     // If this is an input or an indirect output, process the call argument.
6380     // BasicBlocks are labels, currently appearing only in asm's.
6381     if (OpInfo.CallOperandVal) {
6382       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6383         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6384       } else {
6385         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6386       }
6387 
6388       OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
6389                                          DAG.getDataLayout()).getSimpleVT();
6390     }
6391 
6392     OpInfo.ConstraintVT = OpVT;
6393 
6394     // Indirect operand accesses access memory.
6395     if (OpInfo.isIndirect)
6396       hasMemory = true;
6397     else {
6398       for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6399         TargetLowering::ConstraintType
6400           CType = TLI.getConstraintType(OpInfo.Codes[j]);
6401         if (CType == TargetLowering::C_Memory) {
6402           hasMemory = true;
6403           break;
6404         }
6405       }
6406     }
6407   }
6408 
6409   SDValue Chain, Flag;
6410 
6411   // We won't need to flush pending loads if this asm doesn't touch
6412   // memory and is nonvolatile.
6413   if (hasMemory || IA->hasSideEffects())
6414     Chain = getRoot();
6415   else
6416     Chain = DAG.getRoot();
6417 
6418   // Second pass over the constraints: compute which constraint option to use
6419   // and assign registers to constraints that want a specific physreg.
6420   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6421     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6422 
6423     // If this is an output operand with a matching input operand, look up the
6424     // matching input. If their types mismatch, e.g. one is an integer, the
6425     // other is floating point, or their sizes are different, flag it as an
6426     // error.
6427     if (OpInfo.hasMatchingInput()) {
6428       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6429 
6430       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6431         const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6432         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6433             TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6434                                              OpInfo.ConstraintVT);
6435         std::pair<unsigned, const TargetRegisterClass *> InputRC =
6436             TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6437                                              Input.ConstraintVT);
6438         if ((OpInfo.ConstraintVT.isInteger() !=
6439              Input.ConstraintVT.isInteger()) ||
6440             (MatchRC.second != InputRC.second)) {
6441           report_fatal_error("Unsupported asm: input constraint"
6442                              " with a matching output constraint of"
6443                              " incompatible type!");
6444         }
6445         Input.ConstraintVT = OpInfo.ConstraintVT;
6446       }
6447     }
6448 
6449     // Compute the constraint code and ConstraintType to use.
6450     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6451 
6452     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6453         OpInfo.Type == InlineAsm::isClobber)
6454       continue;
6455 
6456     // If this is a memory input, and if the operand is not indirect, do what we
6457     // need to to provide an address for the memory input.
6458     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6459         !OpInfo.isIndirect) {
6460       assert((OpInfo.isMultipleAlternative ||
6461               (OpInfo.Type == InlineAsm::isInput)) &&
6462              "Can only indirectify direct input operands!");
6463 
6464       // Memory operands really want the address of the value.  If we don't have
6465       // an indirect input, put it in the constpool if we can, otherwise spill
6466       // it to a stack slot.
6467       // TODO: This isn't quite right. We need to handle these according to
6468       // the addressing mode that the constraint wants. Also, this may take
6469       // an additional register for the computation and we don't want that
6470       // either.
6471 
6472       // If the operand is a float, integer, or vector constant, spill to a
6473       // constant pool entry to get its address.
6474       const Value *OpVal = OpInfo.CallOperandVal;
6475       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6476           isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6477         OpInfo.CallOperand = DAG.getConstantPool(
6478             cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6479       } else {
6480         // Otherwise, create a stack slot and emit a store to it before the
6481         // asm.
6482         Type *Ty = OpVal->getType();
6483         auto &DL = DAG.getDataLayout();
6484         uint64_t TySize = DL.getTypeAllocSize(Ty);
6485         unsigned Align = DL.getPrefTypeAlignment(Ty);
6486         MachineFunction &MF = DAG.getMachineFunction();
6487         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6488         SDValue StackSlot =
6489             DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
6490         Chain = DAG.getStore(
6491             Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot,
6492             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
6493             false, false, 0);
6494         OpInfo.CallOperand = StackSlot;
6495       }
6496 
6497       // There is no longer a Value* corresponding to this operand.
6498       OpInfo.CallOperandVal = nullptr;
6499 
6500       // It is now an indirect operand.
6501       OpInfo.isIndirect = true;
6502     }
6503 
6504     // If this constraint is for a specific register, allocate it before
6505     // anything else.
6506     if (OpInfo.ConstraintType == TargetLowering::C_Register)
6507       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6508   }
6509 
6510   // Second pass - Loop over all of the operands, assigning virtual or physregs
6511   // to register class operands.
6512   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6513     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6514 
6515     // C_Register operands have already been allocated, Other/Memory don't need
6516     // to be.
6517     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6518       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6519   }
6520 
6521   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6522   std::vector<SDValue> AsmNodeOperands;
6523   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6524   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6525       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
6526 
6527   // If we have a !srcloc metadata node associated with it, we want to attach
6528   // this to the ultimately generated inline asm machineinstr.  To do this, we
6529   // pass in the third operand as this (potentially null) inline asm MDNode.
6530   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6531   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6532 
6533   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6534   // bits as operand 3.
6535   unsigned ExtraInfo = 0;
6536   if (IA->hasSideEffects())
6537     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6538   if (IA->isAlignStack())
6539     ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6540   // Set the asm dialect.
6541   ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6542 
6543   // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6544   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6545     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6546 
6547     // Compute the constraint code and ConstraintType to use.
6548     TLI.ComputeConstraintToUse(OpInfo, SDValue());
6549 
6550     // Ideally, we would only check against memory constraints.  However, the
6551     // meaning of an other constraint can be target-specific and we can't easily
6552     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
6553     // for other constriants as well.
6554     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6555         OpInfo.ConstraintType == TargetLowering::C_Other) {
6556       if (OpInfo.Type == InlineAsm::isInput)
6557         ExtraInfo |= InlineAsm::Extra_MayLoad;
6558       else if (OpInfo.Type == InlineAsm::isOutput)
6559         ExtraInfo |= InlineAsm::Extra_MayStore;
6560       else if (OpInfo.Type == InlineAsm::isClobber)
6561         ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6562     }
6563   }
6564 
6565   AsmNodeOperands.push_back(DAG.getTargetConstant(
6566       ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6567 
6568   // Loop over all of the inputs, copying the operand values into the
6569   // appropriate registers and processing the output regs.
6570   RegsForValue RetValRegs;
6571 
6572   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6573   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6574 
6575   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6576     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6577 
6578     switch (OpInfo.Type) {
6579     case InlineAsm::isOutput: {
6580       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6581           OpInfo.ConstraintType != TargetLowering::C_Register) {
6582         // Memory output, or 'other' output (e.g. 'X' constraint).
6583         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6584 
6585         unsigned ConstraintID =
6586             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6587         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6588                "Failed to convert memory constraint code to constraint id.");
6589 
6590         // Add information to the INLINEASM node to know about this output.
6591         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6592         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6593         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6594                                                         MVT::i32));
6595         AsmNodeOperands.push_back(OpInfo.CallOperand);
6596         break;
6597       }
6598 
6599       // Otherwise, this is a register or register class output.
6600 
6601       // Copy the output from the appropriate register.  Find a register that
6602       // we can use.
6603       if (OpInfo.AssignedRegs.Regs.empty()) {
6604         LLVMContext &Ctx = *DAG.getContext();
6605         Ctx.emitError(CS.getInstruction(),
6606                       "couldn't allocate output register for constraint '" +
6607                           Twine(OpInfo.ConstraintCode) + "'");
6608         return;
6609       }
6610 
6611       // If this is an indirect operand, store through the pointer after the
6612       // asm.
6613       if (OpInfo.isIndirect) {
6614         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6615                                                       OpInfo.CallOperandVal));
6616       } else {
6617         // This is the result value of the call.
6618         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6619         // Concatenate this output onto the outputs list.
6620         RetValRegs.append(OpInfo.AssignedRegs);
6621       }
6622 
6623       // Add information to the INLINEASM node to know that this register is
6624       // set.
6625       OpInfo.AssignedRegs
6626           .AddInlineAsmOperands(OpInfo.isEarlyClobber
6627                                     ? InlineAsm::Kind_RegDefEarlyClobber
6628                                     : InlineAsm::Kind_RegDef,
6629                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6630       break;
6631     }
6632     case InlineAsm::isInput: {
6633       SDValue InOperandVal = OpInfo.CallOperand;
6634 
6635       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6636         // If this is required to match an output register we have already set,
6637         // just use its register.
6638         unsigned OperandNo = OpInfo.getMatchedOperand();
6639 
6640         // Scan until we find the definition we already emitted of this operand.
6641         // When we find it, create a RegsForValue operand.
6642         unsigned CurOp = InlineAsm::Op_FirstOperand;
6643         for (; OperandNo; --OperandNo) {
6644           // Advance to the next operand.
6645           unsigned OpFlag =
6646             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6647           assert((InlineAsm::isRegDefKind(OpFlag) ||
6648                   InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6649                   InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6650           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6651         }
6652 
6653         unsigned OpFlag =
6654           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6655         if (InlineAsm::isRegDefKind(OpFlag) ||
6656             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6657           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6658           if (OpInfo.isIndirect) {
6659             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6660             LLVMContext &Ctx = *DAG.getContext();
6661             Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6662                                                " don't know how to handle tied "
6663                                                "indirect register inputs");
6664             return;
6665           }
6666 
6667           RegsForValue MatchedRegs;
6668           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6669           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6670           MatchedRegs.RegVTs.push_back(RegVT);
6671           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6672           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6673                i != e; ++i) {
6674             if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6675               MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6676             else {
6677               LLVMContext &Ctx = *DAG.getContext();
6678               Ctx.emitError(CS.getInstruction(),
6679                             "inline asm error: This value"
6680                             " type register class is not natively supported!");
6681               return;
6682             }
6683           }
6684           SDLoc dl = getCurSDLoc();
6685           // Use the produced MatchedRegs object to
6686           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6687                                     Chain, &Flag, CS.getInstruction());
6688           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6689                                            true, OpInfo.getMatchedOperand(), dl,
6690                                            DAG, AsmNodeOperands);
6691           break;
6692         }
6693 
6694         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6695         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6696                "Unexpected number of operands");
6697         // Add information to the INLINEASM node to know about this input.
6698         // See InlineAsm.h isUseOperandTiedToDef.
6699         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6700         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6701                                                     OpInfo.getMatchedOperand());
6702         AsmNodeOperands.push_back(DAG.getTargetConstant(
6703             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6704         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6705         break;
6706       }
6707 
6708       // Treat indirect 'X' constraint as memory.
6709       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6710           OpInfo.isIndirect)
6711         OpInfo.ConstraintType = TargetLowering::C_Memory;
6712 
6713       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6714         std::vector<SDValue> Ops;
6715         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6716                                           Ops, DAG);
6717         if (Ops.empty()) {
6718           LLVMContext &Ctx = *DAG.getContext();
6719           Ctx.emitError(CS.getInstruction(),
6720                         "invalid operand for inline asm constraint '" +
6721                             Twine(OpInfo.ConstraintCode) + "'");
6722           return;
6723         }
6724 
6725         // Add information to the INLINEASM node to know about this input.
6726         unsigned ResOpType =
6727           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6728         AsmNodeOperands.push_back(DAG.getTargetConstant(
6729             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6730         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6731         break;
6732       }
6733 
6734       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6735         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6736         assert(InOperandVal.getValueType() ==
6737                    TLI.getPointerTy(DAG.getDataLayout()) &&
6738                "Memory operands expect pointer values");
6739 
6740         unsigned ConstraintID =
6741             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6742         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6743                "Failed to convert memory constraint code to constraint id.");
6744 
6745         // Add information to the INLINEASM node to know about this input.
6746         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6747         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6748         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6749                                                         getCurSDLoc(),
6750                                                         MVT::i32));
6751         AsmNodeOperands.push_back(InOperandVal);
6752         break;
6753       }
6754 
6755       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6756               OpInfo.ConstraintType == TargetLowering::C_Register) &&
6757              "Unknown constraint type!");
6758 
6759       // TODO: Support this.
6760       if (OpInfo.isIndirect) {
6761         LLVMContext &Ctx = *DAG.getContext();
6762         Ctx.emitError(CS.getInstruction(),
6763                       "Don't know how to handle indirect register inputs yet "
6764                       "for constraint '" +
6765                           Twine(OpInfo.ConstraintCode) + "'");
6766         return;
6767       }
6768 
6769       // Copy the input into the appropriate registers.
6770       if (OpInfo.AssignedRegs.Regs.empty()) {
6771         LLVMContext &Ctx = *DAG.getContext();
6772         Ctx.emitError(CS.getInstruction(),
6773                       "couldn't allocate input reg for constraint '" +
6774                           Twine(OpInfo.ConstraintCode) + "'");
6775         return;
6776       }
6777 
6778       SDLoc dl = getCurSDLoc();
6779 
6780       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6781                                         Chain, &Flag, CS.getInstruction());
6782 
6783       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6784                                                dl, DAG, AsmNodeOperands);
6785       break;
6786     }
6787     case InlineAsm::isClobber: {
6788       // Add the clobbered value to the operand list, so that the register
6789       // allocator is aware that the physreg got clobbered.
6790       if (!OpInfo.AssignedRegs.Regs.empty())
6791         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6792                                                  false, 0, getCurSDLoc(), DAG,
6793                                                  AsmNodeOperands);
6794       break;
6795     }
6796     }
6797   }
6798 
6799   // Finish up input operands.  Set the input chain and add the flag last.
6800   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6801   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6802 
6803   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6804                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6805   Flag = Chain.getValue(1);
6806 
6807   // If this asm returns a register value, copy the result from that register
6808   // and set it as the value of the call.
6809   if (!RetValRegs.Regs.empty()) {
6810     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6811                                              Chain, &Flag, CS.getInstruction());
6812 
6813     // FIXME: Why don't we do this for inline asms with MRVs?
6814     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6815       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
6816 
6817       // If any of the results of the inline asm is a vector, it may have the
6818       // wrong width/num elts.  This can happen for register classes that can
6819       // contain multiple different value types.  The preg or vreg allocated may
6820       // not have the same VT as was expected.  Convert it to the right type
6821       // with bit_convert.
6822       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6823         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6824                           ResultType, Val);
6825 
6826       } else if (ResultType != Val.getValueType() &&
6827                  ResultType.isInteger() && Val.getValueType().isInteger()) {
6828         // If a result value was tied to an input value, the computed result may
6829         // have a wider width than the expected result.  Extract the relevant
6830         // portion.
6831         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6832       }
6833 
6834       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6835     }
6836 
6837     setValue(CS.getInstruction(), Val);
6838     // Don't need to use this as a chain in this case.
6839     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6840       return;
6841   }
6842 
6843   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6844 
6845   // Process indirect outputs, first output all of the flagged copies out of
6846   // physregs.
6847   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6848     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6849     const Value *Ptr = IndirectStoresToEmit[i].second;
6850     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6851                                              Chain, &Flag, IA);
6852     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6853   }
6854 
6855   // Emit the non-flagged stores from the physregs.
6856   SmallVector<SDValue, 8> OutChains;
6857   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6858     SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6859                                StoresToEmit[i].first,
6860                                getValue(StoresToEmit[i].second),
6861                                MachinePointerInfo(StoresToEmit[i].second),
6862                                false, false, 0);
6863     OutChains.push_back(Val);
6864   }
6865 
6866   if (!OutChains.empty())
6867     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6868 
6869   DAG.setRoot(Chain);
6870 }
6871 
6872 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6873   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6874                           MVT::Other, getRoot(),
6875                           getValue(I.getArgOperand(0)),
6876                           DAG.getSrcValue(I.getArgOperand(0))));
6877 }
6878 
6879 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6881   const DataLayout &DL = DAG.getDataLayout();
6882   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6883                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
6884                            DAG.getSrcValue(I.getOperand(0)),
6885                            DL.getABITypeAlignment(I.getType()));
6886   setValue(&I, V);
6887   DAG.setRoot(V.getValue(1));
6888 }
6889 
6890 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6891   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6892                           MVT::Other, getRoot(),
6893                           getValue(I.getArgOperand(0)),
6894                           DAG.getSrcValue(I.getArgOperand(0))));
6895 }
6896 
6897 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6898   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6899                           MVT::Other, getRoot(),
6900                           getValue(I.getArgOperand(0)),
6901                           getValue(I.getArgOperand(1)),
6902                           DAG.getSrcValue(I.getArgOperand(0)),
6903                           DAG.getSrcValue(I.getArgOperand(1))));
6904 }
6905 
6906 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
6907                                                     const Instruction &I,
6908                                                     SDValue Op) {
6909   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
6910   if (!Range)
6911     return Op;
6912 
6913   Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
6914   if (!Lo->isNullValue())
6915     return Op;
6916 
6917   Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
6918   unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
6919 
6920   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6921 
6922   SDLoc SL = getCurSDLoc();
6923 
6924   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
6925                              Op, DAG.getValueType(SmallVT));
6926   unsigned NumVals = Op.getNode()->getNumValues();
6927   if (NumVals == 1)
6928     return ZExt;
6929 
6930   SmallVector<SDValue, 4> Ops;
6931 
6932   Ops.push_back(ZExt);
6933   for (unsigned I = 1; I != NumVals; ++I)
6934     Ops.push_back(Op.getValue(I));
6935 
6936   return DAG.getMergeValues(Ops, SL);
6937 }
6938 
6939 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
6940 /// the call being lowered.
6941 ///
6942 /// This is a helper for lowering intrinsics that follow a target calling
6943 /// convention or require stack pointer adjustment. Only a subset of the
6944 /// intrinsic's operands need to participate in the calling convention.
6945 void SelectionDAGBuilder::populateCallLoweringInfo(
6946     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
6947     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
6948     bool IsPatchPoint) {
6949   TargetLowering::ArgListTy Args;
6950   Args.reserve(NumArgs);
6951 
6952   // Populate the argument list.
6953   // Attributes for args start at offset 1, after the return attribute.
6954   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6955        ArgI != ArgE; ++ArgI) {
6956     const Value *V = CS->getOperand(ArgI);
6957 
6958     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6959 
6960     TargetLowering::ArgListEntry Entry;
6961     Entry.Node = getValue(V);
6962     Entry.Ty = V->getType();
6963     Entry.setAttributes(&CS, AttrI);
6964     Args.push_back(Entry);
6965   }
6966 
6967   CLI.setDebugLoc(getCurSDLoc())
6968       .setChain(getRoot())
6969       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args),
6970                  NumArgs)
6971       .setDiscardResult(CS->use_empty())
6972       .setIsPatchPoint(IsPatchPoint);
6973 }
6974 
6975 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6976 /// or patchpoint target node's operand list.
6977 ///
6978 /// Constants are converted to TargetConstants purely as an optimization to
6979 /// avoid constant materialization and register allocation.
6980 ///
6981 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6982 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6983 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6984 /// address materialization and register allocation, but may also be required
6985 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6986 /// alloca in the entry block, then the runtime may assume that the alloca's
6987 /// StackMap location can be read immediately after compilation and that the
6988 /// location is valid at any point during execution (this is similar to the
6989 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6990 /// only available in a register, then the runtime would need to trap when
6991 /// execution reaches the StackMap in order to read the alloca's location.
6992 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6993                                 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6994                                 SelectionDAGBuilder &Builder) {
6995   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6996     SDValue OpVal = Builder.getValue(CS.getArgument(i));
6997     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6998       Ops.push_back(
6999         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7000       Ops.push_back(
7001         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7002     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7003       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7004       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7005           FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
7006     } else
7007       Ops.push_back(OpVal);
7008   }
7009 }
7010 
7011 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7012 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7013   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7014   //                                  [live variables...])
7015 
7016   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7017 
7018   SDValue Chain, InFlag, Callee, NullPtr;
7019   SmallVector<SDValue, 32> Ops;
7020 
7021   SDLoc DL = getCurSDLoc();
7022   Callee = getValue(CI.getCalledValue());
7023   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7024 
7025   // The stackmap intrinsic only records the live variables (the arguemnts
7026   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7027   // intrinsic, this won't be lowered to a function call. This means we don't
7028   // have to worry about calling conventions and target specific lowering code.
7029   // Instead we perform the call lowering right here.
7030   //
7031   // chain, flag = CALLSEQ_START(chain, 0)
7032   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7033   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7034   //
7035   Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7036   InFlag = Chain.getValue(1);
7037 
7038   // Add the <id> and <numBytes> constants.
7039   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7040   Ops.push_back(DAG.getTargetConstant(
7041                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7042   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7043   Ops.push_back(DAG.getTargetConstant(
7044                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7045                   MVT::i32));
7046 
7047   // Push live variables for the stack map.
7048   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7049 
7050   // We are not pushing any register mask info here on the operands list,
7051   // because the stackmap doesn't clobber anything.
7052 
7053   // Push the chain and the glue flag.
7054   Ops.push_back(Chain);
7055   Ops.push_back(InFlag);
7056 
7057   // Create the STACKMAP node.
7058   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7059   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7060   Chain = SDValue(SM, 0);
7061   InFlag = Chain.getValue(1);
7062 
7063   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7064 
7065   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7066 
7067   // Set the root to the target-lowered call chain.
7068   DAG.setRoot(Chain);
7069 
7070   // Inform the Frame Information that we have a stackmap in this function.
7071   FuncInfo.MF->getFrameInfo()->setHasStackMap();
7072 }
7073 
7074 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7075 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7076                                           const BasicBlock *EHPadBB) {
7077   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7078   //                                                 i32 <numBytes>,
7079   //                                                 i8* <target>,
7080   //                                                 i32 <numArgs>,
7081   //                                                 [Args...],
7082   //                                                 [live variables...])
7083 
7084   CallingConv::ID CC = CS.getCallingConv();
7085   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7086   bool HasDef = !CS->getType()->isVoidTy();
7087   SDLoc dl = getCurSDLoc();
7088   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7089 
7090   // Handle immediate and symbolic callees.
7091   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7092     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7093                                    /*isTarget=*/true);
7094   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7095     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7096                                          SDLoc(SymbolicCallee),
7097                                          SymbolicCallee->getValueType(0));
7098 
7099   // Get the real number of arguments participating in the call <numArgs>
7100   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7101   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7102 
7103   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7104   // Intrinsics include all meta-operands up to but not including CC.
7105   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7106   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7107          "Not enough arguments provided to the patchpoint intrinsic");
7108 
7109   // For AnyRegCC the arguments are lowered later on manually.
7110   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7111   Type *ReturnTy =
7112     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7113 
7114   TargetLowering::CallLoweringInfo CLI(DAG);
7115   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7116                            true);
7117   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7118 
7119   SDNode *CallEnd = Result.second.getNode();
7120   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7121     CallEnd = CallEnd->getOperand(0).getNode();
7122 
7123   /// Get a call instruction from the call sequence chain.
7124   /// Tail calls are not allowed.
7125   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7126          "Expected a callseq node.");
7127   SDNode *Call = CallEnd->getOperand(0).getNode();
7128   bool HasGlue = Call->getGluedNode();
7129 
7130   // Replace the target specific call node with the patchable intrinsic.
7131   SmallVector<SDValue, 8> Ops;
7132 
7133   // Add the <id> and <numBytes> constants.
7134   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7135   Ops.push_back(DAG.getTargetConstant(
7136                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7137   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7138   Ops.push_back(DAG.getTargetConstant(
7139                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7140                   MVT::i32));
7141 
7142   // Add the callee.
7143   Ops.push_back(Callee);
7144 
7145   // Adjust <numArgs> to account for any arguments that have been passed on the
7146   // stack instead.
7147   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7148   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7149   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7150   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7151 
7152   // Add the calling convention
7153   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7154 
7155   // Add the arguments we omitted previously. The register allocator should
7156   // place these in any free register.
7157   if (IsAnyRegCC)
7158     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7159       Ops.push_back(getValue(CS.getArgument(i)));
7160 
7161   // Push the arguments from the call instruction up to the register mask.
7162   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7163   Ops.append(Call->op_begin() + 2, e);
7164 
7165   // Push live variables for the stack map.
7166   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7167 
7168   // Push the register mask info.
7169   if (HasGlue)
7170     Ops.push_back(*(Call->op_end()-2));
7171   else
7172     Ops.push_back(*(Call->op_end()-1));
7173 
7174   // Push the chain (this is originally the first operand of the call, but
7175   // becomes now the last or second to last operand).
7176   Ops.push_back(*(Call->op_begin()));
7177 
7178   // Push the glue flag (last operand).
7179   if (HasGlue)
7180     Ops.push_back(*(Call->op_end()-1));
7181 
7182   SDVTList NodeTys;
7183   if (IsAnyRegCC && HasDef) {
7184     // Create the return types based on the intrinsic definition
7185     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7186     SmallVector<EVT, 3> ValueVTs;
7187     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7188     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7189 
7190     // There is always a chain and a glue type at the end
7191     ValueVTs.push_back(MVT::Other);
7192     ValueVTs.push_back(MVT::Glue);
7193     NodeTys = DAG.getVTList(ValueVTs);
7194   } else
7195     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7196 
7197   // Replace the target specific call node with a PATCHPOINT node.
7198   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7199                                          dl, NodeTys, Ops);
7200 
7201   // Update the NodeMap.
7202   if (HasDef) {
7203     if (IsAnyRegCC)
7204       setValue(CS.getInstruction(), SDValue(MN, 0));
7205     else
7206       setValue(CS.getInstruction(), Result.first);
7207   }
7208 
7209   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7210   // call sequence. Furthermore the location of the chain and glue can change
7211   // when the AnyReg calling convention is used and the intrinsic returns a
7212   // value.
7213   if (IsAnyRegCC && HasDef) {
7214     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7215     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7216     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7217   } else
7218     DAG.ReplaceAllUsesWith(Call, MN);
7219   DAG.DeleteNode(Call);
7220 
7221   // Inform the Frame Information that we have a patchpoint in this function.
7222   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7223 }
7224 
7225 /// Returns an AttributeSet representing the attributes applied to the return
7226 /// value of the given call.
7227 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7228   SmallVector<Attribute::AttrKind, 2> Attrs;
7229   if (CLI.RetSExt)
7230     Attrs.push_back(Attribute::SExt);
7231   if (CLI.RetZExt)
7232     Attrs.push_back(Attribute::ZExt);
7233   if (CLI.IsInReg)
7234     Attrs.push_back(Attribute::InReg);
7235 
7236   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7237                            Attrs);
7238 }
7239 
7240 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7241 /// implementation, which just calls LowerCall.
7242 /// FIXME: When all targets are
7243 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7244 std::pair<SDValue, SDValue>
7245 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7246   // Handle the incoming return values from the call.
7247   CLI.Ins.clear();
7248   Type *OrigRetTy = CLI.RetTy;
7249   SmallVector<EVT, 4> RetTys;
7250   SmallVector<uint64_t, 4> Offsets;
7251   auto &DL = CLI.DAG.getDataLayout();
7252   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7253 
7254   SmallVector<ISD::OutputArg, 4> Outs;
7255   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7256 
7257   bool CanLowerReturn =
7258       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7259                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7260 
7261   SDValue DemoteStackSlot;
7262   int DemoteStackIdx = -100;
7263   if (!CanLowerReturn) {
7264     // FIXME: equivalent assert?
7265     // assert(!CS.hasInAllocaArgument() &&
7266     //        "sret demotion is incompatible with inalloca");
7267     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7268     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7269     MachineFunction &MF = CLI.DAG.getMachineFunction();
7270     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7271     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7272 
7273     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
7274     ArgListEntry Entry;
7275     Entry.Node = DemoteStackSlot;
7276     Entry.Ty = StackSlotPtrType;
7277     Entry.isSExt = false;
7278     Entry.isZExt = false;
7279     Entry.isInReg = false;
7280     Entry.isSRet = true;
7281     Entry.isNest = false;
7282     Entry.isByVal = false;
7283     Entry.isReturned = false;
7284     Entry.isSwiftSelf = false;
7285     Entry.Alignment = Align;
7286     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7287     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7288 
7289     // sret demotion isn't compatible with tail-calls, since the sret argument
7290     // points into the callers stack frame.
7291     CLI.IsTailCall = false;
7292   } else {
7293     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7294       EVT VT = RetTys[I];
7295       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7296       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7297       for (unsigned i = 0; i != NumRegs; ++i) {
7298         ISD::InputArg MyFlags;
7299         MyFlags.VT = RegisterVT;
7300         MyFlags.ArgVT = VT;
7301         MyFlags.Used = CLI.IsReturnValueUsed;
7302         if (CLI.RetSExt)
7303           MyFlags.Flags.setSExt();
7304         if (CLI.RetZExt)
7305           MyFlags.Flags.setZExt();
7306         if (CLI.IsInReg)
7307           MyFlags.Flags.setInReg();
7308         CLI.Ins.push_back(MyFlags);
7309       }
7310     }
7311   }
7312 
7313   // Handle all of the outgoing arguments.
7314   CLI.Outs.clear();
7315   CLI.OutVals.clear();
7316   ArgListTy &Args = CLI.getArgs();
7317   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7318     SmallVector<EVT, 4> ValueVTs;
7319     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
7320     Type *FinalType = Args[i].Ty;
7321     if (Args[i].isByVal)
7322       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7323     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7324         FinalType, CLI.CallConv, CLI.IsVarArg);
7325     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7326          ++Value) {
7327       EVT VT = ValueVTs[Value];
7328       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7329       SDValue Op = SDValue(Args[i].Node.getNode(),
7330                            Args[i].Node.getResNo() + Value);
7331       ISD::ArgFlagsTy Flags;
7332       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7333 
7334       if (Args[i].isZExt)
7335         Flags.setZExt();
7336       if (Args[i].isSExt)
7337         Flags.setSExt();
7338       if (Args[i].isInReg)
7339         Flags.setInReg();
7340       if (Args[i].isSRet)
7341         Flags.setSRet();
7342       if (Args[i].isSwiftSelf)
7343         Flags.setSwiftSelf();
7344       if (Args[i].isByVal)
7345         Flags.setByVal();
7346       if (Args[i].isInAlloca) {
7347         Flags.setInAlloca();
7348         // Set the byval flag for CCAssignFn callbacks that don't know about
7349         // inalloca.  This way we can know how many bytes we should've allocated
7350         // and how many bytes a callee cleanup function will pop.  If we port
7351         // inalloca to more targets, we'll have to add custom inalloca handling
7352         // in the various CC lowering callbacks.
7353         Flags.setByVal();
7354       }
7355       if (Args[i].isByVal || Args[i].isInAlloca) {
7356         PointerType *Ty = cast<PointerType>(Args[i].Ty);
7357         Type *ElementTy = Ty->getElementType();
7358         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7359         // For ByVal, alignment should come from FE.  BE will guess if this
7360         // info is not there but there are cases it cannot get right.
7361         unsigned FrameAlign;
7362         if (Args[i].Alignment)
7363           FrameAlign = Args[i].Alignment;
7364         else
7365           FrameAlign = getByValTypeAlignment(ElementTy, DL);
7366         Flags.setByValAlign(FrameAlign);
7367       }
7368       if (Args[i].isNest)
7369         Flags.setNest();
7370       if (NeedsRegBlock)
7371         Flags.setInConsecutiveRegs();
7372       Flags.setOrigAlign(OriginalAlignment);
7373 
7374       MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7375       unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7376       SmallVector<SDValue, 4> Parts(NumParts);
7377       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7378 
7379       if (Args[i].isSExt)
7380         ExtendKind = ISD::SIGN_EXTEND;
7381       else if (Args[i].isZExt)
7382         ExtendKind = ISD::ZERO_EXTEND;
7383 
7384       // Conservatively only handle 'returned' on non-vectors for now
7385       if (Args[i].isReturned && !Op.getValueType().isVector()) {
7386         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7387                "unexpected use of 'returned'");
7388         // Before passing 'returned' to the target lowering code, ensure that
7389         // either the register MVT and the actual EVT are the same size or that
7390         // the return value and argument are extended in the same way; in these
7391         // cases it's safe to pass the argument register value unchanged as the
7392         // return register value (although it's at the target's option whether
7393         // to do so)
7394         // TODO: allow code generation to take advantage of partially preserved
7395         // registers rather than clobbering the entire register when the
7396         // parameter extension method is not compatible with the return
7397         // extension method
7398         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7399             (ExtendKind != ISD::ANY_EXTEND &&
7400              CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7401         Flags.setReturned();
7402       }
7403 
7404       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7405                      CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7406 
7407       for (unsigned j = 0; j != NumParts; ++j) {
7408         // if it isn't first piece, alignment must be 1
7409         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7410                                i < CLI.NumFixedArgs,
7411                                i, j*Parts[j].getValueType().getStoreSize());
7412         if (NumParts > 1 && j == 0)
7413           MyFlags.Flags.setSplit();
7414         else if (j != 0) {
7415           MyFlags.Flags.setOrigAlign(1);
7416           if (j == NumParts - 1)
7417             MyFlags.Flags.setSplitEnd();
7418         }
7419 
7420         CLI.Outs.push_back(MyFlags);
7421         CLI.OutVals.push_back(Parts[j]);
7422       }
7423 
7424       if (NeedsRegBlock && Value == NumValues - 1)
7425         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
7426     }
7427   }
7428 
7429   SmallVector<SDValue, 4> InVals;
7430   CLI.Chain = LowerCall(CLI, InVals);
7431 
7432   // Verify that the target's LowerCall behaved as expected.
7433   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7434          "LowerCall didn't return a valid chain!");
7435   assert((!CLI.IsTailCall || InVals.empty()) &&
7436          "LowerCall emitted a return value for a tail call!");
7437   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7438          "LowerCall didn't emit the correct number of values!");
7439 
7440   // For a tail call, the return value is merely live-out and there aren't
7441   // any nodes in the DAG representing it. Return a special value to
7442   // indicate that a tail call has been emitted and no more Instructions
7443   // should be processed in the current block.
7444   if (CLI.IsTailCall) {
7445     CLI.DAG.setRoot(CLI.Chain);
7446     return std::make_pair(SDValue(), SDValue());
7447   }
7448 
7449   DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7450           assert(InVals[i].getNode() &&
7451                  "LowerCall emitted a null value!");
7452           assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7453                  "LowerCall emitted a value with the wrong type!");
7454         });
7455 
7456   SmallVector<SDValue, 4> ReturnValues;
7457   if (!CanLowerReturn) {
7458     // The instruction result is the result of loading from the
7459     // hidden sret parameter.
7460     SmallVector<EVT, 1> PVTs;
7461     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7462 
7463     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
7464     assert(PVTs.size() == 1 && "Pointers should fit in one register");
7465     EVT PtrVT = PVTs[0];
7466 
7467     unsigned NumValues = RetTys.size();
7468     ReturnValues.resize(NumValues);
7469     SmallVector<SDValue, 4> Chains(NumValues);
7470 
7471     // An aggregate return value cannot wrap around the address space, so
7472     // offsets to its parts don't wrap either.
7473     SDNodeFlags Flags;
7474     Flags.setNoUnsignedWrap(true);
7475 
7476     for (unsigned i = 0; i < NumValues; ++i) {
7477       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7478                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
7479                                                         PtrVT), &Flags);
7480       SDValue L = CLI.DAG.getLoad(
7481           RetTys[i], CLI.DL, CLI.Chain, Add,
7482           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
7483                                             DemoteStackIdx, Offsets[i]),
7484           false, false, false, 1);
7485       ReturnValues[i] = L;
7486       Chains[i] = L.getValue(1);
7487     }
7488 
7489     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7490   } else {
7491     // Collect the legal value parts into potentially illegal values
7492     // that correspond to the original function's return values.
7493     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7494     if (CLI.RetSExt)
7495       AssertOp = ISD::AssertSext;
7496     else if (CLI.RetZExt)
7497       AssertOp = ISD::AssertZext;
7498     unsigned CurReg = 0;
7499     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7500       EVT VT = RetTys[I];
7501       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7502       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7503 
7504       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7505                                               NumRegs, RegisterVT, VT, nullptr,
7506                                               AssertOp));
7507       CurReg += NumRegs;
7508     }
7509 
7510     // For a function returning void, there is no return value. We can't create
7511     // such a node, so we just return a null return value in that case. In
7512     // that case, nothing will actually look at the value.
7513     if (ReturnValues.empty())
7514       return std::make_pair(SDValue(), CLI.Chain);
7515   }
7516 
7517   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7518                                 CLI.DAG.getVTList(RetTys), ReturnValues);
7519   return std::make_pair(Res, CLI.Chain);
7520 }
7521 
7522 void TargetLowering::LowerOperationWrapper(SDNode *N,
7523                                            SmallVectorImpl<SDValue> &Results,
7524                                            SelectionDAG &DAG) const {
7525   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
7526     Results.push_back(Res);
7527 }
7528 
7529 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7530   llvm_unreachable("LowerOperation not implemented for this target!");
7531 }
7532 
7533 void
7534 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7535   SDValue Op = getNonRegisterValue(V);
7536   assert((Op.getOpcode() != ISD::CopyFromReg ||
7537           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7538          "Copy from a reg to the same reg!");
7539   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7540 
7541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7542   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7543                    V->getType());
7544   SDValue Chain = DAG.getEntryNode();
7545 
7546   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7547                               FuncInfo.PreferredExtendType.end())
7548                                  ? ISD::ANY_EXTEND
7549                                  : FuncInfo.PreferredExtendType[V];
7550   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7551   PendingExports.push_back(Chain);
7552 }
7553 
7554 #include "llvm/CodeGen/SelectionDAGISel.h"
7555 
7556 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7557 /// entry block, return true.  This includes arguments used by switches, since
7558 /// the switch may expand into multiple basic blocks.
7559 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7560   // With FastISel active, we may be splitting blocks, so force creation
7561   // of virtual registers for all non-dead arguments.
7562   if (FastISel)
7563     return A->use_empty();
7564 
7565   const BasicBlock &Entry = A->getParent()->front();
7566   for (const User *U : A->users())
7567     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
7568       return false;  // Use not in entry block.
7569 
7570   return true;
7571 }
7572 
7573 void SelectionDAGISel::LowerArguments(const Function &F) {
7574   SelectionDAG &DAG = SDB->DAG;
7575   SDLoc dl = SDB->getCurSDLoc();
7576   const DataLayout &DL = DAG.getDataLayout();
7577   SmallVector<ISD::InputArg, 16> Ins;
7578 
7579   if (!FuncInfo->CanLowerReturn) {
7580     // Put in an sret pointer parameter before all the other parameters.
7581     SmallVector<EVT, 1> ValueVTs;
7582     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7583                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7584 
7585     // NOTE: Assuming that a pointer will never break down to more than one VT
7586     // or one register.
7587     ISD::ArgFlagsTy Flags;
7588     Flags.setSRet();
7589     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7590     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7591                          ISD::InputArg::NoArgIndex, 0);
7592     Ins.push_back(RetArg);
7593   }
7594 
7595   // Set up the incoming argument description vector.
7596   unsigned Idx = 1;
7597   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7598        I != E; ++I, ++Idx) {
7599     SmallVector<EVT, 4> ValueVTs;
7600     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7601     bool isArgValueUsed = !I->use_empty();
7602     unsigned PartBase = 0;
7603     Type *FinalType = I->getType();
7604     if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7605       FinalType = cast<PointerType>(FinalType)->getElementType();
7606     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7607         FinalType, F.getCallingConv(), F.isVarArg());
7608     for (unsigned Value = 0, NumValues = ValueVTs.size();
7609          Value != NumValues; ++Value) {
7610       EVT VT = ValueVTs[Value];
7611       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7612       ISD::ArgFlagsTy Flags;
7613       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7614 
7615       if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7616         Flags.setZExt();
7617       if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7618         Flags.setSExt();
7619       if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7620         Flags.setInReg();
7621       if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7622         Flags.setSRet();
7623       if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftSelf))
7624         Flags.setSwiftSelf();
7625       if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7626         Flags.setByVal();
7627       if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7628         Flags.setInAlloca();
7629         // Set the byval flag for CCAssignFn callbacks that don't know about
7630         // inalloca.  This way we can know how many bytes we should've allocated
7631         // and how many bytes a callee cleanup function will pop.  If we port
7632         // inalloca to more targets, we'll have to add custom inalloca handling
7633         // in the various CC lowering callbacks.
7634         Flags.setByVal();
7635       }
7636       if (F.getCallingConv() == CallingConv::X86_INTR) {
7637         // IA Interrupt passes frame (1st parameter) by value in the stack.
7638         if (Idx == 1)
7639           Flags.setByVal();
7640       }
7641       if (Flags.isByVal() || Flags.isInAlloca()) {
7642         PointerType *Ty = cast<PointerType>(I->getType());
7643         Type *ElementTy = Ty->getElementType();
7644         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7645         // For ByVal, alignment should be passed from FE.  BE will guess if
7646         // this info is not there but there are cases it cannot get right.
7647         unsigned FrameAlign;
7648         if (F.getParamAlignment(Idx))
7649           FrameAlign = F.getParamAlignment(Idx);
7650         else
7651           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
7652         Flags.setByValAlign(FrameAlign);
7653       }
7654       if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7655         Flags.setNest();
7656       if (NeedsRegBlock)
7657         Flags.setInConsecutiveRegs();
7658       Flags.setOrigAlign(OriginalAlignment);
7659 
7660       MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7661       unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7662       for (unsigned i = 0; i != NumRegs; ++i) {
7663         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7664                               Idx-1, PartBase+i*RegisterVT.getStoreSize());
7665         if (NumRegs > 1 && i == 0)
7666           MyFlags.Flags.setSplit();
7667         // if it isn't first piece, alignment must be 1
7668         else if (i > 0) {
7669           MyFlags.Flags.setOrigAlign(1);
7670           if (i == NumRegs - 1)
7671             MyFlags.Flags.setSplitEnd();
7672         }
7673         Ins.push_back(MyFlags);
7674       }
7675       if (NeedsRegBlock && Value == NumValues - 1)
7676         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7677       PartBase += VT.getStoreSize();
7678     }
7679   }
7680 
7681   // Call the target to set up the argument values.
7682   SmallVector<SDValue, 8> InVals;
7683   SDValue NewRoot = TLI->LowerFormalArguments(
7684       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7685 
7686   // Verify that the target's LowerFormalArguments behaved as expected.
7687   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7688          "LowerFormalArguments didn't return a valid chain!");
7689   assert(InVals.size() == Ins.size() &&
7690          "LowerFormalArguments didn't emit the correct number of values!");
7691   DEBUG({
7692       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7693         assert(InVals[i].getNode() &&
7694                "LowerFormalArguments emitted a null value!");
7695         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7696                "LowerFormalArguments emitted a value with the wrong type!");
7697       }
7698     });
7699 
7700   // Update the DAG with the new chain value resulting from argument lowering.
7701   DAG.setRoot(NewRoot);
7702 
7703   // Set up the argument values.
7704   unsigned i = 0;
7705   Idx = 1;
7706   if (!FuncInfo->CanLowerReturn) {
7707     // Create a virtual register for the sret pointer, and put in a copy
7708     // from the sret argument into it.
7709     SmallVector<EVT, 1> ValueVTs;
7710     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7711                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7712     MVT VT = ValueVTs[0].getSimpleVT();
7713     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7714     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7715     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7716                                         RegVT, VT, nullptr, AssertOp);
7717 
7718     MachineFunction& MF = SDB->DAG.getMachineFunction();
7719     MachineRegisterInfo& RegInfo = MF.getRegInfo();
7720     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7721     FuncInfo->DemoteRegister = SRetReg;
7722     NewRoot =
7723         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7724     DAG.setRoot(NewRoot);
7725 
7726     // i indexes lowered arguments.  Bump it past the hidden sret argument.
7727     // Idx indexes LLVM arguments.  Don't touch it.
7728     ++i;
7729   }
7730 
7731   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7732       ++I, ++Idx) {
7733     SmallVector<SDValue, 4> ArgValues;
7734     SmallVector<EVT, 4> ValueVTs;
7735     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7736     unsigned NumValues = ValueVTs.size();
7737 
7738     // If this argument is unused then remember its value. It is used to generate
7739     // debugging information.
7740     if (I->use_empty() && NumValues) {
7741       SDB->setUnusedArgValue(&*I, InVals[i]);
7742 
7743       // Also remember any frame index for use in FastISel.
7744       if (FrameIndexSDNode *FI =
7745           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7746         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7747     }
7748 
7749     for (unsigned Val = 0; Val != NumValues; ++Val) {
7750       EVT VT = ValueVTs[Val];
7751       MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7752       unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7753 
7754       if (!I->use_empty()) {
7755         ISD::NodeType AssertOp = ISD::DELETED_NODE;
7756         if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7757           AssertOp = ISD::AssertSext;
7758         else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7759           AssertOp = ISD::AssertZext;
7760 
7761         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7762                                              NumParts, PartVT, VT,
7763                                              nullptr, AssertOp));
7764       }
7765 
7766       i += NumParts;
7767     }
7768 
7769     // We don't need to do anything else for unused arguments.
7770     if (ArgValues.empty())
7771       continue;
7772 
7773     // Note down frame index.
7774     if (FrameIndexSDNode *FI =
7775         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7776       FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7777 
7778     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7779                                      SDB->getCurSDLoc());
7780 
7781     SDB->setValue(&*I, Res);
7782     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7783       if (LoadSDNode *LNode =
7784           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7785         if (FrameIndexSDNode *FI =
7786             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7787         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7788     }
7789 
7790     // If this argument is live outside of the entry block, insert a copy from
7791     // wherever we got it to the vreg that other BB's will reference it as.
7792     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7793       // If we can, though, try to skip creating an unnecessary vreg.
7794       // FIXME: This isn't very clean... it would be nice to make this more
7795       // general.  It's also subtly incompatible with the hacks FastISel
7796       // uses with vregs.
7797       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7798       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7799         FuncInfo->ValueMap[&*I] = Reg;
7800         continue;
7801       }
7802     }
7803     if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
7804       FuncInfo->InitializeRegForValue(&*I);
7805       SDB->CopyToExportRegsIfNeeded(&*I);
7806     }
7807   }
7808 
7809   assert(i == InVals.size() && "Argument register count mismatch!");
7810 
7811   // Finally, if the target has anything special to do, allow it to do so.
7812   EmitFunctionEntryCode();
7813 }
7814 
7815 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
7816 /// ensure constants are generated when needed.  Remember the virtual registers
7817 /// that need to be added to the Machine PHI nodes as input.  We cannot just
7818 /// directly add them, because expansion might result in multiple MBB's for one
7819 /// BB.  As such, the start of the BB might correspond to a different MBB than
7820 /// the end.
7821 ///
7822 void
7823 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7824   const TerminatorInst *TI = LLVMBB->getTerminator();
7825 
7826   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7827 
7828   // Check PHI nodes in successors that expect a value to be available from this
7829   // block.
7830   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7831     const BasicBlock *SuccBB = TI->getSuccessor(succ);
7832     if (!isa<PHINode>(SuccBB->begin())) continue;
7833     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7834 
7835     // If this terminator has multiple identical successors (common for
7836     // switches), only handle each succ once.
7837     if (!SuccsHandled.insert(SuccMBB).second)
7838       continue;
7839 
7840     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7841 
7842     // At this point we know that there is a 1-1 correspondence between LLVM PHI
7843     // nodes and Machine PHI nodes, but the incoming operands have not been
7844     // emitted yet.
7845     for (BasicBlock::const_iterator I = SuccBB->begin();
7846          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7847       // Ignore dead phi's.
7848       if (PN->use_empty()) continue;
7849 
7850       // Skip empty types
7851       if (PN->getType()->isEmptyTy())
7852         continue;
7853 
7854       unsigned Reg;
7855       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7856 
7857       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7858         unsigned &RegOut = ConstantsOut[C];
7859         if (RegOut == 0) {
7860           RegOut = FuncInfo.CreateRegs(C->getType());
7861           CopyValueToVirtualRegister(C, RegOut);
7862         }
7863         Reg = RegOut;
7864       } else {
7865         DenseMap<const Value *, unsigned>::iterator I =
7866           FuncInfo.ValueMap.find(PHIOp);
7867         if (I != FuncInfo.ValueMap.end())
7868           Reg = I->second;
7869         else {
7870           assert(isa<AllocaInst>(PHIOp) &&
7871                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7872                  "Didn't codegen value into a register!??");
7873           Reg = FuncInfo.CreateRegs(PHIOp->getType());
7874           CopyValueToVirtualRegister(PHIOp, Reg);
7875         }
7876       }
7877 
7878       // Remember that this register needs to added to the machine PHI node as
7879       // the input for this MBB.
7880       SmallVector<EVT, 4> ValueVTs;
7881       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7882       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7883       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7884         EVT VT = ValueVTs[vti];
7885         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7886         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7887           FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7888         Reg += NumRegisters;
7889       }
7890     }
7891   }
7892 
7893   ConstantsOut.clear();
7894 }
7895 
7896 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7897 /// is 0.
7898 MachineBasicBlock *
7899 SelectionDAGBuilder::StackProtectorDescriptor::
7900 AddSuccessorMBB(const BasicBlock *BB,
7901                 MachineBasicBlock *ParentMBB,
7902                 bool IsLikely,
7903                 MachineBasicBlock *SuccMBB) {
7904   // If SuccBB has not been created yet, create it.
7905   if (!SuccMBB) {
7906     MachineFunction *MF = ParentMBB->getParent();
7907     MachineFunction::iterator BBI(ParentMBB);
7908     SuccMBB = MF->CreateMachineBasicBlock(BB);
7909     MF->insert(++BBI, SuccMBB);
7910   }
7911   // Add it as a successor of ParentMBB.
7912   ParentMBB->addSuccessor(
7913       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
7914   return SuccMBB;
7915 }
7916 
7917 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7918   MachineFunction::iterator I(MBB);
7919   if (++I == FuncInfo.MF->end())
7920     return nullptr;
7921   return &*I;
7922 }
7923 
7924 /// During lowering new call nodes can be created (such as memset, etc.).
7925 /// Those will become new roots of the current DAG, but complications arise
7926 /// when they are tail calls. In such cases, the call lowering will update
7927 /// the root, but the builder still needs to know that a tail call has been
7928 /// lowered in order to avoid generating an additional return.
7929 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7930   // If the node is null, we do have a tail call.
7931   if (MaybeTC.getNode() != nullptr)
7932     DAG.setRoot(MaybeTC);
7933   else
7934     HasTailCall = true;
7935 }
7936 
7937 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7938                                   unsigned *TotalCases, unsigned First,
7939                                   unsigned Last,
7940                                   unsigned Density) {
7941   assert(Last >= First);
7942   assert(TotalCases[Last] >= TotalCases[First]);
7943 
7944   APInt LowCase = Clusters[First].Low->getValue();
7945   APInt HighCase = Clusters[Last].High->getValue();
7946   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7947 
7948   // FIXME: A range of consecutive cases has 100% density, but only requires one
7949   // comparison to lower. We should discriminate against such consecutive ranges
7950   // in jump tables.
7951 
7952   uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7953   uint64_t Range = Diff + 1;
7954 
7955   uint64_t NumCases =
7956       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7957 
7958   assert(NumCases < UINT64_MAX / 100);
7959   assert(Range >= NumCases);
7960 
7961   return NumCases * 100 >= Range * Density;
7962 }
7963 
7964 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7965   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7966          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7967 }
7968 
7969 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7970                                          unsigned First, unsigned Last,
7971                                          const SwitchInst *SI,
7972                                          MachineBasicBlock *DefaultMBB,
7973                                          CaseCluster &JTCluster) {
7974   assert(First <= Last);
7975 
7976   auto Prob = BranchProbability::getZero();
7977   unsigned NumCmps = 0;
7978   std::vector<MachineBasicBlock*> Table;
7979   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
7980 
7981   // Initialize probabilities in JTProbs.
7982   for (unsigned I = First; I <= Last; ++I)
7983     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
7984 
7985   for (unsigned I = First; I <= Last; ++I) {
7986     assert(Clusters[I].Kind == CC_Range);
7987     Prob += Clusters[I].Prob;
7988     APInt Low = Clusters[I].Low->getValue();
7989     APInt High = Clusters[I].High->getValue();
7990     NumCmps += (Low == High) ? 1 : 2;
7991     if (I != First) {
7992       // Fill the gap between this and the previous cluster.
7993       APInt PreviousHigh = Clusters[I - 1].High->getValue();
7994       assert(PreviousHigh.slt(Low));
7995       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7996       for (uint64_t J = 0; J < Gap; J++)
7997         Table.push_back(DefaultMBB);
7998     }
7999     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
8000     for (uint64_t J = 0; J < ClusterSize; ++J)
8001       Table.push_back(Clusters[I].MBB);
8002     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
8003   }
8004 
8005   unsigned NumDests = JTProbs.size();
8006   if (isSuitableForBitTests(NumDests, NumCmps,
8007                             Clusters[First].Low->getValue(),
8008                             Clusters[Last].High->getValue())) {
8009     // Clusters[First..Last] should be lowered as bit tests instead.
8010     return false;
8011   }
8012 
8013   // Create the MBB that will load from and jump through the table.
8014   // Note: We create it here, but it's not inserted into the function yet.
8015   MachineFunction *CurMF = FuncInfo.MF;
8016   MachineBasicBlock *JumpTableMBB =
8017       CurMF->CreateMachineBasicBlock(SI->getParent());
8018 
8019   // Add successors. Note: use table order for determinism.
8020   SmallPtrSet<MachineBasicBlock *, 8> Done;
8021   for (MachineBasicBlock *Succ : Table) {
8022     if (Done.count(Succ))
8023       continue;
8024     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
8025     Done.insert(Succ);
8026   }
8027   JumpTableMBB->normalizeSuccProbs();
8028 
8029   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8030   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
8031                      ->createJumpTableIndex(Table);
8032 
8033   // Set up the jump table info.
8034   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
8035   JumpTableHeader JTH(Clusters[First].Low->getValue(),
8036                       Clusters[Last].High->getValue(), SI->getCondition(),
8037                       nullptr, false);
8038   JTCases.emplace_back(std::move(JTH), std::move(JT));
8039 
8040   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
8041                                      JTCases.size() - 1, Prob);
8042   return true;
8043 }
8044 
8045 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
8046                                          const SwitchInst *SI,
8047                                          MachineBasicBlock *DefaultMBB) {
8048 #ifndef NDEBUG
8049   // Clusters must be non-empty, sorted, and only contain Range clusters.
8050   assert(!Clusters.empty());
8051   for (CaseCluster &C : Clusters)
8052     assert(C.Kind == CC_Range);
8053   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
8054     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
8055 #endif
8056 
8057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8058   if (!areJTsAllowed(TLI))
8059     return;
8060 
8061   const int64_t N = Clusters.size();
8062   const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
8063 
8064   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
8065   SmallVector<unsigned, 8> TotalCases(N);
8066 
8067   for (unsigned i = 0; i < N; ++i) {
8068     APInt Hi = Clusters[i].High->getValue();
8069     APInt Lo = Clusters[i].Low->getValue();
8070     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
8071     if (i != 0)
8072       TotalCases[i] += TotalCases[i - 1];
8073   }
8074 
8075   unsigned MinDensity = JumpTableDensity;
8076   if (DefaultMBB->getParent()->getFunction()->optForSize())
8077     MinDensity = OptsizeJumpTableDensity;
8078   if (N >= MinJumpTableSize
8079       && isDense(Clusters, &TotalCases[0], 0, N - 1, MinDensity)) {
8080     // Cheap case: the whole range might be suitable for jump table.
8081     CaseCluster JTCluster;
8082     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
8083       Clusters[0] = JTCluster;
8084       Clusters.resize(1);
8085       return;
8086     }
8087   }
8088 
8089   // The algorithm below is not suitable for -O0.
8090   if (TM.getOptLevel() == CodeGenOpt::None)
8091     return;
8092 
8093   // Split Clusters into minimum number of dense partitions. The algorithm uses
8094   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
8095   // for the Case Statement'" (1994), but builds the MinPartitions array in
8096   // reverse order to make it easier to reconstruct the partitions in ascending
8097   // order. In the choice between two optimal partitionings, it picks the one
8098   // which yields more jump tables.
8099 
8100   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8101   SmallVector<unsigned, 8> MinPartitions(N);
8102   // LastElement[i] is the last element of the partition starting at i.
8103   SmallVector<unsigned, 8> LastElement(N);
8104   // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
8105   SmallVector<unsigned, 8> NumTables(N);
8106 
8107   // Base case: There is only one way to partition Clusters[N-1].
8108   MinPartitions[N - 1] = 1;
8109   LastElement[N - 1] = N - 1;
8110   assert(MinJumpTableSize > 1);
8111   NumTables[N - 1] = 0;
8112 
8113   // Note: loop indexes are signed to avoid underflow.
8114   for (int64_t i = N - 2; i >= 0; i--) {
8115     // Find optimal partitioning of Clusters[i..N-1].
8116     // Baseline: Put Clusters[i] into a partition on its own.
8117     MinPartitions[i] = MinPartitions[i + 1] + 1;
8118     LastElement[i] = i;
8119     NumTables[i] = NumTables[i + 1];
8120 
8121     // Search for a solution that results in fewer partitions.
8122     for (int64_t j = N - 1; j > i; j--) {
8123       // Try building a partition from Clusters[i..j].
8124       if (isDense(Clusters, &TotalCases[0], i, j, MinDensity)) {
8125         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8126         bool IsTable = j - i + 1 >= MinJumpTableSize;
8127         unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
8128 
8129         // If this j leads to fewer partitions, or same number of partitions
8130         // with more lookup tables, it is a better partitioning.
8131         if (NumPartitions < MinPartitions[i] ||
8132             (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
8133           MinPartitions[i] = NumPartitions;
8134           LastElement[i] = j;
8135           NumTables[i] = Tables;
8136         }
8137       }
8138     }
8139   }
8140 
8141   // Iterate over the partitions, replacing some with jump tables in-place.
8142   unsigned DstIndex = 0;
8143   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8144     Last = LastElement[First];
8145     assert(Last >= First);
8146     assert(DstIndex <= First);
8147     unsigned NumClusters = Last - First + 1;
8148 
8149     CaseCluster JTCluster;
8150     if (NumClusters >= MinJumpTableSize &&
8151         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
8152       Clusters[DstIndex++] = JTCluster;
8153     } else {
8154       for (unsigned I = First; I <= Last; ++I)
8155         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
8156     }
8157   }
8158   Clusters.resize(DstIndex);
8159 }
8160 
8161 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
8162   // FIXME: Using the pointer type doesn't seem ideal.
8163   uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
8164   uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
8165   return Range <= BW;
8166 }
8167 
8168 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
8169                                                 unsigned NumCmps,
8170                                                 const APInt &Low,
8171                                                 const APInt &High) {
8172   // FIXME: I don't think NumCmps is the correct metric: a single case and a
8173   // range of cases both require only one branch to lower. Just looking at the
8174   // number of clusters and destinations should be enough to decide whether to
8175   // build bit tests.
8176 
8177   // To lower a range with bit tests, the range must fit the bitwidth of a
8178   // machine word.
8179   if (!rangeFitsInWord(Low, High))
8180     return false;
8181 
8182   // Decide whether it's profitable to lower this range with bit tests. Each
8183   // destination requires a bit test and branch, and there is an overall range
8184   // check branch. For a small number of clusters, separate comparisons might be
8185   // cheaper, and for many destinations, splitting the range might be better.
8186   return (NumDests == 1 && NumCmps >= 3) ||
8187          (NumDests == 2 && NumCmps >= 5) ||
8188          (NumDests == 3 && NumCmps >= 6);
8189 }
8190 
8191 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
8192                                         unsigned First, unsigned Last,
8193                                         const SwitchInst *SI,
8194                                         CaseCluster &BTCluster) {
8195   assert(First <= Last);
8196   if (First == Last)
8197     return false;
8198 
8199   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8200   unsigned NumCmps = 0;
8201   for (int64_t I = First; I <= Last; ++I) {
8202     assert(Clusters[I].Kind == CC_Range);
8203     Dests.set(Clusters[I].MBB->getNumber());
8204     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
8205   }
8206   unsigned NumDests = Dests.count();
8207 
8208   APInt Low = Clusters[First].Low->getValue();
8209   APInt High = Clusters[Last].High->getValue();
8210   assert(Low.slt(High));
8211 
8212   if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
8213     return false;
8214 
8215   APInt LowBound;
8216   APInt CmpRange;
8217 
8218   const int BitWidth = DAG.getTargetLoweringInfo()
8219                            .getPointerTy(DAG.getDataLayout())
8220                            .getSizeInBits();
8221   assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
8222 
8223   // Check if the clusters cover a contiguous range such that no value in the
8224   // range will jump to the default statement.
8225   bool ContiguousRange = true;
8226   for (int64_t I = First + 1; I <= Last; ++I) {
8227     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
8228       ContiguousRange = false;
8229       break;
8230     }
8231   }
8232 
8233   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
8234     // Optimize the case where all the case values fit in a word without having
8235     // to subtract minValue. In this case, we can optimize away the subtraction.
8236     LowBound = APInt::getNullValue(Low.getBitWidth());
8237     CmpRange = High;
8238     ContiguousRange = false;
8239   } else {
8240     LowBound = Low;
8241     CmpRange = High - Low;
8242   }
8243 
8244   CaseBitsVector CBV;
8245   auto TotalProb = BranchProbability::getZero();
8246   for (unsigned i = First; i <= Last; ++i) {
8247     // Find the CaseBits for this destination.
8248     unsigned j;
8249     for (j = 0; j < CBV.size(); ++j)
8250       if (CBV[j].BB == Clusters[i].MBB)
8251         break;
8252     if (j == CBV.size())
8253       CBV.push_back(
8254           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
8255     CaseBits *CB = &CBV[j];
8256 
8257     // Update Mask, Bits and ExtraProb.
8258     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
8259     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
8260     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
8261     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
8262     CB->Bits += Hi - Lo + 1;
8263     CB->ExtraProb += Clusters[i].Prob;
8264     TotalProb += Clusters[i].Prob;
8265   }
8266 
8267   BitTestInfo BTI;
8268   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
8269     // Sort by probability first, number of bits second.
8270     if (a.ExtraProb != b.ExtraProb)
8271       return a.ExtraProb > b.ExtraProb;
8272     return a.Bits > b.Bits;
8273   });
8274 
8275   for (auto &CB : CBV) {
8276     MachineBasicBlock *BitTestBB =
8277         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
8278     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
8279   }
8280   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
8281                             SI->getCondition(), -1U, MVT::Other, false,
8282                             ContiguousRange, nullptr, nullptr, std::move(BTI),
8283                             TotalProb);
8284 
8285   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
8286                                     BitTestCases.size() - 1, TotalProb);
8287   return true;
8288 }
8289 
8290 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
8291                                               const SwitchInst *SI) {
8292 // Partition Clusters into as few subsets as possible, where each subset has a
8293 // range that fits in a machine word and has <= 3 unique destinations.
8294 
8295 #ifndef NDEBUG
8296   // Clusters must be sorted and contain Range or JumpTable clusters.
8297   assert(!Clusters.empty());
8298   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
8299   for (const CaseCluster &C : Clusters)
8300     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
8301   for (unsigned i = 1; i < Clusters.size(); ++i)
8302     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
8303 #endif
8304 
8305   // The algorithm below is not suitable for -O0.
8306   if (TM.getOptLevel() == CodeGenOpt::None)
8307     return;
8308 
8309   // If target does not have legal shift left, do not emit bit tests at all.
8310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8311   EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
8312   if (!TLI.isOperationLegal(ISD::SHL, PTy))
8313     return;
8314 
8315   int BitWidth = PTy.getSizeInBits();
8316   const int64_t N = Clusters.size();
8317 
8318   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8319   SmallVector<unsigned, 8> MinPartitions(N);
8320   // LastElement[i] is the last element of the partition starting at i.
8321   SmallVector<unsigned, 8> LastElement(N);
8322 
8323   // FIXME: This might not be the best algorithm for finding bit test clusters.
8324 
8325   // Base case: There is only one way to partition Clusters[N-1].
8326   MinPartitions[N - 1] = 1;
8327   LastElement[N - 1] = N - 1;
8328 
8329   // Note: loop indexes are signed to avoid underflow.
8330   for (int64_t i = N - 2; i >= 0; --i) {
8331     // Find optimal partitioning of Clusters[i..N-1].
8332     // Baseline: Put Clusters[i] into a partition on its own.
8333     MinPartitions[i] = MinPartitions[i + 1] + 1;
8334     LastElement[i] = i;
8335 
8336     // Search for a solution that results in fewer partitions.
8337     // Note: the search is limited by BitWidth, reducing time complexity.
8338     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
8339       // Try building a partition from Clusters[i..j].
8340 
8341       // Check the range.
8342       if (!rangeFitsInWord(Clusters[i].Low->getValue(),
8343                            Clusters[j].High->getValue()))
8344         continue;
8345 
8346       // Check nbr of destinations and cluster types.
8347       // FIXME: This works, but doesn't seem very efficient.
8348       bool RangesOnly = true;
8349       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8350       for (int64_t k = i; k <= j; k++) {
8351         if (Clusters[k].Kind != CC_Range) {
8352           RangesOnly = false;
8353           break;
8354         }
8355         Dests.set(Clusters[k].MBB->getNumber());
8356       }
8357       if (!RangesOnly || Dests.count() > 3)
8358         break;
8359 
8360       // Check if it's a better partition.
8361       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8362       if (NumPartitions < MinPartitions[i]) {
8363         // Found a better partition.
8364         MinPartitions[i] = NumPartitions;
8365         LastElement[i] = j;
8366       }
8367     }
8368   }
8369 
8370   // Iterate over the partitions, replacing with bit-test clusters in-place.
8371   unsigned DstIndex = 0;
8372   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8373     Last = LastElement[First];
8374     assert(First <= Last);
8375     assert(DstIndex <= First);
8376 
8377     CaseCluster BitTestCluster;
8378     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
8379       Clusters[DstIndex++] = BitTestCluster;
8380     } else {
8381       size_t NumClusters = Last - First + 1;
8382       std::memmove(&Clusters[DstIndex], &Clusters[First],
8383                    sizeof(Clusters[0]) * NumClusters);
8384       DstIndex += NumClusters;
8385     }
8386   }
8387   Clusters.resize(DstIndex);
8388 }
8389 
8390 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
8391                                         MachineBasicBlock *SwitchMBB,
8392                                         MachineBasicBlock *DefaultMBB) {
8393   MachineFunction *CurMF = FuncInfo.MF;
8394   MachineBasicBlock *NextMBB = nullptr;
8395   MachineFunction::iterator BBI(W.MBB);
8396   if (++BBI != FuncInfo.MF->end())
8397     NextMBB = &*BBI;
8398 
8399   unsigned Size = W.LastCluster - W.FirstCluster + 1;
8400 
8401   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8402 
8403   if (Size == 2 && W.MBB == SwitchMBB) {
8404     // If any two of the cases has the same destination, and if one value
8405     // is the same as the other, but has one bit unset that the other has set,
8406     // use bit manipulation to do two compares at once.  For example:
8407     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
8408     // TODO: This could be extended to merge any 2 cases in switches with 3
8409     // cases.
8410     // TODO: Handle cases where W.CaseBB != SwitchBB.
8411     CaseCluster &Small = *W.FirstCluster;
8412     CaseCluster &Big = *W.LastCluster;
8413 
8414     if (Small.Low == Small.High && Big.Low == Big.High &&
8415         Small.MBB == Big.MBB) {
8416       const APInt &SmallValue = Small.Low->getValue();
8417       const APInt &BigValue = Big.Low->getValue();
8418 
8419       // Check that there is only one bit different.
8420       APInt CommonBit = BigValue ^ SmallValue;
8421       if (CommonBit.isPowerOf2()) {
8422         SDValue CondLHS = getValue(Cond);
8423         EVT VT = CondLHS.getValueType();
8424         SDLoc DL = getCurSDLoc();
8425 
8426         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
8427                                  DAG.getConstant(CommonBit, DL, VT));
8428         SDValue Cond = DAG.getSetCC(
8429             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
8430             ISD::SETEQ);
8431 
8432         // Update successor info.
8433         // Both Small and Big will jump to Small.BB, so we sum up the
8434         // probabilities.
8435         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
8436         if (BPI)
8437           addSuccessorWithProb(
8438               SwitchMBB, DefaultMBB,
8439               // The default destination is the first successor in IR.
8440               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
8441         else
8442           addSuccessorWithProb(SwitchMBB, DefaultMBB);
8443 
8444         // Insert the true branch.
8445         SDValue BrCond =
8446             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
8447                         DAG.getBasicBlock(Small.MBB));
8448         // Insert the false branch.
8449         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
8450                              DAG.getBasicBlock(DefaultMBB));
8451 
8452         DAG.setRoot(BrCond);
8453         return;
8454       }
8455     }
8456   }
8457 
8458   if (TM.getOptLevel() != CodeGenOpt::None) {
8459     // Order cases by probability so the most likely case will be checked first.
8460     std::sort(W.FirstCluster, W.LastCluster + 1,
8461               [](const CaseCluster &a, const CaseCluster &b) {
8462       return a.Prob > b.Prob;
8463     });
8464 
8465     // Rearrange the case blocks so that the last one falls through if possible
8466     // without without changing the order of probabilities.
8467     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
8468       --I;
8469       if (I->Prob > W.LastCluster->Prob)
8470         break;
8471       if (I->Kind == CC_Range && I->MBB == NextMBB) {
8472         std::swap(*I, *W.LastCluster);
8473         break;
8474       }
8475     }
8476   }
8477 
8478   // Compute total probability.
8479   BranchProbability DefaultProb = W.DefaultProb;
8480   BranchProbability UnhandledProbs = DefaultProb;
8481   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
8482     UnhandledProbs += I->Prob;
8483 
8484   MachineBasicBlock *CurMBB = W.MBB;
8485   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
8486     MachineBasicBlock *Fallthrough;
8487     if (I == W.LastCluster) {
8488       // For the last cluster, fall through to the default destination.
8489       Fallthrough = DefaultMBB;
8490     } else {
8491       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
8492       CurMF->insert(BBI, Fallthrough);
8493       // Put Cond in a virtual register to make it available from the new blocks.
8494       ExportFromCurrentBlock(Cond);
8495     }
8496     UnhandledProbs -= I->Prob;
8497 
8498     switch (I->Kind) {
8499       case CC_JumpTable: {
8500         // FIXME: Optimize away range check based on pivot comparisons.
8501         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
8502         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
8503 
8504         // The jump block hasn't been inserted yet; insert it here.
8505         MachineBasicBlock *JumpMBB = JT->MBB;
8506         CurMF->insert(BBI, JumpMBB);
8507 
8508         auto JumpProb = I->Prob;
8509         auto FallthroughProb = UnhandledProbs;
8510 
8511         // If the default statement is a target of the jump table, we evenly
8512         // distribute the default probability to successors of CurMBB. Also
8513         // update the probability on the edge from JumpMBB to Fallthrough.
8514         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
8515                                               SE = JumpMBB->succ_end();
8516              SI != SE; ++SI) {
8517           if (*SI == DefaultMBB) {
8518             JumpProb += DefaultProb / 2;
8519             FallthroughProb -= DefaultProb / 2;
8520             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
8521             JumpMBB->normalizeSuccProbs();
8522             break;
8523           }
8524         }
8525 
8526         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
8527         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
8528         CurMBB->normalizeSuccProbs();
8529 
8530         // The jump table header will be inserted in our current block, do the
8531         // range check, and fall through to our fallthrough block.
8532         JTH->HeaderBB = CurMBB;
8533         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
8534 
8535         // If we're in the right place, emit the jump table header right now.
8536         if (CurMBB == SwitchMBB) {
8537           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
8538           JTH->Emitted = true;
8539         }
8540         break;
8541       }
8542       case CC_BitTests: {
8543         // FIXME: Optimize away range check based on pivot comparisons.
8544         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
8545 
8546         // The bit test blocks haven't been inserted yet; insert them here.
8547         for (BitTestCase &BTC : BTB->Cases)
8548           CurMF->insert(BBI, BTC.ThisBB);
8549 
8550         // Fill in fields of the BitTestBlock.
8551         BTB->Parent = CurMBB;
8552         BTB->Default = Fallthrough;
8553 
8554         BTB->DefaultProb = UnhandledProbs;
8555         // If the cases in bit test don't form a contiguous range, we evenly
8556         // distribute the probability on the edge to Fallthrough to two
8557         // successors of CurMBB.
8558         if (!BTB->ContiguousRange) {
8559           BTB->Prob += DefaultProb / 2;
8560           BTB->DefaultProb -= DefaultProb / 2;
8561         }
8562 
8563         // If we're in the right place, emit the bit test header right now.
8564         if (CurMBB == SwitchMBB) {
8565           visitBitTestHeader(*BTB, SwitchMBB);
8566           BTB->Emitted = true;
8567         }
8568         break;
8569       }
8570       case CC_Range: {
8571         const Value *RHS, *LHS, *MHS;
8572         ISD::CondCode CC;
8573         if (I->Low == I->High) {
8574           // Check Cond == I->Low.
8575           CC = ISD::SETEQ;
8576           LHS = Cond;
8577           RHS=I->Low;
8578           MHS = nullptr;
8579         } else {
8580           // Check I->Low <= Cond <= I->High.
8581           CC = ISD::SETLE;
8582           LHS = I->Low;
8583           MHS = Cond;
8584           RHS = I->High;
8585         }
8586 
8587         // The false probability is the sum of all unhandled cases.
8588         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
8589                      UnhandledProbs);
8590 
8591         if (CurMBB == SwitchMBB)
8592           visitSwitchCase(CB, SwitchMBB);
8593         else
8594           SwitchCases.push_back(CB);
8595 
8596         break;
8597       }
8598     }
8599     CurMBB = Fallthrough;
8600   }
8601 }
8602 
8603 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8604                                               CaseClusterIt First,
8605                                               CaseClusterIt Last) {
8606   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8607     if (X.Prob != CC.Prob)
8608       return X.Prob > CC.Prob;
8609 
8610     // Ties are broken by comparing the case value.
8611     return X.Low->getValue().slt(CC.Low->getValue());
8612   });
8613 }
8614 
8615 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8616                                         const SwitchWorkListItem &W,
8617                                         Value *Cond,
8618                                         MachineBasicBlock *SwitchMBB) {
8619   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8620          "Clusters not sorted?");
8621 
8622   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8623 
8624   // Balance the tree based on branch probabilities to create a near-optimal (in
8625   // terms of search time given key frequency) binary search tree. See e.g. Kurt
8626   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8627   CaseClusterIt LastLeft = W.FirstCluster;
8628   CaseClusterIt FirstRight = W.LastCluster;
8629   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
8630   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
8631 
8632   // Move LastLeft and FirstRight towards each other from opposite directions to
8633   // find a partitioning of the clusters which balances the probability on both
8634   // sides. If LeftProb and RightProb are equal, alternate which side is
8635   // taken to ensure 0-probability nodes are distributed evenly.
8636   unsigned I = 0;
8637   while (LastLeft + 1 < FirstRight) {
8638     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
8639       LeftProb += (++LastLeft)->Prob;
8640     else
8641       RightProb += (--FirstRight)->Prob;
8642     I++;
8643   }
8644 
8645   for (;;) {
8646     // Our binary search tree differs from a typical BST in that ours can have up
8647     // to three values in each leaf. The pivot selection above doesn't take that
8648     // into account, which means the tree might require more nodes and be less
8649     // efficient. We compensate for this here.
8650 
8651     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8652     unsigned NumRight = W.LastCluster - FirstRight + 1;
8653 
8654     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8655       // If one side has less than 3 clusters, and the other has more than 3,
8656       // consider taking a cluster from the other side.
8657 
8658       if (NumLeft < NumRight) {
8659         // Consider moving the first cluster on the right to the left side.
8660         CaseCluster &CC = *FirstRight;
8661         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8662         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8663         if (LeftSideRank <= RightSideRank) {
8664           // Moving the cluster to the left does not demote it.
8665           ++LastLeft;
8666           ++FirstRight;
8667           continue;
8668         }
8669       } else {
8670         assert(NumRight < NumLeft);
8671         // Consider moving the last element on the left to the right side.
8672         CaseCluster &CC = *LastLeft;
8673         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8674         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8675         if (RightSideRank <= LeftSideRank) {
8676           // Moving the cluster to the right does not demot it.
8677           --LastLeft;
8678           --FirstRight;
8679           continue;
8680         }
8681       }
8682     }
8683     break;
8684   }
8685 
8686   assert(LastLeft + 1 == FirstRight);
8687   assert(LastLeft >= W.FirstCluster);
8688   assert(FirstRight <= W.LastCluster);
8689 
8690   // Use the first element on the right as pivot since we will make less-than
8691   // comparisons against it.
8692   CaseClusterIt PivotCluster = FirstRight;
8693   assert(PivotCluster > W.FirstCluster);
8694   assert(PivotCluster <= W.LastCluster);
8695 
8696   CaseClusterIt FirstLeft = W.FirstCluster;
8697   CaseClusterIt LastRight = W.LastCluster;
8698 
8699   const ConstantInt *Pivot = PivotCluster->Low;
8700 
8701   // New blocks will be inserted immediately after the current one.
8702   MachineFunction::iterator BBI(W.MBB);
8703   ++BBI;
8704 
8705   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8706   // we can branch to its destination directly if it's squeezed exactly in
8707   // between the known lower bound and Pivot - 1.
8708   MachineBasicBlock *LeftMBB;
8709   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8710       FirstLeft->Low == W.GE &&
8711       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8712     LeftMBB = FirstLeft->MBB;
8713   } else {
8714     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8715     FuncInfo.MF->insert(BBI, LeftMBB);
8716     WorkList.push_back(
8717         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
8718     // Put Cond in a virtual register to make it available from the new blocks.
8719     ExportFromCurrentBlock(Cond);
8720   }
8721 
8722   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8723   // single cluster, RHS.Low == Pivot, and we can branch to its destination
8724   // directly if RHS.High equals the current upper bound.
8725   MachineBasicBlock *RightMBB;
8726   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8727       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8728     RightMBB = FirstRight->MBB;
8729   } else {
8730     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8731     FuncInfo.MF->insert(BBI, RightMBB);
8732     WorkList.push_back(
8733         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
8734     // Put Cond in a virtual register to make it available from the new blocks.
8735     ExportFromCurrentBlock(Cond);
8736   }
8737 
8738   // Create the CaseBlock record that will be used to lower the branch.
8739   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8740                LeftProb, RightProb);
8741 
8742   if (W.MBB == SwitchMBB)
8743     visitSwitchCase(CB, SwitchMBB);
8744   else
8745     SwitchCases.push_back(CB);
8746 }
8747 
8748 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8749   // Extract cases from the switch.
8750   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8751   CaseClusterVector Clusters;
8752   Clusters.reserve(SI.getNumCases());
8753   for (auto I : SI.cases()) {
8754     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8755     const ConstantInt *CaseVal = I.getCaseValue();
8756     BranchProbability Prob =
8757         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
8758             : BranchProbability(1, SI.getNumCases() + 1);
8759     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
8760   }
8761 
8762   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8763 
8764   // Cluster adjacent cases with the same destination. We do this at all
8765   // optimization levels because it's cheap to do and will make codegen faster
8766   // if there are many clusters.
8767   sortAndRangeify(Clusters);
8768 
8769   if (TM.getOptLevel() != CodeGenOpt::None) {
8770     // Replace an unreachable default with the most popular destination.
8771     // FIXME: Exploit unreachable default more aggressively.
8772     bool UnreachableDefault =
8773         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8774     if (UnreachableDefault && !Clusters.empty()) {
8775       DenseMap<const BasicBlock *, unsigned> Popularity;
8776       unsigned MaxPop = 0;
8777       const BasicBlock *MaxBB = nullptr;
8778       for (auto I : SI.cases()) {
8779         const BasicBlock *BB = I.getCaseSuccessor();
8780         if (++Popularity[BB] > MaxPop) {
8781           MaxPop = Popularity[BB];
8782           MaxBB = BB;
8783         }
8784       }
8785       // Set new default.
8786       assert(MaxPop > 0 && MaxBB);
8787       DefaultMBB = FuncInfo.MBBMap[MaxBB];
8788 
8789       // Remove cases that were pointing to the destination that is now the
8790       // default.
8791       CaseClusterVector New;
8792       New.reserve(Clusters.size());
8793       for (CaseCluster &CC : Clusters) {
8794         if (CC.MBB != DefaultMBB)
8795           New.push_back(CC);
8796       }
8797       Clusters = std::move(New);
8798     }
8799   }
8800 
8801   // If there is only the default destination, jump there directly.
8802   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8803   if (Clusters.empty()) {
8804     SwitchMBB->addSuccessor(DefaultMBB);
8805     if (DefaultMBB != NextBlock(SwitchMBB)) {
8806       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8807                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8808     }
8809     return;
8810   }
8811 
8812   findJumpTables(Clusters, &SI, DefaultMBB);
8813   findBitTestClusters(Clusters, &SI);
8814 
8815   DEBUG({
8816     dbgs() << "Case clusters: ";
8817     for (const CaseCluster &C : Clusters) {
8818       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8819       if (C.Kind == CC_BitTests) dbgs() << "BT:";
8820 
8821       C.Low->getValue().print(dbgs(), true);
8822       if (C.Low != C.High) {
8823         dbgs() << '-';
8824         C.High->getValue().print(dbgs(), true);
8825       }
8826       dbgs() << ' ';
8827     }
8828     dbgs() << '\n';
8829   });
8830 
8831   assert(!Clusters.empty());
8832   SwitchWorkList WorkList;
8833   CaseClusterIt First = Clusters.begin();
8834   CaseClusterIt Last = Clusters.end() - 1;
8835   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
8836   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
8837 
8838   while (!WorkList.empty()) {
8839     SwitchWorkListItem W = WorkList.back();
8840     WorkList.pop_back();
8841     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8842 
8843     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8844       // For optimized builds, lower large range as a balanced binary tree.
8845       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8846       continue;
8847     }
8848 
8849     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
8850   }
8851 }
8852