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