LLVM  mainline
SelectionDAGBuilder.cpp
Go to the documentation of this file.
00001 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements routines for translating from LLVM IR into SelectionDAG IR.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "SelectionDAGBuilder.h"
00015 #include "SDNodeDbgValue.h"
00016 #include "llvm/ADT/BitVector.h"
00017 #include "llvm/ADT/Optional.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/BranchProbabilityInfo.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/TargetLibraryInfo.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/CodeGen/Analysis.h"
00026 #include "llvm/CodeGen/FastISel.h"
00027 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00028 #include "llvm/CodeGen/GCMetadata.h"
00029 #include "llvm/CodeGen/GCStrategy.h"
00030 #include "llvm/CodeGen/MachineFrameInfo.h"
00031 #include "llvm/CodeGen/MachineFunction.h"
00032 #include "llvm/CodeGen/MachineInstrBuilder.h"
00033 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00034 #include "llvm/CodeGen/MachineModuleInfo.h"
00035 #include "llvm/CodeGen/MachineRegisterInfo.h"
00036 #include "llvm/CodeGen/SelectionDAG.h"
00037 #include "llvm/CodeGen/StackMaps.h"
00038 #include "llvm/CodeGen/WinEHFuncInfo.h"
00039 #include "llvm/IR/CallingConv.h"
00040 #include "llvm/IR/Constants.h"
00041 #include "llvm/IR/DataLayout.h"
00042 #include "llvm/IR/DebugInfo.h"
00043 #include "llvm/IR/DerivedTypes.h"
00044 #include "llvm/IR/Function.h"
00045 #include "llvm/IR/GlobalVariable.h"
00046 #include "llvm/IR/InlineAsm.h"
00047 #include "llvm/IR/Instructions.h"
00048 #include "llvm/IR/IntrinsicInst.h"
00049 #include "llvm/IR/Intrinsics.h"
00050 #include "llvm/IR/LLVMContext.h"
00051 #include "llvm/IR/Module.h"
00052 #include "llvm/IR/Statepoint.h"
00053 #include "llvm/MC/MCSymbol.h"
00054 #include "llvm/Support/CommandLine.h"
00055 #include "llvm/Support/Debug.h"
00056 #include "llvm/Support/ErrorHandling.h"
00057 #include "llvm/Support/MathExtras.h"
00058 #include "llvm/Support/raw_ostream.h"
00059 #include "llvm/Target/TargetFrameLowering.h"
00060 #include "llvm/Target/TargetInstrInfo.h"
00061 #include "llvm/Target/TargetIntrinsicInfo.h"
00062 #include "llvm/Target/TargetLowering.h"
00063 #include "llvm/Target/TargetOptions.h"
00064 #include "llvm/Target/TargetSelectionDAGInfo.h"
00065 #include "llvm/Target/TargetSubtargetInfo.h"
00066 #include <algorithm>
00067 using namespace llvm;
00068 
00069 #define DEBUG_TYPE "isel"
00070 
00071 /// LimitFloatPrecision - Generate low-precision inline sequences for
00072 /// some float libcalls (6, 8 or 12 bits).
00073 static unsigned LimitFloatPrecision;
00074 
00075 static cl::opt<unsigned, true>
00076 LimitFPPrecision("limit-float-precision",
00077                  cl::desc("Generate low-precision inline sequences "
00078                           "for some float libcalls"),
00079                  cl::location(LimitFloatPrecision),
00080                  cl::init(0));
00081 
00082 // Limit the width of DAG chains. This is important in general to prevent
00083 // prevent DAG-based analysis from blowing up. For example, alias analysis and
00084 // load clustering may not complete in reasonable time. It is difficult to
00085 // recognize and avoid this situation within each individual analysis, and
00086 // future analyses are likely to have the same behavior. Limiting DAG width is
00087 // the safe approach, and will be especially important with global DAGs.
00088 //
00089 // MaxParallelChains default is arbitrarily high to avoid affecting
00090 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
00091 // sequence over this should have been converted to llvm.memcpy by the
00092 // frontend. It easy to induce this behavior with .ll code such as:
00093 // %buffer = alloca [4096 x i8]
00094 // %data = load [4096 x i8]* %argPtr
00095 // store [4096 x i8] %data, [4096 x i8]* %buffer
00096 static const unsigned MaxParallelChains = 64;
00097 
00098 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00099                                       const SDValue *Parts, unsigned NumParts,
00100                                       MVT PartVT, EVT ValueVT, const Value *V);
00101 
00102 /// getCopyFromParts - Create a value that contains the specified legal parts
00103 /// combined into the value they represent.  If the parts combine to a type
00104 /// larger then ValueVT then AssertOp can be used to specify whether the extra
00105 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
00106 /// (ISD::AssertSext).
00107 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
00108                                 const SDValue *Parts,
00109                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
00110                                 const Value *V,
00111                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
00112   if (ValueVT.isVector())
00113     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
00114                                   PartVT, ValueVT, V);
00115 
00116   assert(NumParts > 0 && "No parts to assemble!");
00117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00118   SDValue Val = Parts[0];
00119 
00120   if (NumParts > 1) {
00121     // Assemble the value from multiple parts.
00122     if (ValueVT.isInteger()) {
00123       unsigned PartBits = PartVT.getSizeInBits();
00124       unsigned ValueBits = ValueVT.getSizeInBits();
00125 
00126       // Assemble the power of 2 part.
00127       unsigned RoundParts = NumParts & (NumParts - 1) ?
00128         1 << Log2_32(NumParts) : NumParts;
00129       unsigned RoundBits = PartBits * RoundParts;
00130       EVT RoundVT = RoundBits == ValueBits ?
00131         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
00132       SDValue Lo, Hi;
00133 
00134       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
00135 
00136       if (RoundParts > 2) {
00137         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
00138                               PartVT, HalfVT, V);
00139         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
00140                               RoundParts / 2, PartVT, HalfVT, V);
00141       } else {
00142         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
00143         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
00144       }
00145 
00146       if (TLI.isBigEndian())
00147         std::swap(Lo, Hi);
00148 
00149       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
00150 
00151       if (RoundParts < NumParts) {
00152         // Assemble the trailing non-power-of-2 part.
00153         unsigned OddParts = NumParts - RoundParts;
00154         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
00155         Hi = getCopyFromParts(DAG, DL,
00156                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
00157 
00158         // Combine the round and odd parts.
00159         Lo = Val;
00160         if (TLI.isBigEndian())
00161           std::swap(Lo, Hi);
00162         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00163         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
00164         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
00165                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
00166                                          TLI.getPointerTy()));
00167         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
00168         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
00169       }
00170     } else if (PartVT.isFloatingPoint()) {
00171       // FP split into multiple FP parts (for ppcf128)
00172       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
00173              "Unexpected split");
00174       SDValue Lo, Hi;
00175       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
00176       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
00177       if (TLI.hasBigEndianPartOrdering(ValueVT))
00178         std::swap(Lo, Hi);
00179       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
00180     } else {
00181       // FP split into integer parts (soft fp)
00182       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
00183              !PartVT.isVector() && "Unexpected split");
00184       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
00185       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
00186     }
00187   }
00188 
00189   // There is now one part, held in Val.  Correct it to match ValueVT.
00190   EVT PartEVT = Val.getValueType();
00191 
00192   if (PartEVT == ValueVT)
00193     return Val;
00194 
00195   if (PartEVT.isInteger() && ValueVT.isInteger()) {
00196     if (ValueVT.bitsLT(PartEVT)) {
00197       // For a truncate, see if we have any information to
00198       // indicate whether the truncated bits will always be
00199       // zero or sign-extension.
00200       if (AssertOp != ISD::DELETED_NODE)
00201         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
00202                           DAG.getValueType(ValueVT));
00203       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00204     }
00205     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
00206   }
00207 
00208   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00209     // FP_ROUND's are always exact here.
00210     if (ValueVT.bitsLT(Val.getValueType()))
00211       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
00212                          DAG.getTargetConstant(1, TLI.getPointerTy()));
00213 
00214     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
00215   }
00216 
00217   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
00218     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00219 
00220   llvm_unreachable("Unknown mismatch!");
00221 }
00222 
00223 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
00224                                               const Twine &ErrMsg) {
00225   const Instruction *I = dyn_cast_or_null<Instruction>(V);
00226   if (!V)
00227     return Ctx.emitError(ErrMsg);
00228 
00229   const char *AsmError = ", possible invalid constraint for vector type";
00230   if (const CallInst *CI = dyn_cast<CallInst>(I))
00231     if (isa<InlineAsm>(CI->getCalledValue()))
00232       return Ctx.emitError(I, ErrMsg + AsmError);
00233 
00234   return Ctx.emitError(I, ErrMsg);
00235 }
00236 
00237 /// getCopyFromPartsVector - Create a value that contains the specified legal
00238 /// parts combined into the value they represent.  If the parts combine to a
00239 /// type larger then ValueVT then AssertOp can be used to specify whether the
00240 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
00241 /// ValueVT (ISD::AssertSext).
00242 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00243                                       const SDValue *Parts, unsigned NumParts,
00244                                       MVT PartVT, EVT ValueVT, const Value *V) {
00245   assert(ValueVT.isVector() && "Not a vector value");
00246   assert(NumParts > 0 && "No parts to assemble!");
00247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00248   SDValue Val = Parts[0];
00249 
00250   // Handle a multi-element vector.
00251   if (NumParts > 1) {
00252     EVT IntermediateVT;
00253     MVT RegisterVT;
00254     unsigned NumIntermediates;
00255     unsigned NumRegs =
00256     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
00257                                NumIntermediates, RegisterVT);
00258     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00259     NumParts = NumRegs; // Silence a compiler warning.
00260     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00261     assert(RegisterVT == Parts[0].getSimpleValueType() &&
00262            "Part type doesn't match part!");
00263 
00264     // Assemble the parts into intermediate operands.
00265     SmallVector<SDValue, 8> Ops(NumIntermediates);
00266     if (NumIntermediates == NumParts) {
00267       // If the register was not expanded, truncate or copy the value,
00268       // as appropriate.
00269       for (unsigned i = 0; i != NumParts; ++i)
00270         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
00271                                   PartVT, IntermediateVT, V);
00272     } else if (NumParts > 0) {
00273       // If the intermediate type was expanded, build the intermediate
00274       // operands from the parts.
00275       assert(NumParts % NumIntermediates == 0 &&
00276              "Must expand into a divisible number of parts!");
00277       unsigned Factor = NumParts / NumIntermediates;
00278       for (unsigned i = 0; i != NumIntermediates; ++i)
00279         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
00280                                   PartVT, IntermediateVT, V);
00281     }
00282 
00283     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
00284     // intermediate operands.
00285     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
00286                                                 : ISD::BUILD_VECTOR,
00287                       DL, ValueVT, Ops);
00288   }
00289 
00290   // There is now one part, held in Val.  Correct it to match ValueVT.
00291   EVT PartEVT = Val.getValueType();
00292 
00293   if (PartEVT == ValueVT)
00294     return Val;
00295 
00296   if (PartEVT.isVector()) {
00297     // If the element type of the source/dest vectors are the same, but the
00298     // parts vector has more elements than the value vector, then we have a
00299     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
00300     // elements we want.
00301     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
00302       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
00303              "Cannot narrow, it would be a lossy transformation");
00304       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
00305                          DAG.getConstant(0, TLI.getVectorIdxTy()));
00306     }
00307 
00308     // Vector/Vector bitcast.
00309     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
00310       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00311 
00312     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
00313       "Cannot handle this kind of promotion");
00314     // Promoted vector extract
00315     bool Smaller = ValueVT.bitsLE(PartEVT);
00316     return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00317                        DL, ValueVT, Val);
00318 
00319   }
00320 
00321   // Trivial bitcast if the types are the same size and the destination
00322   // vector type is legal.
00323   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
00324       TLI.isTypeLegal(ValueVT))
00325     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00326 
00327   // Handle cases such as i8 -> <1 x i1>
00328   if (ValueVT.getVectorNumElements() != 1) {
00329     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00330                                       "non-trivial scalar-to-vector conversion");
00331     return DAG.getUNDEF(ValueVT);
00332   }
00333 
00334   if (ValueVT.getVectorNumElements() == 1 &&
00335       ValueVT.getVectorElementType() != PartEVT) {
00336     bool Smaller = ValueVT.bitsLE(PartEVT);
00337     Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00338                        DL, ValueVT.getScalarType(), Val);
00339   }
00340 
00341   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
00342 }
00343 
00344 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
00345                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00346                                  MVT PartVT, const Value *V);
00347 
00348 /// getCopyToParts - Create a series of nodes that contain the specified value
00349 /// split into legal parts.  If the parts contain more bits than Val, then, for
00350 /// integers, ExtendKind can be used to specify how to generate the extra bits.
00351 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
00352                            SDValue Val, SDValue *Parts, unsigned NumParts,
00353                            MVT PartVT, const Value *V,
00354                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
00355   EVT ValueVT = Val.getValueType();
00356 
00357   // Handle the vector case separately.
00358   if (ValueVT.isVector())
00359     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
00360 
00361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00362   unsigned PartBits = PartVT.getSizeInBits();
00363   unsigned OrigNumParts = NumParts;
00364   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
00365 
00366   if (NumParts == 0)
00367     return;
00368 
00369   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
00370   EVT PartEVT = PartVT;
00371   if (PartEVT == ValueVT) {
00372     assert(NumParts == 1 && "No-op copy with multiple parts!");
00373     Parts[0] = Val;
00374     return;
00375   }
00376 
00377   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
00378     // If the parts cover more bits than the value has, promote the value.
00379     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00380       assert(NumParts == 1 && "Do not know what to promote to!");
00381       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
00382     } else {
00383       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00384              ValueVT.isInteger() &&
00385              "Unknown mismatch!");
00386       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00387       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
00388       if (PartVT == MVT::x86mmx)
00389         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00390     }
00391   } else if (PartBits == ValueVT.getSizeInBits()) {
00392     // Different types of the same size.
00393     assert(NumParts == 1 && PartEVT != ValueVT);
00394     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00395   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
00396     // If the parts cover less bits than value has, truncate the value.
00397     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00398            ValueVT.isInteger() &&
00399            "Unknown mismatch!");
00400     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00401     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00402     if (PartVT == MVT::x86mmx)
00403       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00404   }
00405 
00406   // The value may have changed - recompute ValueVT.
00407   ValueVT = Val.getValueType();
00408   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
00409          "Failed to tile the value with PartVT!");
00410 
00411   if (NumParts == 1) {
00412     if (PartEVT != ValueVT)
00413       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00414                                         "scalar-to-vector conversion failed");
00415 
00416     Parts[0] = Val;
00417     return;
00418   }
00419 
00420   // Expand the value into multiple parts.
00421   if (NumParts & (NumParts - 1)) {
00422     // The number of parts is not a power of 2.  Split off and copy the tail.
00423     assert(PartVT.isInteger() && ValueVT.isInteger() &&
00424            "Do not know what to expand to!");
00425     unsigned RoundParts = 1 << Log2_32(NumParts);
00426     unsigned RoundBits = RoundParts * PartBits;
00427     unsigned OddParts = NumParts - RoundParts;
00428     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
00429                                  DAG.getIntPtrConstant(RoundBits));
00430     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
00431 
00432     if (TLI.isBigEndian())
00433       // The odd parts were reversed by getCopyToParts - unreverse them.
00434       std::reverse(Parts + RoundParts, Parts + NumParts);
00435 
00436     NumParts = RoundParts;
00437     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00438     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00439   }
00440 
00441   // The number of parts is a power of 2.  Repeatedly bisect the value using
00442   // EXTRACT_ELEMENT.
00443   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
00444                          EVT::getIntegerVT(*DAG.getContext(),
00445                                            ValueVT.getSizeInBits()),
00446                          Val);
00447 
00448   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
00449     for (unsigned i = 0; i < NumParts; i += StepSize) {
00450       unsigned ThisBits = StepSize * PartBits / 2;
00451       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
00452       SDValue &Part0 = Parts[i];
00453       SDValue &Part1 = Parts[i+StepSize/2];
00454 
00455       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00456                           ThisVT, Part0, DAG.getIntPtrConstant(1));
00457       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00458                           ThisVT, Part0, DAG.getIntPtrConstant(0));
00459 
00460       if (ThisBits == PartBits && ThisVT != PartVT) {
00461         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
00462         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
00463       }
00464     }
00465   }
00466 
00467   if (TLI.isBigEndian())
00468     std::reverse(Parts, Parts + OrigNumParts);
00469 }
00470 
00471 
00472 /// getCopyToPartsVector - Create a series of nodes that contain the specified
00473 /// value split into legal parts.
00474 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
00475                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00476                                  MVT PartVT, const Value *V) {
00477   EVT ValueVT = Val.getValueType();
00478   assert(ValueVT.isVector() && "Not a vector");
00479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00480 
00481   if (NumParts == 1) {
00482     EVT PartEVT = PartVT;
00483     if (PartEVT == ValueVT) {
00484       // Nothing to do.
00485     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
00486       // Bitconvert vector->vector case.
00487       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00488     } else if (PartVT.isVector() &&
00489                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
00490                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
00491       EVT ElementVT = PartVT.getVectorElementType();
00492       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
00493       // undef elements.
00494       SmallVector<SDValue, 16> Ops;
00495       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
00496         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00497                                   ElementVT, Val, DAG.getConstant(i,
00498                                                   TLI.getVectorIdxTy())));
00499 
00500       for (unsigned i = ValueVT.getVectorNumElements(),
00501            e = PartVT.getVectorNumElements(); i != e; ++i)
00502         Ops.push_back(DAG.getUNDEF(ElementVT));
00503 
00504       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
00505 
00506       // FIXME: Use CONCAT for 2x -> 4x.
00507 
00508       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
00509       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
00510     } else if (PartVT.isVector() &&
00511                PartEVT.getVectorElementType().bitsGE(
00512                  ValueVT.getVectorElementType()) &&
00513                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
00514 
00515       // Promoted vector extract
00516       bool Smaller = PartEVT.bitsLE(ValueVT);
00517       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00518                         DL, PartVT, Val);
00519     } else{
00520       // Vector -> scalar conversion.
00521       assert(ValueVT.getVectorNumElements() == 1 &&
00522              "Only trivial vector-to-scalar conversions should get here!");
00523       Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00524                         PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
00525 
00526       bool Smaller = ValueVT.bitsLE(PartVT);
00527       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00528                          DL, PartVT, Val);
00529     }
00530 
00531     Parts[0] = Val;
00532     return;
00533   }
00534 
00535   // Handle a multi-element vector.
00536   EVT IntermediateVT;
00537   MVT RegisterVT;
00538   unsigned NumIntermediates;
00539   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
00540                                                 IntermediateVT,
00541                                                 NumIntermediates, RegisterVT);
00542   unsigned NumElements = ValueVT.getVectorNumElements();
00543 
00544   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00545   NumParts = NumRegs; // Silence a compiler warning.
00546   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00547 
00548   // Split the vector into intermediate operands.
00549   SmallVector<SDValue, 8> Ops(NumIntermediates);
00550   for (unsigned i = 0; i != NumIntermediates; ++i) {
00551     if (IntermediateVT.isVector())
00552       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
00553                            IntermediateVT, Val,
00554                    DAG.getConstant(i * (NumElements / NumIntermediates),
00555                                    TLI.getVectorIdxTy()));
00556     else
00557       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00558                            IntermediateVT, Val,
00559                            DAG.getConstant(i, TLI.getVectorIdxTy()));
00560   }
00561 
00562   // Split the intermediate operands into legal parts.
00563   if (NumParts == NumIntermediates) {
00564     // If the register was not expanded, promote or copy the value,
00565     // as appropriate.
00566     for (unsigned i = 0; i != NumParts; ++i)
00567       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
00568   } else if (NumParts > 0) {
00569     // If the intermediate type was expanded, split each the value into
00570     // legal parts.
00571     assert(NumIntermediates != 0 && "division by zero");
00572     assert(NumParts % NumIntermediates == 0 &&
00573            "Must expand into a divisible number of parts!");
00574     unsigned Factor = NumParts / NumIntermediates;
00575     for (unsigned i = 0; i != NumIntermediates; ++i)
00576       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
00577   }
00578 }
00579 
00580 namespace {
00581   /// RegsForValue - This struct represents the registers (physical or virtual)
00582   /// that a particular set of values is assigned, and the type information
00583   /// about the value. The most common situation is to represent one value at a
00584   /// time, but struct or array values are handled element-wise as multiple
00585   /// values.  The splitting of aggregates is performed recursively, so that we
00586   /// never have aggregate-typed registers. The values at this point do not
00587   /// necessarily have legal types, so each value may require one or more
00588   /// registers of some legal type.
00589   ///
00590   struct RegsForValue {
00591     /// ValueVTs - The value types of the values, which may not be legal, and
00592     /// may need be promoted or synthesized from one or more registers.
00593     ///
00594     SmallVector<EVT, 4> ValueVTs;
00595 
00596     /// RegVTs - The value types of the registers. This is the same size as
00597     /// ValueVTs and it records, for each value, what the type of the assigned
00598     /// register or registers are. (Individual values are never synthesized
00599     /// from more than one type of register.)
00600     ///
00601     /// With virtual registers, the contents of RegVTs is redundant with TLI's
00602     /// getRegisterType member function, however when with physical registers
00603     /// it is necessary to have a separate record of the types.
00604     ///
00605     SmallVector<MVT, 4> RegVTs;
00606 
00607     /// Regs - This list holds the registers assigned to the values.
00608     /// Each legal or promoted value requires one register, and each
00609     /// expanded value requires multiple registers.
00610     ///
00611     SmallVector<unsigned, 4> Regs;
00612 
00613     RegsForValue() {}
00614 
00615     RegsForValue(const SmallVector<unsigned, 4> &regs,
00616                  MVT regvt, EVT valuevt)
00617       : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
00618 
00619     RegsForValue(LLVMContext &Context, const TargetLowering &tli,
00620                  unsigned Reg, Type *Ty) {
00621       ComputeValueVTs(tli, Ty, ValueVTs);
00622 
00623       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00624         EVT ValueVT = ValueVTs[Value];
00625         unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
00626         MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
00627         for (unsigned i = 0; i != NumRegs; ++i)
00628           Regs.push_back(Reg + i);
00629         RegVTs.push_back(RegisterVT);
00630         Reg += NumRegs;
00631       }
00632     }
00633 
00634     /// append - Add the specified values to this one.
00635     void append(const RegsForValue &RHS) {
00636       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
00637       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
00638       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
00639     }
00640 
00641     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00642     /// this value and returns the result as a ValueVTs value.  This uses
00643     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00644     /// If the Flag pointer is NULL, no flag is used.
00645     SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
00646                             SDLoc dl,
00647                             SDValue &Chain, SDValue *Flag,
00648                             const Value *V = nullptr) const;
00649 
00650     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00651     /// specified value into the registers specified by this object.  This uses
00652     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00653     /// If the Flag pointer is NULL, no flag is used.
00654     void
00655     getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
00656                   SDValue *Flag, const Value *V,
00657                   ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
00658 
00659     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00660     /// operand list.  This adds the code marker, matching input operand index
00661     /// (if applicable), and includes the number of values added into it.
00662     void AddInlineAsmOperands(unsigned Kind,
00663                               bool HasMatching, unsigned MatchingIdx,
00664                               SelectionDAG &DAG,
00665                               std::vector<SDValue> &Ops) const;
00666   };
00667 }
00668 
00669 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00670 /// this value and returns the result as a ValueVT value.  This uses
00671 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00672 /// If the Flag pointer is NULL, no flag is used.
00673 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
00674                                       FunctionLoweringInfo &FuncInfo,
00675                                       SDLoc dl,
00676                                       SDValue &Chain, SDValue *Flag,
00677                                       const Value *V) const {
00678   // A Value with type {} or [0 x %t] needs no registers.
00679   if (ValueVTs.empty())
00680     return SDValue();
00681 
00682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00683 
00684   // Assemble the legal parts into the final values.
00685   SmallVector<SDValue, 4> Values(ValueVTs.size());
00686   SmallVector<SDValue, 8> Parts;
00687   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00688     // Copy the legal parts from the registers.
00689     EVT ValueVT = ValueVTs[Value];
00690     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00691     MVT RegisterVT = RegVTs[Value];
00692 
00693     Parts.resize(NumRegs);
00694     for (unsigned i = 0; i != NumRegs; ++i) {
00695       SDValue P;
00696       if (!Flag) {
00697         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
00698       } else {
00699         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
00700         *Flag = P.getValue(2);
00701       }
00702 
00703       Chain = P.getValue(1);
00704       Parts[i] = P;
00705 
00706       // If the source register was virtual and if we know something about it,
00707       // add an assert node.
00708       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
00709           !RegisterVT.isInteger() || RegisterVT.isVector())
00710         continue;
00711 
00712       const FunctionLoweringInfo::LiveOutInfo *LOI =
00713         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
00714       if (!LOI)
00715         continue;
00716 
00717       unsigned RegSize = RegisterVT.getSizeInBits();
00718       unsigned NumSignBits = LOI->NumSignBits;
00719       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
00720 
00721       if (NumZeroBits == RegSize) {
00722         // The current value is a zero.
00723         // Explicitly express that as it would be easier for
00724         // optimizations to kick in.
00725         Parts[i] = DAG.getConstant(0, RegisterVT);
00726         continue;
00727       }
00728 
00729       // FIXME: We capture more information than the dag can represent.  For
00730       // now, just use the tightest assertzext/assertsext possible.
00731       bool isSExt = true;
00732       EVT FromVT(MVT::Other);
00733       if (NumSignBits == RegSize)
00734         isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
00735       else if (NumZeroBits >= RegSize-1)
00736         isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
00737       else if (NumSignBits > RegSize-8)
00738         isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
00739       else if (NumZeroBits >= RegSize-8)
00740         isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
00741       else if (NumSignBits > RegSize-16)
00742         isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
00743       else if (NumZeroBits >= RegSize-16)
00744         isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
00745       else if (NumSignBits > RegSize-32)
00746         isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
00747       else if (NumZeroBits >= RegSize-32)
00748         isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
00749       else
00750         continue;
00751 
00752       // Add an assertion node.
00753       assert(FromVT != MVT::Other);
00754       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
00755                              RegisterVT, P, DAG.getValueType(FromVT));
00756     }
00757 
00758     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
00759                                      NumRegs, RegisterVT, ValueVT, V);
00760     Part += NumRegs;
00761     Parts.clear();
00762   }
00763 
00764   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
00765 }
00766 
00767 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00768 /// specified value into the registers specified by this object.  This uses
00769 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00770 /// If the Flag pointer is NULL, no flag is used.
00771 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
00772                                  SDValue &Chain, SDValue *Flag, const Value *V,
00773                                  ISD::NodeType PreferredExtendType) const {
00774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00775   ISD::NodeType ExtendKind = PreferredExtendType;
00776 
00777   // Get the list of the values's legal parts.
00778   unsigned NumRegs = Regs.size();
00779   SmallVector<SDValue, 8> Parts(NumRegs);
00780   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00781     EVT ValueVT = ValueVTs[Value];
00782     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00783     MVT RegisterVT = RegVTs[Value];
00784 
00785     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
00786       ExtendKind = ISD::ZERO_EXTEND;
00787 
00788     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
00789                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
00790     Part += NumParts;
00791   }
00792 
00793   // Copy the parts into the registers.
00794   SmallVector<SDValue, 8> Chains(NumRegs);
00795   for (unsigned i = 0; i != NumRegs; ++i) {
00796     SDValue Part;
00797     if (!Flag) {
00798       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
00799     } else {
00800       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
00801       *Flag = Part.getValue(1);
00802     }
00803 
00804     Chains[i] = Part.getValue(0);
00805   }
00806 
00807   if (NumRegs == 1 || Flag)
00808     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
00809     // flagged to it. That is the CopyToReg nodes and the user are considered
00810     // a single scheduling unit. If we create a TokenFactor and return it as
00811     // chain, then the TokenFactor is both a predecessor (operand) of the
00812     // user as well as a successor (the TF operands are flagged to the user).
00813     // c1, f1 = CopyToReg
00814     // c2, f2 = CopyToReg
00815     // c3     = TokenFactor c1, c2
00816     // ...
00817     //        = op c3, ..., f2
00818     Chain = Chains[NumRegs-1];
00819   else
00820     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
00821 }
00822 
00823 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00824 /// operand list.  This adds the code marker and includes the number of
00825 /// values added into it.
00826 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
00827                                         unsigned MatchingIdx,
00828                                         SelectionDAG &DAG,
00829                                         std::vector<SDValue> &Ops) const {
00830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00831 
00832   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
00833   if (HasMatching)
00834     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
00835   else if (!Regs.empty() &&
00836            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
00837     // Put the register class of the virtual registers in the flag word.  That
00838     // way, later passes can recompute register class constraints for inline
00839     // assembly as well as normal instructions.
00840     // Don't do this for tied operands that can use the regclass information
00841     // from the def.
00842     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
00843     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
00844     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
00845   }
00846 
00847   SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
00848   Ops.push_back(Res);
00849 
00850   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
00851   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
00852     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
00853     MVT RegisterVT = RegVTs[Value];
00854     for (unsigned i = 0; i != NumRegs; ++i) {
00855       assert(Reg < Regs.size() && "Mismatch in # registers expected");
00856       unsigned TheReg = Regs[Reg++];
00857       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
00858 
00859       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
00860         // If we clobbered the stack pointer, MFI should know about it.
00861         assert(DAG.getMachineFunction().getFrameInfo()->
00862             hasInlineAsmWithSPAdjust());
00863       }
00864     }
00865   }
00866 }
00867 
00868 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
00869                                const TargetLibraryInfo *li) {
00870   AA = &aa;
00871   GFI = gfi;
00872   LibInfo = li;
00873   DL = DAG.getTarget().getDataLayout();
00874   Context = DAG.getContext();
00875   LPadToCallSiteMap.clear();
00876 }
00877 
00878 /// clear - Clear out the current SelectionDAG and the associated
00879 /// state and prepare this SelectionDAGBuilder object to be used
00880 /// for a new block. This doesn't clear out information about
00881 /// additional blocks that are needed to complete switch lowering
00882 /// or PHI node updating; that information is cleared out as it is
00883 /// consumed.
00884 void SelectionDAGBuilder::clear() {
00885   NodeMap.clear();
00886   UnusedArgNodeMap.clear();
00887   PendingLoads.clear();
00888   PendingExports.clear();
00889   CurInst = nullptr;
00890   HasTailCall = false;
00891   SDNodeOrder = LowestSDNodeOrder;
00892   StatepointLowering.clear();
00893 }
00894 
00895 /// clearDanglingDebugInfo - Clear the dangling debug information
00896 /// map. This function is separated from the clear so that debug
00897 /// information that is dangling in a basic block can be properly
00898 /// resolved in a different basic block. This allows the
00899 /// SelectionDAG to resolve dangling debug information attached
00900 /// to PHI nodes.
00901 void SelectionDAGBuilder::clearDanglingDebugInfo() {
00902   DanglingDebugInfoMap.clear();
00903 }
00904 
00905 /// getRoot - Return the current virtual root of the Selection DAG,
00906 /// flushing any PendingLoad items. This must be done before emitting
00907 /// a store or any other node that may need to be ordered after any
00908 /// prior load instructions.
00909 ///
00910 SDValue SelectionDAGBuilder::getRoot() {
00911   if (PendingLoads.empty())
00912     return DAG.getRoot();
00913 
00914   if (PendingLoads.size() == 1) {
00915     SDValue Root = PendingLoads[0];
00916     DAG.setRoot(Root);
00917     PendingLoads.clear();
00918     return Root;
00919   }
00920 
00921   // Otherwise, we have to make a token factor node.
00922   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00923                              PendingLoads);
00924   PendingLoads.clear();
00925   DAG.setRoot(Root);
00926   return Root;
00927 }
00928 
00929 /// getControlRoot - Similar to getRoot, but instead of flushing all the
00930 /// PendingLoad items, flush all the PendingExports items. It is necessary
00931 /// to do this before emitting a terminator instruction.
00932 ///
00933 SDValue SelectionDAGBuilder::getControlRoot() {
00934   SDValue Root = DAG.getRoot();
00935 
00936   if (PendingExports.empty())
00937     return Root;
00938 
00939   // Turn all of the CopyToReg chains into one factored node.
00940   if (Root.getOpcode() != ISD::EntryToken) {
00941     unsigned i = 0, e = PendingExports.size();
00942     for (; i != e; ++i) {
00943       assert(PendingExports[i].getNode()->getNumOperands() > 1);
00944       if (PendingExports[i].getNode()->getOperand(0) == Root)
00945         break;  // Don't add the root if we already indirectly depend on it.
00946     }
00947 
00948     if (i == e)
00949       PendingExports.push_back(Root);
00950   }
00951 
00952   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00953                      PendingExports);
00954   PendingExports.clear();
00955   DAG.setRoot(Root);
00956   return Root;
00957 }
00958 
00959 void SelectionDAGBuilder::visit(const Instruction &I) {
00960   // Set up outgoing PHI node register values before emitting the terminator.
00961   if (isa<TerminatorInst>(&I))
00962     HandlePHINodesInSuccessorBlocks(I.getParent());
00963 
00964   ++SDNodeOrder;
00965 
00966   CurInst = &I;
00967 
00968   visit(I.getOpcode(), I);
00969 
00970   if (!isa<TerminatorInst>(&I) && !HasTailCall)
00971     CopyToExportRegsIfNeeded(&I);
00972 
00973   CurInst = nullptr;
00974 }
00975 
00976 void SelectionDAGBuilder::visitPHI(const PHINode &) {
00977   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
00978 }
00979 
00980 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
00981   // Note: this doesn't use InstVisitor, because it has to work with
00982   // ConstantExpr's in addition to instructions.
00983   switch (Opcode) {
00984   default: llvm_unreachable("Unknown instruction type encountered!");
00985     // Build the switch statement using the Instruction.def file.
00986 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00987     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
00988 #include "llvm/IR/Instruction.def"
00989   }
00990 }
00991 
00992 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
00993 // generate the debug data structures now that we've seen its definition.
00994 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
00995                                                    SDValue Val) {
00996   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
00997   if (DDI.getDI()) {
00998     const DbgValueInst *DI = DDI.getDI();
00999     DebugLoc dl = DDI.getdl();
01000     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
01001     MDLocalVariable *Variable = DI->getVariable();
01002     MDExpression *Expr = DI->getExpression();
01003     assert(Variable->isValidLocationForIntrinsic(dl) &&
01004            "Expected inlined-at fields to agree");
01005     uint64_t Offset = DI->getOffset();
01006     // A dbg.value for an alloca is always indirect.
01007     bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
01008     SDDbgValue *SDV;
01009     if (Val.getNode()) {
01010       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
01011                                     Val)) {
01012         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
01013                               IsIndirect, Offset, dl, DbgSDNodeOrder);
01014         DAG.AddDbgValue(SDV, Val.getNode(), false);
01015       }
01016     } else
01017       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01018     DanglingDebugInfoMap[V] = DanglingDebugInfo();
01019   }
01020 }
01021 
01022 /// getCopyFromRegs - If there was virtual register allocated for the value V
01023 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
01024 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
01025   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
01026   SDValue res;
01027 
01028   if (It != FuncInfo.ValueMap.end()) {
01029     unsigned InReg = It->second;
01030     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
01031                      Ty);
01032     SDValue Chain = DAG.getEntryNode();
01033     res = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
01034     resolveDanglingDebugInfo(V, res);
01035   }
01036 
01037   return res;
01038 }
01039 
01040 /// getValue - Return an SDValue for the given Value.
01041 SDValue SelectionDAGBuilder::getValue(const Value *V) {
01042   // If we already have an SDValue for this value, use it. It's important
01043   // to do this first, so that we don't create a CopyFromReg if we already
01044   // have a regular SDValue.
01045   SDValue &N = NodeMap[V];
01046   if (N.getNode()) return N;
01047 
01048   // If there's a virtual register allocated and initialized for this
01049   // value, use it.
01050   SDValue copyFromReg = getCopyFromRegs(V, V->getType());
01051   if (copyFromReg.getNode()) {
01052     return copyFromReg;
01053   }
01054 
01055   // Otherwise create a new SDValue and remember it.
01056   SDValue Val = getValueImpl(V);
01057   NodeMap[V] = Val;
01058   resolveDanglingDebugInfo(V, Val);
01059   return Val;
01060 }
01061 
01062 /// getNonRegisterValue - Return an SDValue for the given Value, but
01063 /// don't look in FuncInfo.ValueMap for a virtual register.
01064 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
01065   // If we already have an SDValue for this value, use it.
01066   SDValue &N = NodeMap[V];
01067   if (N.getNode()) return N;
01068 
01069   // Otherwise create a new SDValue and remember it.
01070   SDValue Val = getValueImpl(V);
01071   NodeMap[V] = Val;
01072   resolveDanglingDebugInfo(V, Val);
01073   return Val;
01074 }
01075 
01076 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
01077 /// Create an SDValue for the given value.
01078 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
01079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01080 
01081   if (const Constant *C = dyn_cast<Constant>(V)) {
01082     EVT VT = TLI.getValueType(V->getType(), true);
01083 
01084     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
01085       return DAG.getConstant(*CI, VT);
01086 
01087     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
01088       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
01089 
01090     if (isa<ConstantPointerNull>(C)) {
01091       unsigned AS = V->getType()->getPointerAddressSpace();
01092       return DAG.getConstant(0, TLI.getPointerTy(AS));
01093     }
01094 
01095     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
01096       return DAG.getConstantFP(*CFP, VT);
01097 
01098     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
01099       return DAG.getUNDEF(VT);
01100 
01101     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01102       visit(CE->getOpcode(), *CE);
01103       SDValue N1 = NodeMap[V];
01104       assert(N1.getNode() && "visit didn't populate the NodeMap!");
01105       return N1;
01106     }
01107 
01108     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
01109       SmallVector<SDValue, 4> Constants;
01110       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
01111            OI != OE; ++OI) {
01112         SDNode *Val = getValue(*OI).getNode();
01113         // If the operand is an empty aggregate, there are no values.
01114         if (!Val) continue;
01115         // Add each leaf value from the operand to the Constants list
01116         // to form a flattened list of all the values.
01117         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01118           Constants.push_back(SDValue(Val, i));
01119       }
01120 
01121       return DAG.getMergeValues(Constants, getCurSDLoc());
01122     }
01123 
01124     if (const ConstantDataSequential *CDS =
01125           dyn_cast<ConstantDataSequential>(C)) {
01126       SmallVector<SDValue, 4> Ops;
01127       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01128         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
01129         // Add each leaf value from the operand to the Constants list
01130         // to form a flattened list of all the values.
01131         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01132           Ops.push_back(SDValue(Val, i));
01133       }
01134 
01135       if (isa<ArrayType>(CDS->getType()))
01136         return DAG.getMergeValues(Ops, getCurSDLoc());
01137       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
01138                                       VT, Ops);
01139     }
01140 
01141     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
01142       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
01143              "Unknown struct or array constant!");
01144 
01145       SmallVector<EVT, 4> ValueVTs;
01146       ComputeValueVTs(TLI, C->getType(), ValueVTs);
01147       unsigned NumElts = ValueVTs.size();
01148       if (NumElts == 0)
01149         return SDValue(); // empty struct
01150       SmallVector<SDValue, 4> Constants(NumElts);
01151       for (unsigned i = 0; i != NumElts; ++i) {
01152         EVT EltVT = ValueVTs[i];
01153         if (isa<UndefValue>(C))
01154           Constants[i] = DAG.getUNDEF(EltVT);
01155         else if (EltVT.isFloatingPoint())
01156           Constants[i] = DAG.getConstantFP(0, EltVT);
01157         else
01158           Constants[i] = DAG.getConstant(0, EltVT);
01159       }
01160 
01161       return DAG.getMergeValues(Constants, getCurSDLoc());
01162     }
01163 
01164     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
01165       return DAG.getBlockAddress(BA, VT);
01166 
01167     VectorType *VecTy = cast<VectorType>(V->getType());
01168     unsigned NumElements = VecTy->getNumElements();
01169 
01170     // Now that we know the number and type of the elements, get that number of
01171     // elements into the Ops array based on what kind of constant it is.
01172     SmallVector<SDValue, 16> Ops;
01173     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
01174       for (unsigned i = 0; i != NumElements; ++i)
01175         Ops.push_back(getValue(CV->getOperand(i)));
01176     } else {
01177       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
01178       EVT EltVT = TLI.getValueType(VecTy->getElementType());
01179 
01180       SDValue Op;
01181       if (EltVT.isFloatingPoint())
01182         Op = DAG.getConstantFP(0, EltVT);
01183       else
01184         Op = DAG.getConstant(0, EltVT);
01185       Ops.assign(NumElements, Op);
01186     }
01187 
01188     // Create a BUILD_VECTOR node.
01189     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
01190   }
01191 
01192   // If this is a static alloca, generate it as the frameindex instead of
01193   // computation.
01194   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
01195     DenseMap<const AllocaInst*, int>::iterator SI =
01196       FuncInfo.StaticAllocaMap.find(AI);
01197     if (SI != FuncInfo.StaticAllocaMap.end())
01198       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
01199   }
01200 
01201   // If this is an instruction which fast-isel has deferred, select it now.
01202   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
01203     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
01204     RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
01205     SDValue Chain = DAG.getEntryNode();
01206     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
01207   }
01208 
01209   llvm_unreachable("Can't get register for value!");
01210 }
01211 
01212 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
01213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01214   SDValue Chain = getControlRoot();
01215   SmallVector<ISD::OutputArg, 8> Outs;
01216   SmallVector<SDValue, 8> OutVals;
01217 
01218   if (!FuncInfo.CanLowerReturn) {
01219     unsigned DemoteReg = FuncInfo.DemoteRegister;
01220     const Function *F = I.getParent()->getParent();
01221 
01222     // Emit a store of the return value through the virtual register.
01223     // Leave Outs empty so that LowerReturn won't try to load return
01224     // registers the usual way.
01225     SmallVector<EVT, 1> PtrValueVTs;
01226     ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
01227                     PtrValueVTs);
01228 
01229     SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
01230     SDValue RetOp = getValue(I.getOperand(0));
01231 
01232     SmallVector<EVT, 4> ValueVTs;
01233     SmallVector<uint64_t, 4> Offsets;
01234     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
01235     unsigned NumValues = ValueVTs.size();
01236 
01237     SmallVector<SDValue, 4> Chains(NumValues);
01238     for (unsigned i = 0; i != NumValues; ++i) {
01239       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
01240                                 RetPtr.getValueType(), RetPtr,
01241                                 DAG.getIntPtrConstant(Offsets[i]));
01242       Chains[i] =
01243         DAG.getStore(Chain, getCurSDLoc(),
01244                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
01245                      // FIXME: better loc info would be nice.
01246                      Add, MachinePointerInfo(), false, false, 0);
01247     }
01248 
01249     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
01250                         MVT::Other, Chains);
01251   } else if (I.getNumOperands() != 0) {
01252     SmallVector<EVT, 4> ValueVTs;
01253     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
01254     unsigned NumValues = ValueVTs.size();
01255     if (NumValues) {
01256       SDValue RetOp = getValue(I.getOperand(0));
01257 
01258       const Function *F = I.getParent()->getParent();
01259 
01260       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
01261       if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01262                                           Attribute::SExt))
01263         ExtendKind = ISD::SIGN_EXTEND;
01264       else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01265                                                Attribute::ZExt))
01266         ExtendKind = ISD::ZERO_EXTEND;
01267 
01268       LLVMContext &Context = F->getContext();
01269       bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01270                                                       Attribute::InReg);
01271 
01272       for (unsigned j = 0; j != NumValues; ++j) {
01273         EVT VT = ValueVTs[j];
01274 
01275         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
01276           VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
01277 
01278         unsigned NumParts = TLI.getNumRegisters(Context, VT);
01279         MVT PartVT = TLI.getRegisterType(Context, VT);
01280         SmallVector<SDValue, 4> Parts(NumParts);
01281         getCopyToParts(DAG, getCurSDLoc(),
01282                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
01283                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
01284 
01285         // 'inreg' on function refers to return value
01286         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
01287         if (RetInReg)
01288           Flags.setInReg();
01289 
01290         // Propagate extension type if any
01291         if (ExtendKind == ISD::SIGN_EXTEND)
01292           Flags.setSExt();
01293         else if (ExtendKind == ISD::ZERO_EXTEND)
01294           Flags.setZExt();
01295 
01296         for (unsigned i = 0; i < NumParts; ++i) {
01297           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
01298                                         VT, /*isfixed=*/true, 0, 0));
01299           OutVals.push_back(Parts[i]);
01300         }
01301       }
01302     }
01303   }
01304 
01305   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
01306   CallingConv::ID CallConv =
01307     DAG.getMachineFunction().getFunction()->getCallingConv();
01308   Chain = DAG.getTargetLoweringInfo().LowerReturn(
01309       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
01310 
01311   // Verify that the target's LowerReturn behaved as expected.
01312   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
01313          "LowerReturn didn't return a valid chain!");
01314 
01315   // Update the DAG with the new chain value resulting from return lowering.
01316   DAG.setRoot(Chain);
01317 }
01318 
01319 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
01320 /// created for it, emit nodes to copy the value into the virtual
01321 /// registers.
01322 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
01323   // Skip empty types
01324   if (V->getType()->isEmptyTy())
01325     return;
01326 
01327   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
01328   if (VMI != FuncInfo.ValueMap.end()) {
01329     assert(!V->use_empty() && "Unused value assigned virtual registers!");
01330     CopyValueToVirtualRegister(V, VMI->second);
01331   }
01332 }
01333 
01334 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
01335 /// the current basic block, add it to ValueMap now so that we'll get a
01336 /// CopyTo/FromReg.
01337 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
01338   // No need to export constants.
01339   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
01340 
01341   // Already exported?
01342   if (FuncInfo.isExportedInst(V)) return;
01343 
01344   unsigned Reg = FuncInfo.InitializeRegForValue(V);
01345   CopyValueToVirtualRegister(V, Reg);
01346 }
01347 
01348 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
01349                                                      const BasicBlock *FromBB) {
01350   // The operands of the setcc have to be in this block.  We don't know
01351   // how to export them from some other block.
01352   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
01353     // Can export from current BB.
01354     if (VI->getParent() == FromBB)
01355       return true;
01356 
01357     // Is already exported, noop.
01358     return FuncInfo.isExportedInst(V);
01359   }
01360 
01361   // If this is an argument, we can export it if the BB is the entry block or
01362   // if it is already exported.
01363   if (isa<Argument>(V)) {
01364     if (FromBB == &FromBB->getParent()->getEntryBlock())
01365       return true;
01366 
01367     // Otherwise, can only export this if it is already exported.
01368     return FuncInfo.isExportedInst(V);
01369   }
01370 
01371   // Otherwise, constants can always be exported.
01372   return true;
01373 }
01374 
01375 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
01376 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
01377                                             const MachineBasicBlock *Dst) const {
01378   BranchProbabilityInfo *BPI = FuncInfo.BPI;
01379   if (!BPI)
01380     return 0;
01381   const BasicBlock *SrcBB = Src->getBasicBlock();
01382   const BasicBlock *DstBB = Dst->getBasicBlock();
01383   return BPI->getEdgeWeight(SrcBB, DstBB);
01384 }
01385 
01386 void SelectionDAGBuilder::
01387 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
01388                        uint32_t Weight /* = 0 */) {
01389   if (!Weight)
01390     Weight = getEdgeWeight(Src, Dst);
01391   Src->addSuccessor(Dst, Weight);
01392 }
01393 
01394 
01395 static bool InBlock(const Value *V, const BasicBlock *BB) {
01396   if (const Instruction *I = dyn_cast<Instruction>(V))
01397     return I->getParent() == BB;
01398   return true;
01399 }
01400 
01401 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
01402 /// This function emits a branch and is used at the leaves of an OR or an
01403 /// AND operator tree.
01404 ///
01405 void
01406 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
01407                                                   MachineBasicBlock *TBB,
01408                                                   MachineBasicBlock *FBB,
01409                                                   MachineBasicBlock *CurBB,
01410                                                   MachineBasicBlock *SwitchBB,
01411                                                   uint32_t TWeight,
01412                                                   uint32_t FWeight) {
01413   const BasicBlock *BB = CurBB->getBasicBlock();
01414 
01415   // If the leaf of the tree is a comparison, merge the condition into
01416   // the caseblock.
01417   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
01418     // The operands of the cmp have to be in this block.  We don't know
01419     // how to export them from some other block.  If this is the first block
01420     // of the sequence, no exporting is needed.
01421     if (CurBB == SwitchBB ||
01422         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
01423          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
01424       ISD::CondCode Condition;
01425       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
01426         Condition = getICmpCondCode(IC->getPredicate());
01427       } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
01428         Condition = getFCmpCondCode(FC->getPredicate());
01429         if (TM.Options.NoNaNsFPMath)
01430           Condition = getFCmpCodeWithoutNaN(Condition);
01431       } else {
01432         (void)Condition; // silence warning.
01433         llvm_unreachable("Unknown compare instruction");
01434       }
01435 
01436       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
01437                    TBB, FBB, CurBB, TWeight, FWeight);
01438       SwitchCases.push_back(CB);
01439       return;
01440     }
01441   }
01442 
01443   // Create a CaseBlock record representing this branch.
01444   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
01445                nullptr, TBB, FBB, CurBB, TWeight, FWeight);
01446   SwitchCases.push_back(CB);
01447 }
01448 
01449 /// Scale down both weights to fit into uint32_t.
01450 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
01451   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
01452   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
01453   NewTrue = NewTrue / Scale;
01454   NewFalse = NewFalse / Scale;
01455 }
01456 
01457 /// FindMergedConditions - If Cond is an expression like
01458 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
01459                                                MachineBasicBlock *TBB,
01460                                                MachineBasicBlock *FBB,
01461                                                MachineBasicBlock *CurBB,
01462                                                MachineBasicBlock *SwitchBB,
01463                                                unsigned Opc, uint32_t TWeight,
01464                                                uint32_t FWeight) {
01465   // If this node is not part of the or/and tree, emit it as a branch.
01466   const Instruction *BOp = dyn_cast<Instruction>(Cond);
01467   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
01468       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
01469       BOp->getParent() != CurBB->getBasicBlock() ||
01470       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
01471       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
01472     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
01473                                  TWeight, FWeight);
01474     return;
01475   }
01476 
01477   //  Create TmpBB after CurBB.
01478   MachineFunction::iterator BBI = CurBB;
01479   MachineFunction &MF = DAG.getMachineFunction();
01480   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
01481   CurBB->getParent()->insert(++BBI, TmpBB);
01482 
01483   if (Opc == Instruction::Or) {
01484     // Codegen X | Y as:
01485     // BB1:
01486     //   jmp_if_X TBB
01487     //   jmp TmpBB
01488     // TmpBB:
01489     //   jmp_if_Y TBB
01490     //   jmp FBB
01491     //
01492 
01493     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01494     // The requirement is that
01495     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
01496     //     = TrueProb for orignal BB.
01497     // Assuming the orignal weights are A and B, one choice is to set BB1's
01498     // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
01499     // assumes that
01500     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
01501     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
01502     // TmpBB, but the math is more complicated.
01503 
01504     uint64_t NewTrueWeight = TWeight;
01505     uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
01506     ScaleWeights(NewTrueWeight, NewFalseWeight);
01507     // Emit the LHS condition.
01508     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
01509                          NewTrueWeight, NewFalseWeight);
01510 
01511     NewTrueWeight = TWeight;
01512     NewFalseWeight = 2 * (uint64_t)FWeight;
01513     ScaleWeights(NewTrueWeight, NewFalseWeight);
01514     // Emit the RHS condition into TmpBB.
01515     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
01516                          NewTrueWeight, NewFalseWeight);
01517   } else {
01518     assert(Opc == Instruction::And && "Unknown merge op!");
01519     // Codegen X & Y as:
01520     // BB1:
01521     //   jmp_if_X TmpBB
01522     //   jmp FBB
01523     // TmpBB:
01524     //   jmp_if_Y TBB
01525     //   jmp FBB
01526     //
01527     //  This requires creation of TmpBB after CurBB.
01528 
01529     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01530     // The requirement is that
01531     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
01532     //     = FalseProb for orignal BB.
01533     // Assuming the orignal weights are A and B, one choice is to set BB1's
01534     // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
01535     // assumes that
01536     //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
01537 
01538     uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
01539     uint64_t NewFalseWeight = FWeight;
01540     ScaleWeights(NewTrueWeight, NewFalseWeight);
01541     // Emit the LHS condition.
01542     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
01543                          NewTrueWeight, NewFalseWeight);
01544 
01545     NewTrueWeight = 2 * (uint64_t)TWeight;
01546     NewFalseWeight = FWeight;
01547     ScaleWeights(NewTrueWeight, NewFalseWeight);
01548     // Emit the RHS condition into TmpBB.
01549     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
01550                          NewTrueWeight, NewFalseWeight);
01551   }
01552 }
01553 
01554 /// If the set of cases should be emitted as a series of branches, return true.
01555 /// If we should emit this as a bunch of and/or'd together conditions, return
01556 /// false.
01557 bool
01558 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
01559   if (Cases.size() != 2) return true;
01560 
01561   // If this is two comparisons of the same values or'd or and'd together, they
01562   // will get folded into a single comparison, so don't emit two blocks.
01563   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
01564        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
01565       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
01566        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
01567     return false;
01568   }
01569 
01570   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
01571   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
01572   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
01573       Cases[0].CC == Cases[1].CC &&
01574       isa<Constant>(Cases[0].CmpRHS) &&
01575       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
01576     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
01577       return false;
01578     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
01579       return false;
01580   }
01581 
01582   return true;
01583 }
01584 
01585 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
01586   MachineBasicBlock *BrMBB = FuncInfo.MBB;
01587 
01588   // Update machine-CFG edges.
01589   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
01590 
01591   if (I.isUnconditional()) {
01592     // Update machine-CFG edges.
01593     BrMBB->addSuccessor(Succ0MBB);
01594 
01595     // If this is not a fall-through branch or optimizations are switched off,
01596     // emit the branch.
01597     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
01598       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
01599                               MVT::Other, getControlRoot(),
01600                               DAG.getBasicBlock(Succ0MBB)));
01601 
01602     return;
01603   }
01604 
01605   // If this condition is one of the special cases we handle, do special stuff
01606   // now.
01607   const Value *CondVal = I.getCondition();
01608   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
01609 
01610   // If this is a series of conditions that are or'd or and'd together, emit
01611   // this as a sequence of branches instead of setcc's with and/or operations.
01612   // As long as jumps are not expensive, this should improve performance.
01613   // For example, instead of something like:
01614   //     cmp A, B
01615   //     C = seteq
01616   //     cmp D, E
01617   //     F = setle
01618   //     or C, F
01619   //     jnz foo
01620   // Emit:
01621   //     cmp A, B
01622   //     je foo
01623   //     cmp D, E
01624   //     jle foo
01625   //
01626   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
01627     if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
01628         BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
01629                              BOp->getOpcode() == Instruction::Or)) {
01630       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
01631                            BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
01632                            getEdgeWeight(BrMBB, Succ1MBB));
01633       // If the compares in later blocks need to use values not currently
01634       // exported from this block, export them now.  This block should always
01635       // be the first entry.
01636       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
01637 
01638       // Allow some cases to be rejected.
01639       if (ShouldEmitAsBranches(SwitchCases)) {
01640         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
01641           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
01642           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
01643         }
01644 
01645         // Emit the branch for this block.
01646         visitSwitchCase(SwitchCases[0], BrMBB);
01647         SwitchCases.erase(SwitchCases.begin());
01648         return;
01649       }
01650 
01651       // Okay, we decided not to do this, remove any inserted MBB's and clear
01652       // SwitchCases.
01653       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
01654         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
01655 
01656       SwitchCases.clear();
01657     }
01658   }
01659 
01660   // Create a CaseBlock record representing this branch.
01661   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
01662                nullptr, Succ0MBB, Succ1MBB, BrMBB);
01663 
01664   // Use visitSwitchCase to actually insert the fast branch sequence for this
01665   // cond branch.
01666   visitSwitchCase(CB, BrMBB);
01667 }
01668 
01669 /// visitSwitchCase - Emits the necessary code to represent a single node in
01670 /// the binary search tree resulting from lowering a switch instruction.
01671 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
01672                                           MachineBasicBlock *SwitchBB) {
01673   SDValue Cond;
01674   SDValue CondLHS = getValue(CB.CmpLHS);
01675   SDLoc dl = getCurSDLoc();
01676 
01677   // Build the setcc now.
01678   if (!CB.CmpMHS) {
01679     // Fold "(X == true)" to X and "(X == false)" to !X to
01680     // handle common cases produced by branch lowering.
01681     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
01682         CB.CC == ISD::SETEQ)
01683       Cond = CondLHS;
01684     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
01685              CB.CC == ISD::SETEQ) {
01686       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
01687       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
01688     } else
01689       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
01690   } else {
01691     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
01692 
01693     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
01694     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
01695 
01696     SDValue CmpOp = getValue(CB.CmpMHS);
01697     EVT VT = CmpOp.getValueType();
01698 
01699     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
01700       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
01701                           ISD::SETLE);
01702     } else {
01703       SDValue SUB = DAG.getNode(ISD::SUB, dl,
01704                                 VT, CmpOp, DAG.getConstant(Low, VT));
01705       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
01706                           DAG.getConstant(High-Low, VT), ISD::SETULE);
01707     }
01708   }
01709 
01710   // Update successor info
01711   addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
01712   // TrueBB and FalseBB are always different unless the incoming IR is
01713   // degenerate. This only happens when running llc on weird IR.
01714   if (CB.TrueBB != CB.FalseBB)
01715     addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
01716 
01717   // If the lhs block is the next block, invert the condition so that we can
01718   // fall through to the lhs instead of the rhs block.
01719   if (CB.TrueBB == NextBlock(SwitchBB)) {
01720     std::swap(CB.TrueBB, CB.FalseBB);
01721     SDValue True = DAG.getConstant(1, Cond.getValueType());
01722     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
01723   }
01724 
01725   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
01726                                MVT::Other, getControlRoot(), Cond,
01727                                DAG.getBasicBlock(CB.TrueBB));
01728 
01729   // Insert the false branch. Do this even if it's a fall through branch,
01730   // this makes it easier to do DAG optimizations which require inverting
01731   // the branch condition.
01732   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
01733                        DAG.getBasicBlock(CB.FalseBB));
01734 
01735   DAG.setRoot(BrCond);
01736 }
01737 
01738 /// visitJumpTable - Emit JumpTable node in the current MBB
01739 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
01740   // Emit the code for the jump table
01741   assert(JT.Reg != -1U && "Should lower JT Header first!");
01742   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
01743   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
01744                                      JT.Reg, PTy);
01745   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
01746   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
01747                                     MVT::Other, Index.getValue(1),
01748                                     Table, Index);
01749   DAG.setRoot(BrJumpTable);
01750 }
01751 
01752 /// visitJumpTableHeader - This function emits necessary code to produce index
01753 /// in the JumpTable from switch case.
01754 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
01755                                                JumpTableHeader &JTH,
01756                                                MachineBasicBlock *SwitchBB) {
01757   // Subtract the lowest switch case value from the value being switched on and
01758   // conditional branch to default mbb if the result is greater than the
01759   // difference between smallest and largest cases.
01760   SDValue SwitchOp = getValue(JTH.SValue);
01761   EVT VT = SwitchOp.getValueType();
01762   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
01763                             DAG.getConstant(JTH.First, VT));
01764 
01765   // The SDNode we just created, which holds the value being switched on minus
01766   // the smallest case value, needs to be copied to a virtual register so it
01767   // can be used as an index into the jump table in a subsequent basic block.
01768   // This value may be smaller or larger than the target's pointer type, and
01769   // therefore require extension or truncating.
01770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01771   SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
01772 
01773   unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
01774   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
01775                                     JumpTableReg, SwitchOp);
01776   JT.Reg = JumpTableReg;
01777 
01778   // Emit the range check for the jump table, and branch to the default block
01779   // for the switch statement if the value being switched on exceeds the largest
01780   // case in the switch.
01781   SDValue CMP =
01782       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
01783                                                          Sub.getValueType()),
01784                    Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
01785 
01786   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01787                                MVT::Other, CopyTo, CMP,
01788                                DAG.getBasicBlock(JT.Default));
01789 
01790   // Avoid emitting unnecessary branches to the next block.
01791   if (JT.MBB != NextBlock(SwitchBB))
01792     BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
01793                          DAG.getBasicBlock(JT.MBB));
01794 
01795   DAG.setRoot(BrCond);
01796 }
01797 
01798 /// Codegen a new tail for a stack protector check ParentMBB which has had its
01799 /// tail spliced into a stack protector check success bb.
01800 ///
01801 /// For a high level explanation of how this fits into the stack protector
01802 /// generation see the comment on the declaration of class
01803 /// StackProtectorDescriptor.
01804 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
01805                                                   MachineBasicBlock *ParentBB) {
01806 
01807   // First create the loads to the guard/stack slot for the comparison.
01808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01809   EVT PtrTy = TLI.getPointerTy();
01810 
01811   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
01812   int FI = MFI->getStackProtectorIndex();
01813 
01814   const Value *IRGuard = SPD.getGuard();
01815   SDValue GuardPtr = getValue(IRGuard);
01816   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
01817 
01818   unsigned Align =
01819     TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
01820 
01821   SDValue Guard;
01822 
01823   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
01824   // guard value from the virtual register holding the value. Otherwise, emit a
01825   // volatile load to retrieve the stack guard value.
01826   unsigned GuardReg = SPD.getGuardReg();
01827 
01828   if (GuardReg && TLI.useLoadStackGuardNode())
01829     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
01830                                PtrTy);
01831   else
01832     Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
01833                         GuardPtr, MachinePointerInfo(IRGuard, 0),
01834                         true, false, false, Align);
01835 
01836   SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
01837                                   StackSlotPtr,
01838                                   MachinePointerInfo::getFixedStack(FI),
01839                                   true, false, false, Align);
01840 
01841   // Perform the comparison via a subtract/getsetcc.
01842   EVT VT = Guard.getValueType();
01843   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
01844 
01845   SDValue Cmp =
01846       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
01847                                                          Sub.getValueType()),
01848                    Sub, DAG.getConstant(0, VT), ISD::SETNE);
01849 
01850   // If the sub is not 0, then we know the guard/stackslot do not equal, so
01851   // branch to failure MBB.
01852   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01853                                MVT::Other, StackSlot.getOperand(0),
01854                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
01855   // Otherwise branch to success MBB.
01856   SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
01857                            MVT::Other, BrCond,
01858                            DAG.getBasicBlock(SPD.getSuccessMBB()));
01859 
01860   DAG.setRoot(Br);
01861 }
01862 
01863 /// Codegen the failure basic block for a stack protector check.
01864 ///
01865 /// A failure stack protector machine basic block consists simply of a call to
01866 /// __stack_chk_fail().
01867 ///
01868 /// For a high level explanation of how this fits into the stack protector
01869 /// generation see the comment on the declaration of class
01870 /// StackProtectorDescriptor.
01871 void
01872 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
01873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01874   SDValue Chain =
01875       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
01876                       nullptr, 0, false, getCurSDLoc(), false, false).second;
01877   DAG.setRoot(Chain);
01878 }
01879 
01880 /// visitBitTestHeader - This function emits necessary code to produce value
01881 /// suitable for "bit tests"
01882 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
01883                                              MachineBasicBlock *SwitchBB) {
01884   // Subtract the minimum value
01885   SDValue SwitchOp = getValue(B.SValue);
01886   EVT VT = SwitchOp.getValueType();
01887   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
01888                             DAG.getConstant(B.First, VT));
01889 
01890   // Check range
01891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01892   SDValue RangeCmp =
01893       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
01894                                                          Sub.getValueType()),
01895                    Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
01896 
01897   // Determine the type of the test operands.
01898   bool UsePtrType = false;
01899   if (!TLI.isTypeLegal(VT))
01900     UsePtrType = true;
01901   else {
01902     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
01903       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
01904         // Switch table case range are encoded into series of masks.
01905         // Just use pointer type, it's guaranteed to fit.
01906         UsePtrType = true;
01907         break;
01908       }
01909   }
01910   if (UsePtrType) {
01911     VT = TLI.getPointerTy();
01912     Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
01913   }
01914 
01915   B.RegVT = VT.getSimpleVT();
01916   B.Reg = FuncInfo.CreateReg(B.RegVT);
01917   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
01918                                     B.Reg, Sub);
01919 
01920   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
01921 
01922   addSuccessorWithWeight(SwitchBB, B.Default);
01923   addSuccessorWithWeight(SwitchBB, MBB);
01924 
01925   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01926                                 MVT::Other, CopyTo, RangeCmp,
01927                                 DAG.getBasicBlock(B.Default));
01928 
01929   // Avoid emitting unnecessary branches to the next block.
01930   if (MBB != NextBlock(SwitchBB))
01931     BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
01932                           DAG.getBasicBlock(MBB));
01933 
01934   DAG.setRoot(BrRange);
01935 }
01936 
01937 /// visitBitTestCase - this function produces one "bit test"
01938 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
01939                                            MachineBasicBlock* NextMBB,
01940                                            uint32_t BranchWeightToNext,
01941                                            unsigned Reg,
01942                                            BitTestCase &B,
01943                                            MachineBasicBlock *SwitchBB) {
01944   MVT VT = BB.RegVT;
01945   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
01946                                        Reg, VT);
01947   SDValue Cmp;
01948   unsigned PopCount = countPopulation(B.Mask);
01949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01950   if (PopCount == 1) {
01951     // Testing for a single bit; just compare the shift count with what it
01952     // would need to be to shift a 1 bit in that position.
01953     Cmp = DAG.getSetCC(
01954         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
01955         DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
01956   } else if (PopCount == BB.Range) {
01957     // There is only one zero bit in the range, test for it directly.
01958     Cmp = DAG.getSetCC(
01959         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
01960         DAG.getConstant(countTrailingOnes(B.Mask), VT), ISD::SETNE);
01961   } else {
01962     // Make desired shift
01963     SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
01964                                     DAG.getConstant(1, VT), ShiftOp);
01965 
01966     // Emit bit tests and jumps
01967     SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
01968                                 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
01969     Cmp = DAG.getSetCC(getCurSDLoc(),
01970                        TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
01971                        DAG.getConstant(0, VT), ISD::SETNE);
01972   }
01973 
01974   // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
01975   addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
01976   // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
01977   addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
01978 
01979   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01980                               MVT::Other, getControlRoot(),
01981                               Cmp, DAG.getBasicBlock(B.TargetBB));
01982 
01983   // Avoid emitting unnecessary branches to the next block.
01984   if (NextMBB != NextBlock(SwitchBB))
01985     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
01986                         DAG.getBasicBlock(NextMBB));
01987 
01988   DAG.setRoot(BrAnd);
01989 }
01990 
01991 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
01992   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
01993 
01994   // Retrieve successors.
01995   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
01996   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
01997 
01998   const Value *Callee(I.getCalledValue());
01999   const Function *Fn = dyn_cast<Function>(Callee);
02000   if (isa<InlineAsm>(Callee))
02001     visitInlineAsm(&I);
02002   else if (Fn && Fn->isIntrinsic()) {
02003     switch (Fn->getIntrinsicID()) {
02004     default:
02005       llvm_unreachable("Cannot invoke this intrinsic");
02006     case Intrinsic::donothing:
02007       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
02008       break;
02009     case Intrinsic::experimental_patchpoint_void:
02010     case Intrinsic::experimental_patchpoint_i64:
02011       visitPatchpoint(&I, LandingPad);
02012       break;
02013     case Intrinsic::experimental_gc_statepoint:
02014       LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
02015       break;
02016     }
02017   } else
02018     LowerCallTo(&I, getValue(Callee), false, LandingPad);
02019 
02020   // If the value of the invoke is used outside of its defining block, make it
02021   // available as a virtual register.
02022   // We already took care of the exported value for the statepoint instruction
02023   // during call to the LowerStatepoint.
02024   if (!isStatepoint(I)) {
02025     CopyToExportRegsIfNeeded(&I);
02026   }
02027 
02028   // Update successor info
02029   addSuccessorWithWeight(InvokeMBB, Return);
02030   addSuccessorWithWeight(InvokeMBB, LandingPad);
02031 
02032   // Drop into normal successor.
02033   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
02034                           MVT::Other, getControlRoot(),
02035                           DAG.getBasicBlock(Return)));
02036 }
02037 
02038 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
02039   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
02040 }
02041 
02042 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
02043   assert(FuncInfo.MBB->isLandingPad() &&
02044          "Call to landingpad not in landing pad!");
02045 
02046   MachineBasicBlock *MBB = FuncInfo.MBB;
02047   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
02048   AddLandingPadInfo(LP, MMI, MBB);
02049 
02050   // If there aren't registers to copy the values into (e.g., during SjLj
02051   // exceptions), then don't bother to create these DAG nodes.
02052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02053   if (TLI.getExceptionPointerRegister() == 0 &&
02054       TLI.getExceptionSelectorRegister() == 0)
02055     return;
02056 
02057   SmallVector<EVT, 2> ValueVTs;
02058   ComputeValueVTs(TLI, LP.getType(), ValueVTs);
02059   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
02060 
02061   // Get the two live-in registers as SDValues. The physregs have already been
02062   // copied into virtual registers.
02063   SDValue Ops[2];
02064   if (FuncInfo.ExceptionPointerVirtReg) {
02065     Ops[0] = DAG.getZExtOrTrunc(
02066         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
02067                            FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
02068         getCurSDLoc(), ValueVTs[0]);
02069   } else {
02070     Ops[0] = DAG.getConstant(0, TLI.getPointerTy());
02071   }
02072   Ops[1] = DAG.getZExtOrTrunc(
02073       DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
02074                          FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
02075       getCurSDLoc(), ValueVTs[1]);
02076 
02077   // Merge into one.
02078   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02079                             DAG.getVTList(ValueVTs), Ops);
02080   setValue(&LP, Res);
02081 }
02082 
02083 unsigned
02084 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
02085                                              MachineBasicBlock *LPadBB) {
02086   SDValue Chain = getControlRoot();
02087 
02088   // Get the typeid that we will dispatch on later.
02089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02090   const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
02091   unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
02092   unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
02093   SDValue Sel = DAG.getConstant(TypeID, TLI.getPointerTy());
02094   Chain = DAG.getCopyToReg(Chain, getCurSDLoc(), VReg, Sel);
02095 
02096   // Branch to the main landing pad block.
02097   MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
02098   ClauseMBB->addSuccessor(LPadBB);
02099   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, Chain,
02100                           DAG.getBasicBlock(LPadBB)));
02101   return VReg;
02102 }
02103 
02104 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
02105 /// small case ranges).
02106 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
02107                                                  CaseRecVector& WorkList,
02108                                                  const Value* SV,
02109                                                  MachineBasicBlock *Default,
02110                                                  MachineBasicBlock *SwitchBB) {
02111   // Size is the number of Cases represented by this range.
02112   size_t Size = CR.Range.second - CR.Range.first;
02113   if (Size > 3)
02114     return false;
02115 
02116   // Get the MachineFunction which holds the current MBB.  This is used when
02117   // inserting any additional MBBs necessary to represent the switch.
02118   MachineFunction *CurMF = FuncInfo.MF;
02119 
02120   // Figure out which block is immediately after the current one.
02121   MachineBasicBlock *NextMBB = nullptr;
02122   MachineFunction::iterator BBI = CR.CaseBB;
02123   if (++BBI != FuncInfo.MF->end())
02124     NextMBB = BBI;
02125 
02126   BranchProbabilityInfo *BPI = FuncInfo.BPI;
02127   // If any two of the cases has the same destination, and if one value
02128   // is the same as the other, but has one bit unset that the other has set,
02129   // use bit manipulation to do two compares at once.  For example:
02130   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
02131   // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
02132   // TODO: Handle cases where CR.CaseBB != SwitchBB.
02133   if (Size == 2 && CR.CaseBB == SwitchBB) {
02134     Case &Small = *CR.Range.first;
02135     Case &Big = *(CR.Range.second-1);
02136 
02137     if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
02138       const APInt& SmallValue = Small.Low->getValue();
02139       const APInt& BigValue = Big.Low->getValue();
02140 
02141       // Check that there is only one bit different.
02142       if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
02143           (SmallValue | BigValue) == BigValue) {
02144         // Isolate the common bit.
02145         APInt CommonBit = BigValue & ~SmallValue;
02146         assert((SmallValue | CommonBit) == BigValue &&
02147                CommonBit.countPopulation() == 1 && "Not a common bit?");
02148 
02149         SDValue CondLHS = getValue(SV);
02150         EVT VT = CondLHS.getValueType();
02151         SDLoc DL = getCurSDLoc();
02152 
02153         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
02154                                  DAG.getConstant(CommonBit, VT));
02155         SDValue Cond = DAG.getSetCC(DL, MVT::i1,
02156                                     Or, DAG.getConstant(BigValue, VT),
02157                                     ISD::SETEQ);
02158 
02159         // Update successor info.
02160         // Both Small and Big will jump to Small.BB, so we sum up the weights.
02161         addSuccessorWithWeight(SwitchBB, Small.BB,
02162                                Small.ExtraWeight + Big.ExtraWeight);
02163         addSuccessorWithWeight(SwitchBB, Default,
02164           // The default destination is the first successor in IR.
02165           BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
02166 
02167         // Insert the true branch.
02168         SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
02169                                      getControlRoot(), Cond,
02170                                      DAG.getBasicBlock(Small.BB));
02171 
02172         // Insert the false branch.
02173         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
02174                              DAG.getBasicBlock(Default));
02175 
02176         DAG.setRoot(BrCond);
02177         return true;
02178       }
02179     }
02180   }
02181 
02182   // Order cases by weight so the most likely case will be checked first.
02183   uint32_t UnhandledWeights = 0;
02184   if (BPI) {
02185     for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
02186       uint32_t IWeight = I->ExtraWeight;
02187       UnhandledWeights += IWeight;
02188       for (CaseItr J = CR.Range.first; J < I; ++J) {
02189         uint32_t JWeight = J->ExtraWeight;
02190         if (IWeight > JWeight)
02191           std::swap(*I, *J);
02192       }
02193     }
02194   }
02195   // Rearrange the case blocks so that the last one falls through if possible.
02196   Case &BackCase = *(CR.Range.second-1);
02197   if (Size > 1 && NextMBB && Default != NextMBB && BackCase.BB != NextMBB) {
02198     // The last case block won't fall through into 'NextMBB' if we emit the
02199     // branches in this order.  See if rearranging a case value would help.
02200     // We start at the bottom as it's the case with the least weight.
02201     for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
02202       if (I->BB == NextMBB) {
02203         std::swap(*I, BackCase);
02204         break;
02205       }
02206   }
02207 
02208   // Create a CaseBlock record representing a conditional branch to
02209   // the Case's target mbb if the value being switched on SV is equal
02210   // to C.
02211   MachineBasicBlock *CurBlock = CR.CaseBB;
02212   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
02213     MachineBasicBlock *FallThrough;
02214     if (I != E-1) {
02215       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
02216       CurMF->insert(BBI, FallThrough);
02217 
02218       // Put SV in a virtual register to make it available from the new blocks.
02219       ExportFromCurrentBlock(SV);
02220     } else {
02221       // If the last case doesn't match, go to the default block.
02222       FallThrough = Default;
02223     }
02224 
02225     const Value *RHS, *LHS, *MHS;
02226     ISD::CondCode CC;
02227     if (I->High == I->Low) {
02228       // This is just small small case range :) containing exactly 1 case
02229       CC = ISD::SETEQ;
02230       LHS = SV; RHS = I->High; MHS = nullptr;
02231     } else {
02232       CC = ISD::SETLE;
02233       LHS = I->Low; MHS = SV; RHS = I->High;
02234     }
02235 
02236     // The false weight should be sum of all un-handled cases.
02237     UnhandledWeights -= I->ExtraWeight;
02238     CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
02239                  /* me */ CurBlock,
02240                  /* trueweight */ I->ExtraWeight,
02241                  /* falseweight */ UnhandledWeights);
02242 
02243     // If emitting the first comparison, just call visitSwitchCase to emit the
02244     // code into the current block.  Otherwise, push the CaseBlock onto the
02245     // vector to be later processed by SDISel, and insert the node's MBB
02246     // before the next MBB.
02247     if (CurBlock == SwitchBB)
02248       visitSwitchCase(CB, SwitchBB);
02249     else
02250       SwitchCases.push_back(CB);
02251 
02252     CurBlock = FallThrough;
02253   }
02254 
02255   return true;
02256 }
02257 
02258 static inline bool areJTsAllowed(const TargetLowering &TLI) {
02259   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
02260          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
02261 }
02262 
02263 static APInt ComputeRange(const APInt &First, const APInt &Last) {
02264   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
02265   APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
02266   return (LastExt - FirstExt + 1ULL);
02267 }
02268 
02269 /// handleJTSwitchCase - Emit jumptable for current switch case range
02270 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
02271                                              CaseRecVector &WorkList,
02272                                              const Value *SV,
02273                                              MachineBasicBlock *Default,
02274                                              MachineBasicBlock *SwitchBB) {
02275   Case& FrontCase = *CR.Range.first;
02276   Case& BackCase  = *(CR.Range.second-1);
02277 
02278   const APInt &First = FrontCase.Low->getValue();
02279   const APInt &Last  = BackCase.High->getValue();
02280 
02281   APInt TSize(First.getBitWidth(), 0);
02282   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
02283     TSize += I->size();
02284 
02285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02286   if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
02287     return false;
02288 
02289   APInt Range = ComputeRange(First, Last);
02290   // The density is TSize / Range. Require at least 40%.
02291   // It should not be possible for IntTSize to saturate for sane code, but make
02292   // sure we handle Range saturation correctly.
02293   uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
02294   uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
02295   if (IntTSize * 10 < IntRange * 4)
02296     return false;
02297 
02298   DEBUG(dbgs() << "Lowering jump table\n"
02299                << "First entry: " << First << ". Last entry: " << Last << '\n'
02300                << "Range: " << Range << ". Size: " << TSize << ".\n\n");
02301 
02302   // Get the MachineFunction which holds the current MBB.  This is used when
02303   // inserting any additional MBBs necessary to represent the switch.
02304   MachineFunction *CurMF = FuncInfo.MF;
02305 
02306   // Figure out which block is immediately after the current one.
02307   MachineFunction::iterator BBI = CR.CaseBB;
02308   ++BBI;
02309 
02310   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02311 
02312   // Create a new basic block to hold the code for loading the address
02313   // of the jump table, and jumping to it.  Update successor information;
02314   // we will either branch to the default case for the switch, or the jump
02315   // table.
02316   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02317   CurMF->insert(BBI, JumpTableBB);
02318 
02319   addSuccessorWithWeight(CR.CaseBB, Default);
02320   addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
02321 
02322   // Build a vector of destination BBs, corresponding to each target
02323   // of the jump table. If the value of the jump table slot corresponds to
02324   // a case statement, push the case's BB onto the vector, otherwise, push
02325   // the default BB.
02326   std::vector<MachineBasicBlock*> DestBBs;
02327   APInt TEI = First;
02328   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
02329     const APInt &Low = I->Low->getValue();
02330     const APInt &High = I->High->getValue();
02331 
02332     if (Low.sle(TEI) && TEI.sle(High)) {
02333       DestBBs.push_back(I->BB);
02334       if (TEI==High)
02335         ++I;
02336     } else {
02337       DestBBs.push_back(Default);
02338     }
02339   }
02340 
02341   // Calculate weight for each unique destination in CR.
02342   DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
02343   if (FuncInfo.BPI) {
02344     for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
02345       DestWeights[I->BB] += I->ExtraWeight;
02346   }
02347 
02348   // Update successor info. Add one edge to each unique successor.
02349   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
02350   for (MachineBasicBlock *DestBB : DestBBs) {
02351     if (!SuccsHandled[DestBB->getNumber()]) {
02352       SuccsHandled[DestBB->getNumber()] = true;
02353       auto I = DestWeights.find(DestBB);
02354       addSuccessorWithWeight(JumpTableBB, DestBB,
02355                              I != DestWeights.end() ? I->second : 0);
02356     }
02357   }
02358 
02359   // Create a jump table index for this jump table.
02360   unsigned JTEncoding = TLI.getJumpTableEncoding();
02361   unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
02362                        ->createJumpTableIndex(DestBBs);
02363 
02364   // Set the jump table information so that we can codegen it as a second
02365   // MachineBasicBlock
02366   JumpTable JT(-1U, JTI, JumpTableBB, Default);
02367   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
02368   if (CR.CaseBB == SwitchBB)
02369     visitJumpTableHeader(JT, JTH, SwitchBB);
02370 
02371   JTCases.push_back(JumpTableBlock(JTH, JT));
02372   return true;
02373 }
02374 
02375 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
02376 /// 2 subtrees.
02377 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
02378                                                   CaseRecVector& WorkList,
02379                                                   const Value* SV,
02380                                                   MachineBasicBlock* SwitchBB) {
02381   Case& FrontCase = *CR.Range.first;
02382   Case& BackCase  = *(CR.Range.second-1);
02383 
02384   // Size is the number of Cases represented by this range.
02385   unsigned Size = CR.Range.second - CR.Range.first;
02386 
02387   const APInt &First = FrontCase.Low->getValue();
02388   const APInt &Last  = BackCase.High->getValue();
02389   double FMetric = 0;
02390   CaseItr Pivot = CR.Range.first + Size/2;
02391 
02392   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
02393   // (heuristically) allow us to emit JumpTable's later.
02394   APInt TSize(First.getBitWidth(), 0);
02395   for (CaseItr I = CR.Range.first, E = CR.Range.second;
02396        I!=E; ++I)
02397     TSize += I->size();
02398 
02399   APInt LSize = FrontCase.size();
02400   APInt RSize = TSize-LSize;
02401   DEBUG(dbgs() << "Selecting best pivot: \n"
02402                << "First: " << First << ", Last: " << Last <<'\n'
02403                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
02404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02405   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
02406        J!=E; ++I, ++J) {
02407     const APInt &LEnd = I->High->getValue();
02408     const APInt &RBegin = J->Low->getValue();
02409     APInt Range = ComputeRange(LEnd, RBegin);
02410     assert((Range - 2ULL).isNonNegative() &&
02411            "Invalid case distance");
02412     // Use volatile double here to avoid excess precision issues on some hosts,
02413     // e.g. that use 80-bit X87 registers.
02414     // Only consider the density of sub-ranges that actually have sufficient
02415     // entries to be lowered as a jump table.
02416     volatile double LDensity =
02417         LSize.ult(TLI.getMinimumJumpTableEntries())
02418             ? 0.0
02419             : LSize.roundToDouble() / (LEnd - First + 1ULL).roundToDouble();
02420     volatile double RDensity =
02421         RSize.ult(TLI.getMinimumJumpTableEntries())
02422             ? 0.0
02423             : RSize.roundToDouble() / (Last - RBegin + 1ULL).roundToDouble();
02424     volatile double Metric = Range.logBase2() * (LDensity + RDensity);
02425     // Should always split in some non-trivial place
02426     DEBUG(dbgs() <<"=>Step\n"
02427                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
02428                  << "LDensity: " << LDensity
02429                  << ", RDensity: " << RDensity << '\n'
02430                  << "Metric: " << Metric << '\n');
02431     if (FMetric < Metric) {
02432       Pivot = J;
02433       FMetric = Metric;
02434       DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
02435     }
02436 
02437     LSize += J->size();
02438     RSize -= J->size();
02439   }
02440 
02441   if (FMetric == 0 || !areJTsAllowed(TLI))
02442     Pivot = CR.Range.first + Size/2;
02443   splitSwitchCase(CR, Pivot, WorkList, SV, SwitchBB);
02444   return true;
02445 }
02446 
02447 void SelectionDAGBuilder::splitSwitchCase(CaseRec &CR, CaseItr Pivot,
02448                                           CaseRecVector &WorkList,
02449                                           const Value *SV,
02450                                           MachineBasicBlock *SwitchBB) {
02451   // Get the MachineFunction which holds the current MBB.  This is used when
02452   // inserting any additional MBBs necessary to represent the switch.
02453   MachineFunction *CurMF = FuncInfo.MF;
02454 
02455   // Figure out which block is immediately after the current one.
02456   MachineFunction::iterator BBI = CR.CaseBB;
02457   ++BBI;
02458 
02459   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02460 
02461   CaseRange LHSR(CR.Range.first, Pivot);
02462   CaseRange RHSR(Pivot, CR.Range.second);
02463   const ConstantInt *C = Pivot->Low;
02464   MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
02465 
02466   // We know that we branch to the LHS if the Value being switched on is
02467   // less than the Pivot value, C.  We use this to optimize our binary
02468   // tree a bit, by recognizing that if SV is greater than or equal to the
02469   // LHS's Case Value, and that Case Value is exactly one less than the
02470   // Pivot's Value, then we can branch directly to the LHS's Target,
02471   // rather than creating a leaf node for it.
02472   if ((LHSR.second - LHSR.first) == 1 && LHSR.first->High == CR.GE &&
02473       C->getValue() == (CR.GE->getValue() + 1LL)) {
02474     TrueBB = LHSR.first->BB;
02475   } else {
02476     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02477     CurMF->insert(BBI, TrueBB);
02478     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
02479 
02480     // Put SV in a virtual register to make it available from the new blocks.
02481     ExportFromCurrentBlock(SV);
02482   }
02483 
02484   // Similar to the optimization above, if the Value being switched on is
02485   // known to be less than the Constant CR.LT, and the current Case Value
02486   // is CR.LT - 1, then we can branch directly to the target block for
02487   // the current Case Value, rather than emitting a RHS leaf node for it.
02488   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
02489       RHSR.first->Low->getValue() == (CR.LT->getValue() - 1LL)) {
02490     FalseBB = RHSR.first->BB;
02491   } else {
02492     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02493     CurMF->insert(BBI, FalseBB);
02494     WorkList.push_back(CaseRec(FalseBB, CR.LT, C, RHSR));
02495 
02496     // Put SV in a virtual register to make it available from the new blocks.
02497     ExportFromCurrentBlock(SV);
02498   }
02499 
02500   // Create a CaseBlock record representing a conditional branch to
02501   // the LHS node if the value being switched on SV is less than C.
02502   // Otherwise, branch to LHS.
02503   CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
02504 
02505   if (CR.CaseBB == SwitchBB)
02506     visitSwitchCase(CB, SwitchBB);
02507   else
02508     SwitchCases.push_back(CB);
02509 }
02510 
02511 /// handleBitTestsSwitchCase - if current case range has few destination and
02512 /// range span less, than machine word bitwidth, encode case range into series
02513 /// of masks and emit bit tests with these masks.
02514 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
02515                                                    CaseRecVector& WorkList,
02516                                                    const Value* SV,
02517                                                    MachineBasicBlock* Default,
02518                                                    MachineBasicBlock* SwitchBB) {
02519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02520   EVT PTy = TLI.getPointerTy();
02521   unsigned IntPtrBits = PTy.getSizeInBits();
02522 
02523   Case& FrontCase = *CR.Range.first;
02524   Case& BackCase  = *(CR.Range.second-1);
02525 
02526   // Get the MachineFunction which holds the current MBB.  This is used when
02527   // inserting any additional MBBs necessary to represent the switch.
02528   MachineFunction *CurMF = FuncInfo.MF;
02529 
02530   // If target does not have legal shift left, do not emit bit tests at all.
02531   if (!TLI.isOperationLegal(ISD::SHL, PTy))
02532     return false;
02533 
02534   size_t numCmps = 0;
02535   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
02536     // Single case counts one, case range - two.
02537     numCmps += (I->Low == I->High ? 1 : 2);
02538   }
02539 
02540   // Count unique destinations
02541   SmallSet<MachineBasicBlock*, 4> Dests;
02542   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
02543     Dests.insert(I->BB);
02544     if (Dests.size() > 3)
02545       // Don't bother the code below, if there are too much unique destinations
02546       return false;
02547   }
02548   DEBUG(dbgs() << "Total number of unique destinations: "
02549         << Dests.size() << '\n'
02550         << "Total number of comparisons: " << numCmps << '\n');
02551 
02552   // Compute span of values.
02553   const APInt& minValue = FrontCase.Low->getValue();
02554   const APInt& maxValue = BackCase.High->getValue();
02555   APInt cmpRange = maxValue - minValue;
02556 
02557   DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
02558                << "Low bound: " << minValue << '\n'
02559                << "High bound: " << maxValue << '\n');
02560 
02561   if (cmpRange.uge(IntPtrBits) ||
02562       (!(Dests.size() == 1 && numCmps >= 3) &&
02563        !(Dests.size() == 2 && numCmps >= 5) &&
02564        !(Dests.size() >= 3 && numCmps >= 6)))
02565     return false;
02566 
02567   DEBUG(dbgs() << "Emitting bit tests\n");
02568   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
02569 
02570   // Optimize the case where all the case values fit in a
02571   // word without having to subtract minValue. In this case,
02572   // we can optimize away the subtraction.
02573   if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
02574     cmpRange = maxValue;
02575   } else {
02576     lowBound = minValue;
02577   }
02578 
02579   CaseBitsVector CasesBits;
02580   unsigned i, count = 0;
02581 
02582   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
02583     MachineBasicBlock* Dest = I->BB;
02584     for (i = 0; i < count; ++i)
02585       if (Dest == CasesBits[i].BB)
02586         break;
02587 
02588     if (i == count) {
02589       assert((count < 3) && "Too much destinations to test!");
02590       CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
02591       count++;
02592     }
02593 
02594     const APInt& lowValue = I->Low->getValue();
02595     const APInt& highValue = I->High->getValue();
02596 
02597     uint64_t lo = (lowValue - lowBound).getZExtValue();
02598     uint64_t hi = (highValue - lowBound).getZExtValue();
02599     CasesBits[i].ExtraWeight += I->ExtraWeight;
02600 
02601     for (uint64_t j = lo; j <= hi; j++) {
02602       CasesBits[i].Mask |=  1ULL << j;
02603       CasesBits[i].Bits++;
02604     }
02605 
02606   }
02607   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
02608 
02609   BitTestInfo BTC;
02610 
02611   // Figure out which block is immediately after the current one.
02612   MachineFunction::iterator BBI = CR.CaseBB;
02613   ++BBI;
02614 
02615   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02616 
02617   DEBUG(dbgs() << "Cases:\n");
02618   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
02619     DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
02620                  << ", Bits: " << CasesBits[i].Bits
02621                  << ", BB: " << CasesBits[i].BB << '\n');
02622 
02623     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02624     CurMF->insert(BBI, CaseBB);
02625     BTC.push_back(BitTestCase(CasesBits[i].Mask,
02626                               CaseBB,
02627                               CasesBits[i].BB, CasesBits[i].ExtraWeight));
02628 
02629     // Put SV in a virtual register to make it available from the new blocks.
02630     ExportFromCurrentBlock(SV);
02631   }
02632 
02633   BitTestBlock BTB(lowBound, cmpRange, SV,
02634                    -1U, MVT::Other, (CR.CaseBB == SwitchBB),
02635                    CR.CaseBB, Default, std::move(BTC));
02636 
02637   if (CR.CaseBB == SwitchBB)
02638     visitBitTestHeader(BTB, SwitchBB);
02639 
02640   BitTestCases.push_back(std::move(BTB));
02641 
02642   return true;
02643 }
02644 
02645 void SelectionDAGBuilder::Clusterify(CaseVector &Cases, const SwitchInst *SI) {
02646   BranchProbabilityInfo *BPI = FuncInfo.BPI;
02647 
02648   // Extract cases from the switch and sort them.
02649   typedef std::pair<const ConstantInt*, unsigned> CasePair;
02650   std::vector<CasePair> Sorted;
02651   Sorted.reserve(SI->getNumCases());
02652   for (auto I : SI->cases())
02653     Sorted.push_back(std::make_pair(I.getCaseValue(), I.getSuccessorIndex()));
02654   std::sort(Sorted.begin(), Sorted.end(), [](CasePair a, CasePair b) {
02655     return a.first->getValue().slt(b.first->getValue());
02656   });
02657 
02658   // Merge adjacent cases with the same destination, build Cases vector.
02659   assert(Cases.empty() && "Cases should be empty before Clusterify;");
02660   Cases.reserve(SI->getNumCases());
02661   MachineBasicBlock *PreviousSucc = nullptr;
02662   for (CasePair &CP : Sorted) {
02663     const ConstantInt *CaseVal = CP.first;
02664     unsigned SuccIndex = CP.second;
02665     MachineBasicBlock *Succ = FuncInfo.MBBMap[SI->getSuccessor(SuccIndex)];
02666     uint32_t Weight = BPI ? BPI->getEdgeWeight(SI->getParent(), SuccIndex) : 0;
02667 
02668     if (PreviousSucc == Succ &&
02669         (CaseVal->getValue() - Cases.back().High->getValue()) == 1) {
02670       // If this case has the same successor and is a neighbour, merge it into
02671       // the previous cluster.
02672       Cases.back().High = CaseVal;
02673       Cases.back().ExtraWeight += Weight;
02674     } else {
02675       Cases.push_back(Case(CaseVal, CaseVal, Succ, Weight));
02676     }
02677 
02678     PreviousSucc = Succ;
02679   }
02680 
02681   DEBUG({
02682       size_t numCmps = 0;
02683       for (auto &I : Cases)
02684         // A range counts double, since it requires two compares.
02685         numCmps += I.Low != I.High ? 2 : 1;
02686 
02687       dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
02688              << ". Total compares: " << numCmps << '\n';
02689     });
02690 }
02691 
02692 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
02693                                            MachineBasicBlock *Last) {
02694   // Update JTCases.
02695   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
02696     if (JTCases[i].first.HeaderBB == First)
02697       JTCases[i].first.HeaderBB = Last;
02698 
02699   // Update BitTestCases.
02700   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
02701     if (BitTestCases[i].Parent == First)
02702       BitTestCases[i].Parent = Last;
02703 }
02704 
02705 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
02706   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
02707 
02708   // Create a vector of Cases, sorted so that we can efficiently create a binary
02709   // search tree from them.
02710   CaseVector Cases;
02711   Clusterify(Cases, &SI);
02712 
02713   // Get the default destination MBB.
02714   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
02715 
02716   if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
02717       !Cases.empty()) {
02718     // Replace an unreachable default destination with the most popular case
02719     // destination.
02720     DenseMap<const BasicBlock *, unsigned> Popularity;
02721     unsigned MaxPop = 0;
02722     const BasicBlock *MaxBB = nullptr;
02723     for (auto I : SI.cases()) {
02724       const BasicBlock *BB = I.getCaseSuccessor();
02725       if (++Popularity[BB] > MaxPop) {
02726         MaxPop = Popularity[BB];
02727         MaxBB = BB;
02728       }
02729     }
02730 
02731     // Set new default.
02732     assert(MaxPop > 0);
02733     assert(MaxBB);
02734     Default = FuncInfo.MBBMap[MaxBB];
02735 
02736     // Remove cases that were pointing to the destination that is now the default.
02737     Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
02738                                [&](const Case &C) { return C.BB == Default; }),
02739                 Cases.end());
02740   }
02741 
02742   // If there is only the default destination, go there directly.
02743   if (Cases.empty()) {
02744     // Update machine-CFG edges.
02745     SwitchMBB->addSuccessor(Default);
02746 
02747     // If this is not a fall-through branch, emit the branch.
02748     if (Default != NextBlock(SwitchMBB)) {
02749       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
02750                               getControlRoot(), DAG.getBasicBlock(Default)));
02751     }
02752     return;
02753   }
02754 
02755   // Get the Value to be switched on.
02756   const Value *SV = SI.getCondition();
02757 
02758   // Push the initial CaseRec onto the worklist
02759   CaseRecVector WorkList;
02760   WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
02761                              CaseRange(Cases.begin(),Cases.end())));
02762 
02763   while (!WorkList.empty()) {
02764     // Grab a record representing a case range to process off the worklist
02765     CaseRec CR = WorkList.back();
02766     WorkList.pop_back();
02767 
02768     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
02769       continue;
02770 
02771     // If the range has few cases (two or less) emit a series of specific
02772     // tests.
02773     if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
02774       continue;
02775 
02776     // If the switch has more than N blocks, and is at least 40% dense, and the
02777     // target supports indirect branches, then emit a jump table rather than
02778     // lowering the switch to a binary tree of conditional branches.
02779     // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
02780     if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
02781       continue;
02782 
02783     // Emit binary tree. We need to pick a pivot, and push left and right ranges
02784     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
02785     handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
02786   }
02787 }
02788 
02789 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
02790   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
02791 
02792   // Update machine-CFG edges with unique successors.
02793   SmallSet<BasicBlock*, 32> Done;
02794   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
02795     BasicBlock *BB = I.getSuccessor(i);
02796     bool Inserted = Done.insert(BB).second;
02797     if (!Inserted)
02798         continue;
02799 
02800     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
02801     addSuccessorWithWeight(IndirectBrMBB, Succ);
02802   }
02803 
02804   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
02805                           MVT::Other, getControlRoot(),
02806                           getValue(I.getAddress())));
02807 }
02808 
02809 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
02810   if (DAG.getTarget().Options.TrapUnreachable)
02811     DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
02812 }
02813 
02814 void SelectionDAGBuilder::visitFSub(const User &I) {
02815   // -0.0 - X --> fneg
02816   Type *Ty = I.getType();
02817   if (isa<Constant>(I.getOperand(0)) &&
02818       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
02819     SDValue Op2 = getValue(I.getOperand(1));
02820     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
02821                              Op2.getValueType(), Op2));
02822     return;
02823   }
02824 
02825   visitBinary(I, ISD::FSUB);
02826 }
02827 
02828 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
02829   SDValue Op1 = getValue(I.getOperand(0));
02830   SDValue Op2 = getValue(I.getOperand(1));
02831 
02832   bool nuw = false;
02833   bool nsw = false;
02834   bool exact = false;
02835   if (const OverflowingBinaryOperator *OFBinOp =
02836           dyn_cast<const OverflowingBinaryOperator>(&I)) {
02837     nuw = OFBinOp->hasNoUnsignedWrap();
02838     nsw = OFBinOp->hasNoSignedWrap();
02839   }
02840   if (const PossiblyExactOperator *ExactOp =
02841           dyn_cast<const PossiblyExactOperator>(&I))
02842     exact = ExactOp->isExact();
02843 
02844   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
02845                                      Op1, Op2, nuw, nsw, exact);
02846   setValue(&I, BinNodeValue);
02847 }
02848 
02849 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
02850   SDValue Op1 = getValue(I.getOperand(0));
02851   SDValue Op2 = getValue(I.getOperand(1));
02852 
02853   EVT ShiftTy =
02854       DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
02855 
02856   // Coerce the shift amount to the right type if we can.
02857   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
02858     unsigned ShiftSize = ShiftTy.getSizeInBits();
02859     unsigned Op2Size = Op2.getValueType().getSizeInBits();
02860     SDLoc DL = getCurSDLoc();
02861 
02862     // If the operand is smaller than the shift count type, promote it.
02863     if (ShiftSize > Op2Size)
02864       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
02865 
02866     // If the operand is larger than the shift count type but the shift
02867     // count type has enough bits to represent any shift value, truncate
02868     // it now. This is a common case and it exposes the truncate to
02869     // optimization early.
02870     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
02871       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
02872     // Otherwise we'll need to temporarily settle for some other convenient
02873     // type.  Type legalization will make adjustments once the shiftee is split.
02874     else
02875       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
02876   }
02877 
02878   bool nuw = false;
02879   bool nsw = false;
02880   bool exact = false;
02881 
02882   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
02883 
02884     if (const OverflowingBinaryOperator *OFBinOp =
02885             dyn_cast<const OverflowingBinaryOperator>(&I)) {
02886       nuw = OFBinOp->hasNoUnsignedWrap();
02887       nsw = OFBinOp->hasNoSignedWrap();
02888     }
02889     if (const PossiblyExactOperator *ExactOp =
02890             dyn_cast<const PossiblyExactOperator>(&I))
02891       exact = ExactOp->isExact();
02892   }
02893 
02894   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
02895                             nuw, nsw, exact);
02896   setValue(&I, Res);
02897 }
02898 
02899 void SelectionDAGBuilder::visitSDiv(const User &I) {
02900   SDValue Op1 = getValue(I.getOperand(0));
02901   SDValue Op2 = getValue(I.getOperand(1));
02902 
02903   // Turn exact SDivs into multiplications.
02904   // FIXME: This should be in DAGCombiner, but it doesn't have access to the
02905   // exact bit.
02906   if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
02907       !isa<ConstantSDNode>(Op1) &&
02908       isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
02909     setValue(&I, DAG.getTargetLoweringInfo()
02910                      .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
02911   else
02912     setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
02913                              Op1, Op2));
02914 }
02915 
02916 void SelectionDAGBuilder::visitICmp(const User &I) {
02917   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
02918   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
02919     predicate = IC->getPredicate();
02920   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
02921     predicate = ICmpInst::Predicate(IC->getPredicate());
02922   SDValue Op1 = getValue(I.getOperand(0));
02923   SDValue Op2 = getValue(I.getOperand(1));
02924   ISD::CondCode Opcode = getICmpCondCode(predicate);
02925 
02926   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02927   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
02928 }
02929 
02930 void SelectionDAGBuilder::visitFCmp(const User &I) {
02931   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
02932   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
02933     predicate = FC->getPredicate();
02934   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
02935     predicate = FCmpInst::Predicate(FC->getPredicate());
02936   SDValue Op1 = getValue(I.getOperand(0));
02937   SDValue Op2 = getValue(I.getOperand(1));
02938   ISD::CondCode Condition = getFCmpCondCode(predicate);
02939   if (TM.Options.NoNaNsFPMath)
02940     Condition = getFCmpCodeWithoutNaN(Condition);
02941   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02942   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
02943 }
02944 
02945 void SelectionDAGBuilder::visitSelect(const User &I) {
02946   SmallVector<EVT, 4> ValueVTs;
02947   ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
02948   unsigned NumValues = ValueVTs.size();
02949   if (NumValues == 0) return;
02950 
02951   SmallVector<SDValue, 4> Values(NumValues);
02952   SDValue Cond     = getValue(I.getOperand(0));
02953   SDValue TrueVal  = getValue(I.getOperand(1));
02954   SDValue FalseVal = getValue(I.getOperand(2));
02955   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
02956     ISD::VSELECT : ISD::SELECT;
02957 
02958   for (unsigned i = 0; i != NumValues; ++i)
02959     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
02960                             TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
02961                             Cond,
02962                             SDValue(TrueVal.getNode(),
02963                                     TrueVal.getResNo() + i),
02964                             SDValue(FalseVal.getNode(),
02965                                     FalseVal.getResNo() + i));
02966 
02967   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02968                            DAG.getVTList(ValueVTs), Values));
02969 }
02970 
02971 void SelectionDAGBuilder::visitTrunc(const User &I) {
02972   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
02973   SDValue N = getValue(I.getOperand(0));
02974   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02975   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
02976 }
02977 
02978 void SelectionDAGBuilder::visitZExt(const User &I) {
02979   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02980   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
02981   SDValue N = getValue(I.getOperand(0));
02982   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02983   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
02984 }
02985 
02986 void SelectionDAGBuilder::visitSExt(const User &I) {
02987   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02988   // SExt also can't be a cast to bool for same reason. So, nothing much to do
02989   SDValue N = getValue(I.getOperand(0));
02990   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02991   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
02992 }
02993 
02994 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
02995   // FPTrunc is never a no-op cast, no need to check
02996   SDValue N = getValue(I.getOperand(0));
02997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02998   EVT DestVT = TLI.getValueType(I.getType());
02999   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
03000                            DAG.getTargetConstant(0, TLI.getPointerTy())));
03001 }
03002 
03003 void SelectionDAGBuilder::visitFPExt(const User &I) {
03004   // FPExt is never a no-op cast, no need to check
03005   SDValue N = getValue(I.getOperand(0));
03006   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03007   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
03008 }
03009 
03010 void SelectionDAGBuilder::visitFPToUI(const User &I) {
03011   // FPToUI is never a no-op cast, no need to check
03012   SDValue N = getValue(I.getOperand(0));
03013   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03014   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
03015 }
03016 
03017 void SelectionDAGBuilder::visitFPToSI(const User &I) {
03018   // FPToSI is never a no-op cast, no need to check
03019   SDValue N = getValue(I.getOperand(0));
03020   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03021   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
03022 }
03023 
03024 void SelectionDAGBuilder::visitUIToFP(const User &I) {
03025   // UIToFP is never a no-op cast, no need to check
03026   SDValue N = getValue(I.getOperand(0));
03027   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03028   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
03029 }
03030 
03031 void SelectionDAGBuilder::visitSIToFP(const User &I) {
03032   // SIToFP is never a no-op cast, no need to check
03033   SDValue N = getValue(I.getOperand(0));
03034   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03035   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
03036 }
03037 
03038 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
03039   // What to do depends on the size of the integer and the size of the pointer.
03040   // We can either truncate, zero extend, or no-op, accordingly.
03041   SDValue N = getValue(I.getOperand(0));
03042   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03043   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
03044 }
03045 
03046 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
03047   // What to do depends on the size of the integer and the size of the pointer.
03048   // We can either truncate, zero extend, or no-op, accordingly.
03049   SDValue N = getValue(I.getOperand(0));
03050   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03051   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
03052 }
03053 
03054 void SelectionDAGBuilder::visitBitCast(const User &I) {
03055   SDValue N = getValue(I.getOperand(0));
03056   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
03057 
03058   // BitCast assures us that source and destination are the same size so this is
03059   // either a BITCAST or a no-op.
03060   if (DestVT != N.getValueType())
03061     setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
03062                              DestVT, N)); // convert types.
03063   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
03064   // might fold any kind of constant expression to an integer constant and that
03065   // is not what we are looking for. Only regcognize a bitcast of a genuine
03066   // constant integer as an opaque constant.
03067   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
03068     setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
03069                                  /*isOpaque*/true));
03070   else
03071     setValue(&I, N);            // noop cast.
03072 }
03073 
03074 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
03075   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03076   const Value *SV = I.getOperand(0);
03077   SDValue N = getValue(SV);
03078   EVT DestVT = TLI.getValueType(I.getType());
03079 
03080   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
03081   unsigned DestAS = I.getType()->getPointerAddressSpace();
03082 
03083   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
03084     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
03085 
03086   setValue(&I, N);
03087 }
03088 
03089 void SelectionDAGBuilder::visitInsertElement(const User &I) {
03090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03091   SDValue InVec = getValue(I.getOperand(0));
03092   SDValue InVal = getValue(I.getOperand(1));
03093   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
03094                                      getCurSDLoc(), TLI.getVectorIdxTy());
03095   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
03096                            TLI.getValueType(I.getType()), InVec, InVal, InIdx));
03097 }
03098 
03099 void SelectionDAGBuilder::visitExtractElement(const User &I) {
03100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03101   SDValue InVec = getValue(I.getOperand(0));
03102   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
03103                                      getCurSDLoc(), TLI.getVectorIdxTy());
03104   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
03105                            TLI.getValueType(I.getType()), InVec, InIdx));
03106 }
03107 
03108 // Utility for visitShuffleVector - Return true if every element in Mask,
03109 // beginning from position Pos and ending in Pos+Size, falls within the
03110 // specified sequential range [L, L+Pos). or is undef.
03111 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
03112                                 unsigned Pos, unsigned Size, int Low) {
03113   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
03114     if (Mask[i] >= 0 && Mask[i] != Low)
03115       return false;
03116   return true;
03117 }
03118 
03119 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
03120   SDValue Src1 = getValue(I.getOperand(0));
03121   SDValue Src2 = getValue(I.getOperand(1));
03122 
03123   SmallVector<int, 8> Mask;
03124   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
03125   unsigned MaskNumElts = Mask.size();
03126 
03127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03128   EVT VT = TLI.getValueType(I.getType());
03129   EVT SrcVT = Src1.getValueType();
03130   unsigned SrcNumElts = SrcVT.getVectorNumElements();
03131 
03132   if (SrcNumElts == MaskNumElts) {
03133     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03134                                       &Mask[0]));
03135     return;
03136   }
03137 
03138   // Normalize the shuffle vector since mask and vector length don't match.
03139   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
03140     // Mask is longer than the source vectors and is a multiple of the source
03141     // vectors.  We can use concatenate vector to make the mask and vectors
03142     // lengths match.
03143     if (SrcNumElts*2 == MaskNumElts) {
03144       // First check for Src1 in low and Src2 in high
03145       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
03146           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
03147         // The shuffle is concatenating two vectors together.
03148         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
03149                                  VT, Src1, Src2));
03150         return;
03151       }
03152       // Then check for Src2 in low and Src1 in high
03153       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
03154           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
03155         // The shuffle is concatenating two vectors together.
03156         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
03157                                  VT, Src2, Src1));
03158         return;
03159       }
03160     }
03161 
03162     // Pad both vectors with undefs to make them the same length as the mask.
03163     unsigned NumConcat = MaskNumElts / SrcNumElts;
03164     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
03165     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
03166     SDValue UndefVal = DAG.getUNDEF(SrcVT);
03167 
03168     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
03169     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
03170     MOps1[0] = Src1;
03171     MOps2[0] = Src2;
03172 
03173     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
03174                                                   getCurSDLoc(), VT, MOps1);
03175     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
03176                                                   getCurSDLoc(), VT, MOps2);
03177 
03178     // Readjust mask for new input vector length.
03179     SmallVector<int, 8> MappedOps;
03180     for (unsigned i = 0; i != MaskNumElts; ++i) {
03181       int Idx = Mask[i];
03182       if (Idx >= (int)SrcNumElts)
03183         Idx -= SrcNumElts - MaskNumElts;
03184       MappedOps.push_back(Idx);
03185     }
03186 
03187     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03188                                       &MappedOps[0]));
03189     return;
03190   }
03191 
03192   if (SrcNumElts > MaskNumElts) {
03193     // Analyze the access pattern of the vector to see if we can extract
03194     // two subvectors and do the shuffle. The analysis is done by calculating
03195     // the range of elements the mask access on both vectors.
03196     int MinRange[2] = { static_cast<int>(SrcNumElts),
03197                         static_cast<int>(SrcNumElts)};
03198     int MaxRange[2] = {-1, -1};
03199 
03200     for (unsigned i = 0; i != MaskNumElts; ++i) {
03201       int Idx = Mask[i];
03202       unsigned Input = 0;
03203       if (Idx < 0)
03204         continue;
03205 
03206       if (Idx >= (int)SrcNumElts) {
03207         Input = 1;
03208         Idx -= SrcNumElts;
03209       }
03210       if (Idx > MaxRange[Input])
03211         MaxRange[Input] = Idx;
03212       if (Idx < MinRange[Input])
03213         MinRange[Input] = Idx;
03214     }
03215 
03216     // Check if the access is smaller than the vector size and can we find
03217     // a reasonable extract index.
03218     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
03219                                    // Extract.
03220     int StartIdx[2];  // StartIdx to extract from
03221     for (unsigned Input = 0; Input < 2; ++Input) {
03222       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
03223         RangeUse[Input] = 0; // Unused
03224         StartIdx[Input] = 0;
03225         continue;
03226       }
03227 
03228       // Find a good start index that is a multiple of the mask length. Then
03229       // see if the rest of the elements are in range.
03230       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
03231       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
03232           StartIdx[Input] + MaskNumElts <= SrcNumElts)
03233         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
03234     }
03235 
03236     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
03237       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
03238       return;
03239     }
03240     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
03241       // Extract appropriate subvector and generate a vector shuffle
03242       for (unsigned Input = 0; Input < 2; ++Input) {
03243         SDValue &Src = Input == 0 ? Src1 : Src2;
03244         if (RangeUse[Input] == 0)
03245           Src = DAG.getUNDEF(VT);
03246         else
03247           Src = DAG.getNode(
03248               ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
03249               DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
03250       }
03251 
03252       // Calculate new mask.
03253       SmallVector<int, 8> MappedOps;
03254       for (unsigned i = 0; i != MaskNumElts; ++i) {
03255         int Idx = Mask[i];
03256         if (Idx >= 0) {
03257           if (Idx < (int)SrcNumElts)
03258             Idx -= StartIdx[0];
03259           else
03260             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
03261         }
03262         MappedOps.push_back(Idx);
03263       }
03264 
03265       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03266                                         &MappedOps[0]));
03267       return;
03268     }
03269   }
03270 
03271   // We can't use either concat vectors or extract subvectors so fall back to
03272   // replacing the shuffle with extract and build vector.
03273   // to insert and build vector.
03274   EVT EltVT = VT.getVectorElementType();
03275   EVT IdxVT = TLI.getVectorIdxTy();
03276   SmallVector<SDValue,8> Ops;
03277   for (unsigned i = 0; i != MaskNumElts; ++i) {
03278     int Idx = Mask[i];
03279     SDValue Res;
03280 
03281     if (Idx < 0) {
03282       Res = DAG.getUNDEF(EltVT);
03283     } else {
03284       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
03285       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
03286 
03287       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
03288                         EltVT, Src, DAG.getConstant(Idx, IdxVT));
03289     }
03290 
03291     Ops.push_back(Res);
03292   }
03293 
03294   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
03295 }
03296 
03297 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
03298   const Value *Op0 = I.getOperand(0);
03299   const Value *Op1 = I.getOperand(1);
03300   Type *AggTy = I.getType();
03301   Type *ValTy = Op1->getType();
03302   bool IntoUndef = isa<UndefValue>(Op0);
03303   bool FromUndef = isa<UndefValue>(Op1);
03304 
03305   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
03306 
03307   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03308   SmallVector<EVT, 4> AggValueVTs;
03309   ComputeValueVTs(TLI, AggTy, AggValueVTs);
03310   SmallVector<EVT, 4> ValValueVTs;
03311   ComputeValueVTs(TLI, ValTy, ValValueVTs);
03312 
03313   unsigned NumAggValues = AggValueVTs.size();
03314   unsigned NumValValues = ValValueVTs.size();
03315   SmallVector<SDValue, 4> Values(NumAggValues);
03316 
03317   // Ignore an insertvalue that produces an empty object
03318   if (!NumAggValues) {
03319     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
03320     return;
03321   }
03322 
03323   SDValue Agg = getValue(Op0);
03324   unsigned i = 0;
03325   // Copy the beginning value(s) from the original aggregate.
03326   for (; i != LinearIndex; ++i)
03327     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03328                 SDValue(Agg.getNode(), Agg.getResNo() + i);
03329   // Copy values from the inserted value(s).
03330   if (NumValValues) {
03331     SDValue Val = getValue(Op1);
03332     for (; i != LinearIndex + NumValValues; ++i)
03333       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03334                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
03335   }
03336   // Copy remaining value(s) from the original aggregate.
03337   for (; i != NumAggValues; ++i)
03338     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03339                 SDValue(Agg.getNode(), Agg.getResNo() + i);
03340 
03341   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03342                            DAG.getVTList(AggValueVTs), Values));
03343 }
03344 
03345 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
03346   const Value *Op0 = I.getOperand(0);
03347   Type *AggTy = Op0->getType();
03348   Type *ValTy = I.getType();
03349   bool OutOfUndef = isa<UndefValue>(Op0);
03350 
03351   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
03352 
03353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03354   SmallVector<EVT, 4> ValValueVTs;
03355   ComputeValueVTs(TLI, ValTy, ValValueVTs);
03356 
03357   unsigned NumValValues = ValValueVTs.size();
03358 
03359   // Ignore a extractvalue that produces an empty object
03360   if (!NumValValues) {
03361     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
03362     return;
03363   }
03364 
03365   SmallVector<SDValue, 4> Values(NumValValues);
03366 
03367   SDValue Agg = getValue(Op0);
03368   // Copy out the selected value(s).
03369   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
03370     Values[i - LinearIndex] =
03371       OutOfUndef ?
03372         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
03373         SDValue(Agg.getNode(), Agg.getResNo() + i);
03374 
03375   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03376                            DAG.getVTList(ValValueVTs), Values));
03377 }
03378 
03379 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
03380   Value *Op0 = I.getOperand(0);
03381   // Note that the pointer operand may be a vector of pointers. Take the scalar
03382   // element which holds a pointer.
03383   Type *Ty = Op0->getType()->getScalarType();
03384   unsigned AS = Ty->getPointerAddressSpace();
03385   SDValue N = getValue(Op0);
03386 
03387   for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
03388        OI != E; ++OI) {
03389     const Value *Idx = *OI;
03390     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
03391       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
03392       if (Field) {
03393         // N = N + Offset
03394         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
03395         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
03396                         DAG.getConstant(Offset, N.getValueType()));
03397       }
03398 
03399       Ty = StTy->getElementType(Field);
03400     } else {
03401       Ty = cast<SequentialType>(Ty)->getElementType();
03402       MVT PtrTy = DAG.getTargetLoweringInfo().getPointerTy(AS);
03403       unsigned PtrSize = PtrTy.getSizeInBits();
03404       APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
03405 
03406       // If this is a constant subscript, handle it quickly.
03407       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
03408         if (CI->isZero())
03409           continue;
03410         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
03411         SDValue OffsVal = DAG.getConstant(Offs, PtrTy);
03412         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N, OffsVal);
03413         continue;
03414       }
03415 
03416       // N = N + Idx * ElementSize;
03417       SDValue IdxN = getValue(Idx);
03418 
03419       // If the index is smaller or larger than intptr_t, truncate or extend
03420       // it.
03421       IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
03422 
03423       // If this is a multiply by a power of two, turn it into a shl
03424       // immediately.  This is a very common case.
03425       if (ElementSize != 1) {
03426         if (ElementSize.isPowerOf2()) {
03427           unsigned Amt = ElementSize.logBase2();
03428           IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
03429                              N.getValueType(), IdxN,
03430                              DAG.getConstant(Amt, IdxN.getValueType()));
03431         } else {
03432           SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
03433           IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
03434                              N.getValueType(), IdxN, Scale);
03435         }
03436       }
03437 
03438       N = DAG.getNode(ISD::ADD, getCurSDLoc(),
03439                       N.getValueType(), N, IdxN);
03440     }
03441   }
03442 
03443   setValue(&I, N);
03444 }
03445 
03446 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
03447   // If this is a fixed sized alloca in the entry block of the function,
03448   // allocate it statically on the stack.
03449   if (FuncInfo.StaticAllocaMap.count(&I))
03450     return;   // getValue will auto-populate this.
03451 
03452   Type *Ty = I.getAllocatedType();
03453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03454   uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
03455   unsigned Align =
03456       std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
03457                I.getAlignment());
03458 
03459   SDValue AllocSize = getValue(I.getArraySize());
03460 
03461   EVT IntPtr = TLI.getPointerTy();
03462   if (AllocSize.getValueType() != IntPtr)
03463     AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
03464 
03465   AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
03466                           AllocSize,
03467                           DAG.getConstant(TySize, IntPtr));
03468 
03469   // Handle alignment.  If the requested alignment is less than or equal to
03470   // the stack alignment, ignore it.  If the size is greater than or equal to
03471   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
03472   unsigned StackAlign =
03473       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
03474   if (Align <= StackAlign)
03475     Align = 0;
03476 
03477   // Round the size of the allocation up to the stack alignment size
03478   // by add SA-1 to the size.
03479   AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
03480                           AllocSize.getValueType(), AllocSize,
03481                           DAG.getIntPtrConstant(StackAlign-1));
03482 
03483   // Mask out the low bits for alignment purposes.
03484   AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
03485                           AllocSize.getValueType(), AllocSize,
03486                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
03487 
03488   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
03489   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
03490   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
03491   setValue(&I, DSA);
03492   DAG.setRoot(DSA.getValue(1));
03493 
03494   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
03495 }
03496 
03497 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
03498   if (I.isAtomic())
03499     return visitAtomicLoad(I);
03500 
03501   const Value *SV = I.getOperand(0);
03502   SDValue Ptr = getValue(SV);
03503 
03504   Type *Ty = I.getType();
03505 
03506   bool isVolatile = I.isVolatile();
03507   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
03508   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
03509   unsigned Alignment = I.getAlignment();
03510 
03511   AAMDNodes AAInfo;
03512   I.getAAMetadata(AAInfo);
03513   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
03514 
03515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03516   SmallVector<EVT, 4> ValueVTs;
03517   SmallVector<uint64_t, 4> Offsets;
03518   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
03519   unsigned NumValues = ValueVTs.size();
03520   if (NumValues == 0)
03521     return;
03522 
03523   SDValue Root;
03524   bool ConstantMemory = false;
03525   if (isVolatile || NumValues > MaxParallelChains)
03526     // Serialize volatile loads with other side effects.
03527     Root = getRoot();
03528   else if (AA->pointsToConstantMemory(
03529              AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
03530     // Do not serialize (non-volatile) loads of constant memory with anything.
03531     Root = DAG.getEntryNode();
03532     ConstantMemory = true;
03533   } else {
03534     // Do not serialize non-volatile loads against each other.
03535     Root = DAG.getRoot();
03536   }
03537 
03538   if (isVolatile)
03539     Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
03540 
03541   SmallVector<SDValue, 4> Values(NumValues);
03542   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
03543                                           NumValues));
03544   EVT PtrVT = Ptr.getValueType();
03545   unsigned ChainI = 0;
03546   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
03547     // Serializing loads here may result in excessive register pressure, and
03548     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
03549     // could recover a bit by hoisting nodes upward in the chain by recognizing
03550     // they are side-effect free or do not alias. The optimizer should really
03551     // avoid this case by converting large object/array copies to llvm.memcpy
03552     // (MaxParallelChains should always remain as failsafe).
03553     if (ChainI == MaxParallelChains) {
03554       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
03555       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
03556                                   makeArrayRef(Chains.data(), ChainI));
03557       Root = Chain;
03558       ChainI = 0;
03559     }
03560     SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
03561                             PtrVT, Ptr,
03562                             DAG.getConstant(Offsets[i], PtrVT));
03563     SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
03564                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
03565                             isNonTemporal, isInvariant, Alignment, AAInfo,
03566                             Ranges);
03567 
03568     Values[i] = L;
03569     Chains[ChainI] = L.getValue(1);
03570   }
03571 
03572   if (!ConstantMemory) {
03573     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
03574                                 makeArrayRef(Chains.data(), ChainI));
03575     if (isVolatile)
03576       DAG.setRoot(Chain);
03577     else
03578       PendingLoads.push_back(Chain);
03579   }
03580 
03581   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03582                            DAG.getVTList(ValueVTs), Values));
03583 }
03584 
03585 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
03586   if (I.isAtomic())
03587     return visitAtomicStore(I);
03588 
03589   const Value *SrcV = I.getOperand(0);
03590   const Value *PtrV = I.getOperand(1);
03591 
03592   SmallVector<EVT, 4> ValueVTs;
03593   SmallVector<uint64_t, 4> Offsets;
03594   ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
03595                   ValueVTs, &Offsets);
03596   unsigned NumValues = ValueVTs.size();
03597   if (NumValues == 0)
03598     return;
03599 
03600   // Get the lowered operands. Note that we do this after
03601   // checking if NumResults is zero, because with zero results
03602   // the operands won't have values in the map.
03603   SDValue Src = getValue(SrcV);
03604   SDValue Ptr = getValue(PtrV);
03605 
03606   SDValue Root = getRoot();
03607   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
03608                                           NumValues));
03609   EVT PtrVT = Ptr.getValueType();
03610   bool isVolatile = I.isVolatile();
03611   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
03612   unsigned Alignment = I.getAlignment();
03613 
03614   AAMDNodes AAInfo;
03615   I.getAAMetadata(AAInfo);
03616 
03617   unsigned ChainI = 0;
03618   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
03619     // See visitLoad comments.
03620     if (ChainI == MaxParallelChains) {
03621       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
03622                                   makeArrayRef(Chains.data(), ChainI));
03623       Root = Chain;
03624       ChainI = 0;
03625     }
03626     SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
03627                               DAG.getConstant(Offsets[i], PtrVT));
03628     SDValue St = DAG.getStore(Root, getCurSDLoc(),
03629                               SDValue(Src.getNode(), Src.getResNo() + i),
03630                               Add, MachinePointerInfo(PtrV, Offsets[i]),
03631                               isVolatile, isNonTemporal, Alignment, AAInfo);
03632     Chains[ChainI] = St;
03633   }
03634 
03635   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
03636                                   makeArrayRef(Chains.data(), ChainI));
03637   DAG.setRoot(StoreNode);
03638 }
03639 
03640 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
03641   SDLoc sdl = getCurSDLoc();
03642 
03643   // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
03644   Value  *PtrOperand = I.getArgOperand(1);
03645   SDValue Ptr = getValue(PtrOperand);
03646   SDValue Src0 = getValue(I.getArgOperand(0));
03647   SDValue Mask = getValue(I.getArgOperand(3));
03648   EVT VT = Src0.getValueType();
03649   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
03650   if (!Alignment)
03651     Alignment = DAG.getEVTAlignment(VT);
03652 
03653   AAMDNodes AAInfo;
03654   I.getAAMetadata(AAInfo);
03655 
03656   MachineMemOperand *MMO =
03657     DAG.getMachineFunction().
03658     getMachineMemOperand(MachinePointerInfo(PtrOperand),
03659                           MachineMemOperand::MOStore,  VT.getStoreSize(),
03660                           Alignment, AAInfo);
03661   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
03662                                          MMO, false);
03663   DAG.setRoot(StoreNode);
03664   setValue(&I, StoreNode);
03665 }
03666 
03667 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
03668   SDLoc sdl = getCurSDLoc();
03669 
03670   // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
03671   Value  *PtrOperand = I.getArgOperand(0);
03672   SDValue Ptr = getValue(PtrOperand);
03673   SDValue Src0 = getValue(I.getArgOperand(3));
03674   SDValue Mask = getValue(I.getArgOperand(2));
03675 
03676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03677   EVT VT = TLI.getValueType(I.getType());
03678   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
03679   if (!Alignment)
03680     Alignment = DAG.getEVTAlignment(VT);
03681 
03682   AAMDNodes AAInfo;
03683   I.getAAMetadata(AAInfo);
03684   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
03685 
03686   SDValue InChain = DAG.getRoot();
03687   if (AA->pointsToConstantMemory(
03688       AliasAnalysis::Location(PtrOperand,
03689                               AA->getTypeStoreSize(I.getType()),
03690                               AAInfo))) {
03691     // Do not serialize (non-volatile) loads of constant memory with anything.
03692     InChain = DAG.getEntryNode();
03693   }
03694 
03695   MachineMemOperand *MMO =
03696     DAG.getMachineFunction().
03697     getMachineMemOperand(MachinePointerInfo(PtrOperand),
03698                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
03699                           Alignment, AAInfo, Ranges);
03700 
03701   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
03702                                    ISD::NON_EXTLOAD);
03703   SDValue OutChain = Load.getValue(1);
03704   DAG.setRoot(OutChain);
03705   setValue(&I, Load);
03706 }
03707 
03708 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
03709   SDLoc dl = getCurSDLoc();
03710   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
03711   AtomicOrdering FailureOrder = I.getFailureOrdering();
03712   SynchronizationScope Scope = I.getSynchScope();
03713 
03714   SDValue InChain = getRoot();
03715 
03716   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
03717   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
03718   SDValue L = DAG.getAtomicCmpSwap(
03719       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
03720       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
03721       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
03722       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
03723 
03724   SDValue OutChain = L.getValue(2);
03725 
03726   setValue(&I, L);
03727   DAG.setRoot(OutChain);
03728 }
03729 
03730 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
03731   SDLoc dl = getCurSDLoc();
03732   ISD::NodeType NT;
03733   switch (I.getOperation()) {
03734   default: llvm_unreachable("Unknown atomicrmw operation");
03735   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
03736   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
03737   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
03738   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
03739   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
03740   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
03741   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
03742   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
03743   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
03744   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
03745   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
03746   }
03747   AtomicOrdering Order = I.getOrdering();
03748   SynchronizationScope Scope = I.getSynchScope();
03749 
03750   SDValue InChain = getRoot();
03751 
03752   SDValue L =
03753     DAG.getAtomic(NT, dl,
03754                   getValue(I.getValOperand()).getSimpleValueType(),
03755                   InChain,
03756                   getValue(I.getPointerOperand()),
03757                   getValue(I.getValOperand()),
03758                   I.getPointerOperand(),
03759                   /* Alignment=*/ 0, Order, Scope);
03760 
03761   SDValue OutChain = L.getValue(1);
03762 
03763   setValue(&I, L);
03764   DAG.setRoot(OutChain);
03765 }
03766 
03767 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
03768   SDLoc dl = getCurSDLoc();
03769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03770   SDValue Ops[3];
03771   Ops[0] = getRoot();
03772   Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
03773   Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
03774   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
03775 }
03776 
03777 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
03778   SDLoc dl = getCurSDLoc();
03779   AtomicOrdering Order = I.getOrdering();
03780   SynchronizationScope Scope = I.getSynchScope();
03781 
03782   SDValue InChain = getRoot();
03783 
03784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03785   EVT VT = TLI.getValueType(I.getType());
03786 
03787   if (I.getAlignment() < VT.getSizeInBits() / 8)
03788     report_fatal_error("Cannot generate unaligned atomic load");
03789 
03790   MachineMemOperand *MMO =
03791       DAG.getMachineFunction().
03792       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
03793                            MachineMemOperand::MOVolatile |
03794                            MachineMemOperand::MOLoad,
03795                            VT.getStoreSize(),
03796                            I.getAlignment() ? I.getAlignment() :
03797                                               DAG.getEVTAlignment(VT));
03798 
03799   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
03800   SDValue L =
03801       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
03802                     getValue(I.getPointerOperand()), MMO,
03803                     Order, Scope);
03804 
03805   SDValue OutChain = L.getValue(1);
03806 
03807   setValue(&I, L);
03808   DAG.setRoot(OutChain);
03809 }
03810 
03811 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
03812   SDLoc dl = getCurSDLoc();
03813 
03814   AtomicOrdering Order = I.getOrdering();
03815   SynchronizationScope Scope = I.getSynchScope();
03816 
03817   SDValue InChain = getRoot();
03818 
03819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03820   EVT VT = TLI.getValueType(I.getValueOperand()->getType());
03821 
03822   if (I.getAlignment() < VT.getSizeInBits() / 8)
03823     report_fatal_error("Cannot generate unaligned atomic store");
03824 
03825   SDValue OutChain =
03826     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
03827                   InChain,
03828                   getValue(I.getPointerOperand()),
03829                   getValue(I.getValueOperand()),
03830                   I.getPointerOperand(), I.getAlignment(),
03831                   Order, Scope);
03832 
03833   DAG.setRoot(OutChain);
03834 }
03835 
03836 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
03837 /// node.
03838 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
03839                                                unsigned Intrinsic) {
03840   bool HasChain = !I.doesNotAccessMemory();
03841   bool OnlyLoad = HasChain && I.onlyReadsMemory();
03842 
03843   // Build the operand list.
03844   SmallVector<SDValue, 8> Ops;
03845   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
03846     if (OnlyLoad) {
03847       // We don't need to serialize loads against other loads.
03848       Ops.push_back(DAG.getRoot());
03849     } else {
03850       Ops.push_back(getRoot());
03851     }
03852   }
03853 
03854   // Info is set by getTgtMemInstrinsic
03855   TargetLowering::IntrinsicInfo Info;
03856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03857   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
03858 
03859   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
03860   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
03861       Info.opc == ISD::INTRINSIC_W_CHAIN)
03862     Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
03863 
03864   // Add all operands of the call to the operand list.
03865   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
03866     SDValue Op = getValue(I.getArgOperand(i));
03867     Ops.push_back(Op);
03868   }
03869 
03870   SmallVector<EVT, 4> ValueVTs;
03871   ComputeValueVTs(TLI, I.getType(), ValueVTs);
03872 
03873   if (HasChain)
03874     ValueVTs.push_back(MVT::Other);
03875 
03876   SDVTList VTs = DAG.getVTList(ValueVTs);
03877 
03878   // Create the node.
03879   SDValue Result;
03880   if (IsTgtIntrinsic) {
03881     // This is target intrinsic that touches memory
03882     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
03883                                      VTs, Ops, Info.memVT,
03884                                    MachinePointerInfo(Info.ptrVal, Info.offset),
03885                                      Info.align, Info.vol,
03886                                      Info.readMem, Info.writeMem, Info.size);
03887   } else if (!HasChain) {
03888     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
03889   } else if (!I.getType()->isVoidTy()) {
03890     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
03891   } else {
03892     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
03893   }
03894 
03895   if (HasChain) {
03896     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
03897     if (OnlyLoad)
03898       PendingLoads.push_back(Chain);
03899     else
03900       DAG.setRoot(Chain);
03901   }
03902 
03903   if (!I.getType()->isVoidTy()) {
03904     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
03905       EVT VT = TLI.getValueType(PTy);
03906       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
03907     }
03908 
03909     setValue(&I, Result);
03910   }
03911 }
03912 
03913 /// GetSignificand - Get the significand and build it into a floating-point
03914 /// number with exponent of 1:
03915 ///
03916 ///   Op = (Op & 0x007fffff) | 0x3f800000;
03917 ///
03918 /// where Op is the hexadecimal representation of floating point value.
03919 static SDValue
03920 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
03921   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03922                            DAG.getConstant(0x007fffff, MVT::i32));
03923   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
03924                            DAG.getConstant(0x3f800000, MVT::i32));
03925   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
03926 }
03927 
03928 /// GetExponent - Get the exponent:
03929 ///
03930 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
03931 ///
03932 /// where Op is the hexadecimal representation of floating point value.
03933 static SDValue
03934 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
03935             SDLoc dl) {
03936   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03937                            DAG.getConstant(0x7f800000, MVT::i32));
03938   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
03939                            DAG.getConstant(23, TLI.getPointerTy()));
03940   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
03941                            DAG.getConstant(127, MVT::i32));
03942   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
03943 }
03944 
03945 /// getF32Constant - Get 32-bit floating point constant.
03946 static SDValue
03947 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
03948   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
03949                            MVT::f32);
03950 }
03951 
03952 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
03953                                        SelectionDAG &DAG) {
03954   //   IntegerPartOfX = ((int32_t)(t0);
03955   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
03956 
03957   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
03958   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03959   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
03960 
03961   //   IntegerPartOfX <<= 23;
03962   IntegerPartOfX = DAG.getNode(
03963       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03964       DAG.getConstant(23, DAG.getTargetLoweringInfo().getPointerTy()));
03965 
03966   SDValue TwoToFractionalPartOfX;
03967   if (LimitFloatPrecision <= 6) {
03968     // For floating-point precision of 6:
03969     //
03970     //   TwoToFractionalPartOfX =
03971     //     0.997535578f +
03972     //       (0.735607626f + 0.252464424f * x) * x;
03973     //
03974     // error 0.0144103317, which is 6 bits
03975     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03976                              getF32Constant(DAG, 0x3e814304));
03977     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03978                              getF32Constant(DAG, 0x3f3c50c8));
03979     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03980     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03981                                          getF32Constant(DAG, 0x3f7f5e7e));
03982   } else if (LimitFloatPrecision <= 12) {
03983     // For floating-point precision of 12:
03984     //
03985     //   TwoToFractionalPartOfX =
03986     //     0.999892986f +
03987     //       (0.696457318f +
03988     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03989     //
03990     // error 0.000107046256, which is 13 to 14 bits
03991     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03992                              getF32Constant(DAG, 0x3da235e3));
03993     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03994                              getF32Constant(DAG, 0x3e65b8f3));
03995     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03996     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03997                              getF32Constant(DAG, 0x3f324b07));
03998     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03999     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04000                                          getF32Constant(DAG, 0x3f7ff8fd));
04001   } else { // LimitFloatPrecision <= 18
04002     // For floating-point precision of 18:
04003     //
04004     //   TwoToFractionalPartOfX =
04005     //     0.999999982f +
04006     //       (0.693148872f +
04007     //         (0.240227044f +
04008     //           (0.554906021e-1f +
04009     //             (0.961591928e-2f +
04010     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
04011     // error 2.47208000*10^(-7), which is better than 18 bits
04012     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04013                              getF32Constant(DAG, 0x3924b03e));
04014     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04015                              getF32Constant(DAG, 0x3ab24b87));
04016     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04017     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04018                              getF32Constant(DAG, 0x3c1d8c17));
04019     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04020     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04021                              getF32Constant(DAG, 0x3d634a1d));
04022     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04023     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04024                              getF32Constant(DAG, 0x3e75fe14));
04025     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04026     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
04027                               getF32Constant(DAG, 0x3f317234));
04028     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
04029     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
04030                                          getF32Constant(DAG, 0x3f800000));
04031   }
04032 
04033   // Add the exponent into the result in integer domain.
04034   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
04035   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04036                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
04037 }
04038 
04039 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
04040 /// limited-precision mode.
04041 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04042                          const TargetLowering &TLI) {
04043   if (Op.getValueType() == MVT::f32 &&
04044       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04045 
04046     // Put the exponent in the right bit position for later addition to the
04047     // final result:
04048     //
04049     //   #define LOG2OFe 1.4426950f
04050     //   t0 = Op * LOG2OFe
04051     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
04052                              getF32Constant(DAG, 0x3fb8aa3b));
04053     return getLimitedPrecisionExp2(t0, dl, DAG);
04054   }
04055 
04056   // No special expansion.
04057   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
04058 }
04059 
04060 /// expandLog - Lower a log intrinsic. Handles the special sequences for
04061 /// limited-precision mode.
04062 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04063                          const TargetLowering &TLI) {
04064   if (Op.getValueType() == MVT::f32 &&
04065       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04066     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
04067 
04068     // Scale the exponent by log(2) [0.69314718f].
04069     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
04070     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
04071                                         getF32Constant(DAG, 0x3f317218));
04072 
04073     // Get the significand and build it into a floating-point number with
04074     // exponent of 1.
04075     SDValue X = GetSignificand(DAG, Op1, dl);
04076 
04077     SDValue LogOfMantissa;
04078     if (LimitFloatPrecision <= 6) {
04079       // For floating-point precision of 6:
04080       //
04081       //   LogofMantissa =
04082       //     -1.1609546f +
04083       //       (1.4034025f - 0.23903021f * x) * x;
04084       //
04085       // error 0.0034276066, which is better than 8 bits
04086       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04087                                getF32Constant(DAG, 0xbe74c456));
04088       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04089                                getF32Constant(DAG, 0x3fb3a2b1));
04090       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04091       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04092                                   getF32Constant(DAG, 0x3f949a29));
04093     } else if (LimitFloatPrecision <= 12) {
04094       // For floating-point precision of 12:
04095       //
04096       //   LogOfMantissa =
04097       //     -1.7417939f +
04098       //       (2.8212026f +
04099       //         (-1.4699568f +
04100       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
04101       //
04102       // error 0.000061011436, which is 14 bits
04103       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04104                                getF32Constant(DAG, 0xbd67b6d6));
04105       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04106                                getF32Constant(DAG, 0x3ee4f4b8));
04107       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04108       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04109                                getF32Constant(DAG, 0x3fbc278b));
04110       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04111       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04112                                getF32Constant(DAG, 0x40348e95));
04113       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04114       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04115                                   getF32Constant(DAG, 0x3fdef31a));
04116     } else { // LimitFloatPrecision <= 18
04117       // For floating-point precision of 18:
04118       //
04119       //   LogOfMantissa =
04120       //     -2.1072184f +
04121       //       (4.2372794f +
04122       //         (-3.7029485f +
04123       //           (2.2781945f +
04124       //             (-0.87823314f +
04125       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
04126       //
04127       // error 0.0000023660568, which is better than 18 bits
04128       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04129                                getF32Constant(DAG, 0xbc91e5ac));
04130       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04131                                getF32Constant(DAG, 0x3e4350aa));
04132       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04133       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04134                                getF32Constant(DAG, 0x3f60d3e3));
04135       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04136       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04137                                getF32Constant(DAG, 0x4011cdf0));
04138       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04139       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04140                                getF32Constant(DAG, 0x406cfd1c));
04141       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04142       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04143                                getF32Constant(DAG, 0x408797cb));
04144       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04145       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
04146                                   getF32Constant(DAG, 0x4006dcab));
04147     }
04148 
04149     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
04150   }
04151 
04152   // No special expansion.
04153   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
04154 }
04155 
04156 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
04157 /// limited-precision mode.
04158 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04159                           const TargetLowering &TLI) {
04160   if (Op.getValueType() == MVT::f32 &&
04161       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04162     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
04163 
04164     // Get the exponent.
04165     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
04166 
04167     // Get the significand and build it into a floating-point number with
04168     // exponent of 1.
04169     SDValue X = GetSignificand(DAG, Op1, dl);
04170 
04171     // Different possible minimax approximations of significand in
04172     // floating-point for various degrees of accuracy over [1,2].
04173     SDValue Log2ofMantissa;
04174     if (LimitFloatPrecision <= 6) {
04175       // For floating-point precision of 6:
04176       //
04177       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
04178       //
04179       // error 0.0049451742, which is more than 7 bits
04180       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04181                                getF32Constant(DAG, 0xbeb08fe0));
04182       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04183                                getF32Constant(DAG, 0x40019463));
04184       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04185       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04186                                    getF32Constant(DAG, 0x3fd6633d));
04187     } else if (LimitFloatPrecision <= 12) {
04188       // For floating-point precision of 12:
04189       //
04190       //   Log2ofMantissa =
04191       //     -2.51285454f +
04192       //       (4.07009056f +
04193       //         (-2.12067489f +
04194       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
04195       //
04196       // error 0.0000876136000, which is better than 13 bits
04197       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04198                                getF32Constant(DAG, 0xbda7262e));
04199       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04200                                getF32Constant(DAG, 0x3f25280b));
04201       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04202       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04203                                getF32Constant(DAG, 0x4007b923));
04204       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04205       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04206                                getF32Constant(DAG, 0x40823e2f));
04207       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04208       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04209                                    getF32Constant(DAG, 0x4020d29c));
04210     } else { // LimitFloatPrecision <= 18
04211       // For floating-point precision of 18:
04212       //
04213       //   Log2ofMantissa =
04214       //     -3.0400495f +
04215       //       (6.1129976f +
04216       //         (-5.3420409f +
04217       //           (3.2865683f +
04218       //             (-1.2669343f +
04219       //               (0.27515199f -
04220       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
04221       //
04222       // error 0.0000018516, which is better than 18 bits
04223       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04224                                getF32Constant(DAG, 0xbcd2769e));
04225       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04226                                getF32Constant(DAG, 0x3e8ce0b9));
04227       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04228       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04229                                getF32Constant(DAG, 0x3fa22ae7));
04230       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04231       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04232                                getF32Constant(DAG, 0x40525723));
04233       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04234       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04235                                getF32Constant(DAG, 0x40aaf200));
04236       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04237       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04238                                getF32Constant(DAG, 0x40c39dad));
04239       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04240       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
04241                                    getF32Constant(DAG, 0x4042902c));
04242     }
04243 
04244     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
04245   }
04246 
04247   // No special expansion.
04248   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
04249 }
04250 
04251 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
04252 /// limited-precision mode.
04253 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04254                            const TargetLowering &TLI) {
04255   if (Op.getValueType() == MVT::f32 &&
04256       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04257     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
04258 
04259     // Scale the exponent by log10(2) [0.30102999f].
04260     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
04261     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
04262                                         getF32Constant(DAG, 0x3e9a209a));
04263 
04264     // Get the significand and build it into a floating-point number with
04265     // exponent of 1.
04266     SDValue X = GetSignificand(DAG, Op1, dl);
04267 
04268     SDValue Log10ofMantissa;
04269     if (LimitFloatPrecision <= 6) {
04270       // For floating-point precision of 6:
04271       //
04272       //   Log10ofMantissa =
04273       //     -0.50419619f +
04274       //       (0.60948995f - 0.10380950f * x) * x;
04275       //
04276       // error 0.0014886165, which is 6 bits
04277       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04278                                getF32Constant(DAG, 0xbdd49a13));
04279       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04280                                getF32Constant(DAG, 0x3f1c0789));
04281       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04282       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04283                                     getF32Constant(DAG, 0x3f011300));
04284     } else if (LimitFloatPrecision <= 12) {
04285       // For floating-point precision of 12:
04286       //
04287       //   Log10ofMantissa =
04288       //     -0.64831180f +
04289       //       (0.91751397f +
04290       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
04291       //
04292       // error 0.00019228036, which is better than 12 bits
04293       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04294                                getF32Constant(DAG, 0x3d431f31));
04295       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
04296                                getF32Constant(DAG, 0x3ea21fb2));
04297       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04298       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04299                                getF32Constant(DAG, 0x3f6ae232));
04300       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04301       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
04302                                     getF32Constant(DAG, 0x3f25f7c3));
04303     } else { // LimitFloatPrecision <= 18
04304       // For floating-point precision of 18:
04305       //
04306       //   Log10ofMantissa =
04307       //     -0.84299375f +
04308       //       (1.5327582f +
04309       //         (-1.0688956f +
04310       //           (0.49102474f +
04311       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
04312       //
04313       // error 0.0000037995730, which is better than 18 bits
04314       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04315                                getF32Constant(DAG, 0x3c5d51ce));
04316       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
04317                                getF32Constant(DAG, 0x3e00685a));
04318       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04319       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04320                                getF32Constant(DAG, 0x3efb6798));
04321       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04322       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
04323                                getF32Constant(DAG, 0x3f88d192));
04324       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04325       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04326                                getF32Constant(DAG, 0x3fc4316c));
04327       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04328       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
04329                                     getF32Constant(DAG, 0x3f57ce70));
04330     }
04331 
04332     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
04333   }
04334 
04335   // No special expansion.
04336   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
04337 }
04338 
04339 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
04340 /// limited-precision mode.
04341 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04342                           const TargetLowering &TLI) {
04343   if (Op.getValueType() == MVT::f32 &&
04344       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
04345     return getLimitedPrecisionExp2(Op, dl, DAG);
04346 
04347   // No special expansion.
04348   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
04349 }
04350 
04351 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
04352 /// limited-precision mode with x == 10.0f.
04353 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
04354                          SelectionDAG &DAG, const TargetLowering &TLI) {
04355   bool IsExp10 = false;
04356   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
04357       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04358     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
04359       APFloat Ten(10.0f);
04360       IsExp10 = LHSC->isExactlyValue(Ten);
04361     }
04362   }
04363 
04364   if (IsExp10) {
04365     // Put the exponent in the right bit position for later addition to the
04366     // final result:
04367     //
04368     //   #define LOG2OF10 3.3219281f
04369     //   t0 = Op * LOG2OF10;
04370     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
04371                              getF32Constant(DAG, 0x40549a78));
04372     return getLimitedPrecisionExp2(t0, dl, DAG);
04373   }
04374 
04375   // No special expansion.
04376   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
04377 }
04378 
04379 
04380 /// ExpandPowI - Expand a llvm.powi intrinsic.
04381 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
04382                           SelectionDAG &DAG) {
04383   // If RHS is a constant, we can expand this out to a multiplication tree,
04384   // otherwise we end up lowering to a call to __powidf2 (for example).  When
04385   // optimizing for size, we only want to do this if the expansion would produce
04386   // a small number of multiplies, otherwise we do the full expansion.
04387   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
04388     // Get the exponent as a positive value.
04389     unsigned Val = RHSC->getSExtValue();
04390     if ((int)Val < 0) Val = -Val;
04391 
04392     // powi(x, 0) -> 1.0
04393     if (Val == 0)
04394       return DAG.getConstantFP(1.0, LHS.getValueType());
04395 
04396     const Function *F = DAG.getMachineFunction().getFunction();
04397     if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
04398         // If optimizing for size, don't insert too many multiplies.  This
04399         // inserts up to 5 multiplies.
04400         countPopulation(Val) + Log2_32(Val) < 7) {
04401       // We use the simple binary decomposition method to generate the multiply
04402       // sequence.  There are more optimal ways to do this (for example,
04403       // powi(x,15) generates one more multiply than it should), but this has
04404       // the benefit of being both really simple and much better than a libcall.
04405       SDValue Res;  // Logically starts equal to 1.0
04406       SDValue CurSquare = LHS;
04407       while (Val) {
04408         if (Val & 1) {
04409           if (Res.getNode())
04410             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
04411           else
04412             Res = CurSquare;  // 1.0*CurSquare.
04413         }
04414 
04415         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
04416                                 CurSquare, CurSquare);
04417         Val >>= 1;
04418       }
04419 
04420       // If the original was negative, invert the result, producing 1/(x*x*x).
04421       if (RHSC->getSExtValue() < 0)
04422         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
04423                           DAG.getConstantFP(1.0, LHS.getValueType()), Res);
04424       return Res;
04425     }
04426   }
04427 
04428   // Otherwise, expand to a libcall.
04429   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
04430 }
04431 
04432 // getTruncatedArgReg - Find underlying register used for an truncated
04433 // argument.
04434 static unsigned getTruncatedArgReg(const SDValue &N) {
04435   if (N.getOpcode() != ISD::TRUNCATE)
04436     return 0;
04437 
04438   const SDValue &Ext = N.getOperand(0);
04439   if (Ext.getOpcode() == ISD::AssertZext ||
04440       Ext.getOpcode() == ISD::AssertSext) {
04441     const SDValue &CFR = Ext.getOperand(0);
04442     if (CFR.getOpcode() == ISD::CopyFromReg)
04443       return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
04444     if (CFR.getOpcode() == ISD::TRUNCATE)
04445       return getTruncatedArgReg(CFR);
04446   }
04447   return 0;
04448 }
04449 
04450 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
04451 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
04452 /// At the end of instruction selection, they will be inserted to the entry BB.
04453 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
04454     const Value *V, MDLocalVariable *Variable, MDExpression *Expr,
04455     MDLocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
04456   const Argument *Arg = dyn_cast<Argument>(V);
04457   if (!Arg)
04458     return false;
04459 
04460   MachineFunction &MF = DAG.getMachineFunction();
04461   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
04462 
04463   // Ignore inlined function arguments here.
04464   //
04465   // FIXME: Should we be checking DL->inlinedAt() to determine this?
04466   DIVariable DV(Variable);
04467   if (!DV->getScope()->getSubprogram()->describes(MF.getFunction()))
04468     return false;
04469 
04470   Optional<MachineOperand> Op;
04471   // Some arguments' frame index is recorded during argument lowering.
04472   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
04473     Op = MachineOperand::CreateFI(FI);
04474 
04475   if (!Op && N.getNode()) {
04476     unsigned Reg;
04477     if (N.getOpcode() == ISD::CopyFromReg)
04478       Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
04479     else
04480       Reg = getTruncatedArgReg(N);
04481     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
04482       MachineRegisterInfo &RegInfo = MF.getRegInfo();
04483       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
04484       if (PR)
04485         Reg = PR;
04486     }
04487     if (Reg)
04488       Op = MachineOperand::CreateReg(Reg, false);
04489   }
04490 
04491   if (!Op) {
04492     // Check if ValueMap has reg number.
04493     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
04494     if (VMI != FuncInfo.ValueMap.end())
04495       Op = MachineOperand::CreateReg(VMI->second, false);
04496   }
04497 
04498   if (!Op && N.getNode())
04499     // Check if frame index is available.
04500     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
04501       if (FrameIndexSDNode *FINode =
04502           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
04503         Op = MachineOperand::CreateFI(FINode->getIndex());
04504 
04505   if (!Op)
04506     return false;
04507 
04508   assert(Variable->isValidLocationForIntrinsic(DL) &&
04509          "Expected inlined-at fields to agree");
04510   if (Op->isReg())
04511     FuncInfo.ArgDbgValues.push_back(
04512         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
04513                 Op->getReg(), Offset, Variable, Expr));
04514   else
04515     FuncInfo.ArgDbgValues.push_back(
04516         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
04517             .addOperand(*Op)
04518             .addImm(Offset)
04519             .addMetadata(Variable)
04520             .addMetadata(Expr));
04521 
04522   return true;
04523 }
04524 
04525 // VisualStudio defines setjmp as _setjmp
04526 #if defined(_MSC_VER) && defined(setjmp) && \
04527                          !defined(setjmp_undefined_for_msvc)
04528 #  pragma push_macro("setjmp")
04529 #  undef setjmp
04530 #  define setjmp_undefined_for_msvc
04531 #endif
04532 
04533 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
04534 /// we want to emit this as a call to a named external function, return the name
04535 /// otherwise lower it and return null.
04536 const char *
04537 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
04538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
04539   SDLoc sdl = getCurSDLoc();
04540   DebugLoc dl = getCurDebugLoc();
04541   SDValue Res;
04542 
04543   switch (Intrinsic) {
04544   default:
04545     // By default, turn this into a target intrinsic node.
04546     visitTargetIntrinsic(I, Intrinsic);
04547     return nullptr;
04548   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
04549   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
04550   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
04551   case Intrinsic::returnaddress:
04552     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
04553                              getValue(I.getArgOperand(0))));
04554     return nullptr;
04555   case Intrinsic::frameaddress:
04556     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
04557                              getValue(I.getArgOperand(0))));
04558     return nullptr;
04559   case Intrinsic::read_register: {
04560     Value *Reg = I.getArgOperand(0);
04561     SDValue RegName =
04562         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
04563     EVT VT = TLI.getValueType(I.getType());
04564     setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
04565     return nullptr;
04566   }
04567   case Intrinsic::write_register: {
04568     Value *Reg = I.getArgOperand(0);
04569     Value *RegValue = I.getArgOperand(1);
04570     SDValue Chain = getValue(RegValue).getOperand(0);
04571     SDValue RegName =
04572         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
04573     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
04574                             RegName, getValue(RegValue)));
04575     return nullptr;
04576   }
04577   case Intrinsic::setjmp:
04578     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
04579   case Intrinsic::longjmp:
04580     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
04581   case Intrinsic::memcpy: {
04582     // FIXME: this definition of "user defined address space" is x86-specific
04583     // Assert for address < 256 since we support only user defined address
04584     // spaces.
04585     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04586            < 256 &&
04587            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04588            < 256 &&
04589            "Unknown address space");
04590     SDValue Op1 = getValue(I.getArgOperand(0));
04591     SDValue Op2 = getValue(I.getArgOperand(1));
04592     SDValue Op3 = getValue(I.getArgOperand(2));
04593     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04594     if (!Align)
04595       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
04596     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04597     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04598     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04599                                false, isTC,
04600                                MachinePointerInfo(I.getArgOperand(0)),
04601                                MachinePointerInfo(I.getArgOperand(1)));
04602     updateDAGForMaybeTailCall(MC);
04603     return nullptr;
04604   }
04605   case Intrinsic::memset: {
04606     // FIXME: this definition of "user defined address space" is x86-specific
04607     // Assert for address < 256 since we support only user defined address
04608     // spaces.
04609     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04610            < 256 &&
04611            "Unknown address space");
04612     SDValue Op1 = getValue(I.getArgOperand(0));
04613     SDValue Op2 = getValue(I.getArgOperand(1));
04614     SDValue Op3 = getValue(I.getArgOperand(2));
04615     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04616     if (!Align)
04617       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
04618     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04619     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04620     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04621                                isTC, MachinePointerInfo(I.getArgOperand(0)));
04622     updateDAGForMaybeTailCall(MS);
04623     return nullptr;
04624   }
04625   case Intrinsic::memmove: {
04626     // FIXME: this definition of "user defined address space" is x86-specific
04627     // Assert for address < 256 since we support only user defined address
04628     // spaces.
04629     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04630            < 256 &&
04631            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04632            < 256 &&
04633            "Unknown address space");
04634     SDValue Op1 = getValue(I.getArgOperand(0));
04635     SDValue Op2 = getValue(I.getArgOperand(1));
04636     SDValue Op3 = getValue(I.getArgOperand(2));
04637     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04638     if (!Align)
04639       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
04640     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04641     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04642     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04643                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
04644                                 MachinePointerInfo(I.getArgOperand(1)));
04645     updateDAGForMaybeTailCall(MM);
04646     return nullptr;
04647   }
04648   case Intrinsic::dbg_declare: {
04649     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
04650     MDLocalVariable *Variable = DI.getVariable();
04651     MDExpression *Expression = DI.getExpression();
04652     const Value *Address = DI.getAddress();
04653     DIVariable DIVar = Variable;
04654     if (!Address || !DIVar) {
04655       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04656       return nullptr;
04657     }
04658 
04659     // Check if address has undef value.
04660     if (isa<UndefValue>(Address) ||
04661         (Address->use_empty() && !isa<Argument>(Address))) {
04662       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04663       return nullptr;
04664     }
04665 
04666     SDValue &N = NodeMap[Address];
04667     if (!N.getNode() && isa<Argument>(Address))
04668       // Check unused arguments map.
04669       N = UnusedArgNodeMap[Address];
04670     SDDbgValue *SDV;
04671     if (N.getNode()) {
04672       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
04673         Address = BCI->getOperand(0);
04674       // Parameters are handled specially.
04675       bool isParameter =
04676         (DIVariable(Variable)->getTag() == dwarf::DW_TAG_arg_variable ||
04677          isa<Argument>(Address));
04678 
04679       const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
04680 
04681       if (isParameter && !AI) {
04682         FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
04683         if (FINode)
04684           // Byval parameter.  We have a frame index at this point.
04685           SDV = DAG.getFrameIndexDbgValue(
04686               Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
04687         else {
04688           // Address is an argument, so try to emit its dbg value using
04689           // virtual register info from the FuncInfo.ValueMap.
04690           EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
04691                                    N);
04692           return nullptr;
04693         }
04694       } else if (AI)
04695         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
04696                               true, 0, dl, SDNodeOrder);
04697       else {
04698         // Can't do anything with other non-AI cases yet.
04699         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04700         DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
04701         DEBUG(Address->dump());
04702         return nullptr;
04703       }
04704       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
04705     } else {
04706       // If Address is an argument then try to emit its dbg value using
04707       // virtual register info from the FuncInfo.ValueMap.
04708       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
04709                                     N)) {
04710         // If variable is pinned by a alloca in dominating bb then
04711         // use StaticAllocaMap.
04712         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
04713           if (AI->getParent() != DI.getParent()) {
04714             DenseMap<const AllocaInst*, int>::iterator SI =
04715               FuncInfo.StaticAllocaMap.find(AI);
04716             if (SI != FuncInfo.StaticAllocaMap.end()) {
04717               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
04718                                               0, dl, SDNodeOrder);
04719               DAG.AddDbgValue(SDV, nullptr, false);
04720               return nullptr;
04721             }
04722           }
04723         }
04724         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04725       }
04726     }
04727     return nullptr;
04728   }
04729   case Intrinsic::dbg_value: {
04730     const DbgValueInst &DI = cast<DbgValueInst>(I);
04731     DIVariable DIVar = DI.getVariable();
04732     if (!DIVar)
04733       return nullptr;
04734 
04735     MDLocalVariable *Variable = DI.getVariable();
04736     MDExpression *Expression = DI.getExpression();
04737     uint64_t Offset = DI.getOffset();
04738     const Value *V = DI.getValue();
04739     if (!V)
04740       return nullptr;
04741 
04742     SDDbgValue *SDV;
04743     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
04744       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
04745                                     SDNodeOrder);
04746       DAG.AddDbgValue(SDV, nullptr, false);
04747     } else {
04748       // Do not use getValue() in here; we don't want to generate code at
04749       // this point if it hasn't been done yet.
04750       SDValue N = NodeMap[V];
04751       if (!N.getNode() && isa<Argument>(V))
04752         // Check unused arguments map.
04753         N = UnusedArgNodeMap[V];
04754       if (N.getNode()) {
04755         // A dbg.value for an alloca is always indirect.
04756         bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
04757         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
04758                                       IsIndirect, N)) {
04759           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
04760                                 IsIndirect, Offset, dl, SDNodeOrder);
04761           DAG.AddDbgValue(SDV, N.getNode(), false);
04762         }
04763       } else if (!V->use_empty() ) {
04764         // Do not call getValue(V) yet, as we don't want to generate code.
04765         // Remember it for later.
04766         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
04767         DanglingDebugInfoMap[V] = DDI;
04768       } else {
04769         // We may expand this to cover more cases.  One case where we have no
04770         // data available is an unreferenced parameter.
04771         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04772       }
04773     }
04774 
04775     // Build a debug info table entry.
04776     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
04777       V = BCI->getOperand(0);
04778     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
04779     // Don't handle byval struct arguments or VLAs, for example.
04780     if (!AI) {
04781       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
04782       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
04783       return nullptr;
04784     }
04785     DenseMap<const AllocaInst*, int>::iterator SI =
04786       FuncInfo.StaticAllocaMap.find(AI);
04787     if (SI == FuncInfo.StaticAllocaMap.end())
04788       return nullptr; // VLAs.
04789     return nullptr;
04790   }
04791 
04792   case Intrinsic::eh_typeid_for: {
04793     // Find the type id for the given typeinfo.
04794     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
04795     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
04796     Res = DAG.getConstant(TypeID, MVT::i32);
04797     setValue(&I, Res);
04798     return nullptr;
04799   }
04800 
04801   case Intrinsic::eh_return_i32:
04802   case Intrinsic::eh_return_i64:
04803     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
04804     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
04805                             MVT::Other,
04806                             getControlRoot(),
04807                             getValue(I.getArgOperand(0)),
04808                             getValue(I.getArgOperand(1))));
04809     return nullptr;
04810   case Intrinsic::eh_unwind_init:
04811     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
04812     return nullptr;
04813   case Intrinsic::eh_dwarf_cfa: {
04814     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
04815                                         TLI.getPointerTy());
04816     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
04817                                  CfaArg.getValueType(),
04818                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
04819                                              CfaArg.getValueType()),
04820                                  CfaArg);
04821     SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
04822                              DAG.getConstant(0, TLI.getPointerTy()));
04823     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
04824                              FA, Offset));
04825     return nullptr;
04826   }
04827   case Intrinsic::eh_sjlj_callsite: {
04828     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
04829     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
04830     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
04831     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
04832 
04833     MMI.setCurrentCallSite(CI->getZExtValue());
04834     return nullptr;
04835   }
04836   case Intrinsic::eh_sjlj_functioncontext: {
04837     // Get and store the index of the function context.
04838     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
04839     AllocaInst *FnCtx =
04840       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
04841     int FI = FuncInfo.StaticAllocaMap[FnCtx];
04842     MFI->setFunctionContextIndex(FI);
04843     return nullptr;
04844   }
04845   case Intrinsic::eh_sjlj_setjmp: {
04846     SDValue Ops[2];
04847     Ops[0] = getRoot();
04848     Ops[1] = getValue(I.getArgOperand(0));
04849     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
04850                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
04851     setValue(&I, Op.getValue(0));
04852     DAG.setRoot(Op.getValue(1));
04853     return nullptr;
04854   }
04855   case Intrinsic::eh_sjlj_longjmp: {
04856     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
04857                             getRoot(), getValue(I.getArgOperand(0))));
04858     return nullptr;
04859   }
04860 
04861   case Intrinsic::masked_load:
04862     visitMaskedLoad(I);
04863     return nullptr;
04864   case Intrinsic::masked_store:
04865     visitMaskedStore(I);
04866     return nullptr;
04867   case Intrinsic::x86_mmx_pslli_w:
04868   case Intrinsic::x86_mmx_pslli_d:
04869   case Intrinsic::x86_mmx_pslli_q:
04870   case Intrinsic::x86_mmx_psrli_w:
04871   case Intrinsic::x86_mmx_psrli_d:
04872   case Intrinsic::x86_mmx_psrli_q:
04873   case Intrinsic::x86_mmx_psrai_w:
04874   case Intrinsic::x86_mmx_psrai_d: {
04875     SDValue ShAmt = getValue(I.getArgOperand(1));
04876     if (isa<ConstantSDNode>(ShAmt)) {
04877       visitTargetIntrinsic(I, Intrinsic);
04878       return nullptr;
04879     }
04880     unsigned NewIntrinsic = 0;
04881     EVT ShAmtVT = MVT::v2i32;
04882     switch (Intrinsic) {
04883     case Intrinsic::x86_mmx_pslli_w:
04884       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
04885       break;
04886     case Intrinsic::x86_mmx_pslli_d:
04887       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
04888       break;
04889     case Intrinsic::x86_mmx_pslli_q:
04890       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
04891       break;
04892     case Intrinsic::x86_mmx_psrli_w:
04893       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
04894       break;
04895     case Intrinsic::x86_mmx_psrli_d:
04896       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
04897       break;
04898     case Intrinsic::x86_mmx_psrli_q:
04899       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
04900       break;
04901     case Intrinsic::x86_mmx_psrai_w:
04902       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
04903       break;
04904     case Intrinsic::x86_mmx_psrai_d:
04905       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
04906       break;
04907     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04908     }
04909 
04910     // The vector shift intrinsics with scalars uses 32b shift amounts but
04911     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
04912     // to be zero.
04913     // We must do this early because v2i32 is not a legal type.
04914     SDValue ShOps[2];
04915     ShOps[0] = ShAmt;
04916     ShOps[1] = DAG.getConstant(0, MVT::i32);
04917     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
04918     EVT DestVT = TLI.getValueType(I.getType());
04919     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
04920     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
04921                        DAG.getConstant(NewIntrinsic, MVT::i32),
04922                        getValue(I.getArgOperand(0)), ShAmt);
04923     setValue(&I, Res);
04924     return nullptr;
04925   }
04926   case Intrinsic::convertff:
04927   case Intrinsic::convertfsi:
04928   case Intrinsic::convertfui:
04929   case Intrinsic::convertsif:
04930   case Intrinsic::convertuif:
04931   case Intrinsic::convertss:
04932   case Intrinsic::convertsu:
04933   case Intrinsic::convertus:
04934   case Intrinsic::convertuu: {
04935     ISD::CvtCode Code = ISD::CVT_INVALID;
04936     switch (Intrinsic) {
04937     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04938     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
04939     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
04940     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
04941     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
04942     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
04943     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
04944     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
04945     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
04946     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
04947     }
04948     EVT DestVT = TLI.getValueType(I.getType());
04949     const Value *Op1 = I.getArgOperand(0);
04950     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
04951                                DAG.getValueType(DestVT),
04952                                DAG.getValueType(getValue(Op1).getValueType()),
04953                                getValue(I.getArgOperand(1)),
04954                                getValue(I.getArgOperand(2)),
04955                                Code);
04956     setValue(&I, Res);
04957     return nullptr;
04958   }
04959   case Intrinsic::powi:
04960     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
04961                             getValue(I.getArgOperand(1)), DAG));
04962     return nullptr;
04963   case Intrinsic::log:
04964     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04965     return nullptr;
04966   case Intrinsic::log2:
04967     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04968     return nullptr;
04969   case Intrinsic::log10:
04970     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04971     return nullptr;
04972   case Intrinsic::exp:
04973     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04974     return nullptr;
04975   case Intrinsic::exp2:
04976     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04977     return nullptr;
04978   case Intrinsic::pow:
04979     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
04980                            getValue(I.getArgOperand(1)), DAG, TLI));
04981     return nullptr;
04982   case Intrinsic::sqrt:
04983   case Intrinsic::fabs:
04984   case Intrinsic::sin:
04985   case Intrinsic::cos:
04986   case Intrinsic::floor:
04987   case Intrinsic::ceil:
04988   case Intrinsic::trunc:
04989   case Intrinsic::rint:
04990   case Intrinsic::nearbyint:
04991   case Intrinsic::round: {
04992     unsigned Opcode;
04993     switch (Intrinsic) {
04994     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04995     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
04996     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
04997     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
04998     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
04999     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
05000     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
05001     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
05002     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
05003     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
05004     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
05005     }
05006 
05007     setValue(&I, DAG.getNode(Opcode, sdl,
05008                              getValue(I.getArgOperand(0)).getValueType(),
05009                              getValue(I.getArgOperand(0))));
05010     return nullptr;
05011   }
05012   case Intrinsic::minnum:
05013     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
05014                              getValue(I.getArgOperand(0)).getValueType(),
05015                              getValue(I.getArgOperand(0)),
05016                              getValue(I.getArgOperand(1))));
05017     return nullptr;
05018   case Intrinsic::maxnum:
05019     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
05020                              getValue(I.getArgOperand(0)).getValueType(),
05021                              getValue(I.getArgOperand(0)),
05022                              getValue(I.getArgOperand(1))));
05023     return nullptr;
05024   case Intrinsic::copysign:
05025     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
05026                              getValue(I.getArgOperand(0)).getValueType(),
05027                              getValue(I.getArgOperand(0)),
05028                              getValue(I.getArgOperand(1))));
05029     return nullptr;
05030   case Intrinsic::fma:
05031     setValue(&I, DAG.getNode(ISD::FMA, sdl,
05032                              getValue(I.getArgOperand(0)).getValueType(),
05033                              getValue(I.getArgOperand(0)),
05034                              getValue(I.getArgOperand(1)),
05035                              getValue(I.getArgOperand(2))));
05036     return nullptr;
05037   case Intrinsic::fmuladd: {
05038     EVT VT = TLI.getValueType(I.getType());
05039     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
05040         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
05041       setValue(&I, DAG.getNode(ISD::FMA, sdl,
05042                                getValue(I.getArgOperand(0)).getValueType(),
05043                                getValue(I.getArgOperand(0)),
05044                                getValue(I.getArgOperand(1)),
05045                                getValue(I.getArgOperand(2))));
05046     } else {
05047       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
05048                                 getValue(I.getArgOperand(0)).getValueType(),
05049                                 getValue(I.getArgOperand(0)),
05050                                 getValue(I.getArgOperand(1)));
05051       SDValue Add = DAG.getNode(ISD::FADD, sdl,
05052                                 getValue(I.getArgOperand(0)).getValueType(),
05053                                 Mul,
05054                                 getValue(I.getArgOperand(2)));
05055       setValue(&I, Add);
05056     }
05057     return nullptr;
05058   }
05059   case Intrinsic::convert_to_fp16:
05060     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
05061                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
05062                                          getValue(I.getArgOperand(0)),
05063                                          DAG.getTargetConstant(0, MVT::i32))));
05064     return nullptr;
05065   case Intrinsic::convert_from_fp16:
05066     setValue(&I,
05067              DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
05068                          DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
05069                                      getValue(I.getArgOperand(0)))));
05070     return nullptr;
05071   case Intrinsic::pcmarker: {
05072     SDValue Tmp = getValue(I.getArgOperand(0));
05073     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
05074     return nullptr;
05075   }
05076   case Intrinsic::readcyclecounter: {
05077     SDValue Op = getRoot();
05078     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
05079                       DAG.getVTList(MVT::i64, MVT::Other), Op);
05080     setValue(&I, Res);
05081     DAG.setRoot(Res.getValue(1));
05082     return nullptr;
05083   }
05084   case Intrinsic::bswap:
05085     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
05086                              getValue(I.getArgOperand(0)).getValueType(),
05087                              getValue(I.getArgOperand(0))));
05088     return nullptr;
05089   case Intrinsic::cttz: {
05090     SDValue Arg = getValue(I.getArgOperand(0));
05091     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
05092     EVT Ty = Arg.getValueType();
05093     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
05094                              sdl, Ty, Arg));
05095     return nullptr;
05096   }
05097   case Intrinsic::ctlz: {
05098     SDValue Arg = getValue(I.getArgOperand(0));
05099     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
05100     EVT Ty = Arg.getValueType();
05101     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
05102                              sdl, Ty, Arg));
05103     return nullptr;
05104   }
05105   case Intrinsic::ctpop: {
05106     SDValue Arg = getValue(I.getArgOperand(0));
05107     EVT Ty = Arg.getValueType();
05108     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
05109     return nullptr;
05110   }
05111   case Intrinsic::stacksave: {
05112     SDValue Op = getRoot();
05113     Res = DAG.getNode(ISD::STACKSAVE, sdl,
05114                       DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
05115     setValue(&I, Res);
05116     DAG.setRoot(Res.getValue(1));
05117     return nullptr;
05118   }
05119   case Intrinsic::stackrestore: {
05120     Res = getValue(I.getArgOperand(0));
05121     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
05122     return nullptr;
05123   }
05124   case Intrinsic::stackprotector: {
05125     // Emit code into the DAG to store the stack guard onto the stack.
05126     MachineFunction &MF = DAG.getMachineFunction();
05127     MachineFrameInfo *MFI = MF.getFrameInfo();
05128     EVT PtrTy = TLI.getPointerTy();
05129     SDValue Src, Chain = getRoot();
05130     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
05131     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
05132 
05133     // See if Ptr is a bitcast. If it is, look through it and see if we can get
05134     // global variable __stack_chk_guard.
05135     if (!GV)
05136       if (const Operator *BC = dyn_cast<Operator>(Ptr))
05137         if (BC->getOpcode() == Instruction::BitCast)
05138           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
05139 
05140     if (GV && TLI.useLoadStackGuardNode()) {
05141       // Emit a LOAD_STACK_GUARD node.
05142       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
05143                                                sdl, PtrTy, Chain);
05144       MachinePointerInfo MPInfo(GV);
05145       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
05146       unsigned Flags = MachineMemOperand::MOLoad |
05147                        MachineMemOperand::MOInvariant;
05148       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
05149                                          PtrTy.getSizeInBits() / 8,
05150                                          DAG.getEVTAlignment(PtrTy));
05151       Node->setMemRefs(MemRefs, MemRefs + 1);
05152 
05153       // Copy the guard value to a virtual register so that it can be
05154       // retrieved in the epilogue.
05155       Src = SDValue(Node, 0);
05156       const TargetRegisterClass *RC =
05157           TLI.getRegClassFor(Src.getSimpleValueType());
05158       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
05159 
05160       SPDescriptor.setGuardReg(Reg);
05161       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
05162     } else {
05163       Src = getValue(I.getArgOperand(0));   // The guard's value.
05164     }
05165 
05166     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
05167 
05168     int FI = FuncInfo.StaticAllocaMap[Slot];
05169     MFI->setStackProtectorIndex(FI);
05170 
05171     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
05172 
05173     // Store the stack protector onto the stack.
05174     Res = DAG.getStore(Chain, sdl, Src, FIN,
05175                        MachinePointerInfo::getFixedStack(FI),
05176                        true, false, 0);
05177     setValue(&I, Res);
05178     DAG.setRoot(Res);
05179     return nullptr;
05180   }
05181   case Intrinsic::objectsize: {
05182     // If we don't know by now, we're never going to know.
05183     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
05184 
05185     assert(CI && "Non-constant type in __builtin_object_size?");
05186 
05187     SDValue Arg = getValue(I.getCalledValue());
05188     EVT Ty = Arg.getValueType();
05189 
05190     if (CI->isZero())
05191       Res = DAG.getConstant(-1ULL, Ty);
05192     else
05193       Res = DAG.getConstant(0, Ty);
05194 
05195     setValue(&I, Res);
05196     return nullptr;
05197   }
05198   case Intrinsic::annotation:
05199   case Intrinsic::ptr_annotation:
05200     // Drop the intrinsic, but forward the value
05201     setValue(&I, getValue(I.getOperand(0)));
05202     return nullptr;
05203   case Intrinsic::assume:
05204   case Intrinsic::var_annotation:
05205     // Discard annotate attributes and assumptions
05206     return nullptr;
05207 
05208   case Intrinsic::init_trampoline: {
05209     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
05210 
05211     SDValue Ops[6];
05212     Ops[0] = getRoot();
05213     Ops[1] = getValue(I.getArgOperand(0));
05214     Ops[2] = getValue(I.getArgOperand(1));
05215     Ops[3] = getValue(I.getArgOperand(2));
05216     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
05217     Ops[5] = DAG.getSrcValue(F);
05218 
05219     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
05220 
05221     DAG.setRoot(Res);
05222     return nullptr;
05223   }
05224   case Intrinsic::adjust_trampoline: {
05225     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
05226                              TLI.getPointerTy(),
05227                              getValue(I.getArgOperand(0))));
05228     return nullptr;
05229   }
05230   case Intrinsic::gcroot:
05231     if (GFI) {
05232       const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
05233       const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
05234 
05235       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
05236       GFI->addStackRoot(FI->getIndex(), TypeMap);
05237     }
05238     return nullptr;
05239   case Intrinsic::gcread:
05240   case Intrinsic::gcwrite:
05241     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
05242   case Intrinsic::flt_rounds:
05243     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
05244     return nullptr;
05245 
05246   case Intrinsic::expect: {
05247     // Just replace __builtin_expect(exp, c) with EXP.
05248     setValue(&I, getValue(I.getArgOperand(0)));
05249     return nullptr;
05250   }
05251 
05252   case Intrinsic::debugtrap:
05253   case Intrinsic::trap: {
05254     StringRef TrapFuncName = TM.Options.getTrapFunctionName();
05255     if (TrapFuncName.empty()) {
05256       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
05257         ISD::TRAP : ISD::DEBUGTRAP;
05258       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
05259       return nullptr;
05260     }
05261     TargetLowering::ArgListTy Args;
05262 
05263     TargetLowering::CallLoweringInfo CLI(DAG);
05264     CLI.setDebugLoc(sdl).setChain(getRoot())
05265       .setCallee(CallingConv::C, I.getType(),
05266                  DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
05267                  std::move(Args), 0);
05268 
05269     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
05270     DAG.setRoot(Result.second);
05271     return nullptr;
05272   }
05273 
05274   case Intrinsic::uadd_with_overflow:
05275   case Intrinsic::sadd_with_overflow:
05276   case Intrinsic::usub_with_overflow:
05277   case Intrinsic::ssub_with_overflow:
05278   case Intrinsic::umul_with_overflow:
05279   case Intrinsic::smul_with_overflow: {
05280     ISD::NodeType Op;
05281     switch (Intrinsic) {
05282     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
05283     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
05284     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
05285     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
05286     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
05287     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
05288     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
05289     }
05290     SDValue Op1 = getValue(I.getArgOperand(0));
05291     SDValue Op2 = getValue(I.getArgOperand(1));
05292 
05293     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
05294     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
05295     return nullptr;
05296   }
05297   case Intrinsic::prefetch: {
05298     SDValue Ops[5];
05299     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
05300     Ops[0] = getRoot();
05301     Ops[1] = getValue(I.getArgOperand(0));
05302     Ops[2] = getValue(I.getArgOperand(1));
05303     Ops[3] = getValue(I.getArgOperand(2));
05304     Ops[4] = getValue(I.getArgOperand(3));
05305     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
05306                                         DAG.getVTList(MVT::Other), Ops,
05307                                         EVT::getIntegerVT(*Context, 8),
05308                                         MachinePointerInfo(I.getArgOperand(0)),
05309                                         0, /* align */
05310                                         false, /* volatile */
05311                                         rw==0, /* read */
05312                                         rw==1)); /* write */
05313     return nullptr;
05314   }
05315   case Intrinsic::lifetime_start:
05316   case Intrinsic::lifetime_end: {
05317     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
05318     // Stack coloring is not enabled in O0, discard region information.
05319     if (TM.getOptLevel() == CodeGenOpt::None)
05320       return nullptr;
05321 
05322     SmallVector<Value *, 4> Allocas;
05323     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
05324 
05325     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
05326            E = Allocas.end(); Object != E; ++Object) {
05327       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
05328 
05329       // Could not find an Alloca.
05330       if (!LifetimeObject)
05331         continue;
05332 
05333       // First check that the Alloca is static, otherwise it won't have a
05334       // valid frame index.
05335       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
05336       if (SI == FuncInfo.StaticAllocaMap.end())
05337         return nullptr;
05338 
05339       int FI = SI->second;
05340 
05341       SDValue Ops[2];
05342       Ops[0] = getRoot();
05343       Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
05344       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
05345 
05346       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
05347       DAG.setRoot(Res);
05348     }
05349     return nullptr;
05350   }
05351   case Intrinsic::invariant_start:
05352     // Discard region information.
05353     setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
05354     return nullptr;
05355   case Intrinsic::invariant_end:
05356     // Discard region information.
05357     return nullptr;
05358   case Intrinsic::stackprotectorcheck: {
05359     // Do not actually emit anything for this basic block. Instead we initialize
05360     // the stack protector descriptor and export the guard variable so we can
05361     // access it in FinishBasicBlock.
05362     const BasicBlock *BB = I.getParent();
05363     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
05364     ExportFromCurrentBlock(SPDescriptor.getGuard());
05365 
05366     // Flush our exports since we are going to process a terminator.
05367     (void)getControlRoot();
05368     return nullptr;
05369   }
05370   case Intrinsic::clear_cache:
05371     return TLI.getClearCacheBuiltinName();
05372   case Intrinsic::eh_actions:
05373     setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
05374     return nullptr;
05375   case Intrinsic::donothing:
05376     // ignore
05377     return nullptr;
05378   case Intrinsic::experimental_stackmap: {
05379     visitStackmap(I);
05380     return nullptr;
05381   }
05382   case Intrinsic::experimental_patchpoint_void:
05383   case Intrinsic::experimental_patchpoint_i64: {
05384     visitPatchpoint(&I);
05385     return nullptr;
05386   }
05387   case Intrinsic::experimental_gc_statepoint: {
05388     visitStatepoint(I);
05389     return nullptr;
05390   }
05391   case Intrinsic::experimental_gc_result_int:
05392   case Intrinsic::experimental_gc_result_float:
05393   case Intrinsic::experimental_gc_result_ptr:
05394   case Intrinsic::experimental_gc_result: {
05395     visitGCResult(I);
05396     return nullptr;
05397   }
05398   case Intrinsic::experimental_gc_relocate: {
05399     visitGCRelocate(I);
05400     return nullptr;
05401   }
05402   case Intrinsic::instrprof_increment:
05403     llvm_unreachable("instrprof failed to lower an increment");
05404 
05405   case Intrinsic::frameescape: {
05406     MachineFunction &MF = DAG.getMachineFunction();
05407     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
05408 
05409     // Directly emit some FRAME_ALLOC machine instrs. Label assignment emission
05410     // is the same on all targets.
05411     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
05412       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
05413       if (isa<ConstantPointerNull>(Arg))
05414         continue; // Skip null pointers. They represent a hole in index space.
05415       AllocaInst *Slot = cast<AllocaInst>(Arg);
05416       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
05417              "can only escape static allocas");
05418       int FI = FuncInfo.StaticAllocaMap[Slot];
05419       MCSymbol *FrameAllocSym =
05420           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
05421               GlobalValue::getRealLinkageName(MF.getName()), Idx);
05422       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
05423               TII->get(TargetOpcode::FRAME_ALLOC))
05424           .addSym(FrameAllocSym)
05425           .addFrameIndex(FI);
05426     }
05427 
05428     return nullptr;
05429   }
05430 
05431   case Intrinsic::framerecover: {
05432     // i8* @llvm.framerecover(i8* %fn, i8* %fp, i32 %idx)
05433     MachineFunction &MF = DAG.getMachineFunction();
05434     MVT PtrVT = TLI.getPointerTy(0);
05435 
05436     // Get the symbol that defines the frame offset.
05437     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
05438     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
05439     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
05440     MCSymbol *FrameAllocSym =
05441         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
05442             GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
05443 
05444     // Create a TargetExternalSymbol for the label to avoid any target lowering
05445     // that would make this PC relative.
05446     StringRef Name = FrameAllocSym->getName();
05447     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
05448     SDValue OffsetSym = DAG.getTargetExternalSymbol(Name.data(), PtrVT);
05449     SDValue OffsetVal =
05450         DAG.getNode(ISD::FRAME_ALLOC_RECOVER, sdl, PtrVT, OffsetSym);
05451 
05452     // Add the offset to the FP.
05453     Value *FP = I.getArgOperand(1);
05454     SDValue FPVal = getValue(FP);
05455     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
05456     setValue(&I, Add);
05457 
05458     return nullptr;
05459   }
05460   case Intrinsic::eh_begincatch:
05461   case Intrinsic::eh_endcatch:
05462     llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
05463   }
05464 }
05465 
05466 std::pair<SDValue, SDValue>
05467 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
05468                                     MachineBasicBlock *LandingPad) {
05469   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
05470   MCSymbol *BeginLabel = nullptr;
05471 
05472   if (LandingPad) {
05473     // Insert a label before the invoke call to mark the try range.  This can be
05474     // used to detect deletion of the invoke via the MachineModuleInfo.
05475     BeginLabel = MMI.getContext().CreateTempSymbol();
05476 
05477     // For SjLj, keep track of which landing pads go with which invokes
05478     // so as to maintain the ordering of pads in the LSDA.
05479     unsigned CallSiteIndex = MMI.getCurrentCallSite();
05480     if (CallSiteIndex) {
05481       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
05482       LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
05483 
05484       // Now that the call site is handled, stop tracking it.
05485       MMI.setCurrentCallSite(0);
05486     }
05487 
05488     // Both PendingLoads and PendingExports must be flushed here;
05489     // this call might not return.
05490     (void)getRoot();
05491     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
05492 
05493     CLI.setChain(getRoot());
05494   }
05495   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
05496   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
05497 
05498   assert((CLI.IsTailCall || Result.second.getNode()) &&
05499          "Non-null chain expected with non-tail call!");
05500   assert((Result.second.getNode() || !Result.first.getNode()) &&
05501          "Null value expected with tail call!");
05502 
05503   if (!Result.second.getNode()) {
05504     // As a special case, a null chain means that a tail call has been emitted
05505     // and the DAG root is already updated.
05506     HasTailCall = true;
05507 
05508     // Since there's no actual continuation from this block, nothing can be
05509     // relying on us setting vregs for them.
05510     PendingExports.clear();
05511   } else {
05512     DAG.setRoot(Result.second);
05513   }
05514 
05515   if (LandingPad) {
05516     // Insert a label at the end of the invoke call to mark the try range.  This
05517     // can be used to detect deletion of the invoke via the MachineModuleInfo.
05518     MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
05519     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
05520 
05521     // Inform MachineModuleInfo of range.
05522     MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
05523   }
05524 
05525   return Result;
05526 }
05527 
05528 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
05529                                       bool isTailCall,
05530                                       MachineBasicBlock *LandingPad) {
05531   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
05532   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
05533   Type *RetTy = FTy->getReturnType();
05534 
05535   TargetLowering::ArgListTy Args;
05536   TargetLowering::ArgListEntry Entry;
05537   Args.reserve(CS.arg_size());
05538 
05539   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
05540        i != e; ++i) {
05541     const Value *V = *i;
05542 
05543     // Skip empty types
05544     if (V->getType()->isEmptyTy())
05545       continue;
05546 
05547     SDValue ArgNode = getValue(V);
05548     Entry.Node = ArgNode; Entry.Ty = V->getType();
05549 
05550     // Skip the first return-type Attribute to get to params.
05551     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
05552     Args.push_back(Entry);
05553 
05554     // If we have an explicit sret argument that is an Instruction, (i.e., it
05555     // might point to function-local memory), we can't meaningfully tail-call.
05556     if (Entry.isSRet && isa<Instruction>(V))
05557       isTailCall = false;
05558   }
05559 
05560   // Check if target-independent constraints permit a tail call here.
05561   // Target-dependent constraints are checked within TLI->LowerCallTo.
05562   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
05563     isTailCall = false;
05564 
05565   TargetLowering::CallLoweringInfo CLI(DAG);
05566   CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
05567     .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
05568     .setTailCall(isTailCall);
05569   std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
05570 
05571   if (Result.first.getNode())
05572     setValue(CS.getInstruction(), Result.first);
05573 }
05574 
05575 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
05576 /// value is equal or not-equal to zero.
05577 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
05578   for (const User *U : V->users()) {
05579     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
05580       if (IC->isEquality())
05581         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
05582           if (C->isNullValue())
05583             continue;
05584     // Unknown instruction.
05585     return false;
05586   }
05587   return true;
05588 }
05589 
05590 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
05591                              Type *LoadTy,
05592                              SelectionDAGBuilder &Builder) {
05593 
05594   // Check to see if this load can be trivially constant folded, e.g. if the
05595   // input is from a string literal.
05596   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
05597     // Cast pointer to the type we really want to load.
05598     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
05599                                          PointerType::getUnqual(LoadTy));
05600 
05601     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
05602             const_cast<Constant *>(LoadInput), *Builder.DL))
05603       return Builder.getValue(LoadCst);
05604   }
05605 
05606   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
05607   // still constant memory, the input chain can be the entry node.
05608   SDValue Root;
05609   bool ConstantMemory = false;
05610 
05611   // Do not serialize (non-volatile) loads of constant memory with anything.
05612   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
05613     Root = Builder.DAG.getEntryNode();
05614     ConstantMemory = true;
05615   } else {
05616     // Do not serialize non-volatile loads against each other.
05617     Root = Builder.DAG.getRoot();
05618   }
05619 
05620   SDValue Ptr = Builder.getValue(PtrVal);
05621   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
05622                                         Ptr, MachinePointerInfo(PtrVal),
05623                                         false /*volatile*/,
05624                                         false /*nontemporal*/,
05625                                         false /*isinvariant*/, 1 /* align=1 */);
05626 
05627   if (!ConstantMemory)
05628     Builder.PendingLoads.push_back(LoadVal.getValue(1));
05629   return LoadVal;
05630 }
05631 
05632 /// processIntegerCallValue - Record the value for an instruction that
05633 /// produces an integer result, converting the type where necessary.
05634 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
05635                                                   SDValue Value,
05636                                                   bool IsSigned) {
05637   EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
05638   if (IsSigned)
05639     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
05640   else
05641     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
05642   setValue(&I, Value);
05643 }
05644 
05645 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
05646 /// If so, return true and lower it, otherwise return false and it will be
05647 /// lowered like a normal call.
05648 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
05649   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
05650   if (I.getNumArgOperands() != 3)
05651     return false;
05652 
05653   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
05654   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
05655       !I.getArgOperand(2)->getType()->isIntegerTy() ||
05656       !I.getType()->isIntegerTy())
05657     return false;
05658 
05659   const Value *Size = I.getArgOperand(2);
05660   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
05661   if (CSize && CSize->getZExtValue() == 0) {
05662     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
05663     setValue(&I, DAG.getConstant(0, CallVT));
05664     return true;
05665   }
05666 
05667   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05668   std::pair<SDValue, SDValue> Res =
05669     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
05670                                 getValue(LHS), getValue(RHS), getValue(Size),
05671                                 MachinePointerInfo(LHS),
05672                                 MachinePointerInfo(RHS));
05673   if (Res.first.getNode()) {
05674     processIntegerCallValue(I, Res.first, true);
05675     PendingLoads.push_back(Res.second);
05676     return true;
05677   }
05678 
05679   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
05680   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
05681   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
05682     bool ActuallyDoIt = true;
05683     MVT LoadVT;
05684     Type *LoadTy;
05685     switch (CSize->getZExtValue()) {
05686     default:
05687       LoadVT = MVT::Other;
05688       LoadTy = nullptr;
05689       ActuallyDoIt = false;
05690       break;
05691     case 2:
05692       LoadVT = MVT::i16;
05693       LoadTy = Type::getInt16Ty(CSize->getContext());
05694       break;
05695     case 4:
05696       LoadVT = MVT::i32;
05697       LoadTy = Type::getInt32Ty(CSize->getContext());
05698       break;
05699     case 8:
05700       LoadVT = MVT::i64;
05701       LoadTy = Type::getInt64Ty(CSize->getContext());
05702       break;
05703         /*
05704     case 16:
05705       LoadVT = MVT::v4i32;
05706       LoadTy = Type::getInt32Ty(CSize->getContext());
05707       LoadTy = VectorType::get(LoadTy, 4);
05708       break;
05709          */
05710     }
05711 
05712     // This turns into unaligned loads.  We only do this if the target natively
05713     // supports the MVT we'll be loading or if it is small enough (<= 4) that
05714     // we'll only produce a small number of byte loads.
05715 
05716     // Require that we can find a legal MVT, and only do this if the target
05717     // supports unaligned loads of that type.  Expanding into byte loads would
05718     // bloat the code.
05719     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
05720     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
05721       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
05722       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
05723       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
05724       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
05725       // TODO: Check alignment of src and dest ptrs.
05726       if (!TLI.isTypeLegal(LoadVT) ||
05727           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
05728           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
05729         ActuallyDoIt = false;
05730     }
05731 
05732     if (ActuallyDoIt) {
05733       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
05734       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
05735 
05736       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
05737                                  ISD::SETNE);
05738       processIntegerCallValue(I, Res, false);
05739       return true;
05740     }
05741   }
05742 
05743 
05744   return false;
05745 }
05746 
05747 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
05748 /// form.  If so, return true and lower it, otherwise return false and it
05749 /// will be lowered like a normal call.
05750 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
05751   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
05752   if (I.getNumArgOperands() != 3)
05753     return false;
05754 
05755   const Value *Src = I.getArgOperand(0);
05756   const Value *Char = I.getArgOperand(1);
05757   const Value *Length = I.getArgOperand(2);
05758   if (!Src->getType()->isPointerTy() ||
05759       !Char->getType()->isIntegerTy() ||
05760       !Length->getType()->isIntegerTy() ||
05761       !I.getType()->isPointerTy())
05762     return false;
05763 
05764   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05765   std::pair<SDValue, SDValue> Res =
05766     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
05767                                 getValue(Src), getValue(Char), getValue(Length),
05768                                 MachinePointerInfo(Src));
05769   if (Res.first.getNode()) {
05770     setValue(&I, Res.first);
05771     PendingLoads.push_back(Res.second);
05772     return true;
05773   }
05774 
05775   return false;
05776 }
05777 
05778 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
05779 /// optimized form.  If so, return true and lower it, otherwise return false
05780 /// and it will be lowered like a normal call.
05781 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
05782   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
05783   if (I.getNumArgOperands() != 2)
05784     return false;
05785 
05786   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05787   if (!Arg0->getType()->isPointerTy() ||
05788       !Arg1->getType()->isPointerTy() ||
05789       !I.getType()->isPointerTy())
05790     return false;
05791 
05792   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05793   std::pair<SDValue, SDValue> Res =
05794     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
05795                                 getValue(Arg0), getValue(Arg1),
05796                                 MachinePointerInfo(Arg0),
05797                                 MachinePointerInfo(Arg1), isStpcpy);
05798   if (Res.first.getNode()) {
05799     setValue(&I, Res.first);
05800     DAG.setRoot(Res.second);
05801     return true;
05802   }
05803 
05804   return false;
05805 }
05806 
05807 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
05808 /// If so, return true and lower it, otherwise return false and it will be
05809 /// lowered like a normal call.
05810 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
05811   // Verify that the prototype makes sense.  int strcmp(void*,void*)
05812   if (I.getNumArgOperands() != 2)
05813     return false;
05814 
05815   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05816   if (!Arg0->getType()->isPointerTy() ||
05817       !Arg1->getType()->isPointerTy() ||
05818       !I.getType()->isIntegerTy())
05819     return false;
05820 
05821   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05822   std::pair<SDValue, SDValue> Res =
05823     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
05824                                 getValue(Arg0), getValue(Arg1),
05825                                 MachinePointerInfo(Arg0),
05826                                 MachinePointerInfo(Arg1));
05827   if (Res.first.getNode()) {
05828     processIntegerCallValue(I, Res.first, true);
05829     PendingLoads.push_back(Res.second);
05830     return true;
05831   }
05832 
05833   return false;
05834 }
05835 
05836 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
05837 /// form.  If so, return true and lower it, otherwise return false and it
05838 /// will be lowered like a normal call.
05839 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
05840   // Verify that the prototype makes sense.  size_t strlen(char *)
05841   if (I.getNumArgOperands() != 1)
05842     return false;
05843 
05844   const Value *Arg0 = I.getArgOperand(0);
05845   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
05846     return false;
05847 
05848   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05849   std::pair<SDValue, SDValue> Res =
05850     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
05851                                 getValue(Arg0), MachinePointerInfo(Arg0));
05852   if (Res.first.getNode()) {
05853     processIntegerCallValue(I, Res.first, false);
05854     PendingLoads.push_back(Res.second);
05855     return true;
05856   }
05857 
05858   return false;
05859 }
05860 
05861 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
05862 /// form.  If so, return true and lower it, otherwise return false and it
05863 /// will be lowered like a normal call.
05864 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
05865   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
05866   if (I.getNumArgOperands() != 2)
05867     return false;
05868 
05869   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05870   if (!Arg0->getType()->isPointerTy() ||
05871       !Arg1->getType()->isIntegerTy() ||
05872       !I.getType()->isIntegerTy())
05873     return false;
05874 
05875   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05876   std::pair<SDValue, SDValue> Res =
05877     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
05878                                  getValue(Arg0), getValue(Arg1),
05879                                  MachinePointerInfo(Arg0));
05880   if (Res.first.getNode()) {
05881     processIntegerCallValue(I, Res.first, false);
05882     PendingLoads.push_back(Res.second);
05883     return true;
05884   }
05885 
05886   return false;
05887 }
05888 
05889 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
05890 /// operation (as expected), translate it to an SDNode with the specified opcode
05891 /// and return true.
05892 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
05893                                               unsigned Opcode) {
05894   // Sanity check that it really is a unary floating-point call.
05895   if (I.getNumArgOperands() != 1 ||
05896       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
05897       I.getType() != I.getArgOperand(0)->getType() ||
05898       !I.onlyReadsMemory())
05899     return false;
05900 
05901   SDValue Tmp = getValue(I.getArgOperand(0));
05902   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
05903   return true;
05904 }
05905 
05906 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
05907 /// operation (as expected), translate it to an SDNode with the specified opcode
05908 /// and return true.
05909 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
05910                                                unsigned Opcode) {
05911   // Sanity check that it really is a binary floating-point call.
05912   if (I.getNumArgOperands() != 2 ||
05913       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
05914       I.getType() != I.getArgOperand(0)->getType() ||
05915       I.getType() != I.getArgOperand(1)->getType() ||
05916       !I.onlyReadsMemory())
05917     return false;
05918 
05919   SDValue Tmp0 = getValue(I.getArgOperand(0));
05920   SDValue Tmp1 = getValue(I.getArgOperand(1));
05921   EVT VT = Tmp0.getValueType();
05922   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
05923   return true;
05924 }
05925 
05926 void SelectionDAGBuilder::visitCall(const CallInst &I) {
05927   // Handle inline assembly differently.
05928   if (isa<InlineAsm>(I.getCalledValue())) {
05929     visitInlineAsm(&I);
05930     return;
05931   }
05932 
05933   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
05934   ComputeUsesVAFloatArgument(I, &MMI);
05935 
05936   const char *RenameFn = nullptr;
05937   if (Function *F = I.getCalledFunction()) {
05938     if (F->isDeclaration()) {
05939       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
05940         if (unsigned IID = II->getIntrinsicID(F)) {
05941           RenameFn = visitIntrinsicCall(I, IID);
05942           if (!RenameFn)
05943             return;
05944         }
05945       }
05946       if (unsigned IID = F->getIntrinsicID()) {
05947         RenameFn = visitIntrinsicCall(I, IID);
05948         if (!RenameFn)
05949           return;
05950       }
05951     }
05952 
05953     // Check for well-known libc/libm calls.  If the function is internal, it
05954     // can't be a library call.
05955     LibFunc::Func Func;
05956     if (!F->hasLocalLinkage() && F->hasName() &&
05957         LibInfo->getLibFunc(F->getName(), Func) &&
05958         LibInfo->hasOptimizedCodeGen(Func)) {
05959       switch (Func) {
05960       default: break;
05961       case LibFunc::copysign:
05962       case LibFunc::copysignf:
05963       case LibFunc::copysignl:
05964         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
05965             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
05966             I.getType() == I.getArgOperand(0)->getType() &&
05967             I.getType() == I.getArgOperand(1)->getType() &&
05968             I.onlyReadsMemory()) {
05969           SDValue LHS = getValue(I.getArgOperand(0));
05970           SDValue RHS = getValue(I.getArgOperand(1));
05971           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
05972                                    LHS.getValueType(), LHS, RHS));
05973           return;
05974         }
05975         break;
05976       case LibFunc::fabs:
05977       case LibFunc::fabsf:
05978       case LibFunc::fabsl:
05979         if (visitUnaryFloatCall(I, ISD::FABS))
05980           return;
05981         break;
05982       case LibFunc::fmin:
05983       case LibFunc::fminf:
05984       case LibFunc::fminl:
05985         if (visitBinaryFloatCall(I, ISD::FMINNUM))
05986           return;
05987         break;
05988       case LibFunc::fmax:
05989       case LibFunc::fmaxf:
05990       case LibFunc::fmaxl:
05991         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
05992           return;
05993         break;
05994       case LibFunc::sin:
05995       case LibFunc::sinf:
05996       case LibFunc::sinl:
05997         if (visitUnaryFloatCall(I, ISD::FSIN))
05998           return;
05999         break;
06000       case LibFunc::cos:
06001       case LibFunc::cosf:
06002       case LibFunc::cosl:
06003         if (visitUnaryFloatCall(I, ISD::FCOS))
06004           return;
06005         break;
06006       case LibFunc::sqrt:
06007       case LibFunc::sqrtf:
06008       case LibFunc::sqrtl:
06009       case LibFunc::sqrt_finite:
06010       case LibFunc::sqrtf_finite:
06011       case LibFunc::sqrtl_finite:
06012         if (visitUnaryFloatCall(I, ISD::FSQRT))
06013           return;
06014         break;
06015       case LibFunc::floor:
06016       case LibFunc::floorf:
06017       case LibFunc::floorl:
06018         if (visitUnaryFloatCall(I, ISD::FFLOOR))
06019           return;
06020         break;
06021       case LibFunc::nearbyint:
06022       case LibFunc::nearbyintf:
06023       case LibFunc::nearbyintl:
06024         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
06025           return;
06026         break;
06027       case LibFunc::ceil:
06028       case LibFunc::ceilf:
06029       case LibFunc::ceill:
06030         if (visitUnaryFloatCall(I, ISD::FCEIL))
06031           return;
06032         break;
06033       case LibFunc::rint:
06034       case LibFunc::rintf:
06035       case LibFunc::rintl:
06036         if (visitUnaryFloatCall(I, ISD::FRINT))
06037           return;
06038         break;
06039       case LibFunc::round:
06040       case LibFunc::roundf:
06041       case LibFunc::roundl:
06042         if (visitUnaryFloatCall(I, ISD::FROUND))
06043           return;
06044         break;
06045       case LibFunc::trunc:
06046       case LibFunc::truncf:
06047       case LibFunc::truncl:
06048         if (visitUnaryFloatCall(I, ISD::FTRUNC))
06049           return;
06050         break;
06051       case LibFunc::log2:
06052       case LibFunc::log2f:
06053       case LibFunc::log2l:
06054         if (visitUnaryFloatCall(I, ISD::FLOG2))
06055           return;
06056         break;
06057       case LibFunc::exp2:
06058       case LibFunc::exp2f:
06059       case LibFunc::exp2l:
06060         if (visitUnaryFloatCall(I, ISD::FEXP2))
06061           return;
06062         break;
06063       case LibFunc::memcmp:
06064         if (visitMemCmpCall(I))
06065           return;
06066         break;
06067       case LibFunc::memchr:
06068         if (visitMemChrCall(I))
06069           return;
06070         break;
06071       case LibFunc::strcpy:
06072         if (visitStrCpyCall(I, false))
06073           return;
06074         break;
06075       case LibFunc::stpcpy:
06076         if (visitStrCpyCall(I, true))
06077           return;
06078         break;
06079       case LibFunc::strcmp:
06080         if (visitStrCmpCall(I))
06081           return;
06082         break;
06083       case LibFunc::strlen:
06084         if (visitStrLenCall(I))
06085           return;
06086         break;
06087       case LibFunc::strnlen:
06088         if (visitStrNLenCall(I))
06089           return;
06090         break;
06091       }
06092     }
06093   }
06094 
06095   SDValue Callee;
06096   if (!RenameFn)
06097     Callee = getValue(I.getCalledValue());
06098   else
06099     Callee = DAG.getExternalSymbol(RenameFn,
06100                                    DAG.getTargetLoweringInfo().getPointerTy());
06101 
06102   // Check if we can potentially perform a tail call. More detailed checking is
06103   // be done within LowerCallTo, after more information about the call is known.
06104   LowerCallTo(&I, Callee, I.isTailCall());
06105 }
06106 
06107 namespace {
06108 
06109 /// AsmOperandInfo - This contains information for each constraint that we are
06110 /// lowering.
06111 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
06112 public:
06113   /// CallOperand - If this is the result output operand or a clobber
06114   /// this is null, otherwise it is the incoming operand to the CallInst.
06115   /// This gets modified as the asm is processed.
06116   SDValue CallOperand;
06117 
06118   /// AssignedRegs - If this is a register or register class operand, this
06119   /// contains the set of register corresponding to the operand.
06120   RegsForValue AssignedRegs;
06121 
06122   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
06123     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
06124   }
06125 
06126   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
06127   /// corresponds to.  If there is no Value* for this operand, it returns
06128   /// MVT::Other.
06129   EVT getCallOperandValEVT(LLVMContext &Context,
06130                            const TargetLowering &TLI,
06131                            const DataLayout *DL) const {
06132     if (!CallOperandVal) return MVT::Other;
06133 
06134     if (isa<BasicBlock>(CallOperandVal))
06135       return TLI.getPointerTy();
06136 
06137     llvm::Type *OpTy = CallOperandVal->getType();
06138 
06139     // FIXME: code duplicated from TargetLowering::ParseConstraints().
06140     // If this is an indirect operand, the operand is a pointer to the
06141     // accessed type.
06142     if (isIndirect) {
06143       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
06144       if (!PtrTy)
06145         report_fatal_error("Indirect operand for inline asm not a pointer!");
06146       OpTy = PtrTy->getElementType();
06147     }
06148 
06149     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
06150     if (StructType *STy = dyn_cast<StructType>(OpTy))
06151       if (STy->getNumElements() == 1)
06152         OpTy = STy->getElementType(0);
06153 
06154     // If OpTy is not a single value, it may be a struct/union that we
06155     // can tile with integers.
06156     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
06157       unsigned BitSize = DL->getTypeSizeInBits(OpTy);
06158       switch (BitSize) {
06159       default: break;
06160       case 1:
06161       case 8:
06162       case 16:
06163       case 32:
06164       case 64:
06165       case 128:
06166         OpTy = IntegerType::get(Context, BitSize);
06167         break;
06168       }
06169     }
06170 
06171     return TLI.getValueType(OpTy, true);
06172   }
06173 };
06174 
06175 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
06176 
06177 } // end anonymous namespace
06178 
06179 /// GetRegistersForValue - Assign registers (virtual or physical) for the
06180 /// specified operand.  We prefer to assign virtual registers, to allow the
06181 /// register allocator to handle the assignment process.  However, if the asm
06182 /// uses features that we can't model on machineinstrs, we have SDISel do the
06183 /// allocation.  This produces generally horrible, but correct, code.
06184 ///
06185 ///   OpInfo describes the operand.
06186 ///
06187 static void GetRegistersForValue(SelectionDAG &DAG,
06188                                  const TargetLowering &TLI,
06189                                  SDLoc DL,
06190                                  SDISelAsmOperandInfo &OpInfo) {
06191   LLVMContext &Context = *DAG.getContext();
06192 
06193   MachineFunction &MF = DAG.getMachineFunction();
06194   SmallVector<unsigned, 4> Regs;
06195 
06196   // If this is a constraint for a single physreg, or a constraint for a
06197   // register class, find it.
06198   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
06199       TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
06200                                        OpInfo.ConstraintCode,
06201                                        OpInfo.ConstraintVT);
06202 
06203   unsigned NumRegs = 1;
06204   if (OpInfo.ConstraintVT != MVT::Other) {
06205     // If this is a FP input in an integer register (or visa versa) insert a bit
06206     // cast of the input value.  More generally, handle any case where the input
06207     // value disagrees with the register class we plan to stick this in.
06208     if (OpInfo.Type == InlineAsm::isInput &&
06209         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
06210       // Try to convert to the first EVT that the reg class contains.  If the
06211       // types are identical size, use a bitcast to convert (e.g. two differing
06212       // vector types).
06213       MVT RegVT = *PhysReg.second->vt_begin();
06214       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
06215         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
06216                                          RegVT, OpInfo.CallOperand);
06217         OpInfo.ConstraintVT = RegVT;
06218       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
06219         // If the input is a FP value and we want it in FP registers, do a
06220         // bitcast to the corresponding integer type.  This turns an f64 value
06221         // into i64, which can be passed with two i32 values on a 32-bit
06222         // machine.
06223         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
06224         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
06225                                          RegVT, OpInfo.CallOperand);
06226         OpInfo.ConstraintVT = RegVT;
06227       }
06228     }
06229 
06230     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
06231   }
06232 
06233   MVT RegVT;
06234   EVT ValueVT = OpInfo.ConstraintVT;
06235 
06236   // If this is a constraint for a specific physical register, like {r17},
06237   // assign it now.
06238   if (unsigned AssignedReg = PhysReg.first) {
06239     const TargetRegisterClass *RC = PhysReg.second;
06240     if (OpInfo.ConstraintVT == MVT::Other)
06241       ValueVT = *RC->vt_begin();
06242 
06243     // Get the actual register value type.  This is important, because the user
06244     // may have asked for (e.g.) the AX register in i32 type.  We need to
06245     // remember that AX is actually i16 to get the right extension.
06246     RegVT = *RC->vt_begin();
06247 
06248     // This is a explicit reference to a physical register.
06249     Regs.push_back(AssignedReg);
06250 
06251     // If this is an expanded reference, add the rest of the regs to Regs.
06252     if (NumRegs != 1) {
06253       TargetRegisterClass::iterator I = RC->begin();
06254       for (; *I != AssignedReg; ++I)
06255         assert(I != RC->end() && "Didn't find reg!");
06256 
06257       // Already added the first reg.
06258       --NumRegs; ++I;
06259       for (; NumRegs; --NumRegs, ++I) {
06260         assert(I != RC->end() && "Ran out of registers to allocate!");
06261         Regs.push_back(*I);
06262       }
06263     }
06264 
06265     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
06266     return;
06267   }
06268 
06269   // Otherwise, if this was a reference to an LLVM register class, create vregs
06270   // for this reference.
06271   if (const TargetRegisterClass *RC = PhysReg.second) {
06272     RegVT = *RC->vt_begin();
06273     if (OpInfo.ConstraintVT == MVT::Other)
06274       ValueVT = RegVT;
06275 
06276     // Create the appropriate number of virtual registers.
06277     MachineRegisterInfo &RegInfo = MF.getRegInfo();
06278     for (; NumRegs; --NumRegs)
06279       Regs.push_back(RegInfo.createVirtualRegister(RC));
06280 
06281     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
06282     return;
06283   }
06284 
06285   // Otherwise, we couldn't allocate enough registers for this.
06286 }
06287 
06288 /// visitInlineAsm - Handle a call to an InlineAsm object.
06289 ///
06290 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
06291   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
06292 
06293   /// ConstraintOperands - Information about all of the constraints.
06294   SDISelAsmOperandInfoVector ConstraintOperands;
06295 
06296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
06297   TargetLowering::AsmOperandInfoVector TargetConstraints =
06298       TLI.ParseConstraints(DAG.getSubtarget().getRegisterInfo(), CS);
06299 
06300   bool hasMemory = false;
06301 
06302   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
06303   unsigned ResNo = 0;   // ResNo - The result number of the next output.
06304   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
06305     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
06306     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
06307 
06308     MVT OpVT = MVT::Other;
06309 
06310     // Compute the value type for each operand.
06311     switch (OpInfo.Type) {
06312     case InlineAsm::isOutput:
06313       // Indirect outputs just consume an argument.
06314       if (OpInfo.isIndirect) {
06315         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
06316         break;
06317       }
06318 
06319       // The return value of the call is this value.  As such, there is no
06320       // corresponding argument.
06321       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
06322       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
06323         OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
06324       } else {
06325         assert(ResNo == 0 && "Asm only has one result!");
06326         OpVT = TLI.getSimpleValueType(CS.getType());
06327       }
06328       ++ResNo;
06329       break;
<