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