LLVM  14.0.0git
SelectionDAGBuilder.cpp
Go to the documentation of this file.
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
31 #include "llvm/Analysis/Loads.h"
37 #include "llvm/CodeGen/Analysis.h"
53 #include "llvm/CodeGen/StackMaps.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/DiagnosticInfo.h"
73 #include "llvm/IR/Function.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/IntrinsicsAArch64.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/MC/MCSymbol.h"
94 #include "llvm/Support/Casting.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
104 #include <cstddef>
105 #include <cstring>
106 #include <iterator>
107 #include <limits>
108 #include <numeric>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122  InsertAssertAlign("insert-assert-align", cl::init(true),
123  cl::desc("Insert the experimental `assertalign` node."),
125 
127  LimitFPPrecision("limit-float-precision",
128  cl::desc("Generate low-precision inline sequences "
129  "for some float libcalls"),
131  cl::init(0));
132 
134  "switch-peel-threshold", cl::Hidden, cl::init(66),
135  cl::desc("Set the case probability threshold for peeling the case from a "
136  "switch statement. A value greater than 100 will void this "
137  "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
156  const SDValue *Parts, unsigned NumParts,
157  MVT PartVT, EVT ValueVT, const Value *V,
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent. If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
166  const SDValue *Parts, unsigned NumParts,
167  MVT PartVT, EVT ValueVT, const Value *V,
168  Optional<CallingConv::ID> CC = None,
169  Optional<ISD::NodeType> AssertOp = None) {
170  // Let the target assemble the parts if it wants to
171  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172  if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173  PartVT, ValueVT, CC))
174  return Val;
175 
176  if (ValueVT.isVector())
177  return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178  CC);
179 
180  assert(NumParts > 0 && "No parts to assemble!");
181  SDValue Val = Parts[0];
182 
183  if (NumParts > 1) {
184  // Assemble the value from multiple parts.
185  if (ValueVT.isInteger()) {
186  unsigned PartBits = PartVT.getSizeInBits();
187  unsigned ValueBits = ValueVT.getSizeInBits();
188 
189  // Assemble the power of 2 part.
190  unsigned RoundParts =
191  (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
192  unsigned RoundBits = PartBits * RoundParts;
193  EVT RoundVT = RoundBits == ValueBits ?
194  ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195  SDValue Lo, Hi;
196 
197  EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199  if (RoundParts > 2) {
200  Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
201  PartVT, HalfVT, V);
202  Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
203  RoundParts / 2, PartVT, HalfVT, V);
204  } else {
205  Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206  Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207  }
208 
209  if (DAG.getDataLayout().isBigEndian())
210  std::swap(Lo, Hi);
211 
212  Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214  if (RoundParts < NumParts) {
215  // Assemble the trailing non-power-of-2 part.
216  unsigned OddParts = NumParts - RoundParts;
217  EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218  Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219  OddVT, V, CC);
220 
221  // Combine the round and odd parts.
222  Lo = Val;
223  if (DAG.getDataLayout().isBigEndian())
224  std::swap(Lo, Hi);
225  EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226  Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227  Hi =
228  DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229  DAG.getConstant(Lo.getValueSizeInBits(), DL,
230  TLI.getPointerTy(DAG.getDataLayout())));
231  Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232  Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233  }
234  } else if (PartVT.isFloatingPoint()) {
235  // FP split into multiple FP parts (for ppcf128)
236  assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237  "Unexpected split");
238  SDValue Lo, Hi;
239  Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240  Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241  if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242  std::swap(Lo, Hi);
243  Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244  } else {
245  // FP split into integer parts (soft fp)
246  assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247  !PartVT.isVector() && "Unexpected split");
248  EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249  Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
250  }
251  }
252 
253  // There is now one part, held in Val. Correct it to match ValueVT.
254  // PartEVT is the type of the register class that holds the value.
255  // ValueVT is the type of the inline asm operation.
256  EVT PartEVT = Val.getValueType();
257 
258  if (PartEVT == ValueVT)
259  return Val;
260 
261  if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262  ValueVT.bitsLT(PartEVT)) {
263  // For an FP value in an integer part, we need to truncate to the right
264  // width first.
265  PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
266  Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267  }
268 
269  // Handle types that have the same size.
270  if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271  return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273  // Handle types with different sizes.
274  if (PartEVT.isInteger() && ValueVT.isInteger()) {
275  if (ValueVT.bitsLT(PartEVT)) {
276  // For a truncate, see if we have any information to
277  // indicate whether the truncated bits will always be
278  // zero or sign-extension.
279  if (AssertOp.hasValue())
280  Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281  DAG.getValueType(ValueVT));
282  return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283  }
284  return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285  }
286 
287  if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288  // FP_ROUND's are always exact here.
289  if (ValueVT.bitsLT(Val.getValueType()))
290  return DAG.getNode(
291  ISD::FP_ROUND, DL, ValueVT, Val,
292  DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
293 
294  return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
295  }
296 
297  // Handle MMX to a narrower integer type by bitcasting MMX to integer and
298  // then truncating.
299  if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
300  ValueVT.bitsLT(PartEVT)) {
301  Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
302  return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303  }
304 
305  report_fatal_error("Unknown mismatch in getCopyFromParts!");
306 }
307 
309  const Twine &ErrMsg) {
310  const Instruction *I = dyn_cast_or_null<Instruction>(V);
311  if (!V)
312  return Ctx.emitError(ErrMsg);
313 
314  const char *AsmError = ", possible invalid constraint for vector type";
315  if (const CallInst *CI = dyn_cast<CallInst>(I))
316  if (CI->isInlineAsm())
317  return Ctx.emitError(I, ErrMsg + AsmError);
318 
319  return Ctx.emitError(I, ErrMsg);
320 }
321 
322 /// getCopyFromPartsVector - Create a value that contains the specified legal
323 /// parts combined into the value they represent. If the parts combine to a
324 /// type larger than ValueVT then AssertOp can be used to specify whether the
325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
326 /// ValueVT (ISD::AssertSext).
328  const SDValue *Parts, unsigned NumParts,
329  MVT PartVT, EVT ValueVT, const Value *V,
330  Optional<CallingConv::ID> CallConv) {
331  assert(ValueVT.isVector() && "Not a vector value");
332  assert(NumParts > 0 && "No parts to assemble!");
333  const bool IsABIRegCopy = CallConv.hasValue();
334 
335  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336  SDValue Val = Parts[0];
337 
338  // Handle a multi-element vector.
339  if (NumParts > 1) {
340  EVT IntermediateVT;
341  MVT RegisterVT;
342  unsigned NumIntermediates;
343  unsigned NumRegs;
344 
345  if (IsABIRegCopy) {
347  *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
348  NumIntermediates, RegisterVT);
349  } else {
350  NumRegs =
351  TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
352  NumIntermediates, RegisterVT);
353  }
354 
355  assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
356  NumParts = NumRegs; // Silence a compiler warning.
357  assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
358  assert(RegisterVT.getSizeInBits() ==
359  Parts[0].getSimpleValueType().getSizeInBits() &&
360  "Part type sizes don't match!");
361 
362  // Assemble the parts into intermediate operands.
363  SmallVector<SDValue, 8> Ops(NumIntermediates);
364  if (NumIntermediates == NumParts) {
365  // If the register was not expanded, truncate or copy the value,
366  // as appropriate.
367  for (unsigned i = 0; i != NumParts; ++i)
368  Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
369  PartVT, IntermediateVT, V, CallConv);
370  } else if (NumParts > 0) {
371  // If the intermediate type was expanded, build the intermediate
372  // operands from the parts.
373  assert(NumParts % NumIntermediates == 0 &&
374  "Must expand into a divisible number of parts!");
375  unsigned Factor = NumParts / NumIntermediates;
376  for (unsigned i = 0; i != NumIntermediates; ++i)
377  Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
378  PartVT, IntermediateVT, V, CallConv);
379  }
380 
381  // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
382  // intermediate operands.
383  EVT BuiltVectorTy =
384  IntermediateVT.isVector()
386  *DAG.getContext(), IntermediateVT.getScalarType(),
387  IntermediateVT.getVectorElementCount() * NumParts)
388  : EVT::getVectorVT(*DAG.getContext(),
389  IntermediateVT.getScalarType(),
390  NumIntermediates);
391  Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
393  DL, BuiltVectorTy, Ops);
394  }
395 
396  // There is now one part, held in Val. Correct it to match ValueVT.
397  EVT PartEVT = Val.getValueType();
398 
399  if (PartEVT == ValueVT)
400  return Val;
401 
402  if (PartEVT.isVector()) {
403  // Vector/Vector bitcast.
404  if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
405  return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406 
407  // If the element type of the source/dest vectors are the same, but the
408  // parts vector has more elements than the value vector, then we have a
409  // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
410  // elements we want.
411  if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
414  (PartEVT.getVectorElementCount().isScalable() ==
415  ValueVT.getVectorElementCount().isScalable()) &&
416  "Cannot narrow, it would be a lossy transformation");
417  PartEVT =
419  ValueVT.getVectorElementCount());
420  Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
421  DAG.getVectorIdxConstant(0, DL));
422  if (PartEVT == ValueVT)
423  return Val;
424  }
425 
426  // Promoted vector extract
427  return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
428  }
429 
430  // Trivial bitcast if the types are the same size and the destination
431  // vector type is legal.
432  if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
433  TLI.isTypeLegal(ValueVT))
434  return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436  if (ValueVT.getVectorNumElements() != 1) {
437  // Certain ABIs require that vectors are passed as integers. For vectors
438  // are the same size, this is an obvious bitcast.
439  if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
440  return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441  } else if (ValueVT.bitsLT(PartEVT)) {
442  const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
443  EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
444  // Drop the extra bits.
445  Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
446  return DAG.getBitcast(ValueVT, Val);
447  }
448 
450  *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451  return DAG.getUNDEF(ValueVT);
452  }
453 
454  // Handle cases such as i8 -> <1 x i1>
455  EVT ValueSVT = ValueVT.getVectorElementType();
456  if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457  if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458  Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459  else
460  Val = ValueVT.isFloatingPoint()
461  ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462  : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463  }
464 
465  return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469  SDValue Val, SDValue *Parts, unsigned NumParts,
470  MVT PartVT, const Value *V,
471  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts. If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477  SDValue *Parts, unsigned NumParts, MVT PartVT,
478  const Value *V,
479  Optional<CallingConv::ID> CallConv = None,
480  ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481  // Let the target split the parts if it wants to
482  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483  if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484  CallConv))
485  return;
486  EVT ValueVT = Val.getValueType();
487 
488  // Handle the vector case separately.
489  if (ValueVT.isVector())
490  return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491  CallConv);
492 
493  unsigned PartBits = PartVT.getSizeInBits();
494  unsigned OrigNumParts = NumParts;
495  assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496  "Copying to an illegal type!");
497 
498  if (NumParts == 0)
499  return;
500 
501  assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502  EVT PartEVT = PartVT;
503  if (PartEVT == ValueVT) {
504  assert(NumParts == 1 && "No-op copy with multiple parts!");
505  Parts[0] = Val;
506  return;
507  }
508 
509  if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510  // If the parts cover more bits than the value has, promote the value.
511  if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512  assert(NumParts == 1 && "Do not know what to promote to!");
513  Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514  } else {
515  if (ValueVT.isFloatingPoint()) {
516  // FP values need to be bitcast, then extended if they are being put
517  // into a larger container.
518  ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
519  Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520  }
521  assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522  ValueVT.isInteger() &&
523  "Unknown mismatch!");
524  ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525  Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526  if (PartVT == MVT::x86mmx)
527  Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528  }
529  } else if (PartBits == ValueVT.getSizeInBits()) {
530  // Different types of the same size.
531  assert(NumParts == 1 && PartEVT != ValueVT);
532  Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533  } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534  // If the parts cover less bits than value has, truncate the value.
535  assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536  ValueVT.isInteger() &&
537  "Unknown mismatch!");
538  ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539  Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540  if (PartVT == MVT::x86mmx)
541  Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542  }
543 
544  // The value may have changed - recompute ValueVT.
545  ValueVT = Val.getValueType();
546  assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547  "Failed to tile the value with PartVT!");
548 
549  if (NumParts == 1) {
550  if (PartEVT != ValueVT) {
552  "scalar-to-vector conversion failed");
553  Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554  }
555 
556  Parts[0] = Val;
557  return;
558  }
559 
560  // Expand the value into multiple parts.
561  if (NumParts & (NumParts - 1)) {
562  // The number of parts is not a power of 2. Split off and copy the tail.
563  assert(PartVT.isInteger() && ValueVT.isInteger() &&
564  "Do not know what to expand to!");
565  unsigned RoundParts = 1 << Log2_32(NumParts);
566  unsigned RoundBits = RoundParts * PartBits;
567  unsigned OddParts = NumParts - RoundParts;
568  SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569  DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571  getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572  CallConv);
573 
574  if (DAG.getDataLayout().isBigEndian())
575  // The odd parts were reversed by getCopyToParts - unreverse them.
576  std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578  NumParts = RoundParts;
579  ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580  Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581  }
582 
583  // The number of parts is a power of 2. Repeatedly bisect the value using
584  // EXTRACT_ELEMENT.
585  Parts[0] = DAG.getNode(ISD::BITCAST, DL,
587  ValueVT.getSizeInBits()),
588  Val);
589 
590  for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591  for (unsigned i = 0; i < NumParts; i += StepSize) {
592  unsigned ThisBits = StepSize * PartBits / 2;
593  EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594  SDValue &Part0 = Parts[i];
595  SDValue &Part1 = Parts[i+StepSize/2];
596 
597  Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598  ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599  Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600  ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602  if (ThisBits == PartBits && ThisVT != PartVT) {
603  Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604  Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605  }
606  }
607  }
608 
609  if (DAG.getDataLayout().isBigEndian())
610  std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
614  const SDLoc &DL, EVT PartVT) {
615  if (!PartVT.isVector())
616  return SDValue();
617 
618  EVT ValueVT = Val.getValueType();
619  ElementCount PartNumElts = PartVT.getVectorElementCount();
620  ElementCount ValueNumElts = ValueVT.getVectorElementCount();
621 
622  // We only support widening vectors with equivalent element types and
623  // fixed/scalable properties. If a target needs to widen a fixed-length type
624  // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
625  if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
626  PartNumElts.isScalable() != ValueNumElts.isScalable() ||
627  PartVT.getVectorElementType() != ValueVT.getVectorElementType())
628  return SDValue();
629 
630  // Widening a scalable vector to another scalable vector is done by inserting
631  // the vector into a larger undef one.
632  if (PartNumElts.isScalable())
633  return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
634  Val, DAG.getVectorIdxConstant(0, DL));
635 
636  EVT ElementVT = PartVT.getVectorElementType();
637  // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
638  // undef elements.
640  DAG.ExtractVectorElements(Val, Ops);
641  SDValue EltUndef = DAG.getUNDEF(ElementVT);
642  Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
643 
644  // FIXME: Use CONCAT for 2x -> 4x.
645  return DAG.getBuildVector(PartVT, DL, Ops);
646 }
647 
648 /// getCopyToPartsVector - Create a series of nodes that contain the specified
649 /// value split into legal parts.
650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
651  SDValue Val, SDValue *Parts, unsigned NumParts,
652  MVT PartVT, const Value *V,
653  Optional<CallingConv::ID> CallConv) {
654  EVT ValueVT = Val.getValueType();
655  assert(ValueVT.isVector() && "Not a vector");
656  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657  const bool IsABIRegCopy = CallConv.hasValue();
658 
659  if (NumParts == 1) {
660  EVT PartEVT = PartVT;
661  if (PartEVT == ValueVT) {
662  // Nothing to do.
663  } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
664  // Bitconvert vector->vector case.
665  Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
666  } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
667  Val = Widened;
668  } else if (PartVT.isVector() &&
669  PartEVT.getVectorElementType().bitsGE(
670  ValueVT.getVectorElementType()) &&
671  PartEVT.getVectorElementCount() ==
672  ValueVT.getVectorElementCount()) {
673 
674  // Promoted vector extract
675  Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676  } else if (PartEVT.isVector() &&
677  PartEVT.getVectorElementType() !=
678  ValueVT.getVectorElementType() &&
679  TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
681  // Combination of widening and promotion.
682  EVT WidenVT =
684  PartVT.getVectorElementCount());
685  SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
686  Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
687  } else {
688  if (ValueVT.getVectorElementCount().isScalar()) {
689  Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
690  DAG.getVectorIdxConstant(0, DL));
691  } else {
692  uint64_t ValueSize = ValueVT.getFixedSizeInBits();
693  assert(PartVT.getFixedSizeInBits() > ValueSize &&
694  "lossy conversion of vector to scalar type");
695  EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
696  Val = DAG.getBitcast(IntermediateType, Val);
697  Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698  }
699  }
700 
701  assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
702  Parts[0] = Val;
703  return;
704  }
705 
706  // Handle a multi-element vector.
707  EVT IntermediateVT;
708  MVT RegisterVT;
709  unsigned NumIntermediates;
710  unsigned NumRegs;
711  if (IsABIRegCopy) {
713  *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
714  NumIntermediates, RegisterVT);
715  } else {
716  NumRegs =
717  TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
718  NumIntermediates, RegisterVT);
719  }
720 
721  assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
722  NumParts = NumRegs; // Silence a compiler warning.
723  assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
724 
725  assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
726  "Mixing scalable and fixed vectors when copying in parts");
727 
728  Optional<ElementCount> DestEltCnt;
729 
730  if (IntermediateVT.isVector())
731  DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
732  else
733  DestEltCnt = ElementCount::getFixed(NumIntermediates);
734 
735  EVT BuiltVectorTy = EVT::getVectorVT(
736  *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
737 
738  if (ValueVT == BuiltVectorTy) {
739  // Nothing to do.
740  } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
741  // Bitconvert vector->vector case.
742  Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743  } else {
744  if (BuiltVectorTy.getVectorElementType().bitsGT(
745  ValueVT.getVectorElementType())) {
746  // Integer promotion.
747  ValueVT = EVT::getVectorVT(*DAG.getContext(),
748  BuiltVectorTy.getVectorElementType(),
749  ValueVT.getVectorElementCount());
750  Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
751  }
752 
753  if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
754  Val = Widened;
755  }
756  }
757 
758  assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
759 
760  // Split the vector into intermediate operands.
761  SmallVector<SDValue, 8> Ops(NumIntermediates);
762  for (unsigned i = 0; i != NumIntermediates; ++i) {
763  if (IntermediateVT.isVector()) {
764  // This does something sensible for scalable vectors - see the
765  // definition of EXTRACT_SUBVECTOR for further details.
766  unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
767  Ops[i] =
768  DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769  DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770  } else {
771  Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772  DAG.getVectorIdxConstant(i, DL));
773  }
774  }
775 
776  // Split the intermediate operands into legal parts.
777  if (NumParts == NumIntermediates) {
778  // If the register was not expanded, promote or copy the value,
779  // as appropriate.
780  for (unsigned i = 0; i != NumParts; ++i)
781  getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782  } else if (NumParts > 0) {
783  // If the intermediate type was expanded, split each the value into
784  // legal parts.
785  assert(NumIntermediates != 0 && "division by zero");
786  assert(NumParts % NumIntermediates == 0 &&
787  "Must expand into a divisible number of parts!");
788  unsigned Factor = NumParts / NumIntermediates;
789  for (unsigned i = 0; i != NumIntermediates; ++i)
790  getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791  CallConv);
792  }
793 }
794 
796  EVT valuevt, Optional<CallingConv::ID> CC)
797  : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798  RegCount(1, regs.size()), CallConv(CC) {}
799 
801  const DataLayout &DL, unsigned Reg, Type *Ty,
803  ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805  CallConv = CC;
806 
807  for (EVT ValueVT : ValueVTs) {
808  unsigned NumRegs =
809  isABIMangled()
810  ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811  : TLI.getNumRegisters(Context, ValueVT);
812  MVT RegisterVT =
813  isABIMangled()
814  ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815  : TLI.getRegisterType(Context, ValueVT);
816  for (unsigned i = 0; i != NumRegs; ++i)
817  Regs.push_back(Reg + i);
818  RegVTs.push_back(RegisterVT);
819  RegCount.push_back(NumRegs);
820  Reg += NumRegs;
821  }
822 }
823 
825  FunctionLoweringInfo &FuncInfo,
826  const SDLoc &dl, SDValue &Chain,
827  SDValue *Flag, const Value *V) const {
828  // A Value with type {} or [0 x %t] needs no registers.
829  if (ValueVTs.empty())
830  return SDValue();
831 
832  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834  // Assemble the legal parts into the final values.
835  SmallVector<SDValue, 4> Values(ValueVTs.size());
837  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838  // Copy the legal parts from the registers.
839  EVT ValueVT = ValueVTs[Value];
840  unsigned NumRegs = RegCount[Value];
841  MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842  *DAG.getContext(),
844  : RegVTs[Value];
845 
846  Parts.resize(NumRegs);
847  for (unsigned i = 0; i != NumRegs; ++i) {
848  SDValue P;
849  if (!Flag) {
850  P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851  } else {
852  P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853  *Flag = P.getValue(2);
854  }
855 
856  Chain = P.getValue(1);
857  Parts[i] = P;
858 
859  // If the source register was virtual and if we know something about it,
860  // add an assert node.
861  if (!Register::isVirtualRegister(Regs[Part + i]) ||
862  !RegisterVT.isInteger())
863  continue;
864 
866  FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867  if (!LOI)
868  continue;
869 
870  unsigned RegSize = RegisterVT.getScalarSizeInBits();
871  unsigned NumSignBits = LOI->NumSignBits;
872  unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874  if (NumZeroBits == RegSize) {
875  // The current value is a zero.
876  // Explicitly express that as it would be easier for
877  // optimizations to kick in.
878  Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879  continue;
880  }
881 
882  // FIXME: We capture more information than the dag can represent. For
883  // now, just use the tightest assertzext/assertsext possible.
884  bool isSExt;
885  EVT FromVT(MVT::Other);
886  if (NumZeroBits) {
887  FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888  isSExt = false;
889  } else if (NumSignBits > 1) {
890  FromVT =
891  EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892  isSExt = true;
893  } else {
894  continue;
895  }
896  // Add an assertion node.
897  assert(FromVT != MVT::Other);
898  Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899  RegisterVT, P, DAG.getValueType(FromVT));
900  }
901 
902  Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903  RegisterVT, ValueVT, V, CallConv);
904  Part += NumRegs;
905  Parts.clear();
906  }
907 
908  return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
912  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913  const Value *V,
914  ISD::NodeType PreferredExtendType) const {
915  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916  ISD::NodeType ExtendKind = PreferredExtendType;
917 
918  // Get the list of the values's legal parts.
919  unsigned NumRegs = Regs.size();
920  SmallVector<SDValue, 8> Parts(NumRegs);
921  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922  unsigned NumParts = RegCount[Value];
923 
924  MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925  *DAG.getContext(),
927  : RegVTs[Value];
928 
929  if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
930  ExtendKind = ISD::ZERO_EXTEND;
931 
932  getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
933  NumParts, RegisterVT, V, CallConv, ExtendKind);
934  Part += NumParts;
935  }
936 
937  // Copy the parts into the registers.
938  SmallVector<SDValue, 8> Chains(NumRegs);
939  for (unsigned i = 0; i != NumRegs; ++i) {
940  SDValue Part;
941  if (!Flag) {
942  Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
943  } else {
944  Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
945  *Flag = Part.getValue(1);
946  }
947 
948  Chains[i] = Part.getValue(0);
949  }
950 
951  if (NumRegs == 1 || Flag)
952  // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
953  // flagged to it. That is the CopyToReg nodes and the user are considered
954  // a single scheduling unit. If we create a TokenFactor and return it as
955  // chain, then the TokenFactor is both a predecessor (operand) of the
956  // user as well as a successor (the TF operands are flagged to the user).
957  // c1, f1 = CopyToReg
958  // c2, f2 = CopyToReg
959  // c3 = TokenFactor c1, c2
960  // ...
961  // = op c3, ..., f2
962  Chain = Chains[NumRegs-1];
963  else
964  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
965 }
966 
967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
968  unsigned MatchingIdx, const SDLoc &dl,
969  SelectionDAG &DAG,
970  std::vector<SDValue> &Ops) const {
971  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
972 
973  unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
974  if (HasMatching)
976  else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
977  // Put the register class of the virtual registers in the flag word. That
978  // way, later passes can recompute register class constraints for inline
979  // assembly as well as normal instructions.
980  // Don't do this for tied operands that can use the regclass information
981  // from the def.
983  const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
985  }
986 
987  SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
988  Ops.push_back(Res);
989 
990  if (Code == InlineAsm::Kind_Clobber) {
991  // Clobbers should always have a 1:1 mapping with registers, and may
992  // reference registers that have illegal (e.g. vector) types. Hence, we
993  // shouldn't try to apply any sort of splitting logic to them.
994  assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
995  "No 1:1 mapping from clobbers to regs?");
997  (void)SP;
998  for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
999  Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1000  assert(
1001  (Regs[I] != SP ||
1003  "If we clobbered the stack pointer, MFI should know about it.");
1004  }
1005  return;
1006  }
1007 
1008  for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1009  MVT RegisterVT = RegVTs[Value];
1010  unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1011  RegisterVT);
1012  for (unsigned i = 0; i != NumRegs; ++i) {
1013  assert(Reg < Regs.size() && "Mismatch in # registers expected");
1014  unsigned TheReg = Regs[Reg++];
1015  Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1016  }
1017  }
1018 }
1019 
1023  unsigned I = 0;
1024  for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1025  unsigned RegCount = std::get<0>(CountAndVT);
1026  MVT RegisterVT = std::get<1>(CountAndVT);
1027  TypeSize RegisterSize = RegisterVT.getSizeInBits();
1028  for (unsigned E = I + RegCount; I != E; ++I)
1029  OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1030  }
1031  return OutVec;
1032 }
1033 
1035  const TargetLibraryInfo *li) {
1036  AA = aa;
1037  GFI = gfi;
1038  LibInfo = li;
1039  Context = DAG.getContext();
1040  LPadToCallSiteMap.clear();
1041  SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1042 }
1043 
1045  NodeMap.clear();
1046  UnusedArgNodeMap.clear();
1047  PendingLoads.clear();
1048  PendingExports.clear();
1049  PendingConstrainedFP.clear();
1050  PendingConstrainedFPStrict.clear();
1051  CurInst = nullptr;
1052  HasTailCall = false;
1053  SDNodeOrder = LowestSDNodeOrder;
1055 }
1056 
1058  DanglingDebugInfoMap.clear();
1059 }
1060 
1061 // Update DAG root to include dependencies on Pending chains.
1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1063  SDValue Root = DAG.getRoot();
1064 
1065  if (Pending.empty())
1066  return Root;
1067 
1068  // Add current root to PendingChains, unless we already indirectly
1069  // depend on it.
1070  if (Root.getOpcode() != ISD::EntryToken) {
1071  unsigned i = 0, e = Pending.size();
1072  for (; i != e; ++i) {
1073  assert(Pending[i].getNode()->getNumOperands() > 1);
1074  if (Pending[i].getNode()->getOperand(0) == Root)
1075  break; // Don't add the root if we already indirectly depend on it.
1076  }
1077 
1078  if (i == e)
1079  Pending.push_back(Root);
1080  }
1081 
1082  if (Pending.size() == 1)
1083  Root = Pending[0];
1084  else
1085  Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1086 
1087  DAG.setRoot(Root);
1088  Pending.clear();
1089  return Root;
1090 }
1091 
1093  return updateRoot(PendingLoads);
1094 }
1095 
1097  // Chain up all pending constrained intrinsics together with all
1098  // pending loads, by simply appending them to PendingLoads and
1099  // then calling getMemoryRoot().
1100  PendingLoads.reserve(PendingLoads.size() +
1101  PendingConstrainedFP.size() +
1102  PendingConstrainedFPStrict.size());
1103  PendingLoads.append(PendingConstrainedFP.begin(),
1104  PendingConstrainedFP.end());
1105  PendingLoads.append(PendingConstrainedFPStrict.begin(),
1106  PendingConstrainedFPStrict.end());
1107  PendingConstrainedFP.clear();
1108  PendingConstrainedFPStrict.clear();
1109  return getMemoryRoot();
1110 }
1111 
1113  // We need to emit pending fpexcept.strict constrained intrinsics,
1114  // so append them to the PendingExports list.
1115  PendingExports.append(PendingConstrainedFPStrict.begin(),
1116  PendingConstrainedFPStrict.end());
1117  PendingConstrainedFPStrict.clear();
1118  return updateRoot(PendingExports);
1119 }
1120 
1122  // Set up outgoing PHI node register values before emitting the terminator.
1123  if (I.isTerminator()) {
1124  HandlePHINodesInSuccessorBlocks(I.getParent());
1125  }
1126 
1127  // Increase the SDNodeOrder if dealing with a non-debug instruction.
1128  if (!isa<DbgInfoIntrinsic>(I))
1129  ++SDNodeOrder;
1130 
1131  CurInst = &I;
1132 
1133  visit(I.getOpcode(), I);
1134 
1135  if (!I.isTerminator() && !HasTailCall &&
1136  !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1138 
1139  CurInst = nullptr;
1140 }
1141 
1142 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1143  llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1144 }
1145 
1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1147  // Note: this doesn't use InstVisitor, because it has to work with
1148  // ConstantExpr's in addition to instructions.
1149  switch (Opcode) {
1150  default: llvm_unreachable("Unknown instruction type encountered!");
1151  // Build the switch statement using the Instruction.def file.
1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1153  case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1154 #include "llvm/IR/Instruction.def"
1155  }
1156 }
1157 
1159  DebugLoc DL, unsigned Order) {
1160  // We treat variadic dbg_values differently at this stage.
1161  if (DI->hasArgList()) {
1162  // For variadic dbg_values we will now insert an undef.
1163  // FIXME: We can potentially recover these!
1165  for (const Value *V : DI->getValues()) {
1166  auto Undef = UndefValue::get(V->getType());
1167  Locs.push_back(SDDbgOperand::fromConst(Undef));
1168  }
1170  DI->getVariable(), DI->getExpression(), Locs, {},
1171  /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1172  DAG.AddDbgValue(SDV, /*isParameter=*/false);
1173  } else {
1174  // TODO: Dangling debug info will eventually either be resolved or produce
1175  // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1176  // between the original dbg.value location and its resolved DBG_VALUE,
1177  // which we should ideally fill with an extra Undef DBG_VALUE.
1178  assert(DI->getNumVariableLocationOps() == 1 &&
1179  "DbgValueInst without an ArgList should have a single location "
1180  "operand.");
1181  DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1182  }
1183 }
1184 
1186  const DIExpression *Expr) {
1187  auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1188  const DbgValueInst *DI = DDI.getDI();
1189  DIVariable *DanglingVariable = DI->getVariable();
1190  DIExpression *DanglingExpr = DI->getExpression();
1191  if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1192  LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1193  return true;
1194  }
1195  return false;
1196  };
1197 
1198  for (auto &DDIMI : DanglingDebugInfoMap) {
1199  DanglingDebugInfoVector &DDIV = DDIMI.second;
1200 
1201  // If debug info is to be dropped, run it through final checks to see
1202  // whether it can be salvaged.
1203  for (auto &DDI : DDIV)
1204  if (isMatchingDbgValue(DDI))
1206 
1207  erase_if(DDIV, isMatchingDbgValue);
1208  }
1209 }
1210 
1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1212 // generate the debug data structures now that we've seen its definition.
1214  SDValue Val) {
1215  auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1216  if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1217  return;
1218 
1219  DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1220  for (auto &DDI : DDIV) {
1221  const DbgValueInst *DI = DDI.getDI();
1222  assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1223  assert(DI && "Ill-formed DanglingDebugInfo");
1224  DebugLoc dl = DDI.getdl();
1225  unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1226  unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1227  DILocalVariable *Variable = DI->getVariable();
1228  DIExpression *Expr = DI->getExpression();
1229  assert(Variable->isValidLocationForIntrinsic(dl) &&
1230  "Expected inlined-at fields to agree");
1231  SDDbgValue *SDV;
1232  if (Val.getNode()) {
1233  // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1234  // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1235  // we couldn't resolve it directly when examining the DbgValue intrinsic
1236  // in the first place we should not be more successful here). Unless we
1237  // have some test case that prove this to be correct we should avoid
1238  // calling EmitFuncArgumentDbgValue here.
1239  if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1240  LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1241  << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
1242  LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1243  // Increase the SDNodeOrder for the DbgValue here to make sure it is
1244  // inserted after the definition of Val when emitting the instructions
1245  // after ISel. An alternative could be to teach
1246  // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1247  LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1248  << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1249  << ValSDNodeOrder << "\n");
1250  SDV = getDbgValue(Val, Variable, Expr, dl,
1251  std::max(DbgSDNodeOrder, ValSDNodeOrder));
1252  DAG.AddDbgValue(SDV, false);
1253  } else
1254  LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1255  << "in EmitFuncArgumentDbgValue\n");
1256  } else {
1257  LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1258  auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1259  auto SDV =
1260  DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1261  DAG.AddDbgValue(SDV, false);
1262  }
1263  }
1264  DDIV.clear();
1265 }
1266 
1268  // TODO: For the variadic implementation, instead of only checking the fail
1269  // state of `handleDebugValue`, we need know specifically which values were
1270  // invalid, so that we attempt to salvage only those values when processing
1271  // a DIArgList.
1272  assert(!DDI.getDI()->hasArgList() &&
1273  "Not implemented for variadic dbg_values");
1274  Value *V = DDI.getDI()->getValue(0);
1275  DILocalVariable *Var = DDI.getDI()->getVariable();
1276  DIExpression *Expr = DDI.getDI()->getExpression();
1277  DebugLoc DL = DDI.getdl();
1278  DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1279  unsigned SDOrder = DDI.getSDNodeOrder();
1280  // Currently we consider only dbg.value intrinsics -- we tell the salvager
1281  // that DW_OP_stack_value is desired.
1282  assert(isa<DbgValueInst>(DDI.getDI()));
1283  bool StackValue = true;
1284 
1285  // Can this Value can be encoded without any further work?
1286  if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1287  return;
1288 
1289  // Attempt to salvage back through as many instructions as possible. Bail if
1290  // a non-instruction is seen, such as a constant expression or global
1291  // variable. FIXME: Further work could recover those too.
1292  while (isa<Instruction>(V)) {
1293  Instruction &VAsInst = *cast<Instruction>(V);
1294  // Temporary "0", awaiting real implementation.
1296  SmallVector<Value *, 4> AdditionalValues;
1297  V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1298  AdditionalValues);
1299  // If we cannot salvage any further, and haven't yet found a suitable debug
1300  // expression, bail out.
1301  if (!V)
1302  break;
1303 
1304  // TODO: If AdditionalValues isn't empty, then the salvage can only be
1305  // represented with a DBG_VALUE_LIST, so we give up. When we have support
1306  // here for variadic dbg_values, remove that condition.
1307  if (!AdditionalValues.empty())
1308  break;
1309 
1310  // New value and expr now represent this debuginfo.
1311  Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1312 
1313  // Some kind of simplification occurred: check whether the operand of the
1314  // salvaged debug expression can be encoded in this DAG.
1315  if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1316  /*IsVariadic=*/false)) {
1317  LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
1318  << DDI.getDI() << "\nBy stripping back to:\n " << V);
1319  return;
1320  }
1321  }
1322 
1323  // This was the final opportunity to salvage this debug information, and it
1324  // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1325  // any earlier variable location.
1326  auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1327  auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1328  DAG.AddDbgValue(SDV, false);
1329 
1330  LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
1331  << "\n");
1332  LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
1333  << "\n");
1334 }
1335 
1337  DILocalVariable *Var,
1338  DIExpression *Expr, DebugLoc dl,
1339  DebugLoc InstDL, unsigned Order,
1340  bool IsVariadic) {
1341  if (Values.empty())
1342  return true;
1343  SmallVector<SDDbgOperand> LocationOps;
1344  SmallVector<SDNode *> Dependencies;
1345  for (const Value *V : Values) {
1346  // Constant value.
1347  if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1348  isa<ConstantPointerNull>(V)) {
1349  LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1350  continue;
1351  }
1352 
1353  // If the Value is a frame index, we can create a FrameIndex debug value
1354  // without relying on the DAG at all.
1355  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1356  auto SI = FuncInfo.StaticAllocaMap.find(AI);
1357  if (SI != FuncInfo.StaticAllocaMap.end()) {
1358  LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1359  continue;
1360  }
1361  }
1362 
1363  // Do not use getValue() in here; we don't want to generate code at
1364  // this point if it hasn't been done yet.
1365  SDValue N = NodeMap[V];
1366  if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1367  N = UnusedArgNodeMap[V];
1368  if (N.getNode()) {
1369  // Only emit func arg dbg value for non-variadic dbg.values for now.
1370  if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1371  return true;
1372  if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1373  // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1374  // describe stack slot locations.
1375  //
1376  // Consider "int x = 0; int *px = &x;". There are two kinds of
1377  // interesting debug values here after optimization:
1378  //
1379  // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1380  // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1381  //
1382  // Both describe the direct values of their associated variables.
1383  Dependencies.push_back(N.getNode());
1384  LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1385  continue;
1386  }
1387  LocationOps.emplace_back(
1388  SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1389  continue;
1390  }
1391 
1392  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1393  // Special rules apply for the first dbg.values of parameter variables in a
1394  // function. Identify them by the fact they reference Argument Values, that
1395  // they're parameters, and they are parameters of the current function. We
1396  // need to let them dangle until they get an SDNode.
1397  bool IsParamOfFunc =
1398  isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1399  if (IsParamOfFunc)
1400  return false;
1401 
1402  // The value is not used in this block yet (or it would have an SDNode).
1403  // We still want the value to appear for the user if possible -- if it has
1404  // an associated VReg, we can refer to that instead.
1405  auto VMI = FuncInfo.ValueMap.find(V);
1406  if (VMI != FuncInfo.ValueMap.end()) {
1407  unsigned Reg = VMI->second;
1408  // If this is a PHI node, it may be split up into several MI PHI nodes
1409  // (in FunctionLoweringInfo::set).
1410  RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1411  V->getType(), None);
1412  if (RFV.occupiesMultipleRegs()) {
1413  // FIXME: We could potentially support variadic dbg_values here.
1414  if (IsVariadic)
1415  return false;
1416  unsigned Offset = 0;
1417  unsigned BitsToDescribe = 0;
1418  if (auto VarSize = Var->getSizeInBits())
1419  BitsToDescribe = *VarSize;
1420  if (auto Fragment = Expr->getFragmentInfo())
1421  BitsToDescribe = Fragment->SizeInBits;
1422  for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1423  // Bail out if all bits are described already.
1424  if (Offset >= BitsToDescribe)
1425  break;
1426  // TODO: handle scalable vectors.
1427  unsigned RegisterSize = RegAndSize.second;
1428  unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1429  ? BitsToDescribe - Offset
1430  : RegisterSize;
1431  auto FragmentExpr = DIExpression::createFragmentExpression(
1432  Expr, Offset, FragmentSize);
1433  if (!FragmentExpr)
1434  continue;
1436  Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1437  DAG.AddDbgValue(SDV, false);
1438  Offset += RegisterSize;
1439  }
1440  return true;
1441  }
1442  // We can use simple vreg locations for variadic dbg_values as well.
1443  LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1444  continue;
1445  }
1446  // We failed to create a SDDbgOperand for V.
1447  return false;
1448  }
1449 
1450  // We have created a SDDbgOperand for each Value in Values.
1451  // Should use Order instead of SDNodeOrder?
1452  assert(!LocationOps.empty());
1453  SDDbgValue *SDV =
1454  DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1455  /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1456  DAG.AddDbgValue(SDV, /*isParameter=*/false);
1457  return true;
1458 }
1459 
1461  // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1462  for (auto &Pair : DanglingDebugInfoMap)
1463  for (auto &DDI : Pair.second)
1466 }
1467 
1468 /// getCopyFromRegs - If there was virtual register allocated for the value V
1469 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1472  SDValue Result;
1473 
1474  if (It != FuncInfo.ValueMap.end()) {
1475  Register InReg = It->second;
1476 
1478  DAG.getDataLayout(), InReg, Ty,
1479  None); // This is not an ABI copy.
1480  SDValue Chain = DAG.getEntryNode();
1481  Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1482  V);
1483  resolveDanglingDebugInfo(V, Result);
1484  }
1485 
1486  return Result;
1487 }
1488 
1489 /// getValue - Return an SDValue for the given Value.
1491  // If we already have an SDValue for this value, use it. It's important
1492  // to do this first, so that we don't create a CopyFromReg if we already
1493  // have a regular SDValue.
1494  SDValue &N = NodeMap[V];
1495  if (N.getNode()) return N;
1496 
1497  // If there's a virtual register allocated and initialized for this
1498  // value, use it.
1499  if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1500  return copyFromReg;
1501 
1502  // Otherwise create a new SDValue and remember it.
1503  SDValue Val = getValueImpl(V);
1504  NodeMap[V] = Val;
1505  resolveDanglingDebugInfo(V, Val);
1506  return Val;
1507 }
1508 
1509 /// getNonRegisterValue - Return an SDValue for the given Value, but
1510 /// don't look in FuncInfo.ValueMap for a virtual register.
1512  // If we already have an SDValue for this value, use it.
1513  SDValue &N = NodeMap[V];
1514  if (N.getNode()) {
1515  if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1516  // Remove the debug location from the node as the node is about to be used
1517  // in a location which may differ from the original debug location. This
1518  // is relevant to Constant and ConstantFP nodes because they can appear
1519  // as constant expressions inside PHI nodes.
1520  N->setDebugLoc(DebugLoc());
1521  }
1522  return N;
1523  }
1524 
1525  // Otherwise create a new SDValue and remember it.
1526  SDValue Val = getValueImpl(V);
1527  NodeMap[V] = Val;
1528  resolveDanglingDebugInfo(V, Val);
1529  return Val;
1530 }
1531 
1532 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1533 /// Create an SDValue for the given value.
1535  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1536 
1537  if (const Constant *C = dyn_cast<Constant>(V)) {
1538  EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1539 
1540  if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541  return DAG.getConstant(*CI, getCurSDLoc(), VT);
1542 
1543  if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1544  return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1545 
1546  if (isa<ConstantPointerNull>(C)) {
1547  unsigned AS = V->getType()->getPointerAddressSpace();
1548  return DAG.getConstant(0, getCurSDLoc(),
1549  TLI.getPointerTy(DAG.getDataLayout(), AS));
1550  }
1551 
1552  if (match(C, m_VScale(DAG.getDataLayout())))
1553  return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1554 
1555  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1556  return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1557 
1558  if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1559  return DAG.getUNDEF(VT);
1560 
1561  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1562  visit(CE->getOpcode(), *CE);
1563  SDValue N1 = NodeMap[V];
1564  assert(N1.getNode() && "visit didn't populate the NodeMap!");
1565  return N1;
1566  }
1567 
1568  if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1570  for (const Use &U : C->operands()) {
1571  SDNode *Val = getValue(U).getNode();
1572  // If the operand is an empty aggregate, there are no values.
1573  if (!Val) continue;
1574  // Add each leaf value from the operand to the Constants list
1575  // to form a flattened list of all the values.
1576  for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1577  Constants.push_back(SDValue(Val, i));
1578  }
1579 
1581  }
1582 
1583  if (const ConstantDataSequential *CDS =
1584  dyn_cast<ConstantDataSequential>(C)) {
1586  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1587  SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1588  // Add each leaf value from the operand to the Constants list
1589  // to form a flattened list of all the values.
1590  for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1591  Ops.push_back(SDValue(Val, i));
1592  }
1593 
1594  if (isa<ArrayType>(CDS->getType()))
1595  return DAG.getMergeValues(Ops, getCurSDLoc());
1596  return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1597  }
1598 
1599  if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1600  assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1601  "Unknown struct or array constant!");
1602 
1603  SmallVector<EVT, 4> ValueVTs;
1604  ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1605  unsigned NumElts = ValueVTs.size();
1606  if (NumElts == 0)
1607  return SDValue(); // empty struct
1609  for (unsigned i = 0; i != NumElts; ++i) {
1610  EVT EltVT = ValueVTs[i];
1611  if (isa<UndefValue>(C))
1612  Constants[i] = DAG.getUNDEF(EltVT);
1613  else if (EltVT.isFloatingPoint())
1614  Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1615  else
1616  Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1617  }
1618 
1620  }
1621 
1622  if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1623  return DAG.getBlockAddress(BA, VT);
1624 
1625  if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1626  return getValue(Equiv->getGlobalValue());
1627 
1628  if (const auto *NC = dyn_cast<NoCFIValue>(C))
1629  return getValue(NC->getGlobalValue());
1630 
1631  VectorType *VecTy = cast<VectorType>(V->getType());
1632 
1633  // Now that we know the number and type of the elements, get that number of
1634  // elements into the Ops array based on what kind of constant it is.
1635  if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1637  unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1638  for (unsigned i = 0; i != NumElements; ++i)
1639  Ops.push_back(getValue(CV->getOperand(i)));
1640 
1641  return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1642  } else if (isa<ConstantAggregateZero>(C)) {
1643  EVT EltVT =
1644  TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1645 
1646  SDValue Op;
1647  if (EltVT.isFloatingPoint())
1648  Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1649  else
1650  Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1651 
1652  if (isa<ScalableVectorType>(VecTy))
1653  return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1654  else {
1656  Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1657  return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1658  }
1659  }
1660  llvm_unreachable("Unknown vector constant");
1661  }
1662 
1663  // If this is a static alloca, generate it as the frameindex instead of
1664  // computation.
1665  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1667  FuncInfo.StaticAllocaMap.find(AI);
1668  if (SI != FuncInfo.StaticAllocaMap.end())
1669  return DAG.getFrameIndex(SI->second,
1671  }
1672 
1673  // If this is an instruction which fast-isel has deferred, select it now.
1674  if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1675  unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1676 
1677  RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1678  Inst->getType(), None);
1679  SDValue Chain = DAG.getEntryNode();
1680  return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1681  }
1682 
1683  if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1684  return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1685  }
1686  if (const auto *BB = dyn_cast<BasicBlock>(V))
1687  return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1688  llvm_unreachable("Can't get register for value!");
1689 }
1690 
1691 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1693  bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1694  bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1695  bool IsSEH = isAsynchronousEHPersonality(Pers);
1696  MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1697  if (!IsSEH)
1698  CatchPadMBB->setIsEHScopeEntry();
1699  // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1700  if (IsMSVCCXX || IsCoreCLR)
1701  CatchPadMBB->setIsEHFuncletEntry();
1702 }
1703 
1704 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1705  // Update machine-CFG edge.
1706  MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1707  FuncInfo.MBB->addSuccessor(TargetMBB);
1708  TargetMBB->setIsEHCatchretTarget(true);
1710 
1712  bool IsSEH = isAsynchronousEHPersonality(Pers);
1713  if (IsSEH) {
1714  // If this is not a fall-through branch or optimizations are switched off,
1715  // emit the branch.
1716  if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1717  TM.getOptLevel() == CodeGenOpt::None)
1719  getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1720  return;
1721  }
1722 
1723  // Figure out the funclet membership for the catchret's successor.
1724  // This will be used by the FuncletLayout pass to determine how to order the
1725  // BB's.
1726  // A 'catchret' returns to the outer scope's color.
1727  Value *ParentPad = I.getCatchSwitchParentPad();
1728  const BasicBlock *SuccessorColor;
1729  if (isa<ConstantTokenNone>(ParentPad))
1730  SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1731  else
1732  SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1733  assert(SuccessorColor && "No parent funclet for catchret!");
1734  MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1735  assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1736 
1737  // Create the terminator node.
1739  getControlRoot(), DAG.getBasicBlock(TargetMBB),
1740  DAG.getBasicBlock(SuccessorColorMBB));
1741  DAG.setRoot(Ret);
1742 }
1743 
1744 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1745  // Don't emit any special code for the cleanuppad instruction. It just marks
1746  // the start of an EH scope/funclet.
1749  if (Pers != EHPersonality::Wasm_CXX) {
1752  }
1753 }
1754 
1755 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1756 // not match, it is OK to add only the first unwind destination catchpad to the
1757 // successors, because there will be at least one invoke instruction within the
1758 // catch scope that points to the next unwind destination, if one exists, so
1759 // CFGSort cannot mess up with BB sorting order.
1760 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1761 // call within them, and catchpads only consisting of 'catch (...)' have a
1762 // '__cxa_end_catch' call within them, both of which generate invokes in case
1763 // the next unwind destination exists, i.e., the next unwind destination is not
1764 // the caller.)
1765 //
1766 // Having at most one EH pad successor is also simpler and helps later
1767 // transformations.
1768 //
1769 // For example,
1770 // current:
1771 // invoke void @foo to ... unwind label %catch.dispatch
1772 // catch.dispatch:
1773 // %0 = catchswitch within ... [label %catch.start] unwind label %next
1774 // catch.start:
1775 // ...
1776 // ... in this BB or some other child BB dominated by this BB there will be an
1777 // invoke that points to 'next' BB as an unwind destination
1778 //
1779 // next: ; We don't need to add this to 'current' BB's successor
1780 // ...
1782  FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1783  BranchProbability Prob,
1784  SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1785  &UnwindDests) {
1786  while (EHPadBB) {
1787  const Instruction *Pad = EHPadBB->getFirstNonPHI();
1788  if (isa<CleanupPadInst>(Pad)) {
1789  // Stop on cleanup pads.
1790  UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1791  UnwindDests.back().first->setIsEHScopeEntry();
1792  break;
1793  } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1794  // Add the catchpad handlers to the possible destinations. We don't
1795  // continue to the unwind destination of the catchswitch for wasm.
1796  for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1797  UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1798  UnwindDests.back().first->setIsEHScopeEntry();
1799  }
1800  break;
1801  } else {
1802  continue;
1803  }
1804  }
1805 }
1806 
1807 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1808 /// many places it could ultimately go. In the IR, we have a single unwind
1809 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1810 /// This function skips over imaginary basic blocks that hold catchswitch
1811 /// instructions, and finds all the "real" machine
1812 /// basic block destinations. As those destinations may not be successors of
1813 /// EHPadBB, here we also calculate the edge probability to those destinations.
1814 /// The passed-in Prob is the edge probability to EHPadBB.
1816  FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1817  BranchProbability Prob,
1818  SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1819  &UnwindDests) {
1820  EHPersonality Personality =
1822  bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1823  bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1824  bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1825  bool IsSEH = isAsynchronousEHPersonality(Personality);
1826 
1827  if (IsWasmCXX) {
1828  findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1829  assert(UnwindDests.size() <= 1 &&
1830  "There should be at most one unwind destination for wasm");
1831  return;
1832  }
1833 
1834  while (EHPadBB) {
1835  const Instruction *Pad = EHPadBB->getFirstNonPHI();
1836  BasicBlock *NewEHPadBB = nullptr;
1837  if (isa<LandingPadInst>(Pad)) {
1838  // Stop on landingpads. They are not funclets.
1839  UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1840  break;
1841  } else if (isa<CleanupPadInst>(Pad)) {
1842  // Stop on cleanup pads. Cleanups are always funclet entries for all known
1843  // personalities.
1844  UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1845  UnwindDests.back().first->setIsEHScopeEntry();
1846  UnwindDests.back().first->setIsEHFuncletEntry();
1847  break;
1848  } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1849  // Add the catchpad handlers to the possible destinations.
1850  for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1851  UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1852  // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1853  if (IsMSVCCXX || IsCoreCLR)
1854  UnwindDests.back().first->setIsEHFuncletEntry();
1855  if (!IsSEH)
1856  UnwindDests.back().first->setIsEHScopeEntry();
1857  }
1858  NewEHPadBB = CatchSwitch->getUnwindDest();
1859  } else {
1860  continue;
1861  }
1862 
1863  BranchProbabilityInfo *BPI = FuncInfo.BPI;
1864  if (BPI && NewEHPadBB)
1865  Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1866  EHPadBB = NewEHPadBB;
1867  }
1868 }
1869 
1870 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1871  // Update successor info.
1873  auto UnwindDest = I.getUnwindDest();
1875  BranchProbability UnwindDestProb =
1876  (BPI && UnwindDest)
1877  ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1879  findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1880  for (auto &UnwindDest : UnwindDests) {
1881  UnwindDest.first->setIsEHPad();
1882  addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1883  }
1885 
1886  // Create the terminator node.
1887  SDValue Ret =
1889  DAG.setRoot(Ret);
1890 }
1891 
1892 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1893  report_fatal_error("visitCatchSwitch not yet implemented!");
1894 }
1895 
1896 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1897  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1898  auto &DL = DAG.getDataLayout();
1899  SDValue Chain = getControlRoot();
1901  SmallVector<SDValue, 8> OutVals;
1902 
1903  // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1904  // lower
1905  //
1906  // %val = call <ty> @llvm.experimental.deoptimize()
1907  // ret <ty> %val
1908  //
1909  // differently.
1910  if (I.getParent()->getTerminatingDeoptimizeCall()) {
1912  return;
1913  }
1914 
1915  if (!FuncInfo.CanLowerReturn) {
1916  unsigned DemoteReg = FuncInfo.DemoteRegister;
1917  const Function *F = I.getParent()->getParent();
1918 
1919  // Emit a store of the return value through the virtual register.
1920  // Leave Outs empty so that LowerReturn won't try to load return
1921  // registers the usual way.
1922  SmallVector<EVT, 1> PtrValueVTs;
1923  ComputeValueVTs(TLI, DL,
1924  F->getReturnType()->getPointerTo(
1926  PtrValueVTs);
1927 
1928  SDValue RetPtr =
1929  DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1930  SDValue RetOp = getValue(I.getOperand(0));
1931 
1932  SmallVector<EVT, 4> ValueVTs, MemVTs;
1934  ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1935  &Offsets);
1936  unsigned NumValues = ValueVTs.size();
1937 
1938  SmallVector<SDValue, 4> Chains(NumValues);
1939  Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1940  for (unsigned i = 0; i != NumValues; ++i) {
1941  // An aggregate return value cannot wrap around the address space, so
1942  // offsets to its parts don't wrap either.
1943  SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1945 
1946  SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1947  if (MemVTs[i] != ValueVTs[i])
1948  Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1949  Chains[i] = DAG.getStore(
1950  Chain, getCurSDLoc(), Val,
1951  // FIXME: better loc info would be nice.
1953  commonAlignment(BaseAlign, Offsets[i]));
1954  }
1955 
1957  MVT::Other, Chains);
1958  } else if (I.getNumOperands() != 0) {
1959  SmallVector<EVT, 4> ValueVTs;
1960  ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1961  unsigned NumValues = ValueVTs.size();
1962  if (NumValues) {
1963  SDValue RetOp = getValue(I.getOperand(0));
1964 
1965  const Function *F = I.getParent()->getParent();
1966 
1967  bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1968  I.getOperand(0)->getType(), F->getCallingConv(),
1969  /*IsVarArg*/ false, DL);
1970 
1971  ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1972  if (F->getAttributes().hasRetAttr(Attribute::SExt))
1973  ExtendKind = ISD::SIGN_EXTEND;
1974  else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1975  ExtendKind = ISD::ZERO_EXTEND;
1976 
1977  LLVMContext &Context = F->getContext();
1978  bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1979 
1980  for (unsigned j = 0; j != NumValues; ++j) {
1981  EVT VT = ValueVTs[j];
1982 
1983  if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1984  VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1985 
1986  CallingConv::ID CC = F->getCallingConv();
1987 
1988  unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1989  MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1990  SmallVector<SDValue, 4> Parts(NumParts);
1992  SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1993  &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1994 
1995  // 'inreg' on function refers to return value
1996  ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1997  if (RetInReg)
1998  Flags.setInReg();
1999 
2000  if (I.getOperand(0)->getType()->isPointerTy()) {
2001  Flags.setPointer();
2002  Flags.setPointerAddrSpace(
2003  cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2004  }
2005 
2006  if (NeedsRegBlock) {
2007  Flags.setInConsecutiveRegs();
2008  if (j == NumValues - 1)
2009  Flags.setInConsecutiveRegsLast();
2010  }
2011 
2012  // Propagate extension type if any
2013  if (ExtendKind == ISD::SIGN_EXTEND)
2014  Flags.setSExt();
2015  else if (ExtendKind == ISD::ZERO_EXTEND)
2016  Flags.setZExt();
2017 
2018  for (unsigned i = 0; i < NumParts; ++i) {
2019  Outs.push_back(ISD::OutputArg(Flags,
2020  Parts[i].getValueType().getSimpleVT(),
2021  VT, /*isfixed=*/true, 0, 0));
2022  OutVals.push_back(Parts[i]);
2023  }
2024  }
2025  }
2026  }
2027 
2028  // Push in swifterror virtual register as the last element of Outs. This makes
2029  // sure swifterror virtual register will be returned in the swifterror
2030  // physical register.
2031  const Function *F = I.getParent()->getParent();
2032  if (TLI.supportSwiftError() &&
2033  F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2034  assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2035  ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2036  Flags.setSwiftError();
2037  Outs.push_back(ISD::OutputArg(
2038  Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2039  /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2040  // Create SDNode for the swifterror virtual register.
2041  OutVals.push_back(
2044  EVT(TLI.getPointerTy(DL))));
2045  }
2046 
2047  bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2048  CallingConv::ID CallConv =
2051  Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2052 
2053  // Verify that the target's LowerReturn behaved as expected.
2054  assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2055  "LowerReturn didn't return a valid chain!");
2056 
2057  // Update the DAG with the new chain value resulting from return lowering.
2058  DAG.setRoot(Chain);
2059 }
2060 
2061 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2062 /// created for it, emit nodes to copy the value into the virtual
2063 /// registers.
2065  // Skip empty types
2066  if (V->getType()->isEmptyTy())
2067  return;
2068 
2070  if (VMI != FuncInfo.ValueMap.end()) {
2071  assert(!V->use_empty() && "Unused value assigned virtual registers!");
2072  CopyValueToVirtualRegister(V, VMI->second);
2073  }
2074 }
2075 
2076 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2077 /// the current basic block, add it to ValueMap now so that we'll get a
2078 /// CopyTo/FromReg.
2080  // No need to export constants.
2081  if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2082 
2083  // Already exported?
2084  if (FuncInfo.isExportedInst(V)) return;
2085 
2086  unsigned Reg = FuncInfo.InitializeRegForValue(V);
2088 }
2089 
2091  const BasicBlock *FromBB) {
2092  // The operands of the setcc have to be in this block. We don't know
2093  // how to export them from some other block.
2094  if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2095  // Can export from current BB.
2096  if (VI->getParent() == FromBB)
2097  return true;
2098 
2099  // Is already exported, noop.
2100  return FuncInfo.isExportedInst(V);
2101  }
2102 
2103  // If this is an argument, we can export it if the BB is the entry block or
2104  // if it is already exported.
2105  if (isa<Argument>(V)) {
2106  if (FromBB->isEntryBlock())
2107  return true;
2108 
2109  // Otherwise, can only export this if it is already exported.
2110  return FuncInfo.isExportedInst(V);
2111  }
2112 
2113  // Otherwise, constants can always be exported.
2114  return true;
2115 }
2116 
2117 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2119 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2120  const MachineBasicBlock *Dst) const {
2122  const BasicBlock *SrcBB = Src->getBasicBlock();
2123  const BasicBlock *DstBB = Dst->getBasicBlock();
2124  if (!BPI) {
2125  // If BPI is not available, set the default probability as 1 / N, where N is
2126  // the number of successors.
2127  auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2128  return BranchProbability(1, SuccSize);
2129  }
2130  return BPI->getEdgeProbability(SrcBB, DstBB);
2131 }
2132 
2133 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2134  MachineBasicBlock *Dst,
2135  BranchProbability Prob) {
2136  if (!FuncInfo.BPI)
2137  Src->addSuccessorWithoutProb(Dst);
2138  else {
2139  if (Prob.isUnknown())
2140  Prob = getEdgeProbability(Src, Dst);
2141  Src->addSuccessor(Dst, Prob);
2142  }
2143 }
2144 
2145 static bool InBlock(const Value *V, const BasicBlock *BB) {
2146  if (const Instruction *I = dyn_cast<Instruction>(V))
2147  return I->getParent() == BB;
2148  return true;
2149 }
2150 
2151 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2152 /// This function emits a branch and is used at the leaves of an OR or an
2153 /// AND operator tree.
2154 void
2156  MachineBasicBlock *TBB,
2157  MachineBasicBlock *FBB,
2158  MachineBasicBlock *CurBB,
2159  MachineBasicBlock *SwitchBB,
2160  BranchProbability TProb,
2161  BranchProbability FProb,
2162  bool InvertCond) {
2163  const BasicBlock *BB = CurBB->getBasicBlock();
2164 
2165  // If the leaf of the tree is a comparison, merge the condition into
2166  // the caseblock.
2167  if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2168  // The operands of the cmp have to be in this block. We don't know
2169  // how to export them from some other block. If this is the first block
2170  // of the sequence, no exporting is needed.
2171  if (CurBB == SwitchBB ||
2172  (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2173  isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2174  ISD::CondCode Condition;
2175  if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2176  ICmpInst::Predicate Pred =
2177  InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2178  Condition = getICmpCondCode(Pred);
2179  } else {
2180  const FCmpInst *FC = cast<FCmpInst>(Cond);
2181  FCmpInst::Predicate Pred =
2182  InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2183  Condition = getFCmpCondCode(Pred);
2184  if (TM.Options.NoNaNsFPMath)
2185  Condition = getFCmpCodeWithoutNaN(Condition);
2186  }
2187 
2188  CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2189  TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2190  SL->SwitchCases.push_back(CB);
2191  return;
2192  }
2193  }
2194 
2195  // Create a CaseBlock record representing this branch.
2196  ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2197  CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2198  nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2199  SL->SwitchCases.push_back(CB);
2200 }
2201 
2203  MachineBasicBlock *TBB,
2204  MachineBasicBlock *FBB,
2205  MachineBasicBlock *CurBB,
2206  MachineBasicBlock *SwitchBB,
2208  BranchProbability TProb,
2209  BranchProbability FProb,
2210  bool InvertCond) {
2211  // Skip over not part of the tree and remember to invert op and operands at
2212  // next level.
2213  Value *NotCond;
2214  if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2215  InBlock(NotCond, CurBB->getBasicBlock())) {
2216  FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2217  !InvertCond);
2218  return;
2219  }
2220 
2221  const Instruction *BOp = dyn_cast<Instruction>(Cond);
2222  const Value *BOpOp0, *BOpOp1;
2223  // Compute the effective opcode for Cond, taking into account whether it needs
2224  // to be inverted, e.g.
2225  // and (not (or A, B)), C
2226  // gets lowered as
2227  // and (and (not A, not B), C)
2229  if (BOp) {
2230  BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2231  ? Instruction::And
2232  : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2233  ? Instruction::Or
2234  : (Instruction::BinaryOps)0);
2235  if (InvertCond) {
2236  if (BOpc == Instruction::And)
2237  BOpc = Instruction::Or;
2238  else if (BOpc == Instruction::Or)
2239  BOpc = Instruction::And;
2240  }
2241  }
2242 
2243  // If this node is not part of the or/and tree, emit it as a branch.
2244  // Note that all nodes in the tree should have same opcode.
2245  bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2246  if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2247  !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2248  !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2249  EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2250  TProb, FProb, InvertCond);
2251  return;
2252  }
2253 
2254  // Create TmpBB after CurBB.
2255  MachineFunction::iterator BBI(CurBB);
2258  CurBB->getParent()->insert(++BBI, TmpBB);
2259 
2260  if (Opc == Instruction::Or) {
2261  // Codegen X | Y as:
2262  // BB1:
2263  // jmp_if_X TBB
2264  // jmp TmpBB
2265  // TmpBB:
2266  // jmp_if_Y TBB
2267  // jmp FBB
2268  //
2269 
2270  // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2271  // The requirement is that
2272  // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2273  // = TrueProb for original BB.
2274  // Assuming the original probabilities are A and B, one choice is to set
2275  // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2276  // A/(1+B) and 2B/(1+B). This choice assumes that
2277  // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2278  // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2279  // TmpBB, but the math is more complicated.
2280 
2281  auto NewTrueProb = TProb / 2;
2282  auto NewFalseProb = TProb / 2 + FProb;
2283  // Emit the LHS condition.
2284  FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2285  NewFalseProb, InvertCond);
2286 
2287  // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2288  SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2289  BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2290  // Emit the RHS condition into TmpBB.
2291  FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2292  Probs[1], InvertCond);
2293  } else {
2294  assert(Opc == Instruction::And && "Unknown merge op!");
2295  // Codegen X & Y as:
2296  // BB1:
2297  // jmp_if_X TmpBB
2298  // jmp FBB
2299  // TmpBB:
2300  // jmp_if_Y TBB
2301  // jmp FBB
2302  //
2303  // This requires creation of TmpBB after CurBB.
2304 
2305  // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2306  // The requirement is that
2307  // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2308  // = FalseProb for original BB.
2309  // Assuming the original probabilities are A and B, one choice is to set
2310  // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2311  // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2312  // TrueProb for BB1 * FalseProb for TmpBB.
2313 
2314  auto NewTrueProb = TProb + FProb / 2;
2315  auto NewFalseProb = FProb / 2;
2316  // Emit the LHS condition.
2317  FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2318  NewFalseProb, InvertCond);
2319 
2320  // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2321  SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2322  BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2323  // Emit the RHS condition into TmpBB.
2324  FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2325  Probs[1], InvertCond);
2326  }
2327 }
2328 
2329 /// If the set of cases should be emitted as a series of branches, return true.
2330 /// If we should emit this as a bunch of and/or'd together conditions, return
2331 /// false.
2332 bool
2333 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2334  if (Cases.size() != 2) return true;
2335 
2336  // If this is two comparisons of the same values or'd or and'd together, they
2337  // will get folded into a single comparison, so don't emit two blocks.
2338  if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2339  Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2340  (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2341  Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2342  return false;
2343  }
2344 
2345  // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2346  // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2347  if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2348  Cases[0].CC == Cases[1].CC &&
2349  isa<Constant>(Cases[0].CmpRHS) &&
2350  cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2351  if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2352  return false;
2353  if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2354  return false;
2355  }
2356 
2357  return true;
2358 }
2359 
2360 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2361  MachineBasicBlock *BrMBB = FuncInfo.MBB;
2362 
2363  // Update machine-CFG edges.
2364  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2365 
2366  if (I.isUnconditional()) {
2367  // Update machine-CFG edges.
2368  BrMBB->addSuccessor(Succ0MBB);
2369 
2370  // If this is not a fall-through branch or optimizations are switched off,
2371  // emit the branch.
2372  if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2375  DAG.getBasicBlock(Succ0MBB)));
2376 
2377  return;
2378  }
2379 
2380  // If this condition is one of the special cases we handle, do special stuff
2381  // now.
2382  const Value *CondVal = I.getCondition();
2383  MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2384 
2385  // If this is a series of conditions that are or'd or and'd together, emit
2386  // this as a sequence of branches instead of setcc's with and/or operations.
2387  // As long as jumps are not expensive (exceptions for multi-use logic ops,
2388  // unpredictable branches, and vector extracts because those jumps are likely
2389  // expensive for any target), this should improve performance.
2390  // For example, instead of something like:
2391  // cmp A, B
2392  // C = seteq
2393  // cmp D, E
2394  // F = setle
2395  // or C, F
2396  // jnz foo
2397  // Emit:
2398  // cmp A, B
2399  // je foo
2400  // cmp D, E
2401  // jle foo
2402  const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2403  if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2404  BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2405  Value *Vec;
2406  const Value *BOp0, *BOp1;
2408  if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2409  Opcode = Instruction::And;
2410  else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2411  Opcode = Instruction::Or;
2412 
2413  if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2414  match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2415  FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2416  getEdgeProbability(BrMBB, Succ0MBB),
2417  getEdgeProbability(BrMBB, Succ1MBB),
2418  /*InvertCond=*/false);
2419  // If the compares in later blocks need to use values not currently
2420  // exported from this block, export them now. This block should always
2421  // be the first entry.
2422  assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2423 
2424  // Allow some cases to be rejected.
2425  if (ShouldEmitAsBranches(SL->SwitchCases)) {
2426  for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2427  ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2428  ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2429  }
2430 
2431  // Emit the branch for this block.
2432  visitSwitchCase(SL->SwitchCases[0], BrMBB);
2433  SL->SwitchCases.erase(SL->SwitchCases.begin());
2434  return;
2435  }
2436 
2437  // Okay, we decided not to do this, remove any inserted MBB's and clear
2438  // SwitchCases.
2439  for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2440  FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2441 
2442  SL->SwitchCases.clear();
2443  }
2444  }
2445 
2446  // Create a CaseBlock record representing this branch.
2447  CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2448  nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2449 
2450  // Use visitSwitchCase to actually insert the fast branch sequence for this
2451  // cond branch.
2452  visitSwitchCase(CB, BrMBB);
2453 }
2454 
2455 /// visitSwitchCase - Emits the necessary code to represent a single node in
2456 /// the binary search tree resulting from lowering a switch instruction.
2458  MachineBasicBlock *SwitchBB) {
2459  SDValue Cond;
2460  SDValue CondLHS = getValue(CB.CmpLHS);
2461  SDLoc dl = CB.DL;
2462 
2463  if (CB.CC == ISD::SETTRUE) {
2464  // Branch or fall through to TrueBB.
2465  addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2466  SwitchBB->normalizeSuccProbs();
2467  if (CB.TrueBB != NextBlock(SwitchBB)) {
2469  DAG.getBasicBlock(CB.TrueBB)));
2470  }
2471  return;
2472  }
2473 
2474  auto &TLI = DAG.getTargetLoweringInfo();
2475  EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2476 
2477  // Build the setcc now.
2478  if (!CB.CmpMHS) {
2479  // Fold "(X == true)" to X and "(X == false)" to !X to
2480  // handle common cases produced by branch lowering.
2481  if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2482  CB.CC == ISD::SETEQ)
2483  Cond = CondLHS;
2484  else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2485  CB.CC == ISD::SETEQ) {
2486  SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2487  Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2488  } else {
2489  SDValue CondRHS = getValue(CB.CmpRHS);
2490 
2491  // If a pointer's DAG type is larger than its memory type then the DAG
2492  // values are zero-extended. This breaks signed comparisons so truncate
2493  // back to the underlying type before doing the compare.
2494  if (CondLHS.getValueType() != MemVT) {
2495  CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2496  CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2497  }
2498  Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2499  }
2500  } else {
2501  assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2502 
2503  const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2504  const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2505 
2506  SDValue CmpOp = getValue(CB.CmpMHS);
2507  EVT VT = CmpOp.getValueType();
2508 
2509  if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2510  Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2511  ISD::SETLE);
2512  } else {
2513  SDValue SUB = DAG.getNode(ISD::SUB, dl,
2514  VT, CmpOp, DAG.getConstant(Low, dl, VT));
2515  Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2516  DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2517  }
2518  }
2519 
2520  // Update successor info
2521  addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2522  // TrueBB and FalseBB are always different unless the incoming IR is
2523  // degenerate. This only happens when running llc on weird IR.
2524  if (CB.TrueBB != CB.FalseBB)
2525  addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2526  SwitchBB->normalizeSuccProbs();
2527 
2528  // If the lhs block is the next block, invert the condition so that we can
2529  // fall through to the lhs instead of the rhs block.
2530  if (CB.TrueBB == NextBlock(SwitchBB)) {
2531  std::swap(CB.TrueBB, CB.FalseBB);
2532  SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2533  Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2534  }
2535 
2536  SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2538  DAG.getBasicBlock(CB.TrueBB));
2539 
2540  // Insert the false branch. Do this even if it's a fall through branch,
2541  // this makes it easier to do DAG optimizations which require inverting
2542  // the branch condition.
2543  BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2544  DAG.getBasicBlock(CB.FalseBB));
2545 
2546  DAG.setRoot(BrCond);
2547 }
2548 
2549 /// visitJumpTable - Emit JumpTable node in the current MBB
2551  // Emit the code for the jump table
2552  assert(JT.Reg != -1U && "Should lower JT Header first!");
2555  JT.Reg, PTy);
2556  SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2557  SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2558  MVT::Other, Index.getValue(1),
2559  Table, Index);
2560  DAG.setRoot(BrJumpTable);
2561 }
2562 
2563 /// visitJumpTableHeader - This function emits necessary code to produce index
2564 /// in the JumpTable from switch case.
2566  JumpTableHeader &JTH,
2567  MachineBasicBlock *SwitchBB) {
2568  SDLoc dl = getCurSDLoc();
2569 
2570  // Subtract the lowest switch case value from the value being switched on.
2571  SDValue SwitchOp = getValue(JTH.SValue);
2572  EVT VT = SwitchOp.getValueType();
2573  SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2574  DAG.getConstant(JTH.First, dl, VT));
2575 
2576  // The SDNode we just created, which holds the value being switched on minus
2577  // the smallest case value, needs to be copied to a virtual register so it
2578  // can be used as an index into the jump table in a subsequent basic block.
2579  // This value may be smaller or larger than the target's pointer type, and
2580  // therefore require extension or truncating.
2581  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2582  SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2583 
2584  unsigned JumpTableReg =
2586  SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2587  JumpTableReg, SwitchOp);
2588  JT.Reg = JumpTableReg;
2589 
2590  if (!JTH.FallthroughUnreachable) {
2591  // Emit the range check for the jump table, and branch to the default block
2592  // for the switch statement if the value being switched on exceeds the
2593  // largest case in the switch.
2594  SDValue CMP = DAG.getSetCC(
2596  Sub.getValueType()),
2597  Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2598 
2599  SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2600  MVT::Other, CopyTo, CMP,
2601  DAG.getBasicBlock(JT.Default));
2602 
2603  // Avoid emitting unnecessary branches to the next block.
2604  if (JT.MBB != NextBlock(SwitchBB))
2605  BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2606  DAG.getBasicBlock(JT.MBB));
2607 
2608  DAG.setRoot(BrCond);
2609  } else {
2610  // Avoid emitting unnecessary branches to the next block.
2611  if (JT.MBB != NextBlock(SwitchBB))
2612  DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2613  DAG.getBasicBlock(JT.MBB)));
2614  else
2615  DAG.setRoot(CopyTo);
2616  }
2617 }
2618 
2619 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2620 /// variable if there exists one.
2622  SDValue &Chain) {
2623  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2624  EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2625  EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2626  MachineFunction &MF = DAG.getMachineFunction();
2627  Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2628  MachineSDNode *Node =
2629  DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2630  if (Global) {
2631  MachinePointerInfo MPInfo(Global);
2635  MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2636  DAG.setNodeMemRefs(Node, {MemRef});
2637  }
2638  if (PtrTy != PtrMemTy)
2639  return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2640  return SDValue(Node, 0);
2641 }
2642 
2643 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2644 /// tail spliced into a stack protector check success bb.
2645 ///
2646 /// For a high level explanation of how this fits into the stack protector
2647 /// generation see the comment on the declaration of class
2648 /// StackProtectorDescriptor.
2650  MachineBasicBlock *ParentBB) {
2651 
2652  // First create the loads to the guard/stack slot for the comparison.
2653  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2654  EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2655  EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2656 
2657  MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2658  int FI = MFI.getStackProtectorIndex();
2659 
2660  SDValue Guard;
2661  SDLoc dl = getCurSDLoc();
2662  SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2663  const Module &M = *ParentBB->getParent()->getFunction().getParent();
2664  Align Align =
2666 
2667  // Generate code to load the content of the guard slot.
2668  SDValue GuardVal = DAG.getLoad(
2669  PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2672 
2673  if (TLI.useStackGuardXorFP())
2674  GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2675 
2676  // Retrieve guard check function, nullptr if instrumentation is inlined.
2677  if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2678  // The target provides a guard check function to validate the guard value.
2679  // Generate a call to that function with the content of the guard slot as
2680  // argument.
2681  FunctionType *FnTy = GuardCheckFn->getFunctionType();
2682  assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2683 
2686  Entry.Node = GuardVal;
2687  Entry.Ty = FnTy->getParamType(0);
2688  if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2689  Entry.IsInReg = true;
2690  Args.push_back(Entry);
2691 
2693  CLI.setDebugLoc(getCurSDLoc())
2695  .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2696  getValue(GuardCheckFn), std::move(Args));
2697 
2698  std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2699  DAG.setRoot(Result.second);
2700  return;
2701  }
2702 
2703  // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2704  // Otherwise, emit a volatile load to retrieve the stack guard value.
2705  SDValue Chain = DAG.getEntryNode();
2706  if (TLI.useLoadStackGuardNode()) {
2707  Guard = getLoadStackGuard(DAG, dl, Chain);
2708  } else {
2709  const Value *IRGuard = TLI.getSDagStackGuard(M);
2710  SDValue GuardPtr = getValue(IRGuard);
2711 
2712  Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2713  MachinePointerInfo(IRGuard, 0), Align,
2715  }
2716 
2717  // Perform the comparison via a getsetcc.
2719  *DAG.getContext(),
2720  Guard.getValueType()),
2721  Guard, GuardVal, ISD::SETNE);
2722 
2723  // If the guard/stackslot do not equal, branch to failure MBB.
2724  SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2725  MVT::Other, GuardVal.getOperand(0),
2726  Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2727  // Otherwise branch to success MBB.
2728  SDValue Br = DAG.getNode(ISD::BR, dl,
2729  MVT::Other, BrCond,
2731 
2732  DAG.setRoot(Br);
2733 }
2734 
2735 /// Codegen the failure basic block for a stack protector check.
2736 ///
2737 /// A failure stack protector machine basic block consists simply of a call to
2738 /// __stack_chk_fail().
2739 ///
2740 /// For a high level explanation of how this fits into the stack protector
2741 /// generation see the comment on the declaration of class
2742 /// StackProtectorDescriptor.
2743 void
2745  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2747  CallOptions.setDiscardResult(true);
2748  SDValue Chain =
2749  TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2750  None, CallOptions, getCurSDLoc()).second;
2751  // On PS4, the "return address" must still be within the calling function,
2752  // even if it's at the very end, so emit an explicit TRAP here.
2753  // Passing 'true' for doesNotReturn above won't generate the trap for us.
2754  if (TM.getTargetTriple().isPS4CPU())
2755  Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2756  // WebAssembly needs an unreachable instruction after a non-returning call,
2757  // because the function return type can be different from __stack_chk_fail's
2758  // return type (void).
2759  if (TM.getTargetTriple().isWasm())
2760  Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2761 
2762  DAG.setRoot(Chain);
2763 }
2764 
2765 /// visitBitTestHeader - This function emits necessary code to produce value
2766 /// suitable for "bit tests"
2768  MachineBasicBlock *SwitchBB) {
2769  SDLoc dl = getCurSDLoc();
2770 
2771  // Subtract the minimum value.
2772  SDValue SwitchOp = getValue(B.SValue);
2773  EVT VT = SwitchOp.getValueType();
2774  SDValue RangeSub =
2775  DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2776 
2777  // Determine the type of the test operands.
2778  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2779  bool UsePtrType = false;
2780  if (!TLI.isTypeLegal(VT)) {
2781  UsePtrType = true;
2782  } else {
2783  for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2784  if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2785  // Switch table case range are encoded into series of masks.
2786  // Just use pointer type, it's guaranteed to fit.
2787  UsePtrType = true;
2788  break;
2789  }
2790  }
2791  SDValue Sub = RangeSub;
2792  if (UsePtrType) {
2793  VT = TLI.getPointerTy(DAG.getDataLayout());
2794  Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2795  }
2796 
2797  B.RegVT = VT.getSimpleVT();
2798  B.Reg = FuncInfo.CreateReg(B.RegVT);
2799  SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2800 
2801  MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2802 
2803  if (!B.FallthroughUnreachable)
2804  addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2805  addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2806  SwitchBB->normalizeSuccProbs();
2807 
2808  SDValue Root = CopyTo;
2809  if (!B.FallthroughUnreachable) {
2810  // Conditional branch to the default block.
2811  SDValue RangeCmp = DAG.getSetCC(dl,
2813  RangeSub.getValueType()),
2814  RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2815  ISD::SETUGT);
2816 
2817  Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2818  DAG.getBasicBlock(B.Default));
2819  }
2820 
2821  // Avoid emitting unnecessary branches to the next block.
2822  if (MBB != NextBlock(SwitchBB))
2823  Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2824 
2825  DAG.setRoot(Root);
2826 }
2827 
2828 /// visitBitTestCase - this function produces one "bit test"
2830  MachineBasicBlock* NextMBB,
2831  BranchProbability BranchProbToNext,
2832  unsigned Reg,
2833  BitTestCase &B,
2834  MachineBasicBlock *SwitchBB) {
2835  SDLoc dl = getCurSDLoc();
2836  MVT VT = BB.RegVT;
2837  SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2838  SDValue Cmp;
2839  unsigned PopCount = countPopulation(B.Mask);
2840  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2841  if (PopCount == 1) {
2842  // Testing for a single bit; just compare the shift count with what it
2843  // would need to be to shift a 1 bit in that position.
2844  Cmp = DAG.getSetCC(
2845  dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2846  ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2847  ISD::SETEQ);
2848  } else if (PopCount == BB.Range) {
2849  // There is only one zero bit in the range, test for it directly.
2850  Cmp = DAG.getSetCC(
2851  dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2852  ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2853  ISD::SETNE);
2854  } else {
2855  // Make desired shift
2856  SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2857  DAG.getConstant(1, dl, VT), ShiftOp);
2858 
2859  // Emit bit tests and jumps
2860  SDValue AndOp = DAG.getNode(ISD::AND, dl,
2861  VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2862  Cmp = DAG.getSetCC(
2863  dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2864  AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2865  }
2866 
2867  // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2868  addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2869  // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2870  addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2871  // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2872  // one as they are relative probabilities (and thus work more like weights),
2873  // and hence we need to normalize them to let the sum of them become one.
2874  SwitchBB->normalizeSuccProbs();
2875 
2876  SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2878  Cmp, DAG.getBasicBlock(B.TargetBB));
2879 
2880  // Avoid emitting unnecessary branches to the next block.
2881  if (NextMBB != NextBlock(SwitchBB))
2882  BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2883  DAG.getBasicBlock(NextMBB));
2884 
2885  DAG.setRoot(BrAnd);
2886 }
2887 
2888 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2889  MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2890 
2891  // Retrieve successors. Look through artificial IR level blocks like
2892  // catchswitch for successors.
2893  MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2894  const BasicBlock *EHPadBB = I.getSuccessor(1);
2895 
2896  // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2897  // have to do anything here to lower funclet bundles.
2898  assert(!I.hasOperandBundlesOtherThan(
2899  {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2900  LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2901  LLVMContext::OB_cfguardtarget,
2902  LLVMContext::OB_clang_arc_attachedcall}) &&
2903  "Cannot lower invokes with arbitrary operand bundles yet!");
2904 
2905  const Value *Callee(I.getCalledOperand());
2906  const Function *Fn = dyn_cast<Function>(Callee);
2907  if (isa<InlineAsm>(Callee))
2908  visitInlineAsm(I, EHPadBB);
2909  else if (Fn && Fn->isIntrinsic()) {
2910  switch (Fn->getIntrinsicID()) {
2911  default:
2912  llvm_unreachable("Cannot invoke this intrinsic");
2913  case Intrinsic::donothing:
2914  // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2915  case Intrinsic::seh_try_begin:
2916  case Intrinsic::seh_scope_begin:
2917  case Intrinsic::seh_try_end:
2918  case Intrinsic::seh_scope_end:
2919  break;
2920  case Intrinsic::experimental_patchpoint_void:
2921  case Intrinsic::experimental_patchpoint_i64:
2922  visitPatchpoint(I, EHPadBB);
2923  break;
2924  case Intrinsic::experimental_gc_statepoint:
2925  LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2926  break;
2927  case Intrinsic::wasm_rethrow: {
2928  // This is usually done in visitTargetIntrinsic, but this intrinsic is
2929  // special because it can be invoked, so we manually lower it to a DAG
2930  // node here.
2932  Ops.push_back(getRoot()); // inchain
2933  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2934  Ops.push_back(
2935  DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2936  TLI.getPointerTy(DAG.getDataLayout())));
2937  SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2939  break;
2940  }
2941  }
2942  } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2943  // Currently we do not lower any intrinsic calls with deopt operand bundles.
2944  // Eventually we will support lowering the @llvm.experimental.deoptimize
2945  // intrinsic, and right now there are no plans to support other intrinsics
2946  // with deopt state.
2947  LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2948  } else {
2949  LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2950  }
2951 
2952  // If the value of the invoke is used outside of its defining block, make it
2953  // available as a virtual register.
2954  // We already took care of the exported value for the statepoint instruction
2955  // during call to the LowerStatepoint.
2956  if (!isa<GCStatepointInst>(I)) {
2958  }
2959 
2962  BranchProbability EHPadBBProb =
2963  BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2965  findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2966 
2967  // Update successor info.
2968  addSuccessorWithProb(InvokeMBB, Return);
2969  for (auto &UnwindDest : UnwindDests) {
2970  UnwindDest.first->setIsEHPad();
2971  addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2972  }
2973  InvokeMBB->normalizeSuccProbs();
2974 
2975  // Drop into normal successor.
2977  DAG.getBasicBlock(Return)));
2978 }
2979 
2980 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2981  MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2982 
2983  // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2984  // have to do anything here to lower funclet bundles.
2985  assert(!I.hasOperandBundlesOtherThan(
2986  {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2987  "Cannot lower callbrs with arbitrary operand bundles yet!");
2988 
2989  assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2990  visitInlineAsm(I);
2992 
2993  // Retrieve successors.
2994  MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2995 
2996  // Update successor info.
2997  addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2998  for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2999  MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
3000  addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3001  Target->setIsInlineAsmBrIndirectTarget();
3002  }
3003  CallBrMBB->normalizeSuccProbs();
3004 
3005  // Drop into default successor.
3008  DAG.getBasicBlock(Return)));
3009 }
3010 
3011 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3012  llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3013 }
3014 
3015 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3016  assert(FuncInfo.MBB->isEHPad() &&
3017  "Call to landingpad not in landing pad!");
3018 
3019  // If there aren't registers to copy the values into (e.g., during SjLj
3020  // exceptions), then don't bother to create these DAG nodes.
3021  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3022  const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3023  if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3024  TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3025  return;
3026 
3027  // If landingpad's return type is token type, we don't create DAG nodes
3028  // for its exception pointer and selector value. The extraction of exception
3029  // pointer or selector value from token type landingpads is not currently
3030  // supported.
3031  if (LP.getType()->isTokenTy())
3032  return;
3033 
3034  SmallVector<EVT, 2> ValueVTs;
3035  SDLoc dl = getCurSDLoc();
3036  ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3037  assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3038 
3039  // Get the two live-in registers as SDValues. The physregs have already been
3040  // copied into virtual registers.
3041  SDValue Ops[2];
3043  Ops[0] = DAG.getZExtOrTrunc(
3046  TLI.getPointerTy(DAG.getDataLayout())),
3047  dl, ValueVTs[0]);
3048  } else {
3049  Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3050  }
3051  Ops[1] = DAG.getZExtOrTrunc(
3054  TLI.getPointerTy(DAG.getDataLayout())),
3055  dl, ValueVTs[1]);
3056 
3057  // Merge into one.
3059  DAG.getVTList(ValueVTs), Ops);
3060  setValue(&LP, Res);
3061 }
3062 
3064  MachineBasicBlock *Last) {
3065  // Update JTCases.
3066  for (JumpTableBlock &JTB : SL->JTCases)
3067  if (JTB.first.HeaderBB == First)
3068  JTB.first.HeaderBB = Last;
3069 
3070  // Update BitTestCases.
3071  for (BitTestBlock &BTB : SL->BitTestCases)
3072  if (BTB.Parent == First)
3073  BTB.Parent = Last;
3074 }
3075 
3076 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3077  MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3078 
3079  // Update machine-CFG edges with unique successors.
3081  for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3082  BasicBlock *BB = I.getSuccessor(i);
3083  bool Inserted = Done.insert(BB).second;
3084  if (!Inserted)
3085  continue;
3086 
3088  addSuccessorWithProb(IndirectBrMBB, Succ);
3089  }
3090  IndirectBrMBB->normalizeSuccProbs();
3091 
3094  getValue(I.getAddress())));
3095 }
3096 
3097 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3099  return;
3100 
3101  // We may be able to ignore unreachable behind a noreturn call.
3103  const BasicBlock &BB = *I.getParent();
3104  if (&I != &BB.front()) {
3106  std::prev(BasicBlock::const_iterator(&I));
3107  if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3108  if (Call->doesNotReturn())
3109  return;
3110  }
3111  }
3112  }
3113 
3115 }
3116 
3117 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3118  SDNodeFlags Flags;
3119  if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3120  Flags.copyFMF(*FPOp);
3121 
3122  SDValue Op = getValue(I.getOperand(0));
3123  SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3124  Op, Flags);
3125  setValue(&I, UnNodeValue);
3126 }
3127 
3128 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3129  SDNodeFlags Flags;
3130  if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3131  Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3132  Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3133  }
3134  if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3135  Flags.setExact(ExactOp->isExact());
3136  if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3137  Flags.copyFMF(*FPOp);
3138 
3139  SDValue Op1 = getValue(I.getOperand(0));
3140  SDValue Op2 = getValue(I.getOperand(1));
3141  SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3142  Op1, Op2, Flags);
3143  setValue(&I, BinNodeValue);
3144 }
3145 
3146 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3147  SDValue Op1 = getValue(I.getOperand(0));
3148  SDValue Op2 = getValue(I.getOperand(1));
3149 
3151  Op1.getValueType(), DAG.getDataLayout());
3152 
3153  // Coerce the shift amount to the right type if we can.
3154  if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3155  unsigned ShiftSize = ShiftTy.getSizeInBits();
3156  unsigned Op2Size = Op2.getValueSizeInBits();
3157  SDLoc DL = getCurSDLoc();
3158 
3159  // If the operand is smaller than the shift count type, promote it.
3160  if (ShiftSize > Op2Size)
3161  Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3162 
3163  // If the operand is larger than the shift count type but the shift
3164  // count type has enough bits to represent any shift value, truncate
3165  // it now. This is a common case and it exposes the truncate to
3166  // optimization early.
3167  else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3168  Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3169  // Otherwise we'll need to temporarily settle for some other convenient
3170  // type. Type legalization will make adjustments once the shiftee is split.
3171  else
3172  Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3173  }
3174 
3175  bool nuw = false;
3176  bool nsw = false;
3177  bool exact = false;
3178 
3179  if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3180 
3181  if (const OverflowingBinaryOperator *OFBinOp =
3182  dyn_cast<const OverflowingBinaryOperator>(&I)) {
3183  nuw = OFBinOp->hasNoUnsignedWrap();
3184  nsw = OFBinOp->hasNoSignedWrap();
3185  }
3186  if (const PossiblyExactOperator *ExactOp =
3187  dyn_cast<const PossiblyExactOperator>(&I))
3188  exact = ExactOp->isExact();
3189  }
3190  SDNodeFlags Flags;
3191  Flags.setExact(exact);
3192  Flags.setNoSignedWrap(nsw);
3193  Flags.setNoUnsignedWrap(nuw);
3194  SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3195  Flags);
3196  setValue(&I, Res);
3197 }
3198 
3199 void SelectionDAGBuilder::visitSDiv(const User &I) {
3200  SDValue Op1 = getValue(I.getOperand(0));
3201  SDValue Op2 = getValue(I.getOperand(1));
3202 
3203  SDNodeFlags Flags;
3204  Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3205  cast<PossiblyExactOperator>(&I)->isExact());
3207  Op2, Flags));
3208 }
3209 
3210 void SelectionDAGBuilder::visitICmp(const User &I) {
3212  if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3213  predicate = IC->getPredicate();
3214  else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3215  predicate = ICmpInst::Predicate(IC->getPredicate());
3216  SDValue Op1 = getValue(I.getOperand(0));
3217  SDValue Op2 = getValue(I.getOperand(1));
3218  ISD::CondCode Opcode = getICmpCondCode(predicate);
3219 
3220  auto &TLI = DAG.getTargetLoweringInfo();
3221  EVT MemVT =
3222  TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3223 
3224  // If a pointer's DAG type is larger than its memory type then the DAG values
3225  // are zero-extended. This breaks signed comparisons so truncate back to the
3226  // underlying type before doing the compare.
3227  if (Op1.getValueType() != MemVT) {
3228  Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3229  Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3230  }
3231 
3233  I.getType());
3234  setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3235 }
3236 
3237 void SelectionDAGBuilder::visitFCmp(const User &I) {
3239  if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3240  predicate = FC->getPredicate();
3241  else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3242  predicate = FCmpInst::Predicate(FC->getPredicate());
3243  SDValue Op1 = getValue(I.getOperand(0));
3244  SDValue Op2 = getValue(I.getOperand(1));
3245 
3246  ISD::CondCode Condition = getFCmpCondCode(predicate);
3247  auto *FPMO = cast<FPMathOperator>(&I);
3248  if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3249  Condition = getFCmpCodeWithoutNaN(Condition);
3250 
3251  SDNodeFlags Flags;
3252  Flags.copyFMF(*FPMO);
3253  SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3254 
3256  I.getType());
3257  setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3258 }
3259 
3260 // Check if the condition of the select has one use or two users that are both
3261 // selects with the same condition.
3262 static bool hasOnlySelectUsers(const Value *Cond) {
3263  return llvm::all_of(Cond->users(), [](const Value *V) {
3264  return isa<SelectInst>(V);
3265  });
3266 }
3267 
3268 void SelectionDAGBuilder::visitSelect(const User &I) {
3269  SmallVector<EVT, 4> ValueVTs;
3271  ValueVTs);
3272  unsigned NumValues = ValueVTs.size();
3273  if (NumValues == 0) return;
3274 
3275  SmallVector<SDValue, 4> Values(NumValues);
3276  SDValue Cond = getValue(I.getOperand(0));
3277  SDValue LHSVal = getValue(I.getOperand(1));
3278  SDValue RHSVal = getValue(I.getOperand(2));
3279  SmallVector<SDValue, 1> BaseOps(1, Cond);
3280  ISD::NodeType OpCode =
3281  Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3282 
3283  bool IsUnaryAbs = false;
3284  bool Negate = false;
3285 
3286  SDNodeFlags Flags;
3287  if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3288  Flags.copyFMF(*FPOp);
3289 
3290  // Min/max matching is only viable if all output VTs are the same.
3291  if (is_splat(ValueVTs)) {
3292  EVT VT = ValueVTs[0];
3293  LLVMContext &Ctx = *DAG.getContext();
3294  auto &TLI = DAG.getTargetLoweringInfo();
3295 
3296  // We care about the legality of the operation after it has been type
3297  // legalized.
3298  while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3299  VT = TLI.getTypeToTransformTo(Ctx, VT);
3300 
3301  // If the vselect is legal, assume we want to leave this as a vector setcc +
3302  // vselect. Otherwise, if this is going to be scalarized, we want to see if
3303  // min/max is legal on the scalar type.
3304  bool UseScalarMinMax = VT.isVector() &&
3306 
3307  Value *LHS, *RHS;
3308  auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3310  switch (SPR.Flavor) {
3311  case SPF_UMAX: Opc = ISD::UMAX; break;
3312  case SPF_UMIN: Opc = ISD::UMIN; break;
3313  case SPF_SMAX: Opc = ISD::SMAX; break;
3314  case SPF_SMIN: Opc = ISD::SMIN; break;
3315  case SPF_FMINNUM:
3316  switch (SPR.NaNBehavior) {
3317  case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3318  case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
3319  case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3320  case SPNB_RETURNS_ANY: {
3322  Opc = ISD::FMINNUM;
3323  else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3324  Opc = ISD::FMINIMUM;
3325  else if (UseScalarMinMax)
3328  break;
3329  }
3330  }
3331  break;
3332  case SPF_FMAXNUM:
3333  switch (SPR.NaNBehavior) {
3334  case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3335  case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
3336  case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3337  case SPNB_RETURNS_ANY:
3338 
3340  Opc = ISD::FMAXNUM;
3341  else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3342  Opc = ISD::FMAXIMUM;
3343  else if (UseScalarMinMax)
3346  break;
3347  }
3348  break;
3349  case SPF_NABS:
3350  Negate = true;
3352  case SPF_ABS:
3353  IsUnaryAbs = true;
3354  Opc = ISD::ABS;
3355  break;
3356  default: break;
3357  }
3358 
3359  if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3360  (TLI.isOperationLegalOrCustom(Opc, VT) ||
3361  (UseScalarMinMax &&
3362  TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3363  // If the underlying comparison instruction is used by any other
3364  // instruction, the consumed instructions won't be destroyed, so it is
3365  // not profitable to convert to a min/max.
3366  hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3367  OpCode = Opc;
3368  LHSVal = getValue(LHS);
3369  RHSVal = getValue(RHS);
3370  BaseOps.clear();
3371  }
3372 
3373  if (IsUnaryAbs) {
3374  OpCode = Opc;
3375  LHSVal = getValue(LHS);
3376  BaseOps.clear();
3377  }
3378  }
3379 
3380  if (IsUnaryAbs) {
3381  for (unsigned i = 0; i != NumValues; ++i) {
3382  SDLoc dl = getCurSDLoc();
3383  EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3384  Values[i] =
3385  DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3386  if (Negate)
3387  Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3388  Values[i]);
3389  }
3390  } else {
3391  for (unsigned i = 0; i != NumValues; ++i) {
3392  SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3393  Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3394  Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3395  Values[i] = DAG.getNode(
3396  OpCode, getCurSDLoc(),
3397  LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3398  }
3399  }
3400 
3402  DAG.getVTList(ValueVTs), Values));
3403 }
3404 
3405 void SelectionDAGBuilder::visitTrunc(const User &I) {
3406  // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3407  SDValue N = getValue(I.getOperand(0));
3409  I.getType());
3410  setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3411 }
3412 
3413 void SelectionDAGBuilder::visitZExt(const User &I) {
3414  // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3415  // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3416  SDValue N = getValue(I.getOperand(0));
3418  I.getType());
3420 }
3421 
3422 void SelectionDAGBuilder::visitSExt(const User &I) {
3423  // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3424  // SExt also can't be a cast to bool for same reason. So, nothing much to do
3425  SDValue N = getValue(I.getOperand(0));
3427  I.getType());
3429 }
3430 
3431 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3432  // FPTrunc is never a no-op cast, no need to check
3433  SDValue N = getValue(I.getOperand(0));
3434  SDLoc dl = getCurSDLoc();
3435  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3436  EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3437  setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3439  0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3440 }
3441 
3442 void SelectionDAGBuilder::visitFPExt(const User &I) {
3443  // FPExt is never a no-op cast, no need to check
3444  SDValue N = getValue(I.getOperand(0));
3446  I.getType());
3447  setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3448 }
3449 
3450 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3451  // FPToUI is never a no-op cast, no need to check
3452  SDValue N = getValue(I.getOperand(0));
3454  I.getType());
3455  setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3459  // FPToSI is never a no-op cast, no need to check
3460  SDValue N = getValue(I.getOperand(0));
3462  I.getType());
3463  setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3464 }
3465 
3466 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3467  // UIToFP is never a no-op cast, no need to check
3468  SDValue N = getValue(I.getOperand(0));
3470  I.getType());
3471  setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3472 }
3473 
3474 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3475  // SIToFP is never a no-op cast, no need to check
3476  SDValue N = getValue(I.getOperand(0));
3478  I.getType());
3479  setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3480 }
3481 
3482 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3483  // What to do depends on the size of the integer and the size of the pointer.
3484  // We can either truncate, zero extend, or no-op, accordingly.
3485  SDValue N = getValue(I.getOperand(0));
3486  auto &TLI = DAG.getTargetLoweringInfo();
3488  I.getType());
3489  EVT PtrMemVT =
3490  TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3491  N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3492  N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3493  setValue(&I, N);
3494 }
3495 
3496 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3497  // What to do depends on the size of the integer and the size of the pointer.
3498  // We can either truncate, zero extend, or no-op, accordingly.
3499  SDValue N = getValue(I.getOperand(0));
3500  auto &TLI = DAG.getTargetLoweringInfo();
3501  EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3502  EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3503  N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3504  N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3505  setValue(&I, N);
3506 }
3507 
3508 void SelectionDAGBuilder::visitBitCast(const User &I) {
3509  SDValue N = getValue(I.getOperand(0));
3510  SDLoc dl = getCurSDLoc();
3512  I.getType());
3513 
3514  // BitCast assures us that source and destination are the same size so this is
3515  // either a BITCAST or a no-op.
3516  if (DestVT != N.getValueType())
3518  DestVT, N)); // convert types.
3519  // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3520  // might fold any kind of constant expression to an integer constant and that
3521  // is not what we are looking for. Only recognize a bitcast of a genuine
3522  // constant integer as an opaque constant.
3523  else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3524  setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3525  /*isOpaque*/true));
3526  else
3527  setValue(&I, N); // noop cast.
3528 }
3529 
3530 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3531  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3532  const Value *SV = I.getOperand(0);
3533  SDValue N = getValue(SV);
3534  EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3535 
3536  unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3537  unsigned DestAS = I.getType()->getPointerAddressSpace();
3538 
3539  if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3540  N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3541 
3542  setValue(&I, N);
3543 }
3544 
3545 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3546  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3547  SDValue InVec = getValue(I.getOperand(0));
3548  SDValue InVal = getValue(I.getOperand(1));
3549  SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3552  TLI.getValueType(DAG.getDataLayout(), I.getType()),
3553  InVec, InVal, InIdx));
3554 }
3555 
3556 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3557  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558  SDValue InVec = getValue(I.getOperand(0));
3559  SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3562  TLI.getValueType(DAG.getDataLayout(), I.getType()),
3563  InVec, InIdx));
3564 }
3565 
3566 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3567  SDValue Src1 = getValue(I.getOperand(0));
3568  SDValue Src2 = getValue(I.getOperand(1));
3570  if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3571  Mask = SVI->getShuffleMask();
3572  else
3573  Mask = cast<ConstantExpr>(I).getShuffleMask();
3574  SDLoc DL = getCurSDLoc();
3575  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3576  EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3577  EVT SrcVT = Src1.getValueType();
3578 
3579  if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3580  VT.isScalableVector()) {
3581  // Canonical splat form of first element of first input vector.
3582  SDValue FirstElt =
3585  setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3586  return;
3587  }
3588 
3589  // For now, we only handle splats for scalable vectors.
3590  // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3591  // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3592  assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3593 
3594  unsigned SrcNumElts = SrcVT.getVectorNumElements();
3595  unsigned MaskNumElts = Mask.size();
3596 
3597  if (SrcNumElts == MaskNumElts) {
3598  setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3599  return;
3600  }
3601 
3602  // Normalize the shuffle vector since mask and vector length don't match.
3603  if (SrcNumElts < MaskNumElts) {
3604  // Mask is longer than the source vectors. We can use concatenate vector to
3605  // make the mask and vectors lengths match.
3606 
3607  if (MaskNumElts % SrcNumElts == 0) {
3608  // Mask length is a multiple of the source vector length.
3609  // Check if the shuffle is some kind of concatenation of the input
3610  // vectors.
3611  unsigned NumConcat = MaskNumElts / SrcNumElts;
3612  bool IsConcat = true;
3613  SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3614  for (unsigned i = 0; i != MaskNumElts; ++i) {
3615  int Idx = Mask[i];
3616  if (Idx < 0)
3617  continue;
3618  // Ensure the indices in each SrcVT sized piece are sequential and that
3619  // the same source is used for the whole piece.
3620  if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3621  (ConcatSrcs[i / SrcNumElts] >= 0 &&
3622  ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3623  IsConcat = false;
3624  break;
3625  }
3626  // Remember which source this index came from.
3627  ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3628  }
3629 
3630  // The shuffle is concatenating multiple vectors together. Just emit
3631  // a CONCAT_VECTORS operation.
3632  if (IsConcat) {
3633  SmallVector<SDValue, 8> ConcatOps;
3634  for (auto Src : ConcatSrcs) {
3635  if (Src < 0)
3636  ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3637  else if (Src == 0)
3638  ConcatOps.push_back(Src1);
3639  else
3640  ConcatOps.push_back(Src2);
3641  }
3642  setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3643  return;
3644  }
3645  }
3646 
3647  unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3648  unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3649  EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3650  PaddedMaskNumElts);
3651 
3652  // Pad both vectors with undefs to make them the same length as the mask.
3653  SDValue UndefVal = DAG.getUNDEF(SrcVT);
3654 
3655  SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3656  SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3657  MOps1[0] = Src1;
3658  MOps2[0] = Src2;
3659 
3660  Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3661  Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3662 
3663  // Readjust mask for new input vector length.
3664  SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3665  for (unsigned i = 0; i != MaskNumElts; ++i) {
3666  int Idx = Mask[i];
3667  if (Idx >= (int)SrcNumElts)
3668  Idx -= SrcNumElts - PaddedMaskNumElts;
3669  MappedOps[i] = Idx;
3670  }
3671 
3672  SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3673 
3674  // If the concatenated vector was padded, extract a subvector with the
3675  // correct number of elements.
3676  if (MaskNumElts != PaddedMaskNumElts)
3677  Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3679 
3680  setValue(&I, Result);
3681  return;
3682  }
3683 
3684  if (SrcNumElts > MaskNumElts) {
3685  // Analyze the access pattern of the vector to see if we can extract
3686  // two subvectors and do the shuffle.
3687  int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
3688  bool CanExtract = true;
3689  for (int Idx : Mask) {
3690  unsigned Input = 0;
3691  if (Idx < 0)
3692  continue;
3693 
3694  if (Idx >= (int)SrcNumElts) {
3695  Input = 1;
3696  Idx -= SrcNumElts;
3697  }
3698 
3699  // If all the indices come from the same MaskNumElts sized portion of
3700  // the sources we can use extract. Also make sure the extract wouldn't
3701  // extract past the end of the source.
3702  int NewStartIdx = alignDown(Idx, MaskNumElts);
3703  if (NewStartIdx + MaskNumElts > SrcNumElts ||
3704  (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3705  CanExtract = false;
3706  // Make sure we always update StartIdx as we use it to track if all
3707  // elements are undef.
3708  StartIdx[Input] = NewStartIdx;
3709  }
3710 
3711  if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3712  setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3713  return;
3714  }
3715  if (CanExtract) {
3716  // Extract appropriate subvector and generate a vector shuffle
3717  for (unsigned Input = 0; Input < 2; ++Input) {
3718  SDValue &Src = Input == 0 ? Src1 : Src2;
3719  if (StartIdx[Input] < 0)
3720  Src = DAG.getUNDEF(VT);
3721  else {
3722  Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3723  DAG.getVectorIdxConstant(StartIdx[Input], DL));
3724  }
3725  }
3726 
3727  // Calculate new mask.
3728  SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3729  for (int &Idx : MappedOps) {
3730  if (Idx >= (int)SrcNumElts)
3731  Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3732  else if (Idx >= 0)
3733  Idx -= StartIdx[0];
3734  }
3735 
3736  setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3737  return;
3738  }
3739  }
3740 
3741  // We can't use either concat vectors or extract subvectors so fall back to
3742  // replacing the shuffle with extract and build vector.
3743  // to insert and build vector.
3744  EVT EltVT = VT.getVectorElementType();
3746  for (int Idx : Mask) {
3747  SDValue Res;
3748 
3749  if (Idx < 0) {
3750  Res = DAG.getUNDEF(EltVT);
3751  } else {
3752  SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3753  if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3754 
3755  Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3756  DAG.getVectorIdxConstant(Idx, DL));
3757  }
3758 
3759  Ops.push_back(Res);
3760  }
3761 
3762  setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3763 }
3764 
3765 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3766  ArrayRef<unsigned> Indices;
3767  if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3768  Indices = IV->getIndices();
3769  else
3770  Indices = cast<ConstantExpr>(&I)->getIndices();
3771 
3772  const Value *Op0 = I.getOperand(0);
3773  const Value *Op1 = I.getOperand(1);
3774  Type *AggTy = I.getType();
3775  Type *ValTy = Op1->getType();
3776  bool IntoUndef = isa<UndefValue>(Op0);
3777  bool FromUndef = isa<UndefValue>(Op1);
3778 
3779  unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3780 
3781  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3782  SmallVector<EVT, 4> AggValueVTs;
3783  ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3784  SmallVector<EVT, 4> ValValueVTs;
3785  ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3786 
3787  unsigned NumAggValues = AggValueVTs.size();
3788  unsigned NumValValues = ValValueVTs.size();
3789  SmallVector<SDValue, 4> Values(NumAggValues);
3790 
3791  // Ignore an insertvalue that produces an empty object
3792  if (!NumAggValues) {
3794  return;
3795  }
3796 
3797  SDValue Agg = getValue(Op0);
3798  unsigned i = 0;
3799  // Copy the beginning value(s) from the original aggregate.
3800  for (; i != LinearIndex; ++i)
3801  Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3802  SDValue(Agg.getNode(), Agg.getResNo() + i);
3803  // Copy values from the inserted value(s).
3804  if (NumValValues) {
3805  SDValue Val = getValue(Op1);
3806  for (; i != LinearIndex + NumValValues; ++i)
3807  Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3808  SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3809  }
3810  // Copy remaining value(s) from the original aggregate.
3811  for (; i != NumAggValues; ++i)
3812  Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3813  SDValue(Agg.getNode(), Agg.getResNo() + i);
3814 
3816  DAG.getVTList(AggValueVTs), Values));
3817 }
3818 
3819 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3820  ArrayRef<unsigned> Indices;
3821  if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3822  Indices = EV->getIndices();
3823  else
3824  Indices = cast<ConstantExpr>(&I)->getIndices();
3825 
3826  const Value *Op0 = I.getOperand(0);
3827  Type *AggTy = Op0->getType();
3828  Type *ValTy = I.getType();
3829  bool OutOfUndef = isa<UndefValue>(Op0);
3830 
3831  unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3832 
3833  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3834  SmallVector<EVT, 4> ValValueVTs;
3835  ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3836 
3837  unsigned NumValValues = ValValueVTs.size();
3838 
3839  // Ignore a extractvalue that produces an empty object
3840  if (!NumValValues) {
3842  return;
3843  }
3844 
3845  SmallVector<SDValue, 4> Values(NumValValues);
3846 
3847  SDValue Agg = getValue(Op0);
3848  // Copy out the selected value(s).
3849  for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3850  Values[i - LinearIndex] =
3851  OutOfUndef ?
3852  DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3853  SDValue(Agg.getNode(), Agg.getResNo() + i);
3854 
3856  DAG.getVTList(ValValueVTs), Values));
3857 }
3858 
3859 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3860  Value *Op0 = I.getOperand(0);
3861  // Note that the pointer operand may be a vector of pointers. Take the scalar
3862  // element which holds a pointer.
3863  unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3864  SDValue N = getValue(Op0);
3865  SDLoc dl = getCurSDLoc();
3866  auto &TLI = DAG.getTargetLoweringInfo();
3867 
3868  // Normalize Vector GEP - all scalar operands should be converted to the
3869  // splat vector.
3870  bool IsVectorGEP = I.getType()->isVectorTy();
3871  ElementCount VectorElementCount =
3872  IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3874 
3875  if (IsVectorGEP && !N.getValueType().isVector()) {
3877  EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3878  if (VectorElementCount.isScalable())
3879  N = DAG.getSplatVector(VT, dl, N);
3880  else
3881  N = DAG.getSplatBuildVector(VT, dl, N);
3882  }
3883 
3884  for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3885  GTI != E; ++GTI) {
3886  const Value *Idx = GTI.getOperand();
3887  if (StructType *StTy = GTI.getStructTypeOrNull()) {
3888  unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3889  if (Field) {
3890  // N = N + Offset
3891  uint64_t Offset =
3893 
3894  // In an inbounds GEP with an offset that is nonnegative even when
3895  // interpreted as signed, assume there is no unsigned overflow.
3896  SDNodeFlags Flags;
3897  if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3898  Flags.setNoUnsignedWrap(true);
3899 
3900  N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3901  DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3902  }
3903  } else {
3904  // IdxSize is the width of the arithmetic according to IR semantics.
3905  // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3906  // (and fix up the result later).
3907  unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3908  MVT IdxTy = MVT::getIntegerVT(IdxSize);
3909  TypeSize ElementSize =
3910  DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3911  // We intentionally mask away the high bits here; ElementSize may not
3912  // fit in IdxTy.
3913  APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3914  bool ElementScalable = ElementSize.isScalable();
3915 
3916  // If this is a scalar constant or a splat vector of constants,
3917  // handle it quickly.
3918  const auto *C = dyn_cast<Constant>(Idx);
3919  if (C && isa<VectorType>(C->getType()))
3920  C = C->getSplatValue();
3921 
3922  const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3923  if (CI && CI->isZero())
3924  continue;
3925  if (CI && !ElementScalable) {
3926  APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3928  SDValue OffsVal;
3929  if (IsVectorGEP)
3930  OffsVal = DAG.getConstant(
3931  Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3932  else
3933  OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3934 
3935  // In an inbounds GEP with an offset that is nonnegative even when
3936  // interpreted as signed, assume there is no unsigned overflow.
3937  SDNodeFlags Flags;
3938  if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3939  Flags.setNoUnsignedWrap(true);
3940 
3941  OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3942 
3943  N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3944  continue;
3945  }
3946 
3947  // N = N + Idx * ElementMul;
3948  SDValue IdxN = getValue(Idx);
3949 
3950  if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3951  EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3952  VectorElementCount);
3953  if (VectorElementCount.isScalable())
3954  IdxN = DAG.getSplatVector(VT, dl, IdxN);
3955  else
3956  IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3957  }
3958 
3959  // If the index is smaller or larger than intptr_t, truncate or extend
3960  // it.
3961  IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3962 
3963  if (ElementScalable) {
3964  EVT VScaleTy = N.getValueType().getScalarType();
3965  SDValue VScale = DAG.getNode(
3966  ISD::VSCALE, dl, VScaleTy,
3967  DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3968  if (IsVectorGEP)
3969  VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3970  IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3971  } else {
3972  // If this is a multiply by a power of two, turn it into a shl
3973  // immediately. This is a very common case.
3974  if (ElementMul != 1) {
3975  if (ElementMul.isPowerOf2()) {
3976  unsigned Amt = ElementMul.logBase2();
3977  IdxN = DAG.getNode(ISD::SHL, dl,
3978  N.getValueType(), IdxN,
3979  DAG.getConstant(Amt, dl, IdxN.getValueType()));
3980  } else {
3981  SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3982  IdxN.getValueType());
3983  IdxN = DAG.getNode(ISD::MUL, dl,
3984  N.getValueType(), IdxN, Scale);
3985  }
3986  }
3987  }
3988 
3989  N = DAG.getNode(ISD::ADD, dl,
3990  N.getValueType(), N, IdxN);
3991  }
3992  }
3993 
3994  MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3995  MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3996  if (IsVectorGEP) {
3997  PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3998  PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3999  }
4000 
4001  if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4002  N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4003 
4004  setValue(&I, N);
4005 }
4006 
4007 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4008  // If this is a fixed sized alloca in the entry block of the function,
4009  // allocate it statically on the stack.
4010  if (FuncInfo.StaticAllocaMap.count(&I))
4011  return; // getValue will auto-populate this.
4012 
4013  SDLoc dl = getCurSDLoc();
4014  Type *Ty = I.getAllocatedType();
4015  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4016  auto &DL = DAG.getDataLayout();
4017  uint64_t TySize = DL.getTypeAllocSize(Ty);
4018  MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4019 
4020  SDValue AllocSize = getValue(I.getArraySize());
4021 
4022  EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4023  if (AllocSize.getValueType() != IntPtr)
4024  AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4025 
4026  AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4027  AllocSize,
4028  DAG.getConstant(TySize, dl, IntPtr));
4029 
4030  // Handle alignment. If the requested alignment is less than or equal to
4031  // the stack alignment, ignore it. If the size is greater than or equal to
4032  // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4034  if (*Alignment <= StackAlign)
4035  Alignment = None;
4036 
4037  const uint64_t StackAlignMask = StackAlign.value() - 1U;
4038  // Round the size of the allocation up to the stack alignment size
4039  // by add SA-1 to the size. This doesn't overflow because we're computing
4040  // an address inside an alloca.
4041  SDNodeFlags Flags;
4042  Flags.setNoUnsignedWrap(true);
4043  AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4044  DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4045 
4046  // Mask out the low bits for alignment purposes.
4047  AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4048  DAG.getConstant(~StackAlignMask, dl, IntPtr));
4049 
4050  SDValue Ops[] = {
4051  getRoot(), AllocSize,
4052  DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4053  SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4054  SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4055  setValue(&I, DSA);
4056  DAG.setRoot(DSA.getValue(1));
4057 
4059 }
4060 
4061 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4062  if (I.isAtomic())
4063  return visitAtomicLoad(I);
4064 
4065  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4066  const Value *SV = I.getOperand(0);
4067  if (TLI.supportSwiftError()) {
4068  // Swifterror values can come from either a function parameter with
4069  // swifterror attribute or an alloca with swifterror attribute.
4070  if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4071  if (Arg->hasSwiftErrorAttr())
4072  return visitLoadFromSwiftError(I);
4073  }
4074 
4075  if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4076  if (Alloca->isSwiftError())
4077  return visitLoadFromSwiftError(I);
4078  }
4079  }
4080 
4081  SDValue Ptr = getValue(SV);
4082 
4083  Type *Ty = I.getType();
4084  Align Alignment = I.getAlign();
4085 
4086  AAMDNodes AAInfo = I.getAAMetadata();
4087  const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4088 
4089  SmallVector<EVT, 4> ValueVTs, MemVTs;
4091  ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4092  unsigned NumValues = ValueVTs.size();
4093  if (NumValues == 0)
4094  return;
4095 
4096  bool isVolatile = I.isVolatile();
4097 
4098  SDValue Root;
4099  bool ConstantMemory = false;
4100  if (isVolatile)
4101  // Serialize volatile loads with other side effects.
4102  Root = getRoot();
4103  else if (NumValues > MaxParallelChains)
4104  Root = getMemoryRoot();
4105  else if (AA &&
4107  SV,
4109  AAInfo))) {
4110  // Do not serialize (non-volatile) loads of constant memory with anything.
4111  Root = DAG.getEntryNode();
4112  ConstantMemory = true;
4113  } else {
4114  // Do not serialize non-volatile loads against each other.
4115  Root = DAG.getRoot();
4116  }
4117 
4118  SDLoc dl = getCurSDLoc();
4119 
4120  if (isVolatile)
4121  Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4122 
4123  // An aggregate load cannot wrap around the address space, so offsets to its
4124  // parts don't wrap either.
4125  SDNodeFlags Flags;
4126  Flags.setNoUnsignedWrap(true);
4127 
4128  SmallVector<SDValue, 4> Values(NumValues);
4130  EVT PtrVT = Ptr.getValueType();
4131 
4132  MachineMemOperand::Flags MMOFlags
4134 
4135  unsigned ChainI = 0;
4136  for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4137  // Serializing loads here may result in excessive register pressure, and
4138  // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4139  // could recover a bit by hoisting nodes upward in the chain by recognizing
4140  // they are side-effect free or do not alias. The optimizer should really
4141  // avoid this case by converting large object/array copies to llvm.memcpy
4142  // (MaxParallelChains should always remain as failsafe).
4143  if (ChainI == MaxParallelChains) {
4144  assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4146  makeArrayRef(Chains.data(), ChainI));
4147  Root = Chain;
4148  ChainI = 0;
4149  }
4150  SDValue A = DAG.getNode(ISD::ADD, dl,
4151  PtrVT, Ptr,
4152  DAG.getConstant(Offsets[i], dl, PtrVT),
4153  Flags);
4154 
4155  SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4156  MachinePointerInfo(SV, Offsets[i]), Alignment,
4157  MMOFlags, AAInfo, Ranges);
4158  Chains[ChainI] = L.getValue(1);
4159 
4160  if (MemVTs[i] != ValueVTs[i])
4161  L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4162 
4163  Values[i] = L;
4164  }
4165 
4166  if (!ConstantMemory) {
4168  makeArrayRef(Chains.data(), ChainI));
4169  if (isVolatile)
4170  DAG.setRoot(Chain);
4171  else
4172  PendingLoads.push_back(Chain);
4173  }
4174 
4176  DAG.getVTList(ValueVTs), Values));
4177 }
4178 
4179 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4181  "call visitStoreToSwiftError when backend supports swifterror");
4182 
4183  SmallVector<EVT, 4> ValueVTs;
4185  const Value *SrcV = I.getOperand(0);
4187  SrcV->getType(), ValueVTs, &Offsets);
4188  assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4189  "expect a single EVT for swifterror");
4190 
4191  SDValue Src = getValue(SrcV);
4192  // Create a virtual register, then update the virtual register.
4193  Register VReg =
4194  SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4195  // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4196  // Chain can be getRoot or getControlRoot.
4197  SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4198  SDValue(Src.getNode(), Src.getResNo()));
4199  DAG.setRoot(CopyNode);
4200 }
4201 
4202 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4204  "call visitLoadFromSwiftError when backend supports swifterror");
4205 
4206  assert(!I.isVolatile() &&
4207  !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4208  !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4209  "Support volatile, non temporal, invariant for load_from_swift_error");
4210 
4211  const Value *SV = I.getOperand(0);
4212  Type *Ty = I.getType();
4213  assert(
4214  (!AA ||
4217  I.getAAMetadata()))) &&
4218  "load_from_swift_error should not be constant memory");
4219 
4220  SmallVector<EVT, 4> ValueVTs;
4223  ValueVTs, &Offsets);
4224  assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4225  "expect a single EVT for swifterror");
4226 
4227  // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4229  getRoot(), getCurSDLoc(),
4230  SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4231 
4232  setValue(&I, L);
4233 }
4234 
4235 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4236  if (I.isAtomic())
4237  return visitAtomicStore(I);
4238 
4239  const Value *SrcV = I.getOperand(0);
4240  const Value *PtrV = I.getOperand(1);
4241 
4242  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4243  if (TLI.supportSwiftError()) {
4244  // Swifterror values can come from either a function parameter with
4245  // swifterror attribute or an alloca with swifterror attribute.
4246  if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4247  if (Arg->hasSwiftErrorAttr())
4248  return visitStoreToSwiftError(I);
4249  }
4250 
4251  if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4252  if (Alloca->isSwiftError())
4253  return visitStoreToSwiftError(I);
4254  }
4255  }
4256 
4257  SmallVector<EVT, 4> ValueVTs, MemVTs;
4260  SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4261  unsigned NumValues = ValueVTs.size();
4262  if (NumValues == 0)
4263  return;
4264 
4265  // Get the lowered operands. Note that we do this after
4266  // checking if NumResults is zero, because with zero results
4267  // the operands won't have values in the map.
4268  SDValue Src = getValue(SrcV);
4269  SDValue Ptr = getValue(PtrV);
4270 
4271  SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4273  SDLoc dl = getCurSDLoc();
4274  Align Alignment = I.getAlign();
4275  AAMDNodes AAInfo = I.getAAMetadata();
4276 
4277  auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4278 
4279  // An aggregate load cannot wrap around the address space, so offsets to its
4280  // parts don't wrap either.
4281  SDNodeFlags Flags;
4282  Flags.setNoUnsignedWrap(true);
4283 
4284  unsigned ChainI = 0;
4285  for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4286  // See visitLoad comments.
4287  if (ChainI == MaxParallelChains) {
4289  makeArrayRef(Chains.data(), ChainI));
4290  Root = Chain;
4291  ChainI = 0;
4292  }
4293  SDValue Add =
4294  DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4295  SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4296  if (MemVTs[i] != ValueVTs[i])
4297  Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4298  SDValue St =
4299  DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4300  Alignment, MMOFlags, AAInfo);
4301  Chains[ChainI] = St;
4302  }
4303 
4304  SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4305  makeArrayRef(Chains.data(), ChainI));
4306  DAG.setRoot(StoreNode);
4307 }
4308 
4309 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4310  bool IsCompressing) {
4311  SDLoc sdl = getCurSDLoc();
4312 
4313  auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4314  MaybeAlign &Alignment) {
4315  // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4316  Src0 = I.getArgOperand(0);
4317  Ptr = I.getArgOperand(1);
4318  Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4319  Mask = I.getArgOperand(3);
4320  };
4321  auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4322  MaybeAlign &Alignment) {
4323  // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4324  Src0 = I.getArgOperand(0);
4325  Ptr = I.getArgOperand(1);
4326  Mask = I.getArgOperand(2);
4327  Alignment = None;
4328  };
4329 
4330  Value *PtrOperand, *MaskOperand, *Src0Operand;
4331  MaybeAlign Alignment;
4332  if (IsCompressing)
4333  getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4334  else
4335  getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4336 
4337  SDValue Ptr = getValue(PtrOperand);
4338  SDValue Src0 = getValue(Src0Operand);
4339  SDValue Mask = getValue(MaskOperand);
4341 
4342  EVT VT = Src0.getValueType();
4343  if (!Alignment)
4344  Alignment = DAG.getEVTAlign(VT);
4345 
4348  MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4349  SDValue StoreNode =
4350  DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4351  ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4352  DAG.setRoot(StoreNode);
4353  setValue(&I, StoreNode);
4354 }
4355 
4356 // Get a uniform base for the Gather/Scatter intrinsic.
4357 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4358 // We try to represent it as a base pointer + vector of indices.
4359 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4360 // The first operand of the GEP may be a single pointer or a vector of pointers
4361 // Example:
4362 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4363 // or
4364 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4365 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4366 //
4367 // When the first GEP operand is a single pointer - it is the uniform base we
4368 // are looking for. If first operand of the GEP is a splat vector - we
4369 // extract the splat value and use it as a uniform base.
4370 // In all other cases the function returns 'false'.
4371 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4372  ISD::MemIndexType &IndexType, SDValue &Scale,
4373  SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4374  SelectionDAG& DAG = SDB->DAG;
4375  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4376  const DataLayout &DL = DAG.getDataLayout();
4377 
4378  assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4379 
4380  // Handle splat constant pointer.
4381  if (auto *C = dyn_cast<Constant>(Ptr)) {
4382  C = C->getSplatValue();
4383  if (!C)
4384  return false;
4385 
4386  Base = SDB->getValue(C);
4387 
4388  ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4389  EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4390  Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4391  IndexType = ISD::SIGNED_SCALED;
4392  Scale = DAG.getTargetConstant(1, SDB->