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/APFloat.h" 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Analysis/AliasAnalysis.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/Analysis/VectorUtils.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/FunctionLoweringInfo.h" 41 #include "llvm/CodeGen/GCMetadata.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineJumpTableInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/RuntimeLibcalls.h" 54 #include "llvm/CodeGen/SelectionDAG.h" 55 #include "llvm/CodeGen/SelectionDAGNodes.h" 56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 57 #include "llvm/CodeGen/StackMaps.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 125 #define DEBUG_TYPE "isel" 126 127 /// LimitFloatPrecision - Generate low-precision inline sequences for 128 /// some float libcalls (6, 8 or 12 bits). 129 static unsigned LimitFloatPrecision; 130 131 static cl::opt<unsigned, true> 132 LimitFPPrecision("limit-float-precision", 133 cl::desc("Generate low-precision inline sequences " 134 "for some float libcalls"), 135 cl::location(LimitFloatPrecision), cl::Hidden, 136 cl::init(0)); 137 138 static cl::opt<unsigned> SwitchPeelThreshold( 139 "switch-peel-threshold", cl::Hidden, cl::init(66), 140 cl::desc("Set the case probability threshold for peeling the case from a " 141 "switch statement. A value greater than 100 will void this " 142 "optimization")); 143 144 // Limit the width of DAG chains. This is important in general to prevent 145 // DAG-based analysis from blowing up. For example, alias analysis and 146 // load clustering may not complete in reasonable time. It is difficult to 147 // recognize and avoid this situation within each individual analysis, and 148 // future analyses are likely to have the same behavior. Limiting DAG width is 149 // the safe approach and will be especially important with global DAGs. 150 // 151 // MaxParallelChains default is arbitrarily high to avoid affecting 152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 153 // sequence over this should have been converted to llvm.memcpy by the 154 // frontend. It is easy to induce this behavior with .ll code such as: 155 // %buffer = alloca [4096 x i8] 156 // %data = load [4096 x i8]* %argPtr 157 // store [4096 x i8] %data, [4096 x i8]* %buffer 158 static const unsigned MaxParallelChains = 64; 159 160 // Return the calling convention if the Value passed requires ABI mangling as it 161 // is a parameter to a function or a return value from a function which is not 162 // an intrinsic. 163 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 164 if (auto *R = dyn_cast<ReturnInst>(V)) 165 return R->getParent()->getParent()->getCallingConv(); 166 167 if (auto *CI = dyn_cast<CallInst>(V)) { 168 const bool IsInlineAsm = CI->isInlineAsm(); 169 const bool IsIndirectFunctionCall = 170 !IsInlineAsm && !CI->getCalledFunction(); 171 172 // It is possible that the call instruction is an inline asm statement or an 173 // indirect function call in which case the return value of 174 // getCalledFunction() would be nullptr. 175 const bool IsInstrinsicCall = 176 !IsInlineAsm && !IsIndirectFunctionCall && 177 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 178 179 if (!IsInlineAsm && !IsInstrinsicCall) 180 return CI->getCallingConv(); 181 } 182 183 return None; 184 } 185 186 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 187 const SDValue *Parts, unsigned NumParts, 188 MVT PartVT, EVT ValueVT, const Value *V, 189 Optional<CallingConv::ID> CC); 190 191 /// getCopyFromParts - Create a value that contains the specified legal parts 192 /// combined into the value they represent. If the parts combine to a type 193 /// larger than ValueVT then AssertOp can be used to specify whether the extra 194 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 195 /// (ISD::AssertSext). 196 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 197 const SDValue *Parts, unsigned NumParts, 198 MVT PartVT, EVT ValueVT, const Value *V, 199 Optional<CallingConv::ID> CC = None, 200 Optional<ISD::NodeType> AssertOp = None) { 201 if (ValueVT.isVector()) 202 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 203 CC); 204 205 assert(NumParts > 0 && "No parts to assemble!"); 206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 207 SDValue Val = Parts[0]; 208 209 if (NumParts > 1) { 210 // Assemble the value from multiple parts. 211 if (ValueVT.isInteger()) { 212 unsigned PartBits = PartVT.getSizeInBits(); 213 unsigned ValueBits = ValueVT.getSizeInBits(); 214 215 // Assemble the power of 2 part. 216 unsigned RoundParts = NumParts & (NumParts - 1) ? 217 1 << Log2_32(NumParts) : NumParts; 218 unsigned RoundBits = PartBits * RoundParts; 219 EVT RoundVT = RoundBits == ValueBits ? 220 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 221 SDValue Lo, Hi; 222 223 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 224 225 if (RoundParts > 2) { 226 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 227 PartVT, HalfVT, V); 228 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 229 RoundParts / 2, PartVT, HalfVT, V); 230 } else { 231 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 232 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 233 } 234 235 if (DAG.getDataLayout().isBigEndian()) 236 std::swap(Lo, Hi); 237 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 239 240 if (RoundParts < NumParts) { 241 // Assemble the trailing non-power-of-2 part. 242 unsigned OddParts = NumParts - RoundParts; 243 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 244 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 245 OddVT, V, CC); 246 247 // Combine the round and odd parts. 248 Lo = Val; 249 if (DAG.getDataLayout().isBigEndian()) 250 std::swap(Lo, Hi); 251 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 252 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 253 Hi = 254 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 255 DAG.getConstant(Lo.getValueSizeInBits(), DL, 256 TLI.getPointerTy(DAG.getDataLayout()))); 257 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 258 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 259 } 260 } else if (PartVT.isFloatingPoint()) { 261 // FP split into multiple FP parts (for ppcf128) 262 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 263 "Unexpected split"); 264 SDValue Lo, Hi; 265 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 266 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 267 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 268 std::swap(Lo, Hi); 269 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 270 } else { 271 // FP split into integer parts (soft fp) 272 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 273 !PartVT.isVector() && "Unexpected split"); 274 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 275 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 276 } 277 } 278 279 // There is now one part, held in Val. Correct it to match ValueVT. 280 // PartEVT is the type of the register class that holds the value. 281 // ValueVT is the type of the inline asm operation. 282 EVT PartEVT = Val.getValueType(); 283 284 if (PartEVT == ValueVT) 285 return Val; 286 287 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 288 ValueVT.bitsLT(PartEVT)) { 289 // For an FP value in an integer part, we need to truncate to the right 290 // width first. 291 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 292 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 293 } 294 295 // Handle types that have the same size. 296 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 297 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 298 299 // Handle types with different sizes. 300 if (PartEVT.isInteger() && ValueVT.isInteger()) { 301 if (ValueVT.bitsLT(PartEVT)) { 302 // For a truncate, see if we have any information to 303 // indicate whether the truncated bits will always be 304 // zero or sign-extension. 305 if (AssertOp.hasValue()) 306 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 307 DAG.getValueType(ValueVT)); 308 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 309 } 310 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 311 } 312 313 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 314 // FP_ROUND's are always exact here. 315 if (ValueVT.bitsLT(Val.getValueType())) 316 return DAG.getNode( 317 ISD::FP_ROUND, DL, ValueVT, Val, 318 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 319 320 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 321 } 322 323 llvm_unreachable("Unknown mismatch!"); 324 } 325 326 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 327 const Twine &ErrMsg) { 328 const Instruction *I = dyn_cast_or_null<Instruction>(V); 329 if (!V) 330 return Ctx.emitError(ErrMsg); 331 332 const char *AsmError = ", possible invalid constraint for vector type"; 333 if (const CallInst *CI = dyn_cast<CallInst>(I)) 334 if (isa<InlineAsm>(CI->getCalledValue())) 335 return Ctx.emitError(I, ErrMsg + AsmError); 336 337 return Ctx.emitError(I, ErrMsg); 338 } 339 340 /// getCopyFromPartsVector - Create a value that contains the specified legal 341 /// parts combined into the value they represent. If the parts combine to a 342 /// type larger than ValueVT then AssertOp can be used to specify whether the 343 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 344 /// ValueVT (ISD::AssertSext). 345 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 346 const SDValue *Parts, unsigned NumParts, 347 MVT PartVT, EVT ValueVT, const Value *V, 348 Optional<CallingConv::ID> CallConv) { 349 assert(ValueVT.isVector() && "Not a vector value"); 350 assert(NumParts > 0 && "No parts to assemble!"); 351 const bool IsABIRegCopy = CallConv.hasValue(); 352 353 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 354 SDValue Val = Parts[0]; 355 356 // Handle a multi-element vector. 357 if (NumParts > 1) { 358 EVT IntermediateVT; 359 MVT RegisterVT; 360 unsigned NumIntermediates; 361 unsigned NumRegs; 362 363 if (IsABIRegCopy) { 364 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 365 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 366 NumIntermediates, RegisterVT); 367 } else { 368 NumRegs = 369 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 370 NumIntermediates, RegisterVT); 371 } 372 373 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 374 NumParts = NumRegs; // Silence a compiler warning. 375 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 376 assert(RegisterVT.getSizeInBits() == 377 Parts[0].getSimpleValueType().getSizeInBits() && 378 "Part type sizes don't match!"); 379 380 // Assemble the parts into intermediate operands. 381 SmallVector<SDValue, 8> Ops(NumIntermediates); 382 if (NumIntermediates == NumParts) { 383 // If the register was not expanded, truncate or copy the value, 384 // as appropriate. 385 for (unsigned i = 0; i != NumParts; ++i) 386 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 387 PartVT, IntermediateVT, V); 388 } else if (NumParts > 0) { 389 // If the intermediate type was expanded, build the intermediate 390 // operands from the parts. 391 assert(NumParts % NumIntermediates == 0 && 392 "Must expand into a divisible number of parts!"); 393 unsigned Factor = NumParts / NumIntermediates; 394 for (unsigned i = 0; i != NumIntermediates; ++i) 395 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 396 PartVT, IntermediateVT, V); 397 } 398 399 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 400 // intermediate operands. 401 EVT BuiltVectorTy = 402 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 403 (IntermediateVT.isVector() 404 ? IntermediateVT.getVectorNumElements() * NumParts 405 : NumIntermediates)); 406 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 407 : ISD::BUILD_VECTOR, 408 DL, BuiltVectorTy, Ops); 409 } 410 411 // There is now one part, held in Val. Correct it to match ValueVT. 412 EVT PartEVT = Val.getValueType(); 413 414 if (PartEVT == ValueVT) 415 return Val; 416 417 if (PartEVT.isVector()) { 418 // If the element type of the source/dest vectors are the same, but the 419 // parts vector has more elements than the value vector, then we have a 420 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 421 // elements we want. 422 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 423 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 424 "Cannot narrow, it would be a lossy transformation"); 425 return DAG.getNode( 426 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 427 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 428 } 429 430 // Vector/Vector bitcast. 431 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 432 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 433 434 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 435 "Cannot handle this kind of promotion"); 436 // Promoted vector extract 437 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 438 439 } 440 441 // Trivial bitcast if the types are the same size and the destination 442 // vector type is legal. 443 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 444 TLI.isTypeLegal(ValueVT)) 445 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 446 447 if (ValueVT.getVectorNumElements() != 1) { 448 // Certain ABIs require that vectors are passed as integers. For vectors 449 // are the same size, this is an obvious bitcast. 450 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 452 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 453 // Bitcast Val back the original type and extract the corresponding 454 // vector we want. 455 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 456 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 457 ValueVT.getVectorElementType(), Elts); 458 Val = DAG.getBitcast(WiderVecType, Val); 459 return DAG.getNode( 460 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 461 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 462 } 463 464 diagnosePossiblyInvalidConstraint( 465 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 466 return DAG.getUNDEF(ValueVT); 467 } 468 469 // Handle cases such as i8 -> <1 x i1> 470 EVT ValueSVT = ValueVT.getVectorElementType(); 471 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 472 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 473 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 474 475 return DAG.getBuildVector(ValueVT, DL, Val); 476 } 477 478 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 479 SDValue Val, SDValue *Parts, unsigned NumParts, 480 MVT PartVT, const Value *V, 481 Optional<CallingConv::ID> CallConv); 482 483 /// getCopyToParts - Create a series of nodes that contain the specified value 484 /// split into legal parts. If the parts contain more bits than Val, then, for 485 /// integers, ExtendKind can be used to specify how to generate the extra bits. 486 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 487 SDValue *Parts, unsigned NumParts, MVT PartVT, 488 const Value *V, 489 Optional<CallingConv::ID> CallConv = None, 490 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 491 EVT ValueVT = Val.getValueType(); 492 493 // Handle the vector case separately. 494 if (ValueVT.isVector()) 495 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 496 CallConv); 497 498 unsigned PartBits = PartVT.getSizeInBits(); 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 515 // If the parts cover more bits than the value has, promote the value. 516 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 517 assert(NumParts == 1 && "Do not know what to promote to!"); 518 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 519 } else { 520 if (ValueVT.isFloatingPoint()) { 521 // FP values need to be bitcast, then extended if they are being put 522 // into a larger container. 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 524 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 525 } 526 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 527 ValueVT.isInteger() && 528 "Unknown mismatch!"); 529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 530 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 531 if (PartVT == MVT::x86mmx) 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } 534 } else if (PartBits == ValueVT.getSizeInBits()) { 535 // Different types of the same size. 536 assert(NumParts == 1 && PartEVT != ValueVT); 537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 538 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 539 // If the parts cover less bits than value has, truncate the value. 540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 541 ValueVT.isInteger() && 542 "Unknown mismatch!"); 543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 544 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 545 if (PartVT == MVT::x86mmx) 546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 547 } 548 549 // The value may have changed - recompute ValueVT. 550 ValueVT = Val.getValueType(); 551 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 552 "Failed to tile the value with PartVT!"); 553 554 if (NumParts == 1) { 555 if (PartEVT != ValueVT) { 556 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 557 "scalar-to-vector conversion failed"); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 Parts[0] = Val; 562 return; 563 } 564 565 // Expand the value into multiple parts. 566 if (NumParts & (NumParts - 1)) { 567 // The number of parts is not a power of 2. Split off and copy the tail. 568 assert(PartVT.isInteger() && ValueVT.isInteger() && 569 "Do not know what to expand to!"); 570 unsigned RoundParts = 1 << Log2_32(NumParts); 571 unsigned RoundBits = RoundParts * PartBits; 572 unsigned OddParts = NumParts - RoundParts; 573 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 574 DAG.getIntPtrConstant(RoundBits, DL)); 575 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 576 CallConv); 577 578 if (DAG.getDataLayout().isBigEndian()) 579 // The odd parts were reversed by getCopyToParts - unreverse them. 580 std::reverse(Parts + RoundParts, Parts + NumParts); 581 582 NumParts = RoundParts; 583 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 584 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 585 } 586 587 // The number of parts is a power of 2. Repeatedly bisect the value using 588 // EXTRACT_ELEMENT. 589 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 590 EVT::getIntegerVT(*DAG.getContext(), 591 ValueVT.getSizeInBits()), 592 Val); 593 594 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 595 for (unsigned i = 0; i < NumParts; i += StepSize) { 596 unsigned ThisBits = StepSize * PartBits / 2; 597 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 598 SDValue &Part0 = Parts[i]; 599 SDValue &Part1 = Parts[i+StepSize/2]; 600 601 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 602 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 603 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 605 606 if (ThisBits == PartBits && ThisVT != PartVT) { 607 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 608 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 609 } 610 } 611 } 612 613 if (DAG.getDataLayout().isBigEndian()) 614 std::reverse(Parts, Parts + OrigNumParts); 615 } 616 617 /// getCopyToPartsVector - Create a series of nodes that contain the specified 618 /// value split into legal parts. 619 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 620 SDValue Val, SDValue *Parts, unsigned NumParts, 621 MVT PartVT, const Value *V, 622 Optional<CallingConv::ID> CallConv) { 623 EVT ValueVT = Val.getValueType(); 624 assert(ValueVT.isVector() && "Not a vector"); 625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 626 const bool IsABIRegCopy = CallConv.hasValue(); 627 628 if (NumParts == 1) { 629 EVT PartEVT = PartVT; 630 if (PartEVT == ValueVT) { 631 // Nothing to do. 632 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 633 // Bitconvert vector->vector case. 634 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 635 } else if (PartVT.isVector() && 636 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 637 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 638 EVT ElementVT = PartVT.getVectorElementType(); 639 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 640 // undef elements. 641 SmallVector<SDValue, 16> Ops; 642 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 643 Ops.push_back(DAG.getNode( 644 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 645 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 646 647 for (unsigned i = ValueVT.getVectorNumElements(), 648 e = PartVT.getVectorNumElements(); i != e; ++i) 649 Ops.push_back(DAG.getUNDEF(ElementVT)); 650 651 Val = DAG.getBuildVector(PartVT, DL, Ops); 652 653 // FIXME: Use CONCAT for 2x -> 4x. 654 655 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 656 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 657 } else if (PartVT.isVector() && 658 PartEVT.getVectorElementType().bitsGE( 659 ValueVT.getVectorElementType()) && 660 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 661 662 // Promoted vector extract 663 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 664 } else { 665 if (ValueVT.getVectorNumElements() == 1) { 666 Val = DAG.getNode( 667 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 668 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 669 } else { 670 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 671 "lossy conversion of vector to scalar type"); 672 EVT IntermediateType = 673 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 674 Val = DAG.getBitcast(IntermediateType, Val); 675 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 676 } 677 } 678 679 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 680 Parts[0] = Val; 681 return; 682 } 683 684 // Handle a multi-element vector. 685 EVT IntermediateVT; 686 MVT RegisterVT; 687 unsigned NumIntermediates; 688 unsigned NumRegs; 689 if (IsABIRegCopy) { 690 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 691 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 692 NumIntermediates, RegisterVT); 693 } else { 694 NumRegs = 695 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 696 NumIntermediates, RegisterVT); 697 } 698 unsigned NumElements = ValueVT.getVectorNumElements(); 699 700 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 701 NumParts = NumRegs; // Silence a compiler warning. 702 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 703 704 // Convert the vector to the appropiate type if necessary. 705 unsigned DestVectorNoElts = 706 NumIntermediates * 707 (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1); 708 EVT BuiltVectorTy = EVT::getVectorVT( 709 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 710 if (Val.getValueType() != BuiltVectorTy) 711 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 712 713 // Split the vector into intermediate operands. 714 SmallVector<SDValue, 8> Ops(NumIntermediates); 715 for (unsigned i = 0; i != NumIntermediates; ++i) { 716 if (IntermediateVT.isVector()) 717 Ops[i] = 718 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 719 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 720 TLI.getVectorIdxTy(DAG.getDataLayout()))); 721 else 722 Ops[i] = DAG.getNode( 723 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 724 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 725 } 726 727 // Split the intermediate operands into legal parts. 728 if (NumParts == NumIntermediates) { 729 // If the register was not expanded, promote or copy the value, 730 // as appropriate. 731 for (unsigned i = 0; i != NumParts; ++i) 732 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 733 } else if (NumParts > 0) { 734 // If the intermediate type was expanded, split each the value into 735 // legal parts. 736 assert(NumIntermediates != 0 && "division by zero"); 737 assert(NumParts % NumIntermediates == 0 && 738 "Must expand into a divisible number of parts!"); 739 unsigned Factor = NumParts / NumIntermediates; 740 for (unsigned i = 0; i != NumIntermediates; ++i) 741 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 742 CallConv); 743 } 744 } 745 746 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 747 EVT valuevt, Optional<CallingConv::ID> CC) 748 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 749 RegCount(1, regs.size()), CallConv(CC) {} 750 751 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 752 const DataLayout &DL, unsigned Reg, Type *Ty, 753 Optional<CallingConv::ID> CC) { 754 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 755 756 CallConv = CC; 757 758 for (EVT ValueVT : ValueVTs) { 759 unsigned NumRegs = 760 isABIMangled() 761 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 762 : TLI.getNumRegisters(Context, ValueVT); 763 MVT RegisterVT = 764 isABIMangled() 765 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 766 : TLI.getRegisterType(Context, ValueVT); 767 for (unsigned i = 0; i != NumRegs; ++i) 768 Regs.push_back(Reg + i); 769 RegVTs.push_back(RegisterVT); 770 RegCount.push_back(NumRegs); 771 Reg += NumRegs; 772 } 773 } 774 775 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 776 FunctionLoweringInfo &FuncInfo, 777 const SDLoc &dl, SDValue &Chain, 778 SDValue *Flag, const Value *V) const { 779 // A Value with type {} or [0 x %t] needs no registers. 780 if (ValueVTs.empty()) 781 return SDValue(); 782 783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 784 785 // Assemble the legal parts into the final values. 786 SmallVector<SDValue, 4> Values(ValueVTs.size()); 787 SmallVector<SDValue, 8> Parts; 788 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 789 // Copy the legal parts from the registers. 790 EVT ValueVT = ValueVTs[Value]; 791 unsigned NumRegs = RegCount[Value]; 792 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 793 *DAG.getContext(), 794 CallConv.getValue(), RegVTs[Value]) 795 : RegVTs[Value]; 796 797 Parts.resize(NumRegs); 798 for (unsigned i = 0; i != NumRegs; ++i) { 799 SDValue P; 800 if (!Flag) { 801 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 802 } else { 803 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 804 *Flag = P.getValue(2); 805 } 806 807 Chain = P.getValue(1); 808 Parts[i] = P; 809 810 // If the source register was virtual and if we know something about it, 811 // add an assert node. 812 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 813 !RegisterVT.isInteger() || RegisterVT.isVector()) 814 continue; 815 816 const FunctionLoweringInfo::LiveOutInfo *LOI = 817 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 818 if (!LOI) 819 continue; 820 821 unsigned RegSize = RegisterVT.getSizeInBits(); 822 unsigned NumSignBits = LOI->NumSignBits; 823 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 824 825 if (NumZeroBits == RegSize) { 826 // The current value is a zero. 827 // Explicitly express that as it would be easier for 828 // optimizations to kick in. 829 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 830 continue; 831 } 832 833 // FIXME: We capture more information than the dag can represent. For 834 // now, just use the tightest assertzext/assertsext possible. 835 bool isSExt; 836 EVT FromVT(MVT::Other); 837 if (NumZeroBits) { 838 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 839 isSExt = false; 840 } else if (NumSignBits > 1) { 841 FromVT = 842 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 843 isSExt = true; 844 } else { 845 continue; 846 } 847 // Add an assertion node. 848 assert(FromVT != MVT::Other); 849 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 850 RegisterVT, P, DAG.getValueType(FromVT)); 851 } 852 853 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 854 RegisterVT, ValueVT, V, CallConv); 855 Part += NumRegs; 856 Parts.clear(); 857 } 858 859 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 860 } 861 862 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 863 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 864 const Value *V, 865 ISD::NodeType PreferredExtendType) const { 866 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 867 ISD::NodeType ExtendKind = PreferredExtendType; 868 869 // Get the list of the values's legal parts. 870 unsigned NumRegs = Regs.size(); 871 SmallVector<SDValue, 8> Parts(NumRegs); 872 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 873 unsigned NumParts = RegCount[Value]; 874 875 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 876 *DAG.getContext(), 877 CallConv.getValue(), RegVTs[Value]) 878 : RegVTs[Value]; 879 880 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 881 ExtendKind = ISD::ZERO_EXTEND; 882 883 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 884 NumParts, RegisterVT, V, CallConv, ExtendKind); 885 Part += NumParts; 886 } 887 888 // Copy the parts into the registers. 889 SmallVector<SDValue, 8> Chains(NumRegs); 890 for (unsigned i = 0; i != NumRegs; ++i) { 891 SDValue Part; 892 if (!Flag) { 893 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 894 } else { 895 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 896 *Flag = Part.getValue(1); 897 } 898 899 Chains[i] = Part.getValue(0); 900 } 901 902 if (NumRegs == 1 || Flag) 903 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 904 // flagged to it. That is the CopyToReg nodes and the user are considered 905 // a single scheduling unit. If we create a TokenFactor and return it as 906 // chain, then the TokenFactor is both a predecessor (operand) of the 907 // user as well as a successor (the TF operands are flagged to the user). 908 // c1, f1 = CopyToReg 909 // c2, f2 = CopyToReg 910 // c3 = TokenFactor c1, c2 911 // ... 912 // = op c3, ..., f2 913 Chain = Chains[NumRegs-1]; 914 else 915 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 916 } 917 918 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 919 unsigned MatchingIdx, const SDLoc &dl, 920 SelectionDAG &DAG, 921 std::vector<SDValue> &Ops) const { 922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 923 924 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 925 if (HasMatching) 926 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 927 else if (!Regs.empty() && 928 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 929 // Put the register class of the virtual registers in the flag word. That 930 // way, later passes can recompute register class constraints for inline 931 // assembly as well as normal instructions. 932 // Don't do this for tied operands that can use the regclass information 933 // from the def. 934 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 935 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 936 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 937 } 938 939 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 940 Ops.push_back(Res); 941 942 if (Code == InlineAsm::Kind_Clobber) { 943 // Clobbers should always have a 1:1 mapping with registers, and may 944 // reference registers that have illegal (e.g. vector) types. Hence, we 945 // shouldn't try to apply any sort of splitting logic to them. 946 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 947 "No 1:1 mapping from clobbers to regs?"); 948 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 949 (void)SP; 950 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 951 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 952 assert( 953 (Regs[I] != SP || 954 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 955 "If we clobbered the stack pointer, MFI should know about it."); 956 } 957 return; 958 } 959 960 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 961 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 962 MVT RegisterVT = RegVTs[Value]; 963 for (unsigned i = 0; i != NumRegs; ++i) { 964 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 965 unsigned TheReg = Regs[Reg++]; 966 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 967 } 968 } 969 } 970 971 SmallVector<std::pair<unsigned, unsigned>, 4> 972 RegsForValue::getRegsAndSizes() const { 973 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 974 unsigned I = 0; 975 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 976 unsigned RegCount = std::get<0>(CountAndVT); 977 MVT RegisterVT = std::get<1>(CountAndVT); 978 unsigned RegisterSize = RegisterVT.getSizeInBits(); 979 for (unsigned E = I + RegCount; I != E; ++I) 980 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 981 } 982 return OutVec; 983 } 984 985 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 986 const TargetLibraryInfo *li) { 987 AA = aa; 988 GFI = gfi; 989 LibInfo = li; 990 DL = &DAG.getDataLayout(); 991 Context = DAG.getContext(); 992 LPadToCallSiteMap.clear(); 993 } 994 995 void SelectionDAGBuilder::clear() { 996 NodeMap.clear(); 997 UnusedArgNodeMap.clear(); 998 PendingLoads.clear(); 999 PendingExports.clear(); 1000 CurInst = nullptr; 1001 HasTailCall = false; 1002 SDNodeOrder = LowestSDNodeOrder; 1003 StatepointLowering.clear(); 1004 } 1005 1006 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1007 DanglingDebugInfoMap.clear(); 1008 } 1009 1010 SDValue SelectionDAGBuilder::getRoot() { 1011 if (PendingLoads.empty()) 1012 return DAG.getRoot(); 1013 1014 if (PendingLoads.size() == 1) { 1015 SDValue Root = PendingLoads[0]; 1016 DAG.setRoot(Root); 1017 PendingLoads.clear(); 1018 return Root; 1019 } 1020 1021 // Otherwise, we have to make a token factor node. 1022 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1023 PendingLoads); 1024 PendingLoads.clear(); 1025 DAG.setRoot(Root); 1026 return Root; 1027 } 1028 1029 SDValue SelectionDAGBuilder::getControlRoot() { 1030 SDValue Root = DAG.getRoot(); 1031 1032 if (PendingExports.empty()) 1033 return Root; 1034 1035 // Turn all of the CopyToReg chains into one factored node. 1036 if (Root.getOpcode() != ISD::EntryToken) { 1037 unsigned i = 0, e = PendingExports.size(); 1038 for (; i != e; ++i) { 1039 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1040 if (PendingExports[i].getNode()->getOperand(0) == Root) 1041 break; // Don't add the root if we already indirectly depend on it. 1042 } 1043 1044 if (i == e) 1045 PendingExports.push_back(Root); 1046 } 1047 1048 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1049 PendingExports); 1050 PendingExports.clear(); 1051 DAG.setRoot(Root); 1052 return Root; 1053 } 1054 1055 void SelectionDAGBuilder::visit(const Instruction &I) { 1056 // Set up outgoing PHI node register values before emitting the terminator. 1057 if (isa<TerminatorInst>(&I)) { 1058 HandlePHINodesInSuccessorBlocks(I.getParent()); 1059 } 1060 1061 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1062 if (!isa<DbgInfoIntrinsic>(I)) 1063 ++SDNodeOrder; 1064 1065 CurInst = &I; 1066 1067 visit(I.getOpcode(), I); 1068 1069 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1070 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1071 // maps to this instruction. 1072 // TODO: We could handle all flags (nsw, etc) here. 1073 // TODO: If an IR instruction maps to >1 node, only the final node will have 1074 // flags set. 1075 if (SDNode *Node = getNodeForIRValue(&I)) { 1076 SDNodeFlags IncomingFlags; 1077 IncomingFlags.copyFMF(*FPMO); 1078 if (!Node->getFlags().isDefined()) 1079 Node->setFlags(IncomingFlags); 1080 else 1081 Node->intersectFlagsWith(IncomingFlags); 1082 } 1083 } 1084 1085 if (!isa<TerminatorInst>(&I) && !HasTailCall && 1086 !isStatepoint(&I)) // statepoints handle their exports internally 1087 CopyToExportRegsIfNeeded(&I); 1088 1089 CurInst = nullptr; 1090 } 1091 1092 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1093 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1094 } 1095 1096 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1097 // Note: this doesn't use InstVisitor, because it has to work with 1098 // ConstantExpr's in addition to instructions. 1099 switch (Opcode) { 1100 default: llvm_unreachable("Unknown instruction type encountered!"); 1101 // Build the switch statement using the Instruction.def file. 1102 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1103 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1104 #include "llvm/IR/Instruction.def" 1105 } 1106 } 1107 1108 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1109 const DIExpression *Expr) { 1110 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1111 const DbgValueInst *DI = DDI.getDI(); 1112 DIVariable *DanglingVariable = DI->getVariable(); 1113 DIExpression *DanglingExpr = DI->getExpression(); 1114 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1115 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1116 return true; 1117 } 1118 return false; 1119 }; 1120 1121 for (auto &DDIMI : DanglingDebugInfoMap) { 1122 DanglingDebugInfoVector &DDIV = DDIMI.second; 1123 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1124 } 1125 } 1126 1127 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1128 // generate the debug data structures now that we've seen its definition. 1129 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1130 SDValue Val) { 1131 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1132 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1133 return; 1134 1135 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1136 for (auto &DDI : DDIV) { 1137 const DbgValueInst *DI = DDI.getDI(); 1138 assert(DI && "Ill-formed DanglingDebugInfo"); 1139 DebugLoc dl = DDI.getdl(); 1140 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1141 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1142 DILocalVariable *Variable = DI->getVariable(); 1143 DIExpression *Expr = DI->getExpression(); 1144 assert(Variable->isValidLocationForIntrinsic(dl) && 1145 "Expected inlined-at fields to agree"); 1146 SDDbgValue *SDV; 1147 if (Val.getNode()) { 1148 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1149 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1150 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1151 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1152 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1153 // inserted after the definition of Val when emitting the instructions 1154 // after ISel. An alternative could be to teach 1155 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1156 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1157 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1158 << ValSDNodeOrder << "\n"); 1159 SDV = getDbgValue(Val, Variable, Expr, dl, 1160 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1161 DAG.AddDbgValue(SDV, Val.getNode(), false); 1162 } else 1163 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1164 << "in EmitFuncArgumentDbgValue\n"); 1165 } else 1166 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1167 } 1168 DDIV.clear(); 1169 } 1170 1171 /// getCopyFromRegs - If there was virtual register allocated for the value V 1172 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1173 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1174 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1175 SDValue Result; 1176 1177 if (It != FuncInfo.ValueMap.end()) { 1178 unsigned InReg = It->second; 1179 1180 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1181 DAG.getDataLayout(), InReg, Ty, getABIRegCopyCC(V)); 1182 SDValue Chain = DAG.getEntryNode(); 1183 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1184 V); 1185 resolveDanglingDebugInfo(V, Result); 1186 } 1187 1188 return Result; 1189 } 1190 1191 /// getValue - Return an SDValue for the given Value. 1192 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1193 // If we already have an SDValue for this value, use it. It's important 1194 // to do this first, so that we don't create a CopyFromReg if we already 1195 // have a regular SDValue. 1196 SDValue &N = NodeMap[V]; 1197 if (N.getNode()) return N; 1198 1199 // If there's a virtual register allocated and initialized for this 1200 // value, use it. 1201 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1202 return copyFromReg; 1203 1204 // Otherwise create a new SDValue and remember it. 1205 SDValue Val = getValueImpl(V); 1206 NodeMap[V] = Val; 1207 resolveDanglingDebugInfo(V, Val); 1208 return Val; 1209 } 1210 1211 // Return true if SDValue exists for the given Value 1212 bool SelectionDAGBuilder::findValue(const Value *V) const { 1213 return (NodeMap.find(V) != NodeMap.end()) || 1214 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1215 } 1216 1217 /// getNonRegisterValue - Return an SDValue for the given Value, but 1218 /// don't look in FuncInfo.ValueMap for a virtual register. 1219 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1220 // If we already have an SDValue for this value, use it. 1221 SDValue &N = NodeMap[V]; 1222 if (N.getNode()) { 1223 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1224 // Remove the debug location from the node as the node is about to be used 1225 // in a location which may differ from the original debug location. This 1226 // is relevant to Constant and ConstantFP nodes because they can appear 1227 // as constant expressions inside PHI nodes. 1228 N->setDebugLoc(DebugLoc()); 1229 } 1230 return N; 1231 } 1232 1233 // Otherwise create a new SDValue and remember it. 1234 SDValue Val = getValueImpl(V); 1235 NodeMap[V] = Val; 1236 resolveDanglingDebugInfo(V, Val); 1237 return Val; 1238 } 1239 1240 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1241 /// Create an SDValue for the given value. 1242 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1243 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1244 1245 if (const Constant *C = dyn_cast<Constant>(V)) { 1246 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1247 1248 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1249 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1250 1251 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1252 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1253 1254 if (isa<ConstantPointerNull>(C)) { 1255 unsigned AS = V->getType()->getPointerAddressSpace(); 1256 return DAG.getConstant(0, getCurSDLoc(), 1257 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1258 } 1259 1260 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1261 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1262 1263 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1264 return DAG.getUNDEF(VT); 1265 1266 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1267 visit(CE->getOpcode(), *CE); 1268 SDValue N1 = NodeMap[V]; 1269 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1270 return N1; 1271 } 1272 1273 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1274 SmallVector<SDValue, 4> Constants; 1275 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1276 OI != OE; ++OI) { 1277 SDNode *Val = getValue(*OI).getNode(); 1278 // If the operand is an empty aggregate, there are no values. 1279 if (!Val) continue; 1280 // Add each leaf value from the operand to the Constants list 1281 // to form a flattened list of all the values. 1282 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1283 Constants.push_back(SDValue(Val, i)); 1284 } 1285 1286 return DAG.getMergeValues(Constants, getCurSDLoc()); 1287 } 1288 1289 if (const ConstantDataSequential *CDS = 1290 dyn_cast<ConstantDataSequential>(C)) { 1291 SmallVector<SDValue, 4> Ops; 1292 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1293 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1294 // Add each leaf value from the operand to the Constants list 1295 // to form a flattened list of all the values. 1296 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1297 Ops.push_back(SDValue(Val, i)); 1298 } 1299 1300 if (isa<ArrayType>(CDS->getType())) 1301 return DAG.getMergeValues(Ops, getCurSDLoc()); 1302 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1303 } 1304 1305 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1306 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1307 "Unknown struct or array constant!"); 1308 1309 SmallVector<EVT, 4> ValueVTs; 1310 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1311 unsigned NumElts = ValueVTs.size(); 1312 if (NumElts == 0) 1313 return SDValue(); // empty struct 1314 SmallVector<SDValue, 4> Constants(NumElts); 1315 for (unsigned i = 0; i != NumElts; ++i) { 1316 EVT EltVT = ValueVTs[i]; 1317 if (isa<UndefValue>(C)) 1318 Constants[i] = DAG.getUNDEF(EltVT); 1319 else if (EltVT.isFloatingPoint()) 1320 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1321 else 1322 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1323 } 1324 1325 return DAG.getMergeValues(Constants, getCurSDLoc()); 1326 } 1327 1328 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1329 return DAG.getBlockAddress(BA, VT); 1330 1331 VectorType *VecTy = cast<VectorType>(V->getType()); 1332 unsigned NumElements = VecTy->getNumElements(); 1333 1334 // Now that we know the number and type of the elements, get that number of 1335 // elements into the Ops array based on what kind of constant it is. 1336 SmallVector<SDValue, 16> Ops; 1337 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1338 for (unsigned i = 0; i != NumElements; ++i) 1339 Ops.push_back(getValue(CV->getOperand(i))); 1340 } else { 1341 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1342 EVT EltVT = 1343 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1344 1345 SDValue Op; 1346 if (EltVT.isFloatingPoint()) 1347 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1348 else 1349 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1350 Ops.assign(NumElements, Op); 1351 } 1352 1353 // Create a BUILD_VECTOR node. 1354 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1355 } 1356 1357 // If this is a static alloca, generate it as the frameindex instead of 1358 // computation. 1359 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1360 DenseMap<const AllocaInst*, int>::iterator SI = 1361 FuncInfo.StaticAllocaMap.find(AI); 1362 if (SI != FuncInfo.StaticAllocaMap.end()) 1363 return DAG.getFrameIndex(SI->second, 1364 TLI.getFrameIndexTy(DAG.getDataLayout())); 1365 } 1366 1367 // If this is an instruction which fast-isel has deferred, select it now. 1368 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1369 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1370 1371 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1372 Inst->getType(), getABIRegCopyCC(V)); 1373 SDValue Chain = DAG.getEntryNode(); 1374 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1375 } 1376 1377 llvm_unreachable("Can't get register for value!"); 1378 } 1379 1380 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1381 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1382 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1383 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1384 bool IsSEH = isAsynchronousEHPersonality(Pers); 1385 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1386 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1387 if (!IsSEH) 1388 CatchPadMBB->setIsEHScopeEntry(); 1389 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1390 if (IsMSVCCXX || IsCoreCLR) 1391 CatchPadMBB->setIsEHFuncletEntry(); 1392 // Wasm does not need catchpads anymore 1393 if (!IsWasmCXX) 1394 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1395 getControlRoot())); 1396 } 1397 1398 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1399 // Update machine-CFG edge. 1400 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1401 FuncInfo.MBB->addSuccessor(TargetMBB); 1402 1403 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1404 bool IsSEH = isAsynchronousEHPersonality(Pers); 1405 if (IsSEH) { 1406 // If this is not a fall-through branch or optimizations are switched off, 1407 // emit the branch. 1408 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1409 TM.getOptLevel() == CodeGenOpt::None) 1410 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1411 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1412 return; 1413 } 1414 1415 // Figure out the funclet membership for the catchret's successor. 1416 // This will be used by the FuncletLayout pass to determine how to order the 1417 // BB's. 1418 // A 'catchret' returns to the outer scope's color. 1419 Value *ParentPad = I.getCatchSwitchParentPad(); 1420 const BasicBlock *SuccessorColor; 1421 if (isa<ConstantTokenNone>(ParentPad)) 1422 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1423 else 1424 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1425 assert(SuccessorColor && "No parent funclet for catchret!"); 1426 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1427 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1428 1429 // Create the terminator node. 1430 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1431 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1432 DAG.getBasicBlock(SuccessorColorMBB)); 1433 DAG.setRoot(Ret); 1434 } 1435 1436 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1437 // Don't emit any special code for the cleanuppad instruction. It just marks 1438 // the start of an EH scope/funclet. 1439 FuncInfo.MBB->setIsEHScopeEntry(); 1440 FuncInfo.MBB->setIsEHFuncletEntry(); 1441 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1442 } 1443 1444 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1445 /// many places it could ultimately go. In the IR, we have a single unwind 1446 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1447 /// This function skips over imaginary basic blocks that hold catchswitch 1448 /// instructions, and finds all the "real" machine 1449 /// basic block destinations. As those destinations may not be successors of 1450 /// EHPadBB, here we also calculate the edge probability to those destinations. 1451 /// The passed-in Prob is the edge probability to EHPadBB. 1452 static void findUnwindDestinations( 1453 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1454 BranchProbability Prob, 1455 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1456 &UnwindDests) { 1457 EHPersonality Personality = 1458 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1459 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1460 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1461 bool IsSEH = isAsynchronousEHPersonality(Personality); 1462 1463 while (EHPadBB) { 1464 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1465 BasicBlock *NewEHPadBB = nullptr; 1466 if (isa<LandingPadInst>(Pad)) { 1467 // Stop on landingpads. They are not funclets. 1468 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1469 break; 1470 } else if (isa<CleanupPadInst>(Pad)) { 1471 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1472 // personalities. 1473 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1474 UnwindDests.back().first->setIsEHScopeEntry(); 1475 UnwindDests.back().first->setIsEHFuncletEntry(); 1476 break; 1477 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1478 // Add the catchpad handlers to the possible destinations. 1479 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1480 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1481 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1482 if (IsMSVCCXX || IsCoreCLR) 1483 UnwindDests.back().first->setIsEHFuncletEntry(); 1484 if (!IsSEH) 1485 UnwindDests.back().first->setIsEHScopeEntry(); 1486 } 1487 NewEHPadBB = CatchSwitch->getUnwindDest(); 1488 } else { 1489 continue; 1490 } 1491 1492 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1493 if (BPI && NewEHPadBB) 1494 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1495 EHPadBB = NewEHPadBB; 1496 } 1497 } 1498 1499 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1500 // Update successor info. 1501 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1502 auto UnwindDest = I.getUnwindDest(); 1503 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1504 BranchProbability UnwindDestProb = 1505 (BPI && UnwindDest) 1506 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1507 : BranchProbability::getZero(); 1508 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1509 for (auto &UnwindDest : UnwindDests) { 1510 UnwindDest.first->setIsEHPad(); 1511 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1512 } 1513 FuncInfo.MBB->normalizeSuccProbs(); 1514 1515 // Create the terminator node. 1516 SDValue Ret = 1517 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1518 DAG.setRoot(Ret); 1519 } 1520 1521 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1522 report_fatal_error("visitCatchSwitch not yet implemented!"); 1523 } 1524 1525 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1527 auto &DL = DAG.getDataLayout(); 1528 SDValue Chain = getControlRoot(); 1529 SmallVector<ISD::OutputArg, 8> Outs; 1530 SmallVector<SDValue, 8> OutVals; 1531 1532 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1533 // lower 1534 // 1535 // %val = call <ty> @llvm.experimental.deoptimize() 1536 // ret <ty> %val 1537 // 1538 // differently. 1539 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1540 LowerDeoptimizingReturn(); 1541 return; 1542 } 1543 1544 if (!FuncInfo.CanLowerReturn) { 1545 unsigned DemoteReg = FuncInfo.DemoteRegister; 1546 const Function *F = I.getParent()->getParent(); 1547 1548 // Emit a store of the return value through the virtual register. 1549 // Leave Outs empty so that LowerReturn won't try to load return 1550 // registers the usual way. 1551 SmallVector<EVT, 1> PtrValueVTs; 1552 ComputeValueVTs(TLI, DL, 1553 F->getReturnType()->getPointerTo( 1554 DAG.getDataLayout().getAllocaAddrSpace()), 1555 PtrValueVTs); 1556 1557 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1558 DemoteReg, PtrValueVTs[0]); 1559 SDValue RetOp = getValue(I.getOperand(0)); 1560 1561 SmallVector<EVT, 4> ValueVTs; 1562 SmallVector<uint64_t, 4> Offsets; 1563 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1564 unsigned NumValues = ValueVTs.size(); 1565 1566 SmallVector<SDValue, 4> Chains(NumValues); 1567 for (unsigned i = 0; i != NumValues; ++i) { 1568 // An aggregate return value cannot wrap around the address space, so 1569 // offsets to its parts don't wrap either. 1570 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1571 Chains[i] = DAG.getStore( 1572 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1573 // FIXME: better loc info would be nice. 1574 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1575 } 1576 1577 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1578 MVT::Other, Chains); 1579 } else if (I.getNumOperands() != 0) { 1580 SmallVector<EVT, 4> ValueVTs; 1581 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1582 unsigned NumValues = ValueVTs.size(); 1583 if (NumValues) { 1584 SDValue RetOp = getValue(I.getOperand(0)); 1585 1586 const Function *F = I.getParent()->getParent(); 1587 1588 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1589 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1590 Attribute::SExt)) 1591 ExtendKind = ISD::SIGN_EXTEND; 1592 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1593 Attribute::ZExt)) 1594 ExtendKind = ISD::ZERO_EXTEND; 1595 1596 LLVMContext &Context = F->getContext(); 1597 bool RetInReg = F->getAttributes().hasAttribute( 1598 AttributeList::ReturnIndex, Attribute::InReg); 1599 1600 for (unsigned j = 0; j != NumValues; ++j) { 1601 EVT VT = ValueVTs[j]; 1602 1603 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1604 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1605 1606 CallingConv::ID CC = F->getCallingConv(); 1607 1608 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1609 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1610 SmallVector<SDValue, 4> Parts(NumParts); 1611 getCopyToParts(DAG, getCurSDLoc(), 1612 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1613 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1614 1615 // 'inreg' on function refers to return value 1616 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1617 if (RetInReg) 1618 Flags.setInReg(); 1619 1620 // Propagate extension type if any 1621 if (ExtendKind == ISD::SIGN_EXTEND) 1622 Flags.setSExt(); 1623 else if (ExtendKind == ISD::ZERO_EXTEND) 1624 Flags.setZExt(); 1625 1626 for (unsigned i = 0; i < NumParts; ++i) { 1627 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1628 VT, /*isfixed=*/true, 0, 0)); 1629 OutVals.push_back(Parts[i]); 1630 } 1631 } 1632 } 1633 } 1634 1635 // Push in swifterror virtual register as the last element of Outs. This makes 1636 // sure swifterror virtual register will be returned in the swifterror 1637 // physical register. 1638 const Function *F = I.getParent()->getParent(); 1639 if (TLI.supportSwiftError() && 1640 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1641 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1642 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1643 Flags.setSwiftError(); 1644 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1645 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1646 true /*isfixed*/, 1 /*origidx*/, 1647 0 /*partOffs*/)); 1648 // Create SDNode for the swifterror virtual register. 1649 OutVals.push_back( 1650 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1651 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1652 EVT(TLI.getPointerTy(DL)))); 1653 } 1654 1655 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1656 CallingConv::ID CallConv = 1657 DAG.getMachineFunction().getFunction().getCallingConv(); 1658 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1659 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1660 1661 // Verify that the target's LowerReturn behaved as expected. 1662 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1663 "LowerReturn didn't return a valid chain!"); 1664 1665 // Update the DAG with the new chain value resulting from return lowering. 1666 DAG.setRoot(Chain); 1667 } 1668 1669 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1670 /// created for it, emit nodes to copy the value into the virtual 1671 /// registers. 1672 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1673 // Skip empty types 1674 if (V->getType()->isEmptyTy()) 1675 return; 1676 1677 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1678 if (VMI != FuncInfo.ValueMap.end()) { 1679 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1680 CopyValueToVirtualRegister(V, VMI->second); 1681 } 1682 } 1683 1684 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1685 /// the current basic block, add it to ValueMap now so that we'll get a 1686 /// CopyTo/FromReg. 1687 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1688 // No need to export constants. 1689 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1690 1691 // Already exported? 1692 if (FuncInfo.isExportedInst(V)) return; 1693 1694 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1695 CopyValueToVirtualRegister(V, Reg); 1696 } 1697 1698 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1699 const BasicBlock *FromBB) { 1700 // The operands of the setcc have to be in this block. We don't know 1701 // how to export them from some other block. 1702 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1703 // Can export from current BB. 1704 if (VI->getParent() == FromBB) 1705 return true; 1706 1707 // Is already exported, noop. 1708 return FuncInfo.isExportedInst(V); 1709 } 1710 1711 // If this is an argument, we can export it if the BB is the entry block or 1712 // if it is already exported. 1713 if (isa<Argument>(V)) { 1714 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1715 return true; 1716 1717 // Otherwise, can only export this if it is already exported. 1718 return FuncInfo.isExportedInst(V); 1719 } 1720 1721 // Otherwise, constants can always be exported. 1722 return true; 1723 } 1724 1725 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1726 BranchProbability 1727 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1728 const MachineBasicBlock *Dst) const { 1729 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1730 const BasicBlock *SrcBB = Src->getBasicBlock(); 1731 const BasicBlock *DstBB = Dst->getBasicBlock(); 1732 if (!BPI) { 1733 // If BPI is not available, set the default probability as 1 / N, where N is 1734 // the number of successors. 1735 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1736 return BranchProbability(1, SuccSize); 1737 } 1738 return BPI->getEdgeProbability(SrcBB, DstBB); 1739 } 1740 1741 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1742 MachineBasicBlock *Dst, 1743 BranchProbability Prob) { 1744 if (!FuncInfo.BPI) 1745 Src->addSuccessorWithoutProb(Dst); 1746 else { 1747 if (Prob.isUnknown()) 1748 Prob = getEdgeProbability(Src, Dst); 1749 Src->addSuccessor(Dst, Prob); 1750 } 1751 } 1752 1753 static bool InBlock(const Value *V, const BasicBlock *BB) { 1754 if (const Instruction *I = dyn_cast<Instruction>(V)) 1755 return I->getParent() == BB; 1756 return true; 1757 } 1758 1759 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1760 /// This function emits a branch and is used at the leaves of an OR or an 1761 /// AND operator tree. 1762 void 1763 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1764 MachineBasicBlock *TBB, 1765 MachineBasicBlock *FBB, 1766 MachineBasicBlock *CurBB, 1767 MachineBasicBlock *SwitchBB, 1768 BranchProbability TProb, 1769 BranchProbability FProb, 1770 bool InvertCond) { 1771 const BasicBlock *BB = CurBB->getBasicBlock(); 1772 1773 // If the leaf of the tree is a comparison, merge the condition into 1774 // the caseblock. 1775 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1776 // The operands of the cmp have to be in this block. We don't know 1777 // how to export them from some other block. If this is the first block 1778 // of the sequence, no exporting is needed. 1779 if (CurBB == SwitchBB || 1780 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1781 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1782 ISD::CondCode Condition; 1783 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1784 ICmpInst::Predicate Pred = 1785 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1786 Condition = getICmpCondCode(Pred); 1787 } else { 1788 const FCmpInst *FC = cast<FCmpInst>(Cond); 1789 FCmpInst::Predicate Pred = 1790 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1791 Condition = getFCmpCondCode(Pred); 1792 if (TM.Options.NoNaNsFPMath) 1793 Condition = getFCmpCodeWithoutNaN(Condition); 1794 } 1795 1796 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1797 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1798 SwitchCases.push_back(CB); 1799 return; 1800 } 1801 } 1802 1803 // Create a CaseBlock record representing this branch. 1804 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1805 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1806 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1807 SwitchCases.push_back(CB); 1808 } 1809 1810 /// FindMergedConditions - If Cond is an expression like 1811 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1812 MachineBasicBlock *TBB, 1813 MachineBasicBlock *FBB, 1814 MachineBasicBlock *CurBB, 1815 MachineBasicBlock *SwitchBB, 1816 Instruction::BinaryOps Opc, 1817 BranchProbability TProb, 1818 BranchProbability FProb, 1819 bool InvertCond) { 1820 // Skip over not part of the tree and remember to invert op and operands at 1821 // next level. 1822 if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) { 1823 const Value *CondOp = BinaryOperator::getNotArgument(Cond); 1824 if (InBlock(CondOp, CurBB->getBasicBlock())) { 1825 FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1826 !InvertCond); 1827 return; 1828 } 1829 } 1830 1831 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1832 // Compute the effective opcode for Cond, taking into account whether it needs 1833 // to be inverted, e.g. 1834 // and (not (or A, B)), C 1835 // gets lowered as 1836 // and (and (not A, not B), C) 1837 unsigned BOpc = 0; 1838 if (BOp) { 1839 BOpc = BOp->getOpcode(); 1840 if (InvertCond) { 1841 if (BOpc == Instruction::And) 1842 BOpc = Instruction::Or; 1843 else if (BOpc == Instruction::Or) 1844 BOpc = Instruction::And; 1845 } 1846 } 1847 1848 // If this node is not part of the or/and tree, emit it as a branch. 1849 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1850 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1851 BOp->getParent() != CurBB->getBasicBlock() || 1852 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1853 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1854 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1855 TProb, FProb, InvertCond); 1856 return; 1857 } 1858 1859 // Create TmpBB after CurBB. 1860 MachineFunction::iterator BBI(CurBB); 1861 MachineFunction &MF = DAG.getMachineFunction(); 1862 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1863 CurBB->getParent()->insert(++BBI, TmpBB); 1864 1865 if (Opc == Instruction::Or) { 1866 // Codegen X | Y as: 1867 // BB1: 1868 // jmp_if_X TBB 1869 // jmp TmpBB 1870 // TmpBB: 1871 // jmp_if_Y TBB 1872 // jmp FBB 1873 // 1874 1875 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1876 // The requirement is that 1877 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1878 // = TrueProb for original BB. 1879 // Assuming the original probabilities are A and B, one choice is to set 1880 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1881 // A/(1+B) and 2B/(1+B). This choice assumes that 1882 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1883 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1884 // TmpBB, but the math is more complicated. 1885 1886 auto NewTrueProb = TProb / 2; 1887 auto NewFalseProb = TProb / 2 + FProb; 1888 // Emit the LHS condition. 1889 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1890 NewTrueProb, NewFalseProb, InvertCond); 1891 1892 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1893 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1894 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1895 // Emit the RHS condition into TmpBB. 1896 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1897 Probs[0], Probs[1], InvertCond); 1898 } else { 1899 assert(Opc == Instruction::And && "Unknown merge op!"); 1900 // Codegen X & Y as: 1901 // BB1: 1902 // jmp_if_X TmpBB 1903 // jmp FBB 1904 // TmpBB: 1905 // jmp_if_Y TBB 1906 // jmp FBB 1907 // 1908 // This requires creation of TmpBB after CurBB. 1909 1910 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1911 // The requirement is that 1912 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1913 // = FalseProb for original BB. 1914 // Assuming the original probabilities are A and B, one choice is to set 1915 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1916 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1917 // TrueProb for BB1 * FalseProb for TmpBB. 1918 1919 auto NewTrueProb = TProb + FProb / 2; 1920 auto NewFalseProb = FProb / 2; 1921 // Emit the LHS condition. 1922 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1923 NewTrueProb, NewFalseProb, InvertCond); 1924 1925 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1926 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1927 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1928 // Emit the RHS condition into TmpBB. 1929 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1930 Probs[0], Probs[1], InvertCond); 1931 } 1932 } 1933 1934 /// If the set of cases should be emitted as a series of branches, return true. 1935 /// If we should emit this as a bunch of and/or'd together conditions, return 1936 /// false. 1937 bool 1938 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1939 if (Cases.size() != 2) return true; 1940 1941 // If this is two comparisons of the same values or'd or and'd together, they 1942 // will get folded into a single comparison, so don't emit two blocks. 1943 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1944 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1945 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1946 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1947 return false; 1948 } 1949 1950 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1951 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1952 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1953 Cases[0].CC == Cases[1].CC && 1954 isa<Constant>(Cases[0].CmpRHS) && 1955 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1956 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1957 return false; 1958 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1959 return false; 1960 } 1961 1962 return true; 1963 } 1964 1965 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1966 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1967 1968 // Update machine-CFG edges. 1969 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1970 1971 if (I.isUnconditional()) { 1972 // Update machine-CFG edges. 1973 BrMBB->addSuccessor(Succ0MBB); 1974 1975 // If this is not a fall-through branch or optimizations are switched off, 1976 // emit the branch. 1977 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1978 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1979 MVT::Other, getControlRoot(), 1980 DAG.getBasicBlock(Succ0MBB))); 1981 1982 return; 1983 } 1984 1985 // If this condition is one of the special cases we handle, do special stuff 1986 // now. 1987 const Value *CondVal = I.getCondition(); 1988 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1989 1990 // If this is a series of conditions that are or'd or and'd together, emit 1991 // this as a sequence of branches instead of setcc's with and/or operations. 1992 // As long as jumps are not expensive, this should improve performance. 1993 // For example, instead of something like: 1994 // cmp A, B 1995 // C = seteq 1996 // cmp D, E 1997 // F = setle 1998 // or C, F 1999 // jnz foo 2000 // Emit: 2001 // cmp A, B 2002 // je foo 2003 // cmp D, E 2004 // jle foo 2005 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2006 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2007 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2008 !I.getMetadata(LLVMContext::MD_unpredictable) && 2009 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2010 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2011 Opcode, 2012 getEdgeProbability(BrMBB, Succ0MBB), 2013 getEdgeProbability(BrMBB, Succ1MBB), 2014 /*InvertCond=*/false); 2015 // If the compares in later blocks need to use values not currently 2016 // exported from this block, export them now. This block should always 2017 // be the first entry. 2018 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2019 2020 // Allow some cases to be rejected. 2021 if (ShouldEmitAsBranches(SwitchCases)) { 2022 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2023 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2024 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2025 } 2026 2027 // Emit the branch for this block. 2028 visitSwitchCase(SwitchCases[0], BrMBB); 2029 SwitchCases.erase(SwitchCases.begin()); 2030 return; 2031 } 2032 2033 // Okay, we decided not to do this, remove any inserted MBB's and clear 2034 // SwitchCases. 2035 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2036 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2037 2038 SwitchCases.clear(); 2039 } 2040 } 2041 2042 // Create a CaseBlock record representing this branch. 2043 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2044 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2045 2046 // Use visitSwitchCase to actually insert the fast branch sequence for this 2047 // cond branch. 2048 visitSwitchCase(CB, BrMBB); 2049 } 2050 2051 /// visitSwitchCase - Emits the necessary code to represent a single node in 2052 /// the binary search tree resulting from lowering a switch instruction. 2053 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2054 MachineBasicBlock *SwitchBB) { 2055 SDValue Cond; 2056 SDValue CondLHS = getValue(CB.CmpLHS); 2057 SDLoc dl = CB.DL; 2058 2059 // Build the setcc now. 2060 if (!CB.CmpMHS) { 2061 // Fold "(X == true)" to X and "(X == false)" to !X to 2062 // handle common cases produced by branch lowering. 2063 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2064 CB.CC == ISD::SETEQ) 2065 Cond = CondLHS; 2066 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2067 CB.CC == ISD::SETEQ) { 2068 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2069 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2070 } else 2071 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2072 } else { 2073 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2074 2075 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2076 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2077 2078 SDValue CmpOp = getValue(CB.CmpMHS); 2079 EVT VT = CmpOp.getValueType(); 2080 2081 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2082 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2083 ISD::SETLE); 2084 } else { 2085 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2086 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2087 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2088 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2089 } 2090 } 2091 2092 // Update successor info 2093 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2094 // TrueBB and FalseBB are always different unless the incoming IR is 2095 // degenerate. This only happens when running llc on weird IR. 2096 if (CB.TrueBB != CB.FalseBB) 2097 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2098 SwitchBB->normalizeSuccProbs(); 2099 2100 // If the lhs block is the next block, invert the condition so that we can 2101 // fall through to the lhs instead of the rhs block. 2102 if (CB.TrueBB == NextBlock(SwitchBB)) { 2103 std::swap(CB.TrueBB, CB.FalseBB); 2104 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2105 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2106 } 2107 2108 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2109 MVT::Other, getControlRoot(), Cond, 2110 DAG.getBasicBlock(CB.TrueBB)); 2111 2112 // Insert the false branch. Do this even if it's a fall through branch, 2113 // this makes it easier to do DAG optimizations which require inverting 2114 // the branch condition. 2115 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2116 DAG.getBasicBlock(CB.FalseBB)); 2117 2118 DAG.setRoot(BrCond); 2119 } 2120 2121 /// visitJumpTable - Emit JumpTable node in the current MBB 2122 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2123 // Emit the code for the jump table 2124 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2125 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2126 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2127 JT.Reg, PTy); 2128 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2129 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2130 MVT::Other, Index.getValue(1), 2131 Table, Index); 2132 DAG.setRoot(BrJumpTable); 2133 } 2134 2135 /// visitJumpTableHeader - This function emits necessary code to produce index 2136 /// in the JumpTable from switch case. 2137 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2138 JumpTableHeader &JTH, 2139 MachineBasicBlock *SwitchBB) { 2140 SDLoc dl = getCurSDLoc(); 2141 2142 // Subtract the lowest switch case value from the value being switched on and 2143 // conditional branch to default mbb if the result is greater than the 2144 // difference between smallest and largest cases. 2145 SDValue SwitchOp = getValue(JTH.SValue); 2146 EVT VT = SwitchOp.getValueType(); 2147 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2148 DAG.getConstant(JTH.First, dl, VT)); 2149 2150 // The SDNode we just created, which holds the value being switched on minus 2151 // the smallest case value, needs to be copied to a virtual register so it 2152 // can be used as an index into the jump table in a subsequent basic block. 2153 // This value may be smaller or larger than the target's pointer type, and 2154 // therefore require extension or truncating. 2155 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2156 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2157 2158 unsigned JumpTableReg = 2159 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2160 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2161 JumpTableReg, SwitchOp); 2162 JT.Reg = JumpTableReg; 2163 2164 // Emit the range check for the jump table, and branch to the default block 2165 // for the switch statement if the value being switched on exceeds the largest 2166 // case in the switch. 2167 SDValue CMP = DAG.getSetCC( 2168 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2169 Sub.getValueType()), 2170 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2171 2172 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2173 MVT::Other, CopyTo, CMP, 2174 DAG.getBasicBlock(JT.Default)); 2175 2176 // Avoid emitting unnecessary branches to the next block. 2177 if (JT.MBB != NextBlock(SwitchBB)) 2178 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2179 DAG.getBasicBlock(JT.MBB)); 2180 2181 DAG.setRoot(BrCond); 2182 } 2183 2184 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2185 /// variable if there exists one. 2186 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2187 SDValue &Chain) { 2188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2189 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2190 MachineFunction &MF = DAG.getMachineFunction(); 2191 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2192 MachineSDNode *Node = 2193 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2194 if (Global) { 2195 MachinePointerInfo MPInfo(Global); 2196 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2197 MachineMemOperand::MODereferenceable; 2198 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2199 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2200 DAG.setNodeMemRefs(Node, {MemRef}); 2201 } 2202 return SDValue(Node, 0); 2203 } 2204 2205 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2206 /// tail spliced into a stack protector check success bb. 2207 /// 2208 /// For a high level explanation of how this fits into the stack protector 2209 /// generation see the comment on the declaration of class 2210 /// StackProtectorDescriptor. 2211 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2212 MachineBasicBlock *ParentBB) { 2213 2214 // First create the loads to the guard/stack slot for the comparison. 2215 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2216 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2217 2218 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2219 int FI = MFI.getStackProtectorIndex(); 2220 2221 SDValue Guard; 2222 SDLoc dl = getCurSDLoc(); 2223 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2224 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2225 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2226 2227 // Generate code to load the content of the guard slot. 2228 SDValue GuardVal = DAG.getLoad( 2229 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2230 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2231 MachineMemOperand::MOVolatile); 2232 2233 if (TLI.useStackGuardXorFP()) 2234 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2235 2236 // Retrieve guard check function, nullptr if instrumentation is inlined. 2237 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2238 // The target provides a guard check function to validate the guard value. 2239 // Generate a call to that function with the content of the guard slot as 2240 // argument. 2241 auto *Fn = cast<Function>(GuardCheck); 2242 FunctionType *FnTy = Fn->getFunctionType(); 2243 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2244 2245 TargetLowering::ArgListTy Args; 2246 TargetLowering::ArgListEntry Entry; 2247 Entry.Node = GuardVal; 2248 Entry.Ty = FnTy->getParamType(0); 2249 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2250 Entry.IsInReg = true; 2251 Args.push_back(Entry); 2252 2253 TargetLowering::CallLoweringInfo CLI(DAG); 2254 CLI.setDebugLoc(getCurSDLoc()) 2255 .setChain(DAG.getEntryNode()) 2256 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2257 getValue(GuardCheck), std::move(Args)); 2258 2259 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2260 DAG.setRoot(Result.second); 2261 return; 2262 } 2263 2264 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2265 // Otherwise, emit a volatile load to retrieve the stack guard value. 2266 SDValue Chain = DAG.getEntryNode(); 2267 if (TLI.useLoadStackGuardNode()) { 2268 Guard = getLoadStackGuard(DAG, dl, Chain); 2269 } else { 2270 const Value *IRGuard = TLI.getSDagStackGuard(M); 2271 SDValue GuardPtr = getValue(IRGuard); 2272 2273 Guard = 2274 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2275 Align, MachineMemOperand::MOVolatile); 2276 } 2277 2278 // Perform the comparison via a subtract/getsetcc. 2279 EVT VT = Guard.getValueType(); 2280 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2281 2282 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2283 *DAG.getContext(), 2284 Sub.getValueType()), 2285 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2286 2287 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2288 // branch to failure MBB. 2289 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2290 MVT::Other, GuardVal.getOperand(0), 2291 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2292 // Otherwise branch to success MBB. 2293 SDValue Br = DAG.getNode(ISD::BR, dl, 2294 MVT::Other, BrCond, 2295 DAG.getBasicBlock(SPD.getSuccessMBB())); 2296 2297 DAG.setRoot(Br); 2298 } 2299 2300 /// Codegen the failure basic block for a stack protector check. 2301 /// 2302 /// A failure stack protector machine basic block consists simply of a call to 2303 /// __stack_chk_fail(). 2304 /// 2305 /// For a high level explanation of how this fits into the stack protector 2306 /// generation see the comment on the declaration of class 2307 /// StackProtectorDescriptor. 2308 void 2309 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2310 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2311 SDValue Chain = 2312 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2313 None, false, getCurSDLoc(), false, false).second; 2314 DAG.setRoot(Chain); 2315 } 2316 2317 /// visitBitTestHeader - This function emits necessary code to produce value 2318 /// suitable for "bit tests" 2319 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2320 MachineBasicBlock *SwitchBB) { 2321 SDLoc dl = getCurSDLoc(); 2322 2323 // Subtract the minimum value 2324 SDValue SwitchOp = getValue(B.SValue); 2325 EVT VT = SwitchOp.getValueType(); 2326 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2327 DAG.getConstant(B.First, dl, VT)); 2328 2329 // Check range 2330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2331 SDValue RangeCmp = DAG.getSetCC( 2332 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2333 Sub.getValueType()), 2334 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2335 2336 // Determine the type of the test operands. 2337 bool UsePtrType = false; 2338 if (!TLI.isTypeLegal(VT)) 2339 UsePtrType = true; 2340 else { 2341 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2342 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2343 // Switch table case range are encoded into series of masks. 2344 // Just use pointer type, it's guaranteed to fit. 2345 UsePtrType = true; 2346 break; 2347 } 2348 } 2349 if (UsePtrType) { 2350 VT = TLI.getPointerTy(DAG.getDataLayout()); 2351 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2352 } 2353 2354 B.RegVT = VT.getSimpleVT(); 2355 B.Reg = FuncInfo.CreateReg(B.RegVT); 2356 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2357 2358 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2359 2360 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2361 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2362 SwitchBB->normalizeSuccProbs(); 2363 2364 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2365 MVT::Other, CopyTo, RangeCmp, 2366 DAG.getBasicBlock(B.Default)); 2367 2368 // Avoid emitting unnecessary branches to the next block. 2369 if (MBB != NextBlock(SwitchBB)) 2370 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2371 DAG.getBasicBlock(MBB)); 2372 2373 DAG.setRoot(BrRange); 2374 } 2375 2376 /// visitBitTestCase - this function produces one "bit test" 2377 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2378 MachineBasicBlock* NextMBB, 2379 BranchProbability BranchProbToNext, 2380 unsigned Reg, 2381 BitTestCase &B, 2382 MachineBasicBlock *SwitchBB) { 2383 SDLoc dl = getCurSDLoc(); 2384 MVT VT = BB.RegVT; 2385 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2386 SDValue Cmp; 2387 unsigned PopCount = countPopulation(B.Mask); 2388 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2389 if (PopCount == 1) { 2390 // Testing for a single bit; just compare the shift count with what it 2391 // would need to be to shift a 1 bit in that position. 2392 Cmp = DAG.getSetCC( 2393 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2394 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2395 ISD::SETEQ); 2396 } else if (PopCount == BB.Range) { 2397 // There is only one zero bit in the range, test for it directly. 2398 Cmp = DAG.getSetCC( 2399 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2400 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2401 ISD::SETNE); 2402 } else { 2403 // Make desired shift 2404 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2405 DAG.getConstant(1, dl, VT), ShiftOp); 2406 2407 // Emit bit tests and jumps 2408 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2409 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2410 Cmp = DAG.getSetCC( 2411 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2412 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2413 } 2414 2415 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2416 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2417 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2418 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2419 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2420 // one as they are relative probabilities (and thus work more like weights), 2421 // and hence we need to normalize them to let the sum of them become one. 2422 SwitchBB->normalizeSuccProbs(); 2423 2424 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2425 MVT::Other, getControlRoot(), 2426 Cmp, DAG.getBasicBlock(B.TargetBB)); 2427 2428 // Avoid emitting unnecessary branches to the next block. 2429 if (NextMBB != NextBlock(SwitchBB)) 2430 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2431 DAG.getBasicBlock(NextMBB)); 2432 2433 DAG.setRoot(BrAnd); 2434 } 2435 2436 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2437 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2438 2439 // Retrieve successors. Look through artificial IR level blocks like 2440 // catchswitch for successors. 2441 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2442 const BasicBlock *EHPadBB = I.getSuccessor(1); 2443 2444 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2445 // have to do anything here to lower funclet bundles. 2446 assert(!I.hasOperandBundlesOtherThan( 2447 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2448 "Cannot lower invokes with arbitrary operand bundles yet!"); 2449 2450 const Value *Callee(I.getCalledValue()); 2451 const Function *Fn = dyn_cast<Function>(Callee); 2452 if (isa<InlineAsm>(Callee)) 2453 visitInlineAsm(&I); 2454 else if (Fn && Fn->isIntrinsic()) { 2455 switch (Fn->getIntrinsicID()) { 2456 default: 2457 llvm_unreachable("Cannot invoke this intrinsic"); 2458 case Intrinsic::donothing: 2459 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2460 break; 2461 case Intrinsic::experimental_patchpoint_void: 2462 case Intrinsic::experimental_patchpoint_i64: 2463 visitPatchpoint(&I, EHPadBB); 2464 break; 2465 case Intrinsic::experimental_gc_statepoint: 2466 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2467 break; 2468 } 2469 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2470 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2471 // Eventually we will support lowering the @llvm.experimental.deoptimize 2472 // intrinsic, and right now there are no plans to support other intrinsics 2473 // with deopt state. 2474 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2475 } else { 2476 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2477 } 2478 2479 // If the value of the invoke is used outside of its defining block, make it 2480 // available as a virtual register. 2481 // We already took care of the exported value for the statepoint instruction 2482 // during call to the LowerStatepoint. 2483 if (!isStatepoint(I)) { 2484 CopyToExportRegsIfNeeded(&I); 2485 } 2486 2487 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2488 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2489 BranchProbability EHPadBBProb = 2490 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2491 : BranchProbability::getZero(); 2492 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2493 2494 // Update successor info. 2495 addSuccessorWithProb(InvokeMBB, Return); 2496 for (auto &UnwindDest : UnwindDests) { 2497 UnwindDest.first->setIsEHPad(); 2498 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2499 } 2500 InvokeMBB->normalizeSuccProbs(); 2501 2502 // Drop into normal successor. 2503 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2504 MVT::Other, getControlRoot(), 2505 DAG.getBasicBlock(Return))); 2506 } 2507 2508 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2509 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2510 } 2511 2512 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2513 assert(FuncInfo.MBB->isEHPad() && 2514 "Call to landingpad not in landing pad!"); 2515 2516 MachineBasicBlock *MBB = FuncInfo.MBB; 2517 addLandingPadInfo(LP, *MBB); 2518 2519 // If there aren't registers to copy the values into (e.g., during SjLj 2520 // exceptions), then don't bother to create these DAG nodes. 2521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2522 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2523 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2524 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2525 return; 2526 2527 // If landingpad's return type is token type, we don't create DAG nodes 2528 // for its exception pointer and selector value. The extraction of exception 2529 // pointer or selector value from token type landingpads is not currently 2530 // supported. 2531 if (LP.getType()->isTokenTy()) 2532 return; 2533 2534 SmallVector<EVT, 2> ValueVTs; 2535 SDLoc dl = getCurSDLoc(); 2536 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2537 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2538 2539 // Get the two live-in registers as SDValues. The physregs have already been 2540 // copied into virtual registers. 2541 SDValue Ops[2]; 2542 if (FuncInfo.ExceptionPointerVirtReg) { 2543 Ops[0] = DAG.getZExtOrTrunc( 2544 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2545 FuncInfo.ExceptionPointerVirtReg, 2546 TLI.getPointerTy(DAG.getDataLayout())), 2547 dl, ValueVTs[0]); 2548 } else { 2549 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2550 } 2551 Ops[1] = DAG.getZExtOrTrunc( 2552 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2553 FuncInfo.ExceptionSelectorVirtReg, 2554 TLI.getPointerTy(DAG.getDataLayout())), 2555 dl, ValueVTs[1]); 2556 2557 // Merge into one. 2558 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2559 DAG.getVTList(ValueVTs), Ops); 2560 setValue(&LP, Res); 2561 } 2562 2563 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2564 #ifndef NDEBUG 2565 for (const CaseCluster &CC : Clusters) 2566 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2567 #endif 2568 2569 llvm::sort(Clusters.begin(), Clusters.end(), 2570 [](const CaseCluster &a, const CaseCluster &b) { 2571 return a.Low->getValue().slt(b.Low->getValue()); 2572 }); 2573 2574 // Merge adjacent clusters with the same destination. 2575 const unsigned N = Clusters.size(); 2576 unsigned DstIndex = 0; 2577 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2578 CaseCluster &CC = Clusters[SrcIndex]; 2579 const ConstantInt *CaseVal = CC.Low; 2580 MachineBasicBlock *Succ = CC.MBB; 2581 2582 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2583 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2584 // If this case has the same successor and is a neighbour, merge it into 2585 // the previous cluster. 2586 Clusters[DstIndex - 1].High = CaseVal; 2587 Clusters[DstIndex - 1].Prob += CC.Prob; 2588 } else { 2589 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2590 sizeof(Clusters[SrcIndex])); 2591 } 2592 } 2593 Clusters.resize(DstIndex); 2594 } 2595 2596 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2597 MachineBasicBlock *Last) { 2598 // Update JTCases. 2599 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2600 if (JTCases[i].first.HeaderBB == First) 2601 JTCases[i].first.HeaderBB = Last; 2602 2603 // Update BitTestCases. 2604 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2605 if (BitTestCases[i].Parent == First) 2606 BitTestCases[i].Parent = Last; 2607 } 2608 2609 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2610 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2611 2612 // Update machine-CFG edges with unique successors. 2613 SmallSet<BasicBlock*, 32> Done; 2614 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2615 BasicBlock *BB = I.getSuccessor(i); 2616 bool Inserted = Done.insert(BB).second; 2617 if (!Inserted) 2618 continue; 2619 2620 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2621 addSuccessorWithProb(IndirectBrMBB, Succ); 2622 } 2623 IndirectBrMBB->normalizeSuccProbs(); 2624 2625 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2626 MVT::Other, getControlRoot(), 2627 getValue(I.getAddress()))); 2628 } 2629 2630 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2631 if (!DAG.getTarget().Options.TrapUnreachable) 2632 return; 2633 2634 // We may be able to ignore unreachable behind a noreturn call. 2635 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2636 const BasicBlock &BB = *I.getParent(); 2637 if (&I != &BB.front()) { 2638 BasicBlock::const_iterator PredI = 2639 std::prev(BasicBlock::const_iterator(&I)); 2640 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2641 if (Call->doesNotReturn()) 2642 return; 2643 } 2644 } 2645 } 2646 2647 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2648 } 2649 2650 void SelectionDAGBuilder::visitFSub(const User &I) { 2651 // -0.0 - X --> fneg 2652 Type *Ty = I.getType(); 2653 if (isa<Constant>(I.getOperand(0)) && 2654 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2655 SDValue Op2 = getValue(I.getOperand(1)); 2656 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2657 Op2.getValueType(), Op2)); 2658 return; 2659 } 2660 2661 visitBinary(I, ISD::FSUB); 2662 } 2663 2664 /// Checks if the given instruction performs a vector reduction, in which case 2665 /// we have the freedom to alter the elements in the result as long as the 2666 /// reduction of them stays unchanged. 2667 static bool isVectorReductionOp(const User *I) { 2668 const Instruction *Inst = dyn_cast<Instruction>(I); 2669 if (!Inst || !Inst->getType()->isVectorTy()) 2670 return false; 2671 2672 auto OpCode = Inst->getOpcode(); 2673 switch (OpCode) { 2674 case Instruction::Add: 2675 case Instruction::Mul: 2676 case Instruction::And: 2677 case Instruction::Or: 2678 case Instruction::Xor: 2679 break; 2680 case Instruction::FAdd: 2681 case Instruction::FMul: 2682 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2683 if (FPOp->getFastMathFlags().isFast()) 2684 break; 2685 LLVM_FALLTHROUGH; 2686 default: 2687 return false; 2688 } 2689 2690 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2691 // Ensure the reduction size is a power of 2. 2692 if (!isPowerOf2_32(ElemNum)) 2693 return false; 2694 2695 unsigned ElemNumToReduce = ElemNum; 2696 2697 // Do DFS search on the def-use chain from the given instruction. We only 2698 // allow four kinds of operations during the search until we reach the 2699 // instruction that extracts the first element from the vector: 2700 // 2701 // 1. The reduction operation of the same opcode as the given instruction. 2702 // 2703 // 2. PHI node. 2704 // 2705 // 3. ShuffleVector instruction together with a reduction operation that 2706 // does a partial reduction. 2707 // 2708 // 4. ExtractElement that extracts the first element from the vector, and we 2709 // stop searching the def-use chain here. 2710 // 2711 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2712 // from 1-3 to the stack to continue the DFS. The given instruction is not 2713 // a reduction operation if we meet any other instructions other than those 2714 // listed above. 2715 2716 SmallVector<const User *, 16> UsersToVisit{Inst}; 2717 SmallPtrSet<const User *, 16> Visited; 2718 bool ReduxExtracted = false; 2719 2720 while (!UsersToVisit.empty()) { 2721 auto User = UsersToVisit.back(); 2722 UsersToVisit.pop_back(); 2723 if (!Visited.insert(User).second) 2724 continue; 2725 2726 for (const auto &U : User->users()) { 2727 auto Inst = dyn_cast<Instruction>(U); 2728 if (!Inst) 2729 return false; 2730 2731 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2732 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2733 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2734 return false; 2735 UsersToVisit.push_back(U); 2736 } else if (const ShuffleVectorInst *ShufInst = 2737 dyn_cast<ShuffleVectorInst>(U)) { 2738 // Detect the following pattern: A ShuffleVector instruction together 2739 // with a reduction that do partial reduction on the first and second 2740 // ElemNumToReduce / 2 elements, and store the result in 2741 // ElemNumToReduce / 2 elements in another vector. 2742 2743 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2744 if (ResultElements < ElemNum) 2745 return false; 2746 2747 if (ElemNumToReduce == 1) 2748 return false; 2749 if (!isa<UndefValue>(U->getOperand(1))) 2750 return false; 2751 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2752 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2753 return false; 2754 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2755 if (ShufInst->getMaskValue(i) != -1) 2756 return false; 2757 2758 // There is only one user of this ShuffleVector instruction, which 2759 // must be a reduction operation. 2760 if (!U->hasOneUse()) 2761 return false; 2762 2763 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2764 if (!U2 || U2->getOpcode() != OpCode) 2765 return false; 2766 2767 // Check operands of the reduction operation. 2768 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2769 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2770 UsersToVisit.push_back(U2); 2771 ElemNumToReduce /= 2; 2772 } else 2773 return false; 2774 } else if (isa<ExtractElementInst>(U)) { 2775 // At this moment we should have reduced all elements in the vector. 2776 if (ElemNumToReduce != 1) 2777 return false; 2778 2779 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2780 if (!Val || !Val->isZero()) 2781 return false; 2782 2783 ReduxExtracted = true; 2784 } else 2785 return false; 2786 } 2787 } 2788 return ReduxExtracted; 2789 } 2790 2791 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2792 SDNodeFlags Flags; 2793 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2794 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2795 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2796 } 2797 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2798 Flags.setExact(ExactOp->isExact()); 2799 } 2800 if (isVectorReductionOp(&I)) { 2801 Flags.setVectorReduction(true); 2802 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2803 } 2804 2805 SDValue Op1 = getValue(I.getOperand(0)); 2806 SDValue Op2 = getValue(I.getOperand(1)); 2807 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2808 Op1, Op2, Flags); 2809 setValue(&I, BinNodeValue); 2810 } 2811 2812 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2813 SDValue Op1 = getValue(I.getOperand(0)); 2814 SDValue Op2 = getValue(I.getOperand(1)); 2815 2816 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2817 Op2.getValueType(), DAG.getDataLayout()); 2818 2819 // Coerce the shift amount to the right type if we can. 2820 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2821 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2822 unsigned Op2Size = Op2.getValueSizeInBits(); 2823 SDLoc DL = getCurSDLoc(); 2824 2825 // If the operand is smaller than the shift count type, promote it. 2826 if (ShiftSize > Op2Size) 2827 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2828 2829 // If the operand is larger than the shift count type but the shift 2830 // count type has enough bits to represent any shift value, truncate 2831 // it now. This is a common case and it exposes the truncate to 2832 // optimization early. 2833 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2834 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2835 // Otherwise we'll need to temporarily settle for some other convenient 2836 // type. Type legalization will make adjustments once the shiftee is split. 2837 else 2838 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2839 } 2840 2841 bool nuw = false; 2842 bool nsw = false; 2843 bool exact = false; 2844 2845 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2846 2847 if (const OverflowingBinaryOperator *OFBinOp = 2848 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2849 nuw = OFBinOp->hasNoUnsignedWrap(); 2850 nsw = OFBinOp->hasNoSignedWrap(); 2851 } 2852 if (const PossiblyExactOperator *ExactOp = 2853 dyn_cast<const PossiblyExactOperator>(&I)) 2854 exact = ExactOp->isExact(); 2855 } 2856 SDNodeFlags Flags; 2857 Flags.setExact(exact); 2858 Flags.setNoSignedWrap(nsw); 2859 Flags.setNoUnsignedWrap(nuw); 2860 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2861 Flags); 2862 setValue(&I, Res); 2863 } 2864 2865 void SelectionDAGBuilder::visitSDiv(const User &I) { 2866 SDValue Op1 = getValue(I.getOperand(0)); 2867 SDValue Op2 = getValue(I.getOperand(1)); 2868 2869 SDNodeFlags Flags; 2870 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2871 cast<PossiblyExactOperator>(&I)->isExact()); 2872 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2873 Op2, Flags)); 2874 } 2875 2876 void SelectionDAGBuilder::visitICmp(const User &I) { 2877 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2878 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2879 predicate = IC->getPredicate(); 2880 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2881 predicate = ICmpInst::Predicate(IC->getPredicate()); 2882 SDValue Op1 = getValue(I.getOperand(0)); 2883 SDValue Op2 = getValue(I.getOperand(1)); 2884 ISD::CondCode Opcode = getICmpCondCode(predicate); 2885 2886 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2887 I.getType()); 2888 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2889 } 2890 2891 void SelectionDAGBuilder::visitFCmp(const User &I) { 2892 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2893 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2894 predicate = FC->getPredicate(); 2895 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2896 predicate = FCmpInst::Predicate(FC->getPredicate()); 2897 SDValue Op1 = getValue(I.getOperand(0)); 2898 SDValue Op2 = getValue(I.getOperand(1)); 2899 2900 ISD::CondCode Condition = getFCmpCondCode(predicate); 2901 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2902 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2903 Condition = getFCmpCodeWithoutNaN(Condition); 2904 2905 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2906 I.getType()); 2907 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2908 } 2909 2910 // Check if the condition of the select has one use or two users that are both 2911 // selects with the same condition. 2912 static bool hasOnlySelectUsers(const Value *Cond) { 2913 return llvm::all_of(Cond->users(), [](const Value *V) { 2914 return isa<SelectInst>(V); 2915 }); 2916 } 2917 2918 void SelectionDAGBuilder::visitSelect(const User &I) { 2919 SmallVector<EVT, 4> ValueVTs; 2920 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2921 ValueVTs); 2922 unsigned NumValues = ValueVTs.size(); 2923 if (NumValues == 0) return; 2924 2925 SmallVector<SDValue, 4> Values(NumValues); 2926 SDValue Cond = getValue(I.getOperand(0)); 2927 SDValue LHSVal = getValue(I.getOperand(1)); 2928 SDValue RHSVal = getValue(I.getOperand(2)); 2929 auto BaseOps = {Cond}; 2930 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2931 ISD::VSELECT : ISD::SELECT; 2932 2933 // Min/max matching is only viable if all output VTs are the same. 2934 if (is_splat(ValueVTs)) { 2935 EVT VT = ValueVTs[0]; 2936 LLVMContext &Ctx = *DAG.getContext(); 2937 auto &TLI = DAG.getTargetLoweringInfo(); 2938 2939 // We care about the legality of the operation after it has been type 2940 // legalized. 2941 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2942 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2943 VT = TLI.getTypeToTransformTo(Ctx, VT); 2944 2945 // If the vselect is legal, assume we want to leave this as a vector setcc + 2946 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2947 // min/max is legal on the scalar type. 2948 bool UseScalarMinMax = VT.isVector() && 2949 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2950 2951 Value *LHS, *RHS; 2952 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2953 ISD::NodeType Opc = ISD::DELETED_NODE; 2954 switch (SPR.Flavor) { 2955 case SPF_UMAX: Opc = ISD::UMAX; break; 2956 case SPF_UMIN: Opc = ISD::UMIN; break; 2957 case SPF_SMAX: Opc = ISD::SMAX; break; 2958 case SPF_SMIN: Opc = ISD::SMIN; break; 2959 case SPF_FMINNUM: 2960 switch (SPR.NaNBehavior) { 2961 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2962 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2963 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2964 case SPNB_RETURNS_ANY: { 2965 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2966 Opc = ISD::FMINNUM; 2967 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2968 Opc = ISD::FMINNAN; 2969 else if (UseScalarMinMax) 2970 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2971 ISD::FMINNUM : ISD::FMINNAN; 2972 break; 2973 } 2974 } 2975 break; 2976 case SPF_FMAXNUM: 2977 switch (SPR.NaNBehavior) { 2978 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2979 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2980 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2981 case SPNB_RETURNS_ANY: 2982 2983 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2984 Opc = ISD::FMAXNUM; 2985 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2986 Opc = ISD::FMAXNAN; 2987 else if (UseScalarMinMax) 2988 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2989 ISD::FMAXNUM : ISD::FMAXNAN; 2990 break; 2991 } 2992 break; 2993 default: break; 2994 } 2995 2996 if (Opc != ISD::DELETED_NODE && 2997 (TLI.isOperationLegalOrCustom(Opc, VT) || 2998 (UseScalarMinMax && 2999 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3000 // If the underlying comparison instruction is used by any other 3001 // instruction, the consumed instructions won't be destroyed, so it is 3002 // not profitable to convert to a min/max. 3003 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3004 OpCode = Opc; 3005 LHSVal = getValue(LHS); 3006 RHSVal = getValue(RHS); 3007 BaseOps = {}; 3008 } 3009 } 3010 3011 for (unsigned i = 0; i != NumValues; ++i) { 3012 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3013 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3014 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3015 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3016 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3017 Ops); 3018 } 3019 3020 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3021 DAG.getVTList(ValueVTs), Values)); 3022 } 3023 3024 void SelectionDAGBuilder::visitTrunc(const User &I) { 3025 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3026 SDValue N = getValue(I.getOperand(0)); 3027 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3028 I.getType()); 3029 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3030 } 3031 3032 void SelectionDAGBuilder::visitZExt(const User &I) { 3033 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3034 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3035 SDValue N = getValue(I.getOperand(0)); 3036 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3037 I.getType()); 3038 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3039 } 3040 3041 void SelectionDAGBuilder::visitSExt(const User &I) { 3042 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3043 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3044 SDValue N = getValue(I.getOperand(0)); 3045 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3046 I.getType()); 3047 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3048 } 3049 3050 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3051 // FPTrunc is never a no-op cast, no need to check 3052 SDValue N = getValue(I.getOperand(0)); 3053 SDLoc dl = getCurSDLoc(); 3054 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3055 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3056 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3057 DAG.getTargetConstant( 3058 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3059 } 3060 3061 void SelectionDAGBuilder::visitFPExt(const User &I) { 3062 // FPExt is never a no-op cast, no need to check 3063 SDValue N = getValue(I.getOperand(0)); 3064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3065 I.getType()); 3066 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3067 } 3068 3069 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3070 // FPToUI is never a no-op cast, no need to check 3071 SDValue N = getValue(I.getOperand(0)); 3072 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3073 I.getType()); 3074 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3075 } 3076 3077 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3078 // FPToSI is never a no-op cast, no need to check 3079 SDValue N = getValue(I.getOperand(0)); 3080 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3081 I.getType()); 3082 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3083 } 3084 3085 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3086 // UIToFP is never a no-op cast, no need to check 3087 SDValue N = getValue(I.getOperand(0)); 3088 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3089 I.getType()); 3090 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3091 } 3092 3093 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3094 // SIToFP is never a no-op cast, no need to check 3095 SDValue N = getValue(I.getOperand(0)); 3096 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3097 I.getType()); 3098 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3099 } 3100 3101 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3102 // What to do depends on the size of the integer and the size of the pointer. 3103 // We can either truncate, zero extend, or no-op, accordingly. 3104 SDValue N = getValue(I.getOperand(0)); 3105 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3106 I.getType()); 3107 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3108 } 3109 3110 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3111 // What to do depends on the size of the integer and the size of the pointer. 3112 // We can either truncate, zero extend, or no-op, accordingly. 3113 SDValue N = getValue(I.getOperand(0)); 3114 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3115 I.getType()); 3116 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3117 } 3118 3119 void SelectionDAGBuilder::visitBitCast(const User &I) { 3120 SDValue N = getValue(I.getOperand(0)); 3121 SDLoc dl = getCurSDLoc(); 3122 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3123 I.getType()); 3124 3125 // BitCast assures us that source and destination are the same size so this is 3126 // either a BITCAST or a no-op. 3127 if (DestVT != N.getValueType()) 3128 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3129 DestVT, N)); // convert types. 3130 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3131 // might fold any kind of constant expression to an integer constant and that 3132 // is not what we are looking for. Only recognize a bitcast of a genuine 3133 // constant integer as an opaque constant. 3134 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3135 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3136 /*isOpaque*/true)); 3137 else 3138 setValue(&I, N); // noop cast. 3139 } 3140 3141 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3143 const Value *SV = I.getOperand(0); 3144 SDValue N = getValue(SV); 3145 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3146 3147 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3148 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3149 3150 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3151 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3152 3153 setValue(&I, N); 3154 } 3155 3156 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3157 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3158 SDValue InVec = getValue(I.getOperand(0)); 3159 SDValue InVal = getValue(I.getOperand(1)); 3160 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3161 TLI.getVectorIdxTy(DAG.getDataLayout())); 3162 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3163 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3164 InVec, InVal, InIdx)); 3165 } 3166 3167 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3168 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3169 SDValue InVec = getValue(I.getOperand(0)); 3170 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3171 TLI.getVectorIdxTy(DAG.getDataLayout())); 3172 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3173 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3174 InVec, InIdx)); 3175 } 3176 3177 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3178 SDValue Src1 = getValue(I.getOperand(0)); 3179 SDValue Src2 = getValue(I.getOperand(1)); 3180 SDLoc DL = getCurSDLoc(); 3181 3182 SmallVector<int, 8> Mask; 3183 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3184 unsigned MaskNumElts = Mask.size(); 3185 3186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3187 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3188 EVT SrcVT = Src1.getValueType(); 3189 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3190 3191 if (SrcNumElts == MaskNumElts) { 3192 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3193 return; 3194 } 3195 3196 // Normalize the shuffle vector since mask and vector length don't match. 3197 if (SrcNumElts < MaskNumElts) { 3198 // Mask is longer than the source vectors. We can use concatenate vector to 3199 // make the mask and vectors lengths match. 3200 3201 if (MaskNumElts % SrcNumElts == 0) { 3202 // Mask length is a multiple of the source vector length. 3203 // Check if the shuffle is some kind of concatenation of the input 3204 // vectors. 3205 unsigned NumConcat = MaskNumElts / SrcNumElts; 3206 bool IsConcat = true; 3207 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3208 for (unsigned i = 0; i != MaskNumElts; ++i) { 3209 int Idx = Mask[i]; 3210 if (Idx < 0) 3211 continue; 3212 // Ensure the indices in each SrcVT sized piece are sequential and that 3213 // the same source is used for the whole piece. 3214 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3215 (ConcatSrcs[i / SrcNumElts] >= 0 && 3216 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3217 IsConcat = false; 3218 break; 3219 } 3220 // Remember which source this index came from. 3221 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3222 } 3223 3224 // The shuffle is concatenating multiple vectors together. Just emit 3225 // a CONCAT_VECTORS operation. 3226 if (IsConcat) { 3227 SmallVector<SDValue, 8> ConcatOps; 3228 for (auto Src : ConcatSrcs) { 3229 if (Src < 0) 3230 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3231 else if (Src == 0) 3232 ConcatOps.push_back(Src1); 3233 else 3234 ConcatOps.push_back(Src2); 3235 } 3236 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3237 return; 3238 } 3239 } 3240 3241 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3242 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3243 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3244 PaddedMaskNumElts); 3245 3246 // Pad both vectors with undefs to make them the same length as the mask. 3247 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3248 3249 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3250 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3251 MOps1[0] = Src1; 3252 MOps2[0] = Src2; 3253 3254 Src1 = Src1.isUndef() 3255 ? DAG.getUNDEF(PaddedVT) 3256 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3257 Src2 = Src2.isUndef() 3258 ? DAG.getUNDEF(PaddedVT) 3259 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3260 3261 // Readjust mask for new input vector length. 3262 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3263 for (unsigned i = 0; i != MaskNumElts; ++i) { 3264 int Idx = Mask[i]; 3265 if (Idx >= (int)SrcNumElts) 3266 Idx -= SrcNumElts - PaddedMaskNumElts; 3267 MappedOps[i] = Idx; 3268 } 3269 3270 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3271 3272 // If the concatenated vector was padded, extract a subvector with the 3273 // correct number of elements. 3274 if (MaskNumElts != PaddedMaskNumElts) 3275 Result = DAG.getNode( 3276 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3277 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3278 3279 setValue(&I, Result); 3280 return; 3281 } 3282 3283 if (SrcNumElts > MaskNumElts) { 3284 // Analyze the access pattern of the vector to see if we can extract 3285 // two subvectors and do the shuffle. 3286 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3287 bool CanExtract = true; 3288 for (int Idx : Mask) { 3289 unsigned Input = 0; 3290 if (Idx < 0) 3291 continue; 3292 3293 if (Idx >= (int)SrcNumElts) { 3294 Input = 1; 3295 Idx -= SrcNumElts; 3296 } 3297 3298 // If all the indices come from the same MaskNumElts sized portion of 3299 // the sources we can use extract. Also make sure the extract wouldn't 3300 // extract past the end of the source. 3301 int NewStartIdx = alignDown(Idx, MaskNumElts); 3302 if (NewStartIdx + MaskNumElts > SrcNumElts || 3303 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3304 CanExtract = false; 3305 // Make sure we always update StartIdx as we use it to track if all 3306 // elements are undef. 3307 StartIdx[Input] = NewStartIdx; 3308 } 3309 3310 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3311 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3312 return; 3313 } 3314 if (CanExtract) { 3315 // Extract appropriate subvector and generate a vector shuffle 3316 for (unsigned Input = 0; Input < 2; ++Input) { 3317 SDValue &Src = Input == 0 ? Src1 : Src2; 3318 if (StartIdx[Input] < 0) 3319 Src = DAG.getUNDEF(VT); 3320 else { 3321 Src = DAG.getNode( 3322 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3323 DAG.getConstant(StartIdx[Input], DL, 3324 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3325 } 3326 } 3327 3328 // Calculate new mask. 3329 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3330 for (int &Idx : MappedOps) { 3331 if (Idx >= (int)SrcNumElts) 3332 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3333 else if (Idx >= 0) 3334 Idx -= StartIdx[0]; 3335 } 3336 3337 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3338 return; 3339 } 3340 } 3341 3342 // We can't use either concat vectors or extract subvectors so fall back to 3343 // replacing the shuffle with extract and build vector. 3344 // to insert and build vector. 3345 EVT EltVT = VT.getVectorElementType(); 3346 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3347 SmallVector<SDValue,8> Ops; 3348 for (int Idx : Mask) { 3349 SDValue Res; 3350 3351 if (Idx < 0) { 3352 Res = DAG.getUNDEF(EltVT); 3353 } else { 3354 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3355 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3356 3357 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3358 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3359 } 3360 3361 Ops.push_back(Res); 3362 } 3363 3364 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3365 } 3366 3367 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3368 ArrayRef<unsigned> Indices; 3369 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3370 Indices = IV->getIndices(); 3371 else 3372 Indices = cast<ConstantExpr>(&I)->getIndices(); 3373 3374 const Value *Op0 = I.getOperand(0); 3375 const Value *Op1 = I.getOperand(1); 3376 Type *AggTy = I.getType(); 3377 Type *ValTy = Op1->getType(); 3378 bool IntoUndef = isa<UndefValue>(Op0); 3379 bool FromUndef = isa<UndefValue>(Op1); 3380 3381 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3382 3383 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3384 SmallVector<EVT, 4> AggValueVTs; 3385 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3386 SmallVector<EVT, 4> ValValueVTs; 3387 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3388 3389 unsigned NumAggValues = AggValueVTs.size(); 3390 unsigned NumValValues = ValValueVTs.size(); 3391 SmallVector<SDValue, 4> Values(NumAggValues); 3392 3393 // Ignore an insertvalue that produces an empty object 3394 if (!NumAggValues) { 3395 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3396 return; 3397 } 3398 3399 SDValue Agg = getValue(Op0); 3400 unsigned i = 0; 3401 // Copy the beginning value(s) from the original aggregate. 3402 for (; i != LinearIndex; ++i) 3403 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3404 SDValue(Agg.getNode(), Agg.getResNo() + i); 3405 // Copy values from the inserted value(s). 3406 if (NumValValues) { 3407 SDValue Val = getValue(Op1); 3408 for (; i != LinearIndex + NumValValues; ++i) 3409 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3410 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3411 } 3412 // Copy remaining value(s) from the original aggregate. 3413 for (; i != NumAggValues; ++i) 3414 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3415 SDValue(Agg.getNode(), Agg.getResNo() + i); 3416 3417 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3418 DAG.getVTList(AggValueVTs), Values)); 3419 } 3420 3421 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3422 ArrayRef<unsigned> Indices; 3423 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3424 Indices = EV->getIndices(); 3425 else 3426 Indices = cast<ConstantExpr>(&I)->getIndices(); 3427 3428 const Value *Op0 = I.getOperand(0); 3429 Type *AggTy = Op0->getType(); 3430 Type *ValTy = I.getType(); 3431 bool OutOfUndef = isa<UndefValue>(Op0); 3432 3433 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3434 3435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3436 SmallVector<EVT, 4> ValValueVTs; 3437 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3438 3439 unsigned NumValValues = ValValueVTs.size(); 3440 3441 // Ignore a extractvalue that produces an empty object 3442 if (!NumValValues) { 3443 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3444 return; 3445 } 3446 3447 SmallVector<SDValue, 4> Values(NumValValues); 3448 3449 SDValue Agg = getValue(Op0); 3450 // Copy out the selected value(s). 3451 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3452 Values[i - LinearIndex] = 3453 OutOfUndef ? 3454 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3455 SDValue(Agg.getNode(), Agg.getResNo() + i); 3456 3457 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3458 DAG.getVTList(ValValueVTs), Values)); 3459 } 3460 3461 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3462 Value *Op0 = I.getOperand(0); 3463 // Note that the pointer operand may be a vector of pointers. Take the scalar 3464 // element which holds a pointer. 3465 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3466 SDValue N = getValue(Op0); 3467 SDLoc dl = getCurSDLoc(); 3468 3469 // Normalize Vector GEP - all scalar operands should be converted to the 3470 // splat vector. 3471 unsigned VectorWidth = I.getType()->isVectorTy() ? 3472 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3473 3474 if (VectorWidth && !N.getValueType().isVector()) { 3475 LLVMContext &Context = *DAG.getContext(); 3476 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3477 N = DAG.getSplatBuildVector(VT, dl, N); 3478 } 3479 3480 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3481 GTI != E; ++GTI) { 3482 const Value *Idx = GTI.getOperand(); 3483 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3484 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3485 if (Field) { 3486 // N = N + Offset 3487 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3488 3489 // In an inbounds GEP with an offset that is nonnegative even when 3490 // interpreted as signed, assume there is no unsigned overflow. 3491 SDNodeFlags Flags; 3492 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3493 Flags.setNoUnsignedWrap(true); 3494 3495 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3496 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3497 } 3498 } else { 3499 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3500 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3501 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3502 3503 // If this is a scalar constant or a splat vector of constants, 3504 // handle it quickly. 3505 const auto *CI = dyn_cast<ConstantInt>(Idx); 3506 if (!CI && isa<ConstantDataVector>(Idx) && 3507 cast<ConstantDataVector>(Idx)->getSplatValue()) 3508 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3509 3510 if (CI) { 3511 if (CI->isZero()) 3512 continue; 3513 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3514 LLVMContext &Context = *DAG.getContext(); 3515 SDValue OffsVal = VectorWidth ? 3516 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3517 DAG.getConstant(Offs, dl, IdxTy); 3518 3519 // In an inbouds GEP with an offset that is nonnegative even when 3520 // interpreted as signed, assume there is no unsigned overflow. 3521 SDNodeFlags Flags; 3522 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3523 Flags.setNoUnsignedWrap(true); 3524 3525 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3526 continue; 3527 } 3528 3529 // N = N + Idx * ElementSize; 3530 SDValue IdxN = getValue(Idx); 3531 3532 if (!IdxN.getValueType().isVector() && VectorWidth) { 3533 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3534 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3535 } 3536 3537 // If the index is smaller or larger than intptr_t, truncate or extend 3538 // it. 3539 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3540 3541 // If this is a multiply by a power of two, turn it into a shl 3542 // immediately. This is a very common case. 3543 if (ElementSize != 1) { 3544 if (ElementSize.isPowerOf2()) { 3545 unsigned Amt = ElementSize.logBase2(); 3546 IdxN = DAG.getNode(ISD::SHL, dl, 3547 N.getValueType(), IdxN, 3548 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3549 } else { 3550 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3551 IdxN = DAG.getNode(ISD::MUL, dl, 3552 N.getValueType(), IdxN, Scale); 3553 } 3554 } 3555 3556 N = DAG.getNode(ISD::ADD, dl, 3557 N.getValueType(), N, IdxN); 3558 } 3559 } 3560 3561 setValue(&I, N); 3562 } 3563 3564 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3565 // If this is a fixed sized alloca in the entry block of the function, 3566 // allocate it statically on the stack. 3567 if (FuncInfo.StaticAllocaMap.count(&I)) 3568 return; // getValue will auto-populate this. 3569 3570 SDLoc dl = getCurSDLoc(); 3571 Type *Ty = I.getAllocatedType(); 3572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3573 auto &DL = DAG.getDataLayout(); 3574 uint64_t TySize = DL.getTypeAllocSize(Ty); 3575 unsigned Align = 3576 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3577 3578 SDValue AllocSize = getValue(I.getArraySize()); 3579 3580 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3581 if (AllocSize.getValueType() != IntPtr) 3582 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3583 3584 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3585 AllocSize, 3586 DAG.getConstant(TySize, dl, IntPtr)); 3587 3588 // Handle alignment. If the requested alignment is less than or equal to 3589 // the stack alignment, ignore it. If the size is greater than or equal to 3590 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3591 unsigned StackAlign = 3592 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3593 if (Align <= StackAlign) 3594 Align = 0; 3595 3596 // Round the size of the allocation up to the stack alignment size 3597 // by add SA-1 to the size. This doesn't overflow because we're computing 3598 // an address inside an alloca. 3599 SDNodeFlags Flags; 3600 Flags.setNoUnsignedWrap(true); 3601 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3602 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3603 3604 // Mask out the low bits for alignment purposes. 3605 AllocSize = 3606 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3607 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3608 3609 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3610 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3611 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3612 setValue(&I, DSA); 3613 DAG.setRoot(DSA.getValue(1)); 3614 3615 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3616 } 3617 3618 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3619 if (I.isAtomic()) 3620 return visitAtomicLoad(I); 3621 3622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3623 const Value *SV = I.getOperand(0); 3624 if (TLI.supportSwiftError()) { 3625 // Swifterror values can come from either a function parameter with 3626 // swifterror attribute or an alloca with swifterror attribute. 3627 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3628 if (Arg->hasSwiftErrorAttr()) 3629 return visitLoadFromSwiftError(I); 3630 } 3631 3632 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3633 if (Alloca->isSwiftError()) 3634 return visitLoadFromSwiftError(I); 3635 } 3636 } 3637 3638 SDValue Ptr = getValue(SV); 3639 3640 Type *Ty = I.getType(); 3641 3642 bool isVolatile = I.isVolatile(); 3643 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3644 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3645 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3646 unsigned Alignment = I.getAlignment(); 3647 3648 AAMDNodes AAInfo; 3649 I.getAAMetadata(AAInfo); 3650 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3651 3652 SmallVector<EVT, 4> ValueVTs; 3653 SmallVector<uint64_t, 4> Offsets; 3654 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3655 unsigned NumValues = ValueVTs.size(); 3656 if (NumValues == 0) 3657 return; 3658 3659 SDValue Root; 3660 bool ConstantMemory = false; 3661 if (isVolatile || NumValues > MaxParallelChains) 3662 // Serialize volatile loads with other side effects. 3663 Root = getRoot(); 3664 else if (AA && AA->pointsToConstantMemory(MemoryLocation( 3665 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3666 // Do not serialize (non-volatile) loads of constant memory with anything. 3667 Root = DAG.getEntryNode(); 3668 ConstantMemory = true; 3669 } else { 3670 // Do not serialize non-volatile loads against each other. 3671 Root = DAG.getRoot(); 3672 } 3673 3674 SDLoc dl = getCurSDLoc(); 3675 3676 if (isVolatile) 3677 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3678 3679 // An aggregate load cannot wrap around the address space, so offsets to its 3680 // parts don't wrap either. 3681 SDNodeFlags Flags; 3682 Flags.setNoUnsignedWrap(true); 3683 3684 SmallVector<SDValue, 4> Values(NumValues); 3685 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3686 EVT PtrVT = Ptr.getValueType(); 3687 unsigned ChainI = 0; 3688 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3689 // Serializing loads here may result in excessive register pressure, and 3690 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3691 // could recover a bit by hoisting nodes upward in the chain by recognizing 3692 // they are side-effect free or do not alias. The optimizer should really 3693 // avoid this case by converting large object/array copies to llvm.memcpy 3694 // (MaxParallelChains should always remain as failsafe). 3695 if (ChainI == MaxParallelChains) { 3696 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3697 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3698 makeArrayRef(Chains.data(), ChainI)); 3699 Root = Chain; 3700 ChainI = 0; 3701 } 3702 SDValue A = DAG.getNode(ISD::ADD, dl, 3703 PtrVT, Ptr, 3704 DAG.getConstant(Offsets[i], dl, PtrVT), 3705 Flags); 3706 auto MMOFlags = MachineMemOperand::MONone; 3707 if (isVolatile) 3708 MMOFlags |= MachineMemOperand::MOVolatile; 3709 if (isNonTemporal) 3710 MMOFlags |= MachineMemOperand::MONonTemporal; 3711 if (isInvariant) 3712 MMOFlags |= MachineMemOperand::MOInvariant; 3713 if (isDereferenceable) 3714 MMOFlags |= MachineMemOperand::MODereferenceable; 3715 MMOFlags |= TLI.getMMOFlags(I); 3716 3717 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3718 MachinePointerInfo(SV, Offsets[i]), Alignment, 3719 MMOFlags, AAInfo, Ranges); 3720 3721 Values[i] = L; 3722 Chains[ChainI] = L.getValue(1); 3723 } 3724 3725 if (!ConstantMemory) { 3726 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3727 makeArrayRef(Chains.data(), ChainI)); 3728 if (isVolatile) 3729 DAG.setRoot(Chain); 3730 else 3731 PendingLoads.push_back(Chain); 3732 } 3733 3734 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3735 DAG.getVTList(ValueVTs), Values)); 3736 } 3737 3738 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3739 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3740 "call visitStoreToSwiftError when backend supports swifterror"); 3741 3742 SmallVector<EVT, 4> ValueVTs; 3743 SmallVector<uint64_t, 4> Offsets; 3744 const Value *SrcV = I.getOperand(0); 3745 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3746 SrcV->getType(), ValueVTs, &Offsets); 3747 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3748 "expect a single EVT for swifterror"); 3749 3750 SDValue Src = getValue(SrcV); 3751 // Create a virtual register, then update the virtual register. 3752 unsigned VReg; bool CreatedVReg; 3753 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3754 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3755 // Chain can be getRoot or getControlRoot. 3756 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3757 SDValue(Src.getNode(), Src.getResNo())); 3758 DAG.setRoot(CopyNode); 3759 if (CreatedVReg) 3760 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3761 } 3762 3763 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3764 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3765 "call visitLoadFromSwiftError when backend supports swifterror"); 3766 3767 assert(!I.isVolatile() && 3768 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3769 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3770 "Support volatile, non temporal, invariant for load_from_swift_error"); 3771 3772 const Value *SV = I.getOperand(0); 3773 Type *Ty = I.getType(); 3774 AAMDNodes AAInfo; 3775 I.getAAMetadata(AAInfo); 3776 assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( 3777 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && 3778 "load_from_swift_error should not be constant memory"); 3779 3780 SmallVector<EVT, 4> ValueVTs; 3781 SmallVector<uint64_t, 4> Offsets; 3782 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3783 ValueVTs, &Offsets); 3784 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3785 "expect a single EVT for swifterror"); 3786 3787 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3788 SDValue L = DAG.getCopyFromReg( 3789 getRoot(), getCurSDLoc(), 3790 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3791 ValueVTs[0]); 3792 3793 setValue(&I, L); 3794 } 3795 3796 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3797 if (I.isAtomic()) 3798 return visitAtomicStore(I); 3799 3800 const Value *SrcV = I.getOperand(0); 3801 const Value *PtrV = I.getOperand(1); 3802 3803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3804 if (TLI.supportSwiftError()) { 3805 // Swifterror values can come from either a function parameter with 3806 // swifterror attribute or an alloca with swifterror attribute. 3807 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3808 if (Arg->hasSwiftErrorAttr()) 3809 return visitStoreToSwiftError(I); 3810 } 3811 3812 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3813 if (Alloca->isSwiftError()) 3814 return visitStoreToSwiftError(I); 3815 } 3816 } 3817 3818 SmallVector<EVT, 4> ValueVTs; 3819 SmallVector<uint64_t, 4> Offsets; 3820 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3821 SrcV->getType(), ValueVTs, &Offsets); 3822 unsigned NumValues = ValueVTs.size(); 3823 if (NumValues == 0) 3824 return; 3825 3826 // Get the lowered operands. Note that we do this after 3827 // checking if NumResults is zero, because with zero results 3828 // the operands won't have values in the map. 3829 SDValue Src = getValue(SrcV); 3830 SDValue Ptr = getValue(PtrV); 3831 3832 SDValue Root = getRoot(); 3833 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3834 SDLoc dl = getCurSDLoc(); 3835 EVT PtrVT = Ptr.getValueType(); 3836 unsigned Alignment = I.getAlignment(); 3837 AAMDNodes AAInfo; 3838 I.getAAMetadata(AAInfo); 3839 3840 auto MMOFlags = MachineMemOperand::MONone; 3841 if (I.isVolatile()) 3842 MMOFlags |= MachineMemOperand::MOVolatile; 3843 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3844 MMOFlags |= MachineMemOperand::MONonTemporal; 3845 MMOFlags |= TLI.getMMOFlags(I); 3846 3847 // An aggregate load cannot wrap around the address space, so offsets to its 3848 // parts don't wrap either. 3849 SDNodeFlags Flags; 3850 Flags.setNoUnsignedWrap(true); 3851 3852 unsigned ChainI = 0; 3853 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3854 // See visitLoad comments. 3855 if (ChainI == MaxParallelChains) { 3856 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3857 makeArrayRef(Chains.data(), ChainI)); 3858 Root = Chain; 3859 ChainI = 0; 3860 } 3861 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3862 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3863 SDValue St = DAG.getStore( 3864 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3865 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3866 Chains[ChainI] = St; 3867 } 3868 3869 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3870 makeArrayRef(Chains.data(), ChainI)); 3871 DAG.setRoot(StoreNode); 3872 } 3873 3874 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3875 bool IsCompressing) { 3876 SDLoc sdl = getCurSDLoc(); 3877 3878 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3879 unsigned& Alignment) { 3880 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3881 Src0 = I.getArgOperand(0); 3882 Ptr = I.getArgOperand(1); 3883 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3884 Mask = I.getArgOperand(3); 3885 }; 3886 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3887 unsigned& Alignment) { 3888 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3889 Src0 = I.getArgOperand(0); 3890 Ptr = I.getArgOperand(1); 3891 Mask = I.getArgOperand(2); 3892 Alignment = 0; 3893 }; 3894 3895 Value *PtrOperand, *MaskOperand, *Src0Operand; 3896 unsigned Alignment; 3897 if (IsCompressing) 3898 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3899 else 3900 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3901 3902 SDValue Ptr = getValue(PtrOperand); 3903 SDValue Src0 = getValue(Src0Operand); 3904 SDValue Mask = getValue(MaskOperand); 3905 3906 EVT VT = Src0.getValueType(); 3907 if (!Alignment) 3908 Alignment = DAG.getEVTAlignment(VT); 3909 3910 AAMDNodes AAInfo; 3911 I.getAAMetadata(AAInfo); 3912 3913 MachineMemOperand *MMO = 3914 DAG.getMachineFunction(). 3915 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3916 MachineMemOperand::MOStore, VT.getStoreSize(), 3917 Alignment, AAInfo); 3918 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3919 MMO, false /* Truncating */, 3920 IsCompressing); 3921 DAG.setRoot(StoreNode); 3922 setValue(&I, StoreNode); 3923 } 3924 3925 // Get a uniform base for the Gather/Scatter intrinsic. 3926 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3927 // We try to represent it as a base pointer + vector of indices. 3928 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3929 // The first operand of the GEP may be a single pointer or a vector of pointers 3930 // Example: 3931 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3932 // or 3933 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3934 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3935 // 3936 // When the first GEP operand is a single pointer - it is the uniform base we 3937 // are looking for. If first operand of the GEP is a splat vector - we 3938 // extract the splat value and use it as a uniform base. 3939 // In all other cases the function returns 'false'. 3940 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3941 SDValue &Scale, SelectionDAGBuilder* SDB) { 3942 SelectionDAG& DAG = SDB->DAG; 3943 LLVMContext &Context = *DAG.getContext(); 3944 3945 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3946 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3947 if (!GEP) 3948 return false; 3949 3950 const Value *GEPPtr = GEP->getPointerOperand(); 3951 if (!GEPPtr->getType()->isVectorTy()) 3952 Ptr = GEPPtr; 3953 else if (!(Ptr = getSplatValue(GEPPtr))) 3954 return false; 3955 3956 unsigned FinalIndex = GEP->getNumOperands() - 1; 3957 Value *IndexVal = GEP->getOperand(FinalIndex); 3958 3959 // Ensure all the other indices are 0. 3960 for (unsigned i = 1; i < FinalIndex; ++i) { 3961 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3962 if (!C || !C->isZero()) 3963 return false; 3964 } 3965 3966 // The operands of the GEP may be defined in another basic block. 3967 // In this case we'll not find nodes for the operands. 3968 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3969 return false; 3970 3971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3972 const DataLayout &DL = DAG.getDataLayout(); 3973 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 3974 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 3975 Base = SDB->getValue(Ptr); 3976 Index = SDB->getValue(IndexVal); 3977 3978 if (!Index.getValueType().isVector()) { 3979 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3980 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3981 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 3982 } 3983 return true; 3984 } 3985 3986 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3987 SDLoc sdl = getCurSDLoc(); 3988 3989 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3990 const Value *Ptr = I.getArgOperand(1); 3991 SDValue Src0 = getValue(I.getArgOperand(0)); 3992 SDValue Mask = getValue(I.getArgOperand(3)); 3993 EVT VT = Src0.getValueType(); 3994 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3995 if (!Alignment) 3996 Alignment = DAG.getEVTAlignment(VT); 3997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3998 3999 AAMDNodes AAInfo; 4000 I.getAAMetadata(AAInfo); 4001 4002 SDValue Base; 4003 SDValue Index; 4004 SDValue Scale; 4005 const Value *BasePtr = Ptr; 4006 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4007 4008 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4009 MachineMemOperand *MMO = DAG.getMachineFunction(). 4010 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4011 MachineMemOperand::MOStore, VT.getStoreSize(), 4012 Alignment, AAInfo); 4013 if (!UniformBase) { 4014 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4015 Index = getValue(Ptr); 4016 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4017 } 4018 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4019 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4020 Ops, MMO); 4021 DAG.setRoot(Scatter); 4022 setValue(&I, Scatter); 4023 } 4024 4025 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4026 SDLoc sdl = getCurSDLoc(); 4027 4028 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4029 unsigned& Alignment) { 4030 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4031 Ptr = I.getArgOperand(0); 4032 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4033 Mask = I.getArgOperand(2); 4034 Src0 = I.getArgOperand(3); 4035 }; 4036 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4037 unsigned& Alignment) { 4038 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4039 Ptr = I.getArgOperand(0); 4040 Alignment = 0; 4041 Mask = I.getArgOperand(1); 4042 Src0 = I.getArgOperand(2); 4043 }; 4044 4045 Value *PtrOperand, *MaskOperand, *Src0Operand; 4046 unsigned Alignment; 4047 if (IsExpanding) 4048 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4049 else 4050 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4051 4052 SDValue Ptr = getValue(PtrOperand); 4053 SDValue Src0 = getValue(Src0Operand); 4054 SDValue Mask = getValue(MaskOperand); 4055 4056 EVT VT = Src0.getValueType(); 4057 if (!Alignment) 4058 Alignment = DAG.getEVTAlignment(VT); 4059 4060 AAMDNodes AAInfo; 4061 I.getAAMetadata(AAInfo); 4062 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4063 4064 // Do not serialize masked loads of constant memory with anything. 4065 bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( 4066 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 4067 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4068 4069 MachineMemOperand *MMO = 4070 DAG.getMachineFunction(). 4071 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4072 MachineMemOperand::MOLoad, VT.getStoreSize(), 4073 Alignment, AAInfo, Ranges); 4074 4075 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4076 ISD::NON_EXTLOAD, IsExpanding); 4077 if (AddToChain) 4078 PendingLoads.push_back(Load.getValue(1)); 4079 setValue(&I, Load); 4080 } 4081 4082 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4083 SDLoc sdl = getCurSDLoc(); 4084 4085 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4086 const Value *Ptr = I.getArgOperand(0); 4087 SDValue Src0 = getValue(I.getArgOperand(3)); 4088 SDValue Mask = getValue(I.getArgOperand(2)); 4089 4090 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4091 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4092 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4093 if (!Alignment) 4094 Alignment = DAG.getEVTAlignment(VT); 4095 4096 AAMDNodes AAInfo; 4097 I.getAAMetadata(AAInfo); 4098 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4099 4100 SDValue Root = DAG.getRoot(); 4101 SDValue Base; 4102 SDValue Index; 4103 SDValue Scale; 4104 const Value *BasePtr = Ptr; 4105 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4106 bool ConstantMemory = false; 4107 if (UniformBase && 4108 AA && AA->pointsToConstantMemory(MemoryLocation( 4109 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 4110 AAInfo))) { 4111 // Do not serialize (non-volatile) loads of constant memory with anything. 4112 Root = DAG.getEntryNode(); 4113 ConstantMemory = true; 4114 } 4115 4116 MachineMemOperand *MMO = 4117 DAG.getMachineFunction(). 4118 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4119 MachineMemOperand::MOLoad, VT.getStoreSize(), 4120 Alignment, AAInfo, Ranges); 4121 4122 if (!UniformBase) { 4123 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4124 Index = getValue(Ptr); 4125 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4126 } 4127 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4128 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4129 Ops, MMO); 4130 4131 SDValue OutChain = Gather.getValue(1); 4132 if (!ConstantMemory) 4133 PendingLoads.push_back(OutChain); 4134 setValue(&I, Gather); 4135 } 4136 4137 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4138 SDLoc dl = getCurSDLoc(); 4139 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4140 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4141 SyncScope::ID SSID = I.getSyncScopeID(); 4142 4143 SDValue InChain = getRoot(); 4144 4145 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4146 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4147 SDValue L = DAG.getAtomicCmpSwap( 4148 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4149 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4150 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4151 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4152 4153 SDValue OutChain = L.getValue(2); 4154 4155 setValue(&I, L); 4156 DAG.setRoot(OutChain); 4157 } 4158 4159 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4160 SDLoc dl = getCurSDLoc(); 4161 ISD::NodeType NT; 4162 switch (I.getOperation()) { 4163 default: llvm_unreachable("Unknown atomicrmw operation"); 4164 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4165 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4166 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4167 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4168 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4169 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4170 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4171 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4172 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4173 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4174 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4175 } 4176 AtomicOrdering Order = I.getOrdering(); 4177 SyncScope::ID SSID = I.getSyncScopeID(); 4178 4179 SDValue InChain = getRoot(); 4180 4181 SDValue L = 4182 DAG.getAtomic(NT, dl, 4183 getValue(I.getValOperand()).getSimpleValueType(), 4184 InChain, 4185 getValue(I.getPointerOperand()), 4186 getValue(I.getValOperand()), 4187 I.getPointerOperand(), 4188 /* Alignment=*/ 0, Order, SSID); 4189 4190 SDValue OutChain = L.getValue(1); 4191 4192 setValue(&I, L); 4193 DAG.setRoot(OutChain); 4194 } 4195 4196 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4197 SDLoc dl = getCurSDLoc(); 4198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4199 SDValue Ops[3]; 4200 Ops[0] = getRoot(); 4201 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4202 TLI.getFenceOperandTy(DAG.getDataLayout())); 4203 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4204 TLI.getFenceOperandTy(DAG.getDataLayout())); 4205 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4206 } 4207 4208 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4209 SDLoc dl = getCurSDLoc(); 4210 AtomicOrdering Order = I.getOrdering(); 4211 SyncScope::ID SSID = I.getSyncScopeID(); 4212 4213 SDValue InChain = getRoot(); 4214 4215 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4216 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4217 4218 if (!TLI.supportsUnalignedAtomics() && 4219 I.getAlignment() < VT.getStoreSize()) 4220 report_fatal_error("Cannot generate unaligned atomic load"); 4221 4222 MachineMemOperand *MMO = 4223 DAG.getMachineFunction(). 4224 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4225 MachineMemOperand::MOVolatile | 4226 MachineMemOperand::MOLoad, 4227 VT.getStoreSize(), 4228 I.getAlignment() ? I.getAlignment() : 4229 DAG.getEVTAlignment(VT), 4230 AAMDNodes(), nullptr, SSID, Order); 4231 4232 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4233 SDValue L = 4234 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4235 getValue(I.getPointerOperand()), MMO); 4236 4237 SDValue OutChain = L.getValue(1); 4238 4239 setValue(&I, L); 4240 DAG.setRoot(OutChain); 4241 } 4242 4243 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4244 SDLoc dl = getCurSDLoc(); 4245 4246 AtomicOrdering Order = I.getOrdering(); 4247 SyncScope::ID SSID = I.getSyncScopeID(); 4248 4249 SDValue InChain = getRoot(); 4250 4251 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4252 EVT VT = 4253 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4254 4255 if (I.getAlignment() < VT.getStoreSize()) 4256 report_fatal_error("Cannot generate unaligned atomic store"); 4257 4258 SDValue OutChain = 4259 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4260 InChain, 4261 getValue(I.getPointerOperand()), 4262 getValue(I.getValueOperand()), 4263 I.getPointerOperand(), I.getAlignment(), 4264 Order, SSID); 4265 4266 DAG.setRoot(OutChain); 4267 } 4268 4269 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4270 /// node. 4271 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4272 unsigned Intrinsic) { 4273 // Ignore the callsite's attributes. A specific call site may be marked with 4274 // readnone, but the lowering code will expect the chain based on the 4275 // definition. 4276 const Function *F = I.getCalledFunction(); 4277 bool HasChain = !F->doesNotAccessMemory(); 4278 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4279 4280 // Build the operand list. 4281 SmallVector<SDValue, 8> Ops; 4282 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4283 if (OnlyLoad) { 4284 // We don't need to serialize loads against other loads. 4285 Ops.push_back(DAG.getRoot()); 4286 } else { 4287 Ops.push_back(getRoot()); 4288 } 4289 } 4290 4291 // Info is set by getTgtMemInstrinsic 4292 TargetLowering::IntrinsicInfo Info; 4293 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4294 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4295 DAG.getMachineFunction(), 4296 Intrinsic); 4297 4298 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4299 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4300 Info.opc == ISD::INTRINSIC_W_CHAIN) 4301 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4302 TLI.getPointerTy(DAG.getDataLayout()))); 4303 4304 // Add all operands of the call to the operand list. 4305 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4306 SDValue Op = getValue(I.getArgOperand(i)); 4307 Ops.push_back(Op); 4308 } 4309 4310 SmallVector<EVT, 4> ValueVTs; 4311 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4312 4313 if (HasChain) 4314 ValueVTs.push_back(MVT::Other); 4315 4316 SDVTList VTs = DAG.getVTList(ValueVTs); 4317 4318 // Create the node. 4319 SDValue Result; 4320 if (IsTgtIntrinsic) { 4321 // This is target intrinsic that touches memory 4322 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4323 Ops, Info.memVT, 4324 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4325 Info.flags, Info.size); 4326 } else if (!HasChain) { 4327 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4328 } else if (!I.getType()->isVoidTy()) { 4329 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4330 } else { 4331 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4332 } 4333 4334 if (HasChain) { 4335 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4336 if (OnlyLoad) 4337 PendingLoads.push_back(Chain); 4338 else 4339 DAG.setRoot(Chain); 4340 } 4341 4342 if (!I.getType()->isVoidTy()) { 4343 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4344 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4345 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4346 } else 4347 Result = lowerRangeToAssertZExt(DAG, I, Result); 4348 4349 setValue(&I, Result); 4350 } 4351 } 4352 4353 /// GetSignificand - Get the significand and build it into a floating-point 4354 /// number with exponent of 1: 4355 /// 4356 /// Op = (Op & 0x007fffff) | 0x3f800000; 4357 /// 4358 /// where Op is the hexadecimal representation of floating point value. 4359 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4360 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4361 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4362 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4363 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4364 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4365 } 4366 4367 /// GetExponent - Get the exponent: 4368 /// 4369 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4370 /// 4371 /// where Op is the hexadecimal representation of floating point value. 4372 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4373 const TargetLowering &TLI, const SDLoc &dl) { 4374 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4375 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4376 SDValue t1 = DAG.getNode( 4377 ISD::SRL, dl, MVT::i32, t0, 4378 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4379 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4380 DAG.getConstant(127, dl, MVT::i32)); 4381 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4382 } 4383 4384 /// getF32Constant - Get 32-bit floating point constant. 4385 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4386 const SDLoc &dl) { 4387 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4388 MVT::f32); 4389 } 4390 4391 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4392 SelectionDAG &DAG) { 4393 // TODO: What fast-math-flags should be set on the floating-point nodes? 4394 4395 // IntegerPartOfX = ((int32_t)(t0); 4396 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4397 4398 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4399 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4400 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4401 4402 // IntegerPartOfX <<= 23; 4403 IntegerPartOfX = DAG.getNode( 4404 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4405 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4406 DAG.getDataLayout()))); 4407 4408 SDValue TwoToFractionalPartOfX; 4409 if (LimitFloatPrecision <= 6) { 4410 // For floating-point precision of 6: 4411 // 4412 // TwoToFractionalPartOfX = 4413 // 0.997535578f + 4414 // (0.735607626f + 0.252464424f * x) * x; 4415 // 4416 // error 0.0144103317, which is 6 bits 4417 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4418 getF32Constant(DAG, 0x3e814304, dl)); 4419 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4420 getF32Constant(DAG, 0x3f3c50c8, dl)); 4421 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4422 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4423 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4424 } else if (LimitFloatPrecision <= 12) { 4425 // For floating-point precision of 12: 4426 // 4427 // TwoToFractionalPartOfX = 4428 // 0.999892986f + 4429 // (0.696457318f + 4430 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4431 // 4432 // error 0.000107046256, which is 13 to 14 bits 4433 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4434 getF32Constant(DAG, 0x3da235e3, dl)); 4435 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4436 getF32Constant(DAG, 0x3e65b8f3, dl)); 4437 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4438 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4439 getF32Constant(DAG, 0x3f324b07, dl)); 4440 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4441 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4442 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4443 } else { // LimitFloatPrecision <= 18 4444 // For floating-point precision of 18: 4445 // 4446 // TwoToFractionalPartOfX = 4447 // 0.999999982f + 4448 // (0.693148872f + 4449 // (0.240227044f + 4450 // (0.554906021e-1f + 4451 // (0.961591928e-2f + 4452 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4453 // error 2.47208000*10^(-7), which is better than 18 bits 4454 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4455 getF32Constant(DAG, 0x3924b03e, dl)); 4456 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4457 getF32Constant(DAG, 0x3ab24b87, dl)); 4458 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4459 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4460 getF32Constant(DAG, 0x3c1d8c17, dl)); 4461 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4462 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4463 getF32Constant(DAG, 0x3d634a1d, dl)); 4464 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4465 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4466 getF32Constant(DAG, 0x3e75fe14, dl)); 4467 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4468 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4469 getF32Constant(DAG, 0x3f317234, dl)); 4470 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4471 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4472 getF32Constant(DAG, 0x3f800000, dl)); 4473 } 4474 4475 // Add the exponent into the result in integer domain. 4476 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4477 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4478 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4479 } 4480 4481 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4482 /// limited-precision mode. 4483 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4484 const TargetLowering &TLI) { 4485 if (Op.getValueType() == MVT::f32 && 4486 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4487 4488 // Put the exponent in the right bit position for later addition to the 4489 // final result: 4490 // 4491 // #define LOG2OFe 1.4426950f 4492 // t0 = Op * LOG2OFe 4493 4494 // TODO: What fast-math-flags should be set here? 4495 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4496 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4497 return getLimitedPrecisionExp2(t0, dl, DAG); 4498 } 4499 4500 // No special expansion. 4501 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4502 } 4503 4504 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4505 /// limited-precision mode. 4506 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4507 const TargetLowering &TLI) { 4508 // TODO: What fast-math-flags should be set on the floating-point nodes? 4509 4510 if (Op.getValueType() == MVT::f32 && 4511 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4512 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4513 4514 // Scale the exponent by log(2) [0.69314718f]. 4515 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4516 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4517 getF32Constant(DAG, 0x3f317218, dl)); 4518 4519 // Get the significand and build it into a floating-point number with 4520 // exponent of 1. 4521 SDValue X = GetSignificand(DAG, Op1, dl); 4522 4523 SDValue LogOfMantissa; 4524 if (LimitFloatPrecision <= 6) { 4525 // For floating-point precision of 6: 4526 // 4527 // LogofMantissa = 4528 // -1.1609546f + 4529 // (1.4034025f - 0.23903021f * x) * x; 4530 // 4531 // error 0.0034276066, which is better than 8 bits 4532 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4533 getF32Constant(DAG, 0xbe74c456, dl)); 4534 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4535 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4536 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4537 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4538 getF32Constant(DAG, 0x3f949a29, dl)); 4539 } else if (LimitFloatPrecision <= 12) { 4540 // For floating-point precision of 12: 4541 // 4542 // LogOfMantissa = 4543 // -1.7417939f + 4544 // (2.8212026f + 4545 // (-1.4699568f + 4546 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4547 // 4548 // error 0.000061011436, which is 14 bits 4549 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4550 getF32Constant(DAG, 0xbd67b6d6, dl)); 4551 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4552 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4553 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4554 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4555 getF32Constant(DAG, 0x3fbc278b, dl)); 4556 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4557 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4558 getF32Constant(DAG, 0x40348e95, dl)); 4559 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4560 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4561 getF32Constant(DAG, 0x3fdef31a, dl)); 4562 } else { // LimitFloatPrecision <= 18 4563 // For floating-point precision of 18: 4564 // 4565 // LogOfMantissa = 4566 // -2.1072184f + 4567 // (4.2372794f + 4568 // (-3.7029485f + 4569 // (2.2781945f + 4570 // (-0.87823314f + 4571 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4572 // 4573 // error 0.0000023660568, which is better than 18 bits 4574 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4575 getF32Constant(DAG, 0xbc91e5ac, dl)); 4576 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4577 getF32Constant(DAG, 0x3e4350aa, dl)); 4578 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4579 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4580 getF32Constant(DAG, 0x3f60d3e3, dl)); 4581 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4582 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4583 getF32Constant(DAG, 0x4011cdf0, dl)); 4584 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4585 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4586 getF32Constant(DAG, 0x406cfd1c, dl)); 4587 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4588 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4589 getF32Constant(DAG, 0x408797cb, dl)); 4590 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4591 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4592 getF32Constant(DAG, 0x4006dcab, dl)); 4593 } 4594 4595 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4596 } 4597 4598 // No special expansion. 4599 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4600 } 4601 4602 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4603 /// limited-precision mode. 4604 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4605 const TargetLowering &TLI) { 4606 // TODO: What fast-math-flags should be set on the floating-point nodes? 4607 4608 if (Op.getValueType() == MVT::f32 && 4609 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4610 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4611 4612 // Get the exponent. 4613 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4614 4615 // Get the significand and build it into a floating-point number with 4616 // exponent of 1. 4617 SDValue X = GetSignificand(DAG, Op1, dl); 4618 4619 // Different possible minimax approximations of significand in 4620 // floating-point for various degrees of accuracy over [1,2]. 4621 SDValue Log2ofMantissa; 4622 if (LimitFloatPrecision <= 6) { 4623 // For floating-point precision of 6: 4624 // 4625 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4626 // 4627 // error 0.0049451742, which is more than 7 bits 4628 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4629 getF32Constant(DAG, 0xbeb08fe0, dl)); 4630 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4631 getF32Constant(DAG, 0x40019463, dl)); 4632 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4633 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4634 getF32Constant(DAG, 0x3fd6633d, dl)); 4635 } else if (LimitFloatPrecision <= 12) { 4636 // For floating-point precision of 12: 4637 // 4638 // Log2ofMantissa = 4639 // -2.51285454f + 4640 // (4.07009056f + 4641 // (-2.12067489f + 4642 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4643 // 4644 // error 0.0000876136000, which is better than 13 bits 4645 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4646 getF32Constant(DAG, 0xbda7262e, dl)); 4647 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4648 getF32Constant(DAG, 0x3f25280b, dl)); 4649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4650 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4651 getF32Constant(DAG, 0x4007b923, dl)); 4652 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4653 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4654 getF32Constant(DAG, 0x40823e2f, dl)); 4655 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4656 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4657 getF32Constant(DAG, 0x4020d29c, dl)); 4658 } else { // LimitFloatPrecision <= 18 4659 // For floating-point precision of 18: 4660 // 4661 // Log2ofMantissa = 4662 // -3.0400495f + 4663 // (6.1129976f + 4664 // (-5.3420409f + 4665 // (3.2865683f + 4666 // (-1.2669343f + 4667 // (0.27515199f - 4668 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4669 // 4670 // error 0.0000018516, which is better than 18 bits 4671 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4672 getF32Constant(DAG, 0xbcd2769e, dl)); 4673 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4674 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4675 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4676 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4677 getF32Constant(DAG, 0x3fa22ae7, dl)); 4678 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4679 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4680 getF32Constant(DAG, 0x40525723, dl)); 4681 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4682 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4683 getF32Constant(DAG, 0x40aaf200, dl)); 4684 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4685 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4686 getF32Constant(DAG, 0x40c39dad, dl)); 4687 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4688 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4689 getF32Constant(DAG, 0x4042902c, dl)); 4690 } 4691 4692 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4693 } 4694 4695 // No special expansion. 4696 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4697 } 4698 4699 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4700 /// limited-precision mode. 4701 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4702 const TargetLowering &TLI) { 4703 // TODO: What fast-math-flags should be set on the floating-point nodes? 4704 4705 if (Op.getValueType() == MVT::f32 && 4706 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4707 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4708 4709 // Scale the exponent by log10(2) [0.30102999f]. 4710 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4711 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4712 getF32Constant(DAG, 0x3e9a209a, dl)); 4713 4714 // Get the significand and build it into a floating-point number with 4715 // exponent of 1. 4716 SDValue X = GetSignificand(DAG, Op1, dl); 4717 4718 SDValue Log10ofMantissa; 4719 if (LimitFloatPrecision <= 6) { 4720 // For floating-point precision of 6: 4721 // 4722 // Log10ofMantissa = 4723 // -0.50419619f + 4724 // (0.60948995f - 0.10380950f * x) * x; 4725 // 4726 // error 0.0014886165, which is 6 bits 4727 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4728 getF32Constant(DAG, 0xbdd49a13, dl)); 4729 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4730 getF32Constant(DAG, 0x3f1c0789, dl)); 4731 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4732 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4733 getF32Constant(DAG, 0x3f011300, dl)); 4734 } else if (LimitFloatPrecision <= 12) { 4735 // For floating-point precision of 12: 4736 // 4737 // Log10ofMantissa = 4738 // -0.64831180f + 4739 // (0.91751397f + 4740 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4741 // 4742 // error 0.00019228036, which is better than 12 bits 4743 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4744 getF32Constant(DAG, 0x3d431f31, dl)); 4745 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4746 getF32Constant(DAG, 0x3ea21fb2, dl)); 4747 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4748 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4749 getF32Constant(DAG, 0x3f6ae232, dl)); 4750 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4751 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4752 getF32Constant(DAG, 0x3f25f7c3, dl)); 4753 } else { // LimitFloatPrecision <= 18 4754 // For floating-point precision of 18: 4755 // 4756 // Log10ofMantissa = 4757 // -0.84299375f + 4758 // (1.5327582f + 4759 // (-1.0688956f + 4760 // (0.49102474f + 4761 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4762 // 4763 // error 0.0000037995730, which is better than 18 bits 4764 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4765 getF32Constant(DAG, 0x3c5d51ce, dl)); 4766 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4767 getF32Constant(DAG, 0x3e00685a, dl)); 4768 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4769 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4770 getF32Constant(DAG, 0x3efb6798, dl)); 4771 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4772 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4773 getF32Constant(DAG, 0x3f88d192, dl)); 4774 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4775 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4776 getF32Constant(DAG, 0x3fc4316c, dl)); 4777 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4778 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4779 getF32Constant(DAG, 0x3f57ce70, dl)); 4780 } 4781 4782 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4783 } 4784 4785 // No special expansion. 4786 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4787 } 4788 4789 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4790 /// limited-precision mode. 4791 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4792 const TargetLowering &TLI) { 4793 if (Op.getValueType() == MVT::f32 && 4794 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4795 return getLimitedPrecisionExp2(Op, dl, DAG); 4796 4797 // No special expansion. 4798 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4799 } 4800 4801 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4802 /// limited-precision mode with x == 10.0f. 4803 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4804 SelectionDAG &DAG, const TargetLowering &TLI) { 4805 bool IsExp10 = false; 4806 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4807 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4808 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4809 APFloat Ten(10.0f); 4810 IsExp10 = LHSC->isExactlyValue(Ten); 4811 } 4812 } 4813 4814 // TODO: What fast-math-flags should be set on the FMUL node? 4815 if (IsExp10) { 4816 // Put the exponent in the right bit position for later addition to the 4817 // final result: 4818 // 4819 // #define LOG2OF10 3.3219281f 4820 // t0 = Op * LOG2OF10; 4821 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4822 getF32Constant(DAG, 0x40549a78, dl)); 4823 return getLimitedPrecisionExp2(t0, dl, DAG); 4824 } 4825 4826 // No special expansion. 4827 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4828 } 4829 4830 /// ExpandPowI - Expand a llvm.powi intrinsic. 4831 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4832 SelectionDAG &DAG) { 4833 // If RHS is a constant, we can expand this out to a multiplication tree, 4834 // otherwise we end up lowering to a call to __powidf2 (for example). When 4835 // optimizing for size, we only want to do this if the expansion would produce 4836 // a small number of multiplies, otherwise we do the full expansion. 4837 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4838 // Get the exponent as a positive value. 4839 unsigned Val = RHSC->getSExtValue(); 4840 if ((int)Val < 0) Val = -Val; 4841 4842 // powi(x, 0) -> 1.0 4843 if (Val == 0) 4844 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4845 4846 const Function &F = DAG.getMachineFunction().getFunction(); 4847 if (!F.optForSize() || 4848 // If optimizing for size, don't insert too many multiplies. 4849 // This inserts up to 5 multiplies. 4850 countPopulation(Val) + Log2_32(Val) < 7) { 4851 // We use the simple binary decomposition method to generate the multiply 4852 // sequence. There are more optimal ways to do this (for example, 4853 // powi(x,15) generates one more multiply than it should), but this has 4854 // the benefit of being both really simple and much better than a libcall. 4855 SDValue Res; // Logically starts equal to 1.0 4856 SDValue CurSquare = LHS; 4857 // TODO: Intrinsics should have fast-math-flags that propagate to these 4858 // nodes. 4859 while (Val) { 4860 if (Val & 1) { 4861 if (Res.getNode()) 4862 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4863 else 4864 Res = CurSquare; // 1.0*CurSquare. 4865 } 4866 4867 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4868 CurSquare, CurSquare); 4869 Val >>= 1; 4870 } 4871 4872 // If the original was negative, invert the result, producing 1/(x*x*x). 4873 if (RHSC->getSExtValue() < 0) 4874 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4875 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4876 return Res; 4877 } 4878 } 4879 4880 // Otherwise, expand to a libcall. 4881 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4882 } 4883 4884 // getUnderlyingArgReg - Find underlying register used for a truncated or 4885 // bitcasted argument. 4886 static unsigned getUnderlyingArgReg(const SDValue &N) { 4887 switch (N.getOpcode()) { 4888 case ISD::CopyFromReg: 4889 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4890 case ISD::BITCAST: 4891 case ISD::AssertZext: 4892 case ISD::AssertSext: 4893 case ISD::TRUNCATE: 4894 return getUnderlyingArgReg(N.getOperand(0)); 4895 default: 4896 return 0; 4897 } 4898 } 4899 4900 /// If the DbgValueInst is a dbg_value of a function argument, create the 4901 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4902 /// instruction selection, they will be inserted to the entry BB. 4903 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4904 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4905 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4906 const Argument *Arg = dyn_cast<Argument>(V); 4907 if (!Arg) 4908 return false; 4909 4910 MachineFunction &MF = DAG.getMachineFunction(); 4911 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4912 4913 bool IsIndirect = false; 4914 Optional<MachineOperand> Op; 4915 // Some arguments' frame index is recorded during argument lowering. 4916 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4917 if (FI != std::numeric_limits<int>::max()) 4918 Op = MachineOperand::CreateFI(FI); 4919 4920 if (!Op && N.getNode()) { 4921 unsigned Reg = getUnderlyingArgReg(N); 4922 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4923 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4924 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4925 if (PR) 4926 Reg = PR; 4927 } 4928 if (Reg) { 4929 Op = MachineOperand::CreateReg(Reg, false); 4930 IsIndirect = IsDbgDeclare; 4931 } 4932 } 4933 4934 if (!Op && N.getNode()) 4935 // Check if frame index is available. 4936 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4937 if (FrameIndexSDNode *FINode = 4938 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4939 Op = MachineOperand::CreateFI(FINode->getIndex()); 4940 4941 if (!Op) { 4942 // Check if ValueMap has reg number. 4943 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4944 if (VMI != FuncInfo.ValueMap.end()) { 4945 const auto &TLI = DAG.getTargetLoweringInfo(); 4946 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4947 V->getType(), getABIRegCopyCC(V)); 4948 if (RFV.occupiesMultipleRegs()) { 4949 unsigned Offset = 0; 4950 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4951 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4952 auto FragmentExpr = DIExpression::createFragmentExpression( 4953 Expr, Offset, RegAndSize.second); 4954 if (!FragmentExpr) 4955 continue; 4956 FuncInfo.ArgDbgValues.push_back( 4957 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4958 Op->getReg(), Variable, *FragmentExpr)); 4959 Offset += RegAndSize.second; 4960 } 4961 return true; 4962 } 4963 Op = MachineOperand::CreateReg(VMI->second, false); 4964 IsIndirect = IsDbgDeclare; 4965 } 4966 } 4967 4968 if (!Op) 4969 return false; 4970 4971 assert(Variable->isValidLocationForIntrinsic(DL) && 4972 "Expected inlined-at fields to agree"); 4973 IsIndirect = (Op->isReg()) ? IsIndirect : true; 4974 FuncInfo.ArgDbgValues.push_back( 4975 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4976 *Op, Variable, Expr)); 4977 4978 return true; 4979 } 4980 4981 /// Return the appropriate SDDbgValue based on N. 4982 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4983 DILocalVariable *Variable, 4984 DIExpression *Expr, 4985 const DebugLoc &dl, 4986 unsigned DbgSDNodeOrder) { 4987 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 4988 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4989 // stack slot locations. 4990 // 4991 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 4992 // debug values here after optimization: 4993 // 4994 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 4995 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 4996 // 4997 // Both describe the direct values of their associated variables. 4998 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 4999 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5000 } 5001 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5002 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5003 } 5004 5005 // VisualStudio defines setjmp as _setjmp 5006 #if defined(_MSC_VER) && defined(setjmp) && \ 5007 !defined(setjmp_undefined_for_msvc) 5008 # pragma push_macro("setjmp") 5009 # undef setjmp 5010 # define setjmp_undefined_for_msvc 5011 #endif 5012 5013 /// Lower the call to the specified intrinsic function. If we want to emit this 5014 /// as a call to a named external function, return the name. Otherwise, lower it 5015 /// and return null. 5016 const char * 5017 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5019 SDLoc sdl = getCurSDLoc(); 5020 DebugLoc dl = getCurDebugLoc(); 5021 SDValue Res; 5022 5023 switch (Intrinsic) { 5024 default: 5025 // By default, turn this into a target intrinsic node. 5026 visitTargetIntrinsic(I, Intrinsic); 5027 return nullptr; 5028 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5029 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5030 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5031 case Intrinsic::returnaddress: 5032 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5033 TLI.getPointerTy(DAG.getDataLayout()), 5034 getValue(I.getArgOperand(0)))); 5035 return nullptr; 5036 case Intrinsic::addressofreturnaddress: 5037 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5038 TLI.getPointerTy(DAG.getDataLayout()))); 5039 return nullptr; 5040 case Intrinsic::frameaddress: 5041 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5042 TLI.getPointerTy(DAG.getDataLayout()), 5043 getValue(I.getArgOperand(0)))); 5044 return nullptr; 5045 case Intrinsic::read_register: { 5046 Value *Reg = I.getArgOperand(0); 5047 SDValue Chain = getRoot(); 5048 SDValue RegName = 5049 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5050 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5051 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5052 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5053 setValue(&I, Res); 5054 DAG.setRoot(Res.getValue(1)); 5055 return nullptr; 5056 } 5057 case Intrinsic::write_register: { 5058 Value *Reg = I.getArgOperand(0); 5059 Value *RegValue = I.getArgOperand(1); 5060 SDValue Chain = getRoot(); 5061 SDValue RegName = 5062 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5063 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5064 RegName, getValue(RegValue))); 5065 return nullptr; 5066 } 5067 case Intrinsic::setjmp: 5068 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5069 case Intrinsic::longjmp: 5070 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5071 case Intrinsic::memcpy: { 5072 const auto &MCI = cast<MemCpyInst>(I); 5073 SDValue Op1 = getValue(I.getArgOperand(0)); 5074 SDValue Op2 = getValue(I.getArgOperand(1)); 5075 SDValue Op3 = getValue(I.getArgOperand(2)); 5076 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5077 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5078 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5079 unsigned Align = MinAlign(DstAlign, SrcAlign); 5080 bool isVol = MCI.isVolatile(); 5081 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5082 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5083 // node. 5084 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5085 false, isTC, 5086 MachinePointerInfo(I.getArgOperand(0)), 5087 MachinePointerInfo(I.getArgOperand(1))); 5088 updateDAGForMaybeTailCall(MC); 5089 return nullptr; 5090 } 5091 case Intrinsic::memset: { 5092 const auto &MSI = cast<MemSetInst>(I); 5093 SDValue Op1 = getValue(I.getArgOperand(0)); 5094 SDValue Op2 = getValue(I.getArgOperand(1)); 5095 SDValue Op3 = getValue(I.getArgOperand(2)); 5096 // @llvm.memset defines 0 and 1 to both mean no alignment. 5097 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5098 bool isVol = MSI.isVolatile(); 5099 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5100 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5101 isTC, MachinePointerInfo(I.getArgOperand(0))); 5102 updateDAGForMaybeTailCall(MS); 5103 return nullptr; 5104 } 5105 case Intrinsic::memmove: { 5106 const auto &MMI = cast<MemMoveInst>(I); 5107 SDValue Op1 = getValue(I.getArgOperand(0)); 5108 SDValue Op2 = getValue(I.getArgOperand(1)); 5109 SDValue Op3 = getValue(I.getArgOperand(2)); 5110 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5111 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5112 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5113 unsigned Align = MinAlign(DstAlign, SrcAlign); 5114 bool isVol = MMI.isVolatile(); 5115 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5116 // FIXME: Support passing different dest/src alignments to the memmove DAG 5117 // node. 5118 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5119 isTC, MachinePointerInfo(I.getArgOperand(0)), 5120 MachinePointerInfo(I.getArgOperand(1))); 5121 updateDAGForMaybeTailCall(MM); 5122 return nullptr; 5123 } 5124 case Intrinsic::memcpy_element_unordered_atomic: { 5125 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5126 SDValue Dst = getValue(MI.getRawDest()); 5127 SDValue Src = getValue(MI.getRawSource()); 5128 SDValue Length = getValue(MI.getLength()); 5129 5130 unsigned DstAlign = MI.getDestAlignment(); 5131 unsigned SrcAlign = MI.getSourceAlignment(); 5132 Type *LengthTy = MI.getLength()->getType(); 5133 unsigned ElemSz = MI.getElementSizeInBytes(); 5134 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5135 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5136 SrcAlign, Length, LengthTy, ElemSz, isTC, 5137 MachinePointerInfo(MI.getRawDest()), 5138 MachinePointerInfo(MI.getRawSource())); 5139 updateDAGForMaybeTailCall(MC); 5140 return nullptr; 5141 } 5142 case Intrinsic::memmove_element_unordered_atomic: { 5143 auto &MI = cast<AtomicMemMoveInst>(I); 5144 SDValue Dst = getValue(MI.getRawDest()); 5145 SDValue Src = getValue(MI.getRawSource()); 5146 SDValue Length = getValue(MI.getLength()); 5147 5148 unsigned DstAlign = MI.getDestAlignment(); 5149 unsigned SrcAlign = MI.getSourceAlignment(); 5150 Type *LengthTy = MI.getLength()->getType(); 5151 unsigned ElemSz = MI.getElementSizeInBytes(); 5152 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5153 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5154 SrcAlign, Length, LengthTy, ElemSz, isTC, 5155 MachinePointerInfo(MI.getRawDest()), 5156 MachinePointerInfo(MI.getRawSource())); 5157 updateDAGForMaybeTailCall(MC); 5158 return nullptr; 5159 } 5160 case Intrinsic::memset_element_unordered_atomic: { 5161 auto &MI = cast<AtomicMemSetInst>(I); 5162 SDValue Dst = getValue(MI.getRawDest()); 5163 SDValue Val = getValue(MI.getValue()); 5164 SDValue Length = getValue(MI.getLength()); 5165 5166 unsigned DstAlign = MI.getDestAlignment(); 5167 Type *LengthTy = MI.getLength()->getType(); 5168 unsigned ElemSz = MI.getElementSizeInBytes(); 5169 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5170 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5171 LengthTy, ElemSz, isTC, 5172 MachinePointerInfo(MI.getRawDest())); 5173 updateDAGForMaybeTailCall(MC); 5174 return nullptr; 5175 } 5176 case Intrinsic::dbg_addr: 5177 case Intrinsic::dbg_declare: { 5178 const auto &DI = cast<DbgVariableIntrinsic>(I); 5179 DILocalVariable *Variable = DI.getVariable(); 5180 DIExpression *Expression = DI.getExpression(); 5181 dropDanglingDebugInfo(Variable, Expression); 5182 assert(Variable && "Missing variable"); 5183 5184 // Check if address has undef value. 5185 const Value *Address = DI.getVariableLocation(); 5186 if (!Address || isa<UndefValue>(Address) || 5187 (Address->use_empty() && !isa<Argument>(Address))) { 5188 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5189 return nullptr; 5190 } 5191 5192 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5193 5194 // Check if this variable can be described by a frame index, typically 5195 // either as a static alloca or a byval parameter. 5196 int FI = std::numeric_limits<int>::max(); 5197 if (const auto *AI = 5198 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5199 if (AI->isStaticAlloca()) { 5200 auto I = FuncInfo.StaticAllocaMap.find(AI); 5201 if (I != FuncInfo.StaticAllocaMap.end()) 5202 FI = I->second; 5203 } 5204 } else if (const auto *Arg = dyn_cast<Argument>( 5205 Address->stripInBoundsConstantOffsets())) { 5206 FI = FuncInfo.getArgumentFrameIndex(Arg); 5207 } 5208 5209 // llvm.dbg.addr is control dependent and always generates indirect 5210 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5211 // the MachineFunction variable table. 5212 if (FI != std::numeric_limits<int>::max()) { 5213 if (Intrinsic == Intrinsic::dbg_addr) { 5214 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5215 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5216 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5217 } 5218 return nullptr; 5219 } 5220 5221 SDValue &N = NodeMap[Address]; 5222 if (!N.getNode() && isa<Argument>(Address)) 5223 // Check unused arguments map. 5224 N = UnusedArgNodeMap[Address]; 5225 SDDbgValue *SDV; 5226 if (N.getNode()) { 5227 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5228 Address = BCI->getOperand(0); 5229 // Parameters are handled specially. 5230 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5231 if (isParameter && FINode) { 5232 // Byval parameter. We have a frame index at this point. 5233 SDV = 5234 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5235 /*IsIndirect*/ true, dl, SDNodeOrder); 5236 } else if (isa<Argument>(Address)) { 5237 // Address is an argument, so try to emit its dbg value using 5238 // virtual register info from the FuncInfo.ValueMap. 5239 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5240 return nullptr; 5241 } else { 5242 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5243 true, dl, SDNodeOrder); 5244 } 5245 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5246 } else { 5247 // If Address is an argument then try to emit its dbg value using 5248 // virtual register info from the FuncInfo.ValueMap. 5249 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5250 N)) { 5251 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5252 } 5253 } 5254 return nullptr; 5255 } 5256 case Intrinsic::dbg_label: { 5257 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5258 DILabel *Label = DI.getLabel(); 5259 assert(Label && "Missing label"); 5260 5261 SDDbgLabel *SDV; 5262 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5263 DAG.AddDbgLabel(SDV); 5264 return nullptr; 5265 } 5266 case Intrinsic::dbg_value: { 5267 const DbgValueInst &DI = cast<DbgValueInst>(I); 5268 assert(DI.getVariable() && "Missing variable"); 5269 5270 DILocalVariable *Variable = DI.getVariable(); 5271 DIExpression *Expression = DI.getExpression(); 5272 dropDanglingDebugInfo(Variable, Expression); 5273 const Value *V = DI.getValue(); 5274 if (!V) 5275 return nullptr; 5276 5277 SDDbgValue *SDV; 5278 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5279 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5280 DAG.AddDbgValue(SDV, nullptr, false); 5281 return nullptr; 5282 } 5283 5284 // Do not use getValue() in here; we don't want to generate code at 5285 // this point if it hasn't been done yet. 5286 SDValue N = NodeMap[V]; 5287 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5288 N = UnusedArgNodeMap[V]; 5289 if (N.getNode()) { 5290 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5291 return nullptr; 5292 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5293 DAG.AddDbgValue(SDV, N.getNode(), false); 5294 return nullptr; 5295 } 5296 5297 // PHI nodes have already been selected, so we should know which VReg that 5298 // is assigns to already. 5299 if (isa<PHINode>(V)) { 5300 auto VMI = FuncInfo.ValueMap.find(V); 5301 if (VMI != FuncInfo.ValueMap.end()) { 5302 unsigned Reg = VMI->second; 5303 // The PHI node may be split up into several MI PHI nodes (in 5304 // FunctionLoweringInfo::set). 5305 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5306 V->getType(), None); 5307 if (RFV.occupiesMultipleRegs()) { 5308 unsigned Offset = 0; 5309 unsigned BitsToDescribe = 0; 5310 if (auto VarSize = Variable->getSizeInBits()) 5311 BitsToDescribe = *VarSize; 5312 if (auto Fragment = Expression->getFragmentInfo()) 5313 BitsToDescribe = Fragment->SizeInBits; 5314 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5315 unsigned RegisterSize = RegAndSize.second; 5316 // Bail out if all bits are described already. 5317 if (Offset >= BitsToDescribe) 5318 break; 5319 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5320 ? BitsToDescribe - Offset 5321 : RegisterSize; 5322 auto FragmentExpr = DIExpression::createFragmentExpression( 5323 Expression, Offset, FragmentSize); 5324 if (!FragmentExpr) 5325 continue; 5326 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5327 false, dl, SDNodeOrder); 5328 DAG.AddDbgValue(SDV, nullptr, false); 5329 Offset += RegisterSize; 5330 } 5331 } else { 5332 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5333 SDNodeOrder); 5334 DAG.AddDbgValue(SDV, nullptr, false); 5335 } 5336 return nullptr; 5337 } 5338 } 5339 5340 // TODO: When we get here we will either drop the dbg.value completely, or 5341 // we try to move it forward by letting it dangle for awhile. So we should 5342 // probably add an extra DbgValue to the DAG here, with a reference to 5343 // "noreg", to indicate that we have lost the debug location for the 5344 // variable. 5345 5346 if (!V->use_empty() ) { 5347 // Do not call getValue(V) yet, as we don't want to generate code. 5348 // Remember it for later. 5349 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5350 return nullptr; 5351 } 5352 5353 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5354 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5355 return nullptr; 5356 } 5357 5358 case Intrinsic::eh_typeid_for: { 5359 // Find the type id for the given typeinfo. 5360 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5361 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5362 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5363 setValue(&I, Res); 5364 return nullptr; 5365 } 5366 5367 case Intrinsic::eh_return_i32: 5368 case Intrinsic::eh_return_i64: 5369 DAG.getMachineFunction().setCallsEHReturn(true); 5370 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5371 MVT::Other, 5372 getControlRoot(), 5373 getValue(I.getArgOperand(0)), 5374 getValue(I.getArgOperand(1)))); 5375 return nullptr; 5376 case Intrinsic::eh_unwind_init: 5377 DAG.getMachineFunction().setCallsUnwindInit(true); 5378 return nullptr; 5379 case Intrinsic::eh_dwarf_cfa: 5380 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5381 TLI.getPointerTy(DAG.getDataLayout()), 5382 getValue(I.getArgOperand(0)))); 5383 return nullptr; 5384 case Intrinsic::eh_sjlj_callsite: { 5385 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5386 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5387 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5388 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5389 5390 MMI.setCurrentCallSite(CI->getZExtValue()); 5391 return nullptr; 5392 } 5393 case Intrinsic::eh_sjlj_functioncontext: { 5394 // Get and store the index of the function context. 5395 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5396 AllocaInst *FnCtx = 5397 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5398 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5399 MFI.setFunctionContextIndex(FI); 5400 return nullptr; 5401 } 5402 case Intrinsic::eh_sjlj_setjmp: { 5403 SDValue Ops[2]; 5404 Ops[0] = getRoot(); 5405 Ops[1] = getValue(I.getArgOperand(0)); 5406 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5407 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5408 setValue(&I, Op.getValue(0)); 5409 DAG.setRoot(Op.getValue(1)); 5410 return nullptr; 5411 } 5412 case Intrinsic::eh_sjlj_longjmp: 5413 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5414 getRoot(), getValue(I.getArgOperand(0)))); 5415 return nullptr; 5416 case Intrinsic::eh_sjlj_setup_dispatch: 5417 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5418 getRoot())); 5419 return nullptr; 5420 case Intrinsic::masked_gather: 5421 visitMaskedGather(I); 5422 return nullptr; 5423 case Intrinsic::masked_load: 5424 visitMaskedLoad(I); 5425 return nullptr; 5426 case Intrinsic::masked_scatter: 5427 visitMaskedScatter(I); 5428 return nullptr; 5429 case Intrinsic::masked_store: 5430 visitMaskedStore(I); 5431 return nullptr; 5432 case Intrinsic::masked_expandload: 5433 visitMaskedLoad(I, true /* IsExpanding */); 5434 return nullptr; 5435 case Intrinsic::masked_compressstore: 5436 visitMaskedStore(I, true /* IsCompressing */); 5437 return nullptr; 5438 case Intrinsic::x86_mmx_pslli_w: 5439 case Intrinsic::x86_mmx_pslli_d: 5440 case Intrinsic::x86_mmx_pslli_q: 5441 case Intrinsic::x86_mmx_psrli_w: 5442 case Intrinsic::x86_mmx_psrli_d: 5443 case Intrinsic::x86_mmx_psrli_q: 5444 case Intrinsic::x86_mmx_psrai_w: 5445 case Intrinsic::x86_mmx_psrai_d: { 5446 SDValue ShAmt = getValue(I.getArgOperand(1)); 5447 if (isa<ConstantSDNode>(ShAmt)) { 5448 visitTargetIntrinsic(I, Intrinsic); 5449 return nullptr; 5450 } 5451 unsigned NewIntrinsic = 0; 5452 EVT ShAmtVT = MVT::v2i32; 5453 switch (Intrinsic) { 5454 case Intrinsic::x86_mmx_pslli_w: 5455 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5456 break; 5457 case Intrinsic::x86_mmx_pslli_d: 5458 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5459 break; 5460 case Intrinsic::x86_mmx_pslli_q: 5461 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5462 break; 5463 case Intrinsic::x86_mmx_psrli_w: 5464 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5465 break; 5466 case Intrinsic::x86_mmx_psrli_d: 5467 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5468 break; 5469 case Intrinsic::x86_mmx_psrli_q: 5470 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5471 break; 5472 case Intrinsic::x86_mmx_psrai_w: 5473 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5474 break; 5475 case Intrinsic::x86_mmx_psrai_d: 5476 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5477 break; 5478 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5479 } 5480 5481 // The vector shift intrinsics with scalars uses 32b shift amounts but 5482 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5483 // to be zero. 5484 // We must do this early because v2i32 is not a legal type. 5485 SDValue ShOps[2]; 5486 ShOps[0] = ShAmt; 5487 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5488 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5489 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5490 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5491 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5492 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5493 getValue(I.getArgOperand(0)), ShAmt); 5494 setValue(&I, Res); 5495 return nullptr; 5496 } 5497 case Intrinsic::powi: 5498 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5499 getValue(I.getArgOperand(1)), DAG)); 5500 return nullptr; 5501 case Intrinsic::log: 5502 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5503 return nullptr; 5504 case Intrinsic::log2: 5505 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5506 return nullptr; 5507 case Intrinsic::log10: 5508 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5509 return nullptr; 5510 case Intrinsic::exp: 5511 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5512 return nullptr; 5513 case Intrinsic::exp2: 5514 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5515 return nullptr; 5516 case Intrinsic::pow: 5517 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5518 getValue(I.getArgOperand(1)), DAG, TLI)); 5519 return nullptr; 5520 case Intrinsic::sqrt: 5521 case Intrinsic::fabs: 5522 case Intrinsic::sin: 5523 case Intrinsic::cos: 5524 case Intrinsic::floor: 5525 case Intrinsic::ceil: 5526 case Intrinsic::trunc: 5527 case Intrinsic::rint: 5528 case Intrinsic::nearbyint: 5529 case Intrinsic::round: 5530 case Intrinsic::canonicalize: { 5531 unsigned Opcode; 5532 switch (Intrinsic) { 5533 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5534 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5535 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5536 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5537 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5538 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5539 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5540 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5541 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5542 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5543 case Intrinsic::round: Opcode = ISD::FROUND; break; 5544 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5545 } 5546 5547 setValue(&I, DAG.getNode(Opcode, sdl, 5548 getValue(I.getArgOperand(0)).getValueType(), 5549 getValue(I.getArgOperand(0)))); 5550 return nullptr; 5551 } 5552 case Intrinsic::minnum: { 5553 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5554 unsigned Opc = 5555 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5556 ? ISD::FMINNAN 5557 : ISD::FMINNUM; 5558 setValue(&I, DAG.getNode(Opc, sdl, VT, 5559 getValue(I.getArgOperand(0)), 5560 getValue(I.getArgOperand(1)))); 5561 return nullptr; 5562 } 5563 case Intrinsic::maxnum: { 5564 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5565 unsigned Opc = 5566 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5567 ? ISD::FMAXNAN 5568 : ISD::FMAXNUM; 5569 setValue(&I, DAG.getNode(Opc, sdl, VT, 5570 getValue(I.getArgOperand(0)), 5571 getValue(I.getArgOperand(1)))); 5572 return nullptr; 5573 } 5574 case Intrinsic::copysign: 5575 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5576 getValue(I.getArgOperand(0)).getValueType(), 5577 getValue(I.getArgOperand(0)), 5578 getValue(I.getArgOperand(1)))); 5579 return nullptr; 5580 case Intrinsic::fma: 5581 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5582 getValue(I.getArgOperand(0)).getValueType(), 5583 getValue(I.getArgOperand(0)), 5584 getValue(I.getArgOperand(1)), 5585 getValue(I.getArgOperand(2)))); 5586 return nullptr; 5587 case Intrinsic::experimental_constrained_fadd: 5588 case Intrinsic::experimental_constrained_fsub: 5589 case Intrinsic::experimental_constrained_fmul: 5590 case Intrinsic::experimental_constrained_fdiv: 5591 case Intrinsic::experimental_constrained_frem: 5592 case Intrinsic::experimental_constrained_fma: 5593 case Intrinsic::experimental_constrained_sqrt: 5594 case Intrinsic::experimental_constrained_pow: 5595 case Intrinsic::experimental_constrained_powi: 5596 case Intrinsic::experimental_constrained_sin: 5597 case Intrinsic::experimental_constrained_cos: 5598 case Intrinsic::experimental_constrained_exp: 5599 case Intrinsic::experimental_constrained_exp2: 5600 case Intrinsic::experimental_constrained_log: 5601 case Intrinsic::experimental_constrained_log10: 5602 case Intrinsic::experimental_constrained_log2: 5603 case Intrinsic::experimental_constrained_rint: 5604 case Intrinsic::experimental_constrained_nearbyint: 5605 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5606 return nullptr; 5607 case Intrinsic::fmuladd: { 5608 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5609 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5610 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5611 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5612 getValue(I.getArgOperand(0)).getValueType(), 5613 getValue(I.getArgOperand(0)), 5614 getValue(I.getArgOperand(1)), 5615 getValue(I.getArgOperand(2)))); 5616 } else { 5617 // TODO: Intrinsic calls should have fast-math-flags. 5618 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5619 getValue(I.getArgOperand(0)).getValueType(), 5620 getValue(I.getArgOperand(0)), 5621 getValue(I.getArgOperand(1))); 5622 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5623 getValue(I.getArgOperand(0)).getValueType(), 5624 Mul, 5625 getValue(I.getArgOperand(2))); 5626 setValue(&I, Add); 5627 } 5628 return nullptr; 5629 } 5630 case Intrinsic::convert_to_fp16: 5631 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5632 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5633 getValue(I.getArgOperand(0)), 5634 DAG.getTargetConstant(0, sdl, 5635 MVT::i32)))); 5636 return nullptr; 5637 case Intrinsic::convert_from_fp16: 5638 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5639 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5640 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5641 getValue(I.getArgOperand(0))))); 5642 return nullptr; 5643 case Intrinsic::pcmarker: { 5644 SDValue Tmp = getValue(I.getArgOperand(0)); 5645 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5646 return nullptr; 5647 } 5648 case Intrinsic::readcyclecounter: { 5649 SDValue Op = getRoot(); 5650 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5651 DAG.getVTList(MVT::i64, MVT::Other), Op); 5652 setValue(&I, Res); 5653 DAG.setRoot(Res.getValue(1)); 5654 return nullptr; 5655 } 5656 case Intrinsic::bitreverse: 5657 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5658 getValue(I.getArgOperand(0)).getValueType(), 5659 getValue(I.getArgOperand(0)))); 5660 return nullptr; 5661 case Intrinsic::bswap: 5662 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5663 getValue(I.getArgOperand(0)).getValueType(), 5664 getValue(I.getArgOperand(0)))); 5665 return nullptr; 5666 case Intrinsic::cttz: { 5667 SDValue Arg = getValue(I.getArgOperand(0)); 5668 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5669 EVT Ty = Arg.getValueType(); 5670 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5671 sdl, Ty, Arg)); 5672 return nullptr; 5673 } 5674 case Intrinsic::ctlz: { 5675 SDValue Arg = getValue(I.getArgOperand(0)); 5676 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5677 EVT Ty = Arg.getValueType(); 5678 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5679 sdl, Ty, Arg)); 5680 return nullptr; 5681 } 5682 case Intrinsic::ctpop: { 5683 SDValue Arg = getValue(I.getArgOperand(0)); 5684 EVT Ty = Arg.getValueType(); 5685 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5686 return nullptr; 5687 } 5688 case Intrinsic::fshl: 5689 case Intrinsic::fshr: { 5690 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5691 SDValue X = getValue(I.getArgOperand(0)); 5692 SDValue Y = getValue(I.getArgOperand(1)); 5693 SDValue Z = getValue(I.getArgOperand(2)); 5694 EVT VT = X.getValueType(); 5695 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5696 SDValue Zero = DAG.getConstant(0, sdl, VT); 5697 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5698 5699 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5700 // avoid the select that is necessary in the general case to filter out 5701 // the 0-shift possibility that leads to UB. 5702 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5703 // TODO: This should also be done if the operation is custom, but we have 5704 // to make sure targets are handling the modulo shift amount as expected. 5705 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5706 if (TLI.isOperationLegal(RotateOpcode, VT)) { 5707 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5708 return nullptr; 5709 } 5710 5711 // Some targets only rotate one way. Try the opposite direction. 5712 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5713 if (TLI.isOperationLegal(RotateOpcode, VT)) { 5714 // Negate the shift amount because it is safe to ignore the high bits. 5715 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5716 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5717 return nullptr; 5718 } 5719 5720 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5721 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5722 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5723 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5724 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5725 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5726 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5727 return nullptr; 5728 } 5729 5730 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5731 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5732 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5733 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5734 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5735 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5736 5737 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5738 // and that is undefined. We must compare and select to avoid UB. 5739 EVT CCVT = MVT::i1; 5740 if (VT.isVector()) 5741 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5742 5743 // For fshl, 0-shift returns the 1st arg (X). 5744 // For fshr, 0-shift returns the 2nd arg (Y). 5745 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5746 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5747 return nullptr; 5748 } 5749 case Intrinsic::stacksave: { 5750 SDValue Op = getRoot(); 5751 Res = DAG.getNode( 5752 ISD::STACKSAVE, sdl, 5753 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5754 setValue(&I, Res); 5755 DAG.setRoot(Res.getValue(1)); 5756 return nullptr; 5757 } 5758 case Intrinsic::stackrestore: 5759 Res = getValue(I.getArgOperand(0)); 5760 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5761 return nullptr; 5762 case Intrinsic::get_dynamic_area_offset: { 5763 SDValue Op = getRoot(); 5764 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5765 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5766 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5767 // target. 5768 if (PtrTy != ResTy) 5769 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5770 " intrinsic!"); 5771 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5772 Op); 5773 DAG.setRoot(Op); 5774 setValue(&I, Res); 5775 return nullptr; 5776 } 5777 case Intrinsic::stackguard: { 5778 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5779 MachineFunction &MF = DAG.getMachineFunction(); 5780 const Module &M = *MF.getFunction().getParent(); 5781 SDValue Chain = getRoot(); 5782 if (TLI.useLoadStackGuardNode()) { 5783 Res = getLoadStackGuard(DAG, sdl, Chain); 5784 } else { 5785 const Value *Global = TLI.getSDagStackGuard(M); 5786 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5787 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5788 MachinePointerInfo(Global, 0), Align, 5789 MachineMemOperand::MOVolatile); 5790 } 5791 if (TLI.useStackGuardXorFP()) 5792 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5793 DAG.setRoot(Chain); 5794 setValue(&I, Res); 5795 return nullptr; 5796 } 5797 case Intrinsic::stackprotector: { 5798 // Emit code into the DAG to store the stack guard onto the stack. 5799 MachineFunction &MF = DAG.getMachineFunction(); 5800 MachineFrameInfo &MFI = MF.getFrameInfo(); 5801 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5802 SDValue Src, Chain = getRoot(); 5803 5804 if (TLI.useLoadStackGuardNode()) 5805 Src = getLoadStackGuard(DAG, sdl, Chain); 5806 else 5807 Src = getValue(I.getArgOperand(0)); // The guard's value. 5808 5809 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5810 5811 int FI = FuncInfo.StaticAllocaMap[Slot]; 5812 MFI.setStackProtectorIndex(FI); 5813 5814 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5815 5816 // Store the stack protector onto the stack. 5817 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5818 DAG.getMachineFunction(), FI), 5819 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5820 setValue(&I, Res); 5821 DAG.setRoot(Res); 5822 return nullptr; 5823 } 5824 case Intrinsic::objectsize: { 5825 // If we don't know by now, we're never going to know. 5826 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5827 5828 assert(CI && "Non-constant type in __builtin_object_size?"); 5829 5830 SDValue Arg = getValue(I.getCalledValue()); 5831 EVT Ty = Arg.getValueType(); 5832 5833 if (CI->isZero()) 5834 Res = DAG.getConstant(-1ULL, sdl, Ty); 5835 else 5836 Res = DAG.getConstant(0, sdl, Ty); 5837 5838 setValue(&I, Res); 5839 return nullptr; 5840 } 5841 case Intrinsic::annotation: 5842 case Intrinsic::ptr_annotation: 5843 case Intrinsic::launder_invariant_group: 5844 case Intrinsic::strip_invariant_group: 5845 // Drop the intrinsic, but forward the value 5846 setValue(&I, getValue(I.getOperand(0))); 5847 return nullptr; 5848 case Intrinsic::assume: 5849 case Intrinsic::var_annotation: 5850 case Intrinsic::sideeffect: 5851 // Discard annotate attributes, assumptions, and artificial side-effects. 5852 return nullptr; 5853 5854 case Intrinsic::codeview_annotation: { 5855 // Emit a label associated with this metadata. 5856 MachineFunction &MF = DAG.getMachineFunction(); 5857 MCSymbol *Label = 5858 MF.getMMI().getContext().createTempSymbol("annotation", true); 5859 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5860 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5861 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5862 DAG.setRoot(Res); 5863 return nullptr; 5864 } 5865 5866 case Intrinsic::init_trampoline: { 5867 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5868 5869 SDValue Ops[6]; 5870 Ops[0] = getRoot(); 5871 Ops[1] = getValue(I.getArgOperand(0)); 5872 Ops[2] = getValue(I.getArgOperand(1)); 5873 Ops[3] = getValue(I.getArgOperand(2)); 5874 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5875 Ops[5] = DAG.getSrcValue(F); 5876 5877 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5878 5879 DAG.setRoot(Res); 5880 return nullptr; 5881 } 5882 case Intrinsic::adjust_trampoline: 5883 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5884 TLI.getPointerTy(DAG.getDataLayout()), 5885 getValue(I.getArgOperand(0)))); 5886 return nullptr; 5887 case Intrinsic::gcroot: { 5888 assert(DAG.getMachineFunction().getFunction().hasGC() && 5889 "only valid in functions with gc specified, enforced by Verifier"); 5890 assert(GFI && "implied by previous"); 5891 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5892 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5893 5894 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5895 GFI->addStackRoot(FI->getIndex(), TypeMap); 5896 return nullptr; 5897 } 5898 case Intrinsic::gcread: 5899 case Intrinsic::gcwrite: 5900 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5901 case Intrinsic::flt_rounds: 5902 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5903 return nullptr; 5904 5905 case Intrinsic::expect: 5906 // Just replace __builtin_expect(exp, c) with EXP. 5907 setValue(&I, getValue(I.getArgOperand(0))); 5908 return nullptr; 5909 5910 case Intrinsic::debugtrap: 5911 case Intrinsic::trap: { 5912 StringRef TrapFuncName = 5913 I.getAttributes() 5914 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5915 .getValueAsString(); 5916 if (TrapFuncName.empty()) { 5917 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5918 ISD::TRAP : ISD::DEBUGTRAP; 5919 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5920 return nullptr; 5921 } 5922 TargetLowering::ArgListTy Args; 5923 5924 TargetLowering::CallLoweringInfo CLI(DAG); 5925 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5926 CallingConv::C, I.getType(), 5927 DAG.getExternalSymbol(TrapFuncName.data(), 5928 TLI.getPointerTy(DAG.getDataLayout())), 5929 std::move(Args)); 5930 5931 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5932 DAG.setRoot(Result.second); 5933 return nullptr; 5934 } 5935 5936 case Intrinsic::uadd_with_overflow: 5937 case Intrinsic::sadd_with_overflow: 5938 case Intrinsic::usub_with_overflow: 5939 case Intrinsic::ssub_with_overflow: 5940 case Intrinsic::umul_with_overflow: 5941 case Intrinsic::smul_with_overflow: { 5942 ISD::NodeType Op; 5943 switch (Intrinsic) { 5944 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5945 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5946 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5947 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5948 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5949 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5950 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5951 } 5952 SDValue Op1 = getValue(I.getArgOperand(0)); 5953 SDValue Op2 = getValue(I.getArgOperand(1)); 5954 5955 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5956 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5957 return nullptr; 5958 } 5959 case Intrinsic::prefetch: { 5960 SDValue Ops[5]; 5961 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5962 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 5963 Ops[0] = DAG.getRoot(); 5964 Ops[1] = getValue(I.getArgOperand(0)); 5965 Ops[2] = getValue(I.getArgOperand(1)); 5966 Ops[3] = getValue(I.getArgOperand(2)); 5967 Ops[4] = getValue(I.getArgOperand(3)); 5968 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5969 DAG.getVTList(MVT::Other), Ops, 5970 EVT::getIntegerVT(*Context, 8), 5971 MachinePointerInfo(I.getArgOperand(0)), 5972 0, /* align */ 5973 Flags); 5974 5975 // Chain the prefetch in parallell with any pending loads, to stay out of 5976 // the way of later optimizations. 5977 PendingLoads.push_back(Result); 5978 Result = getRoot(); 5979 DAG.setRoot(Result); 5980 return nullptr; 5981 } 5982 case Intrinsic::lifetime_start: 5983 case Intrinsic::lifetime_end: { 5984 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5985 // Stack coloring is not enabled in O0, discard region information. 5986 if (TM.getOptLevel() == CodeGenOpt::None) 5987 return nullptr; 5988 5989 SmallVector<Value *, 4> Allocas; 5990 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5991 5992 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5993 E = Allocas.end(); Object != E; ++Object) { 5994 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5995 5996 // Could not find an Alloca. 5997 if (!LifetimeObject) 5998 continue; 5999 6000 // First check that the Alloca is static, otherwise it won't have a 6001 // valid frame index. 6002 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6003 if (SI == FuncInfo.StaticAllocaMap.end()) 6004 return nullptr; 6005 6006 int FI = SI->second; 6007 6008 SDValue Ops[2]; 6009 Ops[0] = getRoot(); 6010 Ops[1] = 6011 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6012 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6013 6014 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6015 DAG.setRoot(Res); 6016 } 6017 return nullptr; 6018 } 6019 case Intrinsic::invariant_start: 6020 // Discard region information. 6021 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6022 return nullptr; 6023 case Intrinsic::invariant_end: 6024 // Discard region information. 6025 return nullptr; 6026 case Intrinsic::clear_cache: 6027 return TLI.getClearCacheBuiltinName(); 6028 case Intrinsic::donothing: 6029 // ignore 6030 return nullptr; 6031 case Intrinsic::experimental_stackmap: 6032 visitStackmap(I); 6033 return nullptr; 6034 case Intrinsic::experimental_patchpoint_void: 6035 case Intrinsic::experimental_patchpoint_i64: 6036 visitPatchpoint(&I); 6037 return nullptr; 6038 case Intrinsic::experimental_gc_statepoint: 6039 LowerStatepoint(ImmutableStatepoint(&I)); 6040 return nullptr; 6041 case Intrinsic::experimental_gc_result: 6042 visitGCResult(cast<GCResultInst>(I)); 6043 return nullptr; 6044 case Intrinsic::experimental_gc_relocate: 6045 visitGCRelocate(cast<GCRelocateInst>(I)); 6046 return nullptr; 6047 case Intrinsic::instrprof_increment: 6048 llvm_unreachable("instrprof failed to lower an increment"); 6049 case Intrinsic::instrprof_value_profile: 6050 llvm_unreachable("instrprof failed to lower a value profiling call"); 6051 case Intrinsic::localescape: { 6052 MachineFunction &MF = DAG.getMachineFunction(); 6053 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6054 6055 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6056 // is the same on all targets. 6057 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6058 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6059 if (isa<ConstantPointerNull>(Arg)) 6060 continue; // Skip null pointers. They represent a hole in index space. 6061 AllocaInst *Slot = cast<AllocaInst>(Arg); 6062 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6063 "can only escape static allocas"); 6064 int FI = FuncInfo.StaticAllocaMap[Slot]; 6065 MCSymbol *FrameAllocSym = 6066 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6067 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6068 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6069 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6070 .addSym(FrameAllocSym) 6071 .addFrameIndex(FI); 6072 } 6073 6074 return nullptr; 6075 } 6076 6077 case Intrinsic::localrecover: { 6078 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6079 MachineFunction &MF = DAG.getMachineFunction(); 6080 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6081 6082 // Get the symbol that defines the frame offset. 6083 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6084 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6085 unsigned IdxVal = 6086 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6087 MCSymbol *FrameAllocSym = 6088 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6089 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6090 6091 // Create a MCSymbol for the label to avoid any target lowering 6092 // that would make this PC relative. 6093 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6094 SDValue OffsetVal = 6095 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6096 6097 // Add the offset to the FP. 6098 Value *FP = I.getArgOperand(1); 6099 SDValue FPVal = getValue(FP); 6100 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6101 setValue(&I, Add); 6102 6103 return nullptr; 6104 } 6105 6106 case Intrinsic::eh_exceptionpointer: 6107 case Intrinsic::eh_exceptioncode: { 6108 // Get the exception pointer vreg, copy from it, and resize it to fit. 6109 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6110 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6111 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6112 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6113 SDValue N = 6114 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6115 if (Intrinsic == Intrinsic::eh_exceptioncode) 6116 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6117 setValue(&I, N); 6118 return nullptr; 6119 } 6120 case Intrinsic::xray_customevent: { 6121 // Here we want to make sure that the intrinsic behaves as if it has a 6122 // specific calling convention, and only for x86_64. 6123 // FIXME: Support other platforms later. 6124 const auto &Triple = DAG.getTarget().getTargetTriple(); 6125 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6126 return nullptr; 6127 6128 SDLoc DL = getCurSDLoc(); 6129 SmallVector<SDValue, 8> Ops; 6130 6131 // We want to say that we always want the arguments in registers. 6132 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6133 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6134 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6135 SDValue Chain = getRoot(); 6136 Ops.push_back(LogEntryVal); 6137 Ops.push_back(StrSizeVal); 6138 Ops.push_back(Chain); 6139 6140 // We need to enforce the calling convention for the callsite, so that 6141 // argument ordering is enforced correctly, and that register allocation can 6142 // see that some registers may be assumed clobbered and have to preserve 6143 // them across calls to the intrinsic. 6144 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6145 DL, NodeTys, Ops); 6146 SDValue patchableNode = SDValue(MN, 0); 6147 DAG.setRoot(patchableNode); 6148 setValue(&I, patchableNode); 6149 return nullptr; 6150 } 6151 case Intrinsic::xray_typedevent: { 6152 // Here we want to make sure that the intrinsic behaves as if it has a 6153 // specific calling convention, and only for x86_64. 6154 // FIXME: Support other platforms later. 6155 const auto &Triple = DAG.getTarget().getTargetTriple(); 6156 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6157 return nullptr; 6158 6159 SDLoc DL = getCurSDLoc(); 6160 SmallVector<SDValue, 8> Ops; 6161 6162 // We want to say that we always want the arguments in registers. 6163 // It's unclear to me how manipulating the selection DAG here forces callers 6164 // to provide arguments in registers instead of on the stack. 6165 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6166 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6167 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6168 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6169 SDValue Chain = getRoot(); 6170 Ops.push_back(LogTypeId); 6171 Ops.push_back(LogEntryVal); 6172 Ops.push_back(StrSizeVal); 6173 Ops.push_back(Chain); 6174 6175 // We need to enforce the calling convention for the callsite, so that 6176 // argument ordering is enforced correctly, and that register allocation can 6177 // see that some registers may be assumed clobbered and have to preserve 6178 // them across calls to the intrinsic. 6179 MachineSDNode *MN = DAG.getMachineNode( 6180 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6181 SDValue patchableNode = SDValue(MN, 0); 6182 DAG.setRoot(patchableNode); 6183 setValue(&I, patchableNode); 6184 return nullptr; 6185 } 6186 case Intrinsic::experimental_deoptimize: 6187 LowerDeoptimizeCall(&I); 6188 return nullptr; 6189 6190 case Intrinsic::experimental_vector_reduce_fadd: 6191 case Intrinsic::experimental_vector_reduce_fmul: 6192 case Intrinsic::experimental_vector_reduce_add: 6193 case Intrinsic::experimental_vector_reduce_mul: 6194 case Intrinsic::experimental_vector_reduce_and: 6195 case Intrinsic::experimental_vector_reduce_or: 6196 case Intrinsic::experimental_vector_reduce_xor: 6197 case Intrinsic::experimental_vector_reduce_smax: 6198 case Intrinsic::experimental_vector_reduce_smin: 6199 case Intrinsic::experimental_vector_reduce_umax: 6200 case Intrinsic::experimental_vector_reduce_umin: 6201 case Intrinsic::experimental_vector_reduce_fmax: 6202 case Intrinsic::experimental_vector_reduce_fmin: 6203 visitVectorReduce(I, Intrinsic); 6204 return nullptr; 6205 6206 case Intrinsic::icall_branch_funnel: { 6207 SmallVector<SDValue, 16> Ops; 6208 Ops.push_back(DAG.getRoot()); 6209 Ops.push_back(getValue(I.getArgOperand(0))); 6210 6211 int64_t Offset; 6212 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6213 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6214 if (!Base) 6215 report_fatal_error( 6216 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6217 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6218 6219 struct BranchFunnelTarget { 6220 int64_t Offset; 6221 SDValue Target; 6222 }; 6223 SmallVector<BranchFunnelTarget, 8> Targets; 6224 6225 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6226 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6227 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6228 if (ElemBase != Base) 6229 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6230 "to the same GlobalValue"); 6231 6232 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6233 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6234 if (!GA) 6235 report_fatal_error( 6236 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6237 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6238 GA->getGlobal(), getCurSDLoc(), 6239 Val.getValueType(), GA->getOffset())}); 6240 } 6241 llvm::sort(Targets.begin(), Targets.end(), 6242 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6243 return T1.Offset < T2.Offset; 6244 }); 6245 6246 for (auto &T : Targets) { 6247 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6248 Ops.push_back(T.Target); 6249 } 6250 6251 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6252 getCurSDLoc(), MVT::Other, Ops), 6253 0); 6254 DAG.setRoot(N); 6255 setValue(&I, N); 6256 HasTailCall = true; 6257 return nullptr; 6258 } 6259 6260 case Intrinsic::wasm_landingpad_index: { 6261 // TODO store landing pad index in a map, which will be used when generating 6262 // LSDA information 6263 return nullptr; 6264 } 6265 } 6266 } 6267 6268 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6269 const ConstrainedFPIntrinsic &FPI) { 6270 SDLoc sdl = getCurSDLoc(); 6271 unsigned Opcode; 6272 switch (FPI.getIntrinsicID()) { 6273 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6274 case Intrinsic::experimental_constrained_fadd: 6275 Opcode = ISD::STRICT_FADD; 6276 break; 6277 case Intrinsic::experimental_constrained_fsub: 6278 Opcode = ISD::STRICT_FSUB; 6279 break; 6280 case Intrinsic::experimental_constrained_fmul: 6281 Opcode = ISD::STRICT_FMUL; 6282 break; 6283 case Intrinsic::experimental_constrained_fdiv: 6284 Opcode = ISD::STRICT_FDIV; 6285 break; 6286 case Intrinsic::experimental_constrained_frem: 6287 Opcode = ISD::STRICT_FREM; 6288 break; 6289 case Intrinsic::experimental_constrained_fma: 6290 Opcode = ISD::STRICT_FMA; 6291 break; 6292 case Intrinsic::experimental_constrained_sqrt: 6293 Opcode = ISD::STRICT_FSQRT; 6294 break; 6295 case Intrinsic::experimental_constrained_pow: 6296 Opcode = ISD::STRICT_FPOW; 6297 break; 6298 case Intrinsic::experimental_constrained_powi: 6299 Opcode = ISD::STRICT_FPOWI; 6300 break; 6301 case Intrinsic::experimental_constrained_sin: 6302 Opcode = ISD::STRICT_FSIN; 6303 break; 6304 case Intrinsic::experimental_constrained_cos: 6305 Opcode = ISD::STRICT_FCOS; 6306 break; 6307 case Intrinsic::experimental_constrained_exp: 6308 Opcode = ISD::STRICT_FEXP; 6309 break; 6310 case Intrinsic::experimental_constrained_exp2: 6311 Opcode = ISD::STRICT_FEXP2; 6312 break; 6313 case Intrinsic::experimental_constrained_log: 6314 Opcode = ISD::STRICT_FLOG; 6315 break; 6316 case Intrinsic::experimental_constrained_log10: 6317 Opcode = ISD::STRICT_FLOG10; 6318 break; 6319 case Intrinsic::experimental_constrained_log2: 6320 Opcode = ISD::STRICT_FLOG2; 6321 break; 6322 case Intrinsic::experimental_constrained_rint: 6323 Opcode = ISD::STRICT_FRINT; 6324 break; 6325 case Intrinsic::experimental_constrained_nearbyint: 6326 Opcode = ISD::STRICT_FNEARBYINT; 6327 break; 6328 } 6329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6330 SDValue Chain = getRoot(); 6331 SmallVector<EVT, 4> ValueVTs; 6332 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6333 ValueVTs.push_back(MVT::Other); // Out chain 6334 6335 SDVTList VTs = DAG.getVTList(ValueVTs); 6336 SDValue Result; 6337 if (FPI.isUnaryOp()) 6338 Result = DAG.getNode(Opcode, sdl, VTs, 6339 { Chain, getValue(FPI.getArgOperand(0)) }); 6340 else if (FPI.isTernaryOp()) 6341 Result = DAG.getNode(Opcode, sdl, VTs, 6342 { Chain, getValue(FPI.getArgOperand(0)), 6343 getValue(FPI.getArgOperand(1)), 6344 getValue(FPI.getArgOperand(2)) }); 6345 else 6346 Result = DAG.getNode(Opcode, sdl, VTs, 6347 { Chain, getValue(FPI.getArgOperand(0)), 6348 getValue(FPI.getArgOperand(1)) }); 6349 6350 assert(Result.getNode()->getNumValues() == 2); 6351 SDValue OutChain = Result.getValue(1); 6352 DAG.setRoot(OutChain); 6353 SDValue FPResult = Result.getValue(0); 6354 setValue(&FPI, FPResult); 6355 } 6356 6357 std::pair<SDValue, SDValue> 6358 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6359 const BasicBlock *EHPadBB) { 6360 MachineFunction &MF = DAG.getMachineFunction(); 6361 MachineModuleInfo &MMI = MF.getMMI(); 6362 MCSymbol *BeginLabel = nullptr; 6363 6364 if (EHPadBB) { 6365 // Insert a label before the invoke call to mark the try range. This can be 6366 // used to detect deletion of the invoke via the MachineModuleInfo. 6367 BeginLabel = MMI.getContext().createTempSymbol(); 6368 6369 // For SjLj, keep track of which landing pads go with which invokes 6370 // so as to maintain the ordering of pads in the LSDA. 6371 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6372 if (CallSiteIndex) { 6373 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6374 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6375 6376 // Now that the call site is handled, stop tracking it. 6377 MMI.setCurrentCallSite(0); 6378 } 6379 6380 // Both PendingLoads and PendingExports must be flushed here; 6381 // this call might not return. 6382 (void)getRoot(); 6383 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6384 6385 CLI.setChain(getRoot()); 6386 } 6387 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6388 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6389 6390 assert((CLI.IsTailCall || Result.second.getNode()) && 6391 "Non-null chain expected with non-tail call!"); 6392 assert((Result.second.getNode() || !Result.first.getNode()) && 6393 "Null value expected with tail call!"); 6394 6395 if (!Result.second.getNode()) { 6396 // As a special case, a null chain means that a tail call has been emitted 6397 // and the DAG root is already updated. 6398 HasTailCall = true; 6399 6400 // Since there's no actual continuation from this block, nothing can be 6401 // relying on us setting vregs for them. 6402 PendingExports.clear(); 6403 } else { 6404 DAG.setRoot(Result.second); 6405 } 6406 6407 if (EHPadBB) { 6408 // Insert a label at the end of the invoke call to mark the try range. This 6409 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6410 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6411 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6412 6413 // Inform MachineModuleInfo of range. 6414 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6415 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6416 // actually use outlined funclets and their LSDA info style. 6417 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6418 assert(CLI.CS); 6419 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6420 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6421 BeginLabel, EndLabel); 6422 } else { 6423 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6424 } 6425 } 6426 6427 return Result; 6428 } 6429 6430 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6431 bool isTailCall, 6432 const BasicBlock *EHPadBB) { 6433 auto &DL = DAG.getDataLayout(); 6434 FunctionType *FTy = CS.getFunctionType(); 6435 Type *RetTy = CS.getType(); 6436 6437 TargetLowering::ArgListTy Args; 6438 Args.reserve(CS.arg_size()); 6439 6440 const Value *SwiftErrorVal = nullptr; 6441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6442 6443 // We can't tail call inside a function with a swifterror argument. Lowering 6444 // does not support this yet. It would have to move into the swifterror 6445 // register before the call. 6446 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6447 if (TLI.supportSwiftError() && 6448 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6449 isTailCall = false; 6450 6451 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6452 i != e; ++i) { 6453 TargetLowering::ArgListEntry Entry; 6454 const Value *V = *i; 6455 6456 // Skip empty types 6457 if (V->getType()->isEmptyTy()) 6458 continue; 6459 6460 SDValue ArgNode = getValue(V); 6461 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6462 6463 Entry.setAttributes(&CS, i - CS.arg_begin()); 6464 6465 // Use swifterror virtual register as input to the call. 6466 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6467 SwiftErrorVal = V; 6468 // We find the virtual register for the actual swifterror argument. 6469 // Instead of using the Value, we use the virtual register instead. 6470 Entry.Node = DAG.getRegister(FuncInfo 6471 .getOrCreateSwiftErrorVRegUseAt( 6472 CS.getInstruction(), FuncInfo.MBB, V) 6473 .first, 6474 EVT(TLI.getPointerTy(DL))); 6475 } 6476 6477 Args.push_back(Entry); 6478 6479 // If we have an explicit sret argument that is an Instruction, (i.e., it 6480 // might point to function-local memory), we can't meaningfully tail-call. 6481 if (Entry.IsSRet && isa<Instruction>(V)) 6482 isTailCall = false; 6483 } 6484 6485 // Check if target-independent constraints permit a tail call here. 6486 // Target-dependent constraints are checked within TLI->LowerCallTo. 6487 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6488 isTailCall = false; 6489 6490 // Disable tail calls if there is an swifterror argument. Targets have not 6491 // been updated to support tail calls. 6492 if (TLI.supportSwiftError() && SwiftErrorVal) 6493 isTailCall = false; 6494 6495 TargetLowering::CallLoweringInfo CLI(DAG); 6496 CLI.setDebugLoc(getCurSDLoc()) 6497 .setChain(getRoot()) 6498 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6499 .setTailCall(isTailCall) 6500 .setConvergent(CS.isConvergent()); 6501 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6502 6503 if (Result.first.getNode()) { 6504 const Instruction *Inst = CS.getInstruction(); 6505 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6506 setValue(Inst, Result.first); 6507 } 6508 6509 // The last element of CLI.InVals has the SDValue for swifterror return. 6510 // Here we copy it to a virtual register and update SwiftErrorMap for 6511 // book-keeping. 6512 if (SwiftErrorVal && TLI.supportSwiftError()) { 6513 // Get the last element of InVals. 6514 SDValue Src = CLI.InVals.back(); 6515 unsigned VReg; bool CreatedVReg; 6516 std::tie(VReg, CreatedVReg) = 6517 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6518 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6519 // We update the virtual register for the actual swifterror argument. 6520 if (CreatedVReg) 6521 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6522 DAG.setRoot(CopyNode); 6523 } 6524 } 6525 6526 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6527 SelectionDAGBuilder &Builder) { 6528 // Check to see if this load can be trivially constant folded, e.g. if the 6529 // input is from a string literal. 6530 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6531 // Cast pointer to the type we really want to load. 6532 Type *LoadTy = 6533 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6534 if (LoadVT.isVector()) 6535 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6536 6537 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6538 PointerType::getUnqual(LoadTy)); 6539 6540 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6541 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6542 return Builder.getValue(LoadCst); 6543 } 6544 6545 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6546 // still constant memory, the input chain can be the entry node. 6547 SDValue Root; 6548 bool ConstantMemory = false; 6549 6550 // Do not serialize (non-volatile) loads of constant memory with anything. 6551 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6552 Root = Builder.DAG.getEntryNode(); 6553 ConstantMemory = true; 6554 } else { 6555 // Do not serialize non-volatile loads against each other. 6556 Root = Builder.DAG.getRoot(); 6557 } 6558 6559 SDValue Ptr = Builder.getValue(PtrVal); 6560 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6561 Ptr, MachinePointerInfo(PtrVal), 6562 /* Alignment = */ 1); 6563 6564 if (!ConstantMemory) 6565 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6566 return LoadVal; 6567 } 6568 6569 /// Record the value for an instruction that produces an integer result, 6570 /// converting the type where necessary. 6571 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6572 SDValue Value, 6573 bool IsSigned) { 6574 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6575 I.getType(), true); 6576 if (IsSigned) 6577 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6578 else 6579 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6580 setValue(&I, Value); 6581 } 6582 6583 /// See if we can lower a memcmp call into an optimized form. If so, return 6584 /// true and lower it. Otherwise return false, and it will be lowered like a 6585 /// normal call. 6586 /// The caller already checked that \p I calls the appropriate LibFunc with a 6587 /// correct prototype. 6588 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6589 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6590 const Value *Size = I.getArgOperand(2); 6591 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6592 if (CSize && CSize->getZExtValue() == 0) { 6593 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6594 I.getType(), true); 6595 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6596 return true; 6597 } 6598 6599 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6600 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6601 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6602 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6603 if (Res.first.getNode()) { 6604 processIntegerCallValue(I, Res.first, true); 6605 PendingLoads.push_back(Res.second); 6606 return true; 6607 } 6608 6609 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6610 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6611 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6612 return false; 6613 6614 // If the target has a fast compare for the given size, it will return a 6615 // preferred load type for that size. Require that the load VT is legal and 6616 // that the target supports unaligned loads of that type. Otherwise, return 6617 // INVALID. 6618 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6620 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6621 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6622 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6623 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6624 // TODO: Check alignment of src and dest ptrs. 6625 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6626 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6627 if (!TLI.isTypeLegal(LVT) || 6628 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6629 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6630 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6631 } 6632 6633 return LVT; 6634 }; 6635 6636 // This turns into unaligned loads. We only do this if the target natively 6637 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6638 // we'll only produce a small number of byte loads. 6639 MVT LoadVT; 6640 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6641 switch (NumBitsToCompare) { 6642 default: 6643 return false; 6644 case 16: 6645 LoadVT = MVT::i16; 6646 break; 6647 case 32: 6648 LoadVT = MVT::i32; 6649 break; 6650 case 64: 6651 case 128: 6652 case 256: 6653 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6654 break; 6655 } 6656 6657 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6658 return false; 6659 6660 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6661 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6662 6663 // Bitcast to a wide integer type if the loads are vectors. 6664 if (LoadVT.isVector()) { 6665 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6666 LoadL = DAG.getBitcast(CmpVT, LoadL); 6667 LoadR = DAG.getBitcast(CmpVT, LoadR); 6668 } 6669 6670 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6671 processIntegerCallValue(I, Cmp, false); 6672 return true; 6673 } 6674 6675 /// See if we can lower a memchr call into an optimized form. If so, return 6676 /// true and lower it. Otherwise return false, and it will be lowered like a 6677 /// normal call. 6678 /// The caller already checked that \p I calls the appropriate LibFunc with a 6679 /// correct prototype. 6680 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6681 const Value *Src = I.getArgOperand(0); 6682 const Value *Char = I.getArgOperand(1); 6683 const Value *Length = I.getArgOperand(2); 6684 6685 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6686 std::pair<SDValue, SDValue> Res = 6687 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6688 getValue(Src), getValue(Char), getValue(Length), 6689 MachinePointerInfo(Src)); 6690 if (Res.first.getNode()) { 6691 setValue(&I, Res.first); 6692 PendingLoads.push_back(Res.second); 6693 return true; 6694 } 6695 6696 return false; 6697 } 6698 6699 /// See if we can lower a mempcpy call into an optimized form. If so, return 6700 /// true and lower it. Otherwise return false, and it will be lowered like a 6701 /// normal call. 6702 /// The caller already checked that \p I calls the appropriate LibFunc with a 6703 /// correct prototype. 6704 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6705 SDValue Dst = getValue(I.getArgOperand(0)); 6706 SDValue Src = getValue(I.getArgOperand(1)); 6707 SDValue Size = getValue(I.getArgOperand(2)); 6708 6709 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6710 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6711 unsigned Align = std::min(DstAlign, SrcAlign); 6712 if (Align == 0) // Alignment of one or both could not be inferred. 6713 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6714 6715 bool isVol = false; 6716 SDLoc sdl = getCurSDLoc(); 6717 6718 // In the mempcpy context we need to pass in a false value for isTailCall 6719 // because the return pointer needs to be adjusted by the size of 6720 // the copied memory. 6721 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6722 false, /*isTailCall=*/false, 6723 MachinePointerInfo(I.getArgOperand(0)), 6724 MachinePointerInfo(I.getArgOperand(1))); 6725 assert(MC.getNode() != nullptr && 6726 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6727 DAG.setRoot(MC); 6728 6729 // Check if Size needs to be truncated or extended. 6730 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6731 6732 // Adjust return pointer to point just past the last dst byte. 6733 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6734 Dst, Size); 6735 setValue(&I, DstPlusSize); 6736 return true; 6737 } 6738 6739 /// See if we can lower a strcpy call into an optimized form. If so, return 6740 /// true and lower it, otherwise return false and it will be lowered like a 6741 /// normal call. 6742 /// The caller already checked that \p I calls the appropriate LibFunc with a 6743 /// correct prototype. 6744 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6745 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6746 6747 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6748 std::pair<SDValue, SDValue> Res = 6749 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6750 getValue(Arg0), getValue(Arg1), 6751 MachinePointerInfo(Arg0), 6752 MachinePointerInfo(Arg1), isStpcpy); 6753 if (Res.first.getNode()) { 6754 setValue(&I, Res.first); 6755 DAG.setRoot(Res.second); 6756 return true; 6757 } 6758 6759 return false; 6760 } 6761 6762 /// See if we can lower a strcmp call into an optimized form. If so, return 6763 /// true and lower it, otherwise return false and it will be lowered like a 6764 /// normal call. 6765 /// The caller already checked that \p I calls the appropriate LibFunc with a 6766 /// correct prototype. 6767 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6768 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6769 6770 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6771 std::pair<SDValue, SDValue> Res = 6772 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6773 getValue(Arg0), getValue(Arg1), 6774 MachinePointerInfo(Arg0), 6775 MachinePointerInfo(Arg1)); 6776 if (Res.first.getNode()) { 6777 processIntegerCallValue(I, Res.first, true); 6778 PendingLoads.push_back(Res.second); 6779 return true; 6780 } 6781 6782 return false; 6783 } 6784 6785 /// See if we can lower a strlen call into an optimized form. If so, return 6786 /// true and lower it, otherwise return false and it will be lowered like a 6787 /// normal call. 6788 /// The caller already checked that \p I calls the appropriate LibFunc with a 6789 /// correct prototype. 6790 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6791 const Value *Arg0 = I.getArgOperand(0); 6792 6793 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6794 std::pair<SDValue, SDValue> Res = 6795 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6796 getValue(Arg0), MachinePointerInfo(Arg0)); 6797 if (Res.first.getNode()) { 6798 processIntegerCallValue(I, Res.first, false); 6799 PendingLoads.push_back(Res.second); 6800 return true; 6801 } 6802 6803 return false; 6804 } 6805 6806 /// See if we can lower a strnlen call into an optimized form. If so, return 6807 /// true and lower it, otherwise return false and it will be lowered like a 6808 /// normal call. 6809 /// The caller already checked that \p I calls the appropriate LibFunc with a 6810 /// correct prototype. 6811 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6812 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6813 6814 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6815 std::pair<SDValue, SDValue> Res = 6816 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6817 getValue(Arg0), getValue(Arg1), 6818 MachinePointerInfo(Arg0)); 6819 if (Res.first.getNode()) { 6820 processIntegerCallValue(I, Res.first, false); 6821 PendingLoads.push_back(Res.second); 6822 return true; 6823 } 6824 6825 return false; 6826 } 6827 6828 /// See if we can lower a unary floating-point operation into an SDNode with 6829 /// the specified Opcode. If so, return true and lower it, otherwise return 6830 /// false and it will be lowered like a normal call. 6831 /// The caller already checked that \p I calls the appropriate LibFunc with a 6832 /// correct prototype. 6833 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6834 unsigned Opcode) { 6835 // We already checked this call's prototype; verify it doesn't modify errno. 6836 if (!I.onlyReadsMemory()) 6837 return false; 6838 6839 SDValue Tmp = getValue(I.getArgOperand(0)); 6840 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6841 return true; 6842 } 6843 6844 /// See if we can lower a binary floating-point operation into an SDNode with 6845 /// the specified Opcode. If so, return true and lower it. Otherwise return 6846 /// false, and it will be lowered like a normal call. 6847 /// The caller already checked that \p I calls the appropriate LibFunc with a 6848 /// correct prototype. 6849 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6850 unsigned Opcode) { 6851 // We already checked this call's prototype; verify it doesn't modify errno. 6852 if (!I.onlyReadsMemory()) 6853 return false; 6854 6855 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6856 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6857 EVT VT = Tmp0.getValueType(); 6858 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6859 return true; 6860 } 6861 6862 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6863 // Handle inline assembly differently. 6864 if (isa<InlineAsm>(I.getCalledValue())) { 6865 visitInlineAsm(&I); 6866 return; 6867 } 6868 6869 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6870 computeUsesVAFloatArgument(I, MMI); 6871 6872 const char *RenameFn = nullptr; 6873 if (Function *F = I.getCalledFunction()) { 6874 if (F->isDeclaration()) { 6875 // Is this an LLVM intrinsic or a target-specific intrinsic? 6876 unsigned IID = F->getIntrinsicID(); 6877 if (!IID) 6878 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6879 IID = II->getIntrinsicID(F); 6880 6881 if (IID) { 6882 RenameFn = visitIntrinsicCall(I, IID); 6883 if (!RenameFn) 6884 return; 6885 } 6886 } 6887 6888 // Check for well-known libc/libm calls. If the function is internal, it 6889 // can't be a library call. Don't do the check if marked as nobuiltin for 6890 // some reason or the call site requires strict floating point semantics. 6891 LibFunc Func; 6892 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6893 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6894 LibInfo->hasOptimizedCodeGen(Func)) { 6895 switch (Func) { 6896 default: break; 6897 case LibFunc_copysign: 6898 case LibFunc_copysignf: 6899 case LibFunc_copysignl: 6900 // We already checked this call's prototype; verify it doesn't modify 6901 // errno. 6902 if (I.onlyReadsMemory()) { 6903 SDValue LHS = getValue(I.getArgOperand(0)); 6904 SDValue RHS = getValue(I.getArgOperand(1)); 6905 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6906 LHS.getValueType(), LHS, RHS)); 6907 return; 6908 } 6909 break; 6910 case LibFunc_fabs: 6911 case LibFunc_fabsf: 6912 case LibFunc_fabsl: 6913 if (visitUnaryFloatCall(I, ISD::FABS)) 6914 return; 6915 break; 6916 case LibFunc_fmin: 6917 case LibFunc_fminf: 6918 case LibFunc_fminl: 6919 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6920 return; 6921 break; 6922 case LibFunc_fmax: 6923 case LibFunc_fmaxf: 6924 case LibFunc_fmaxl: 6925 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6926 return; 6927 break; 6928 case LibFunc_sin: 6929 case LibFunc_sinf: 6930 case LibFunc_sinl: 6931 if (visitUnaryFloatCall(I, ISD::FSIN)) 6932 return; 6933 break; 6934 case LibFunc_cos: 6935 case LibFunc_cosf: 6936 case LibFunc_cosl: 6937 if (visitUnaryFloatCall(I, ISD::FCOS)) 6938 return; 6939 break; 6940 case LibFunc_sqrt: 6941 case LibFunc_sqrtf: 6942 case LibFunc_sqrtl: 6943 case LibFunc_sqrt_finite: 6944 case LibFunc_sqrtf_finite: 6945 case LibFunc_sqrtl_finite: 6946 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6947 return; 6948 break; 6949 case LibFunc_floor: 6950 case LibFunc_floorf: 6951 case LibFunc_floorl: 6952 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6953 return; 6954 break; 6955 case LibFunc_nearbyint: 6956 case LibFunc_nearbyintf: 6957 case LibFunc_nearbyintl: 6958 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6959 return; 6960 break; 6961 case LibFunc_ceil: 6962 case LibFunc_ceilf: 6963 case LibFunc_ceill: 6964 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6965 return; 6966 break; 6967 case LibFunc_rint: 6968 case LibFunc_rintf: 6969 case LibFunc_rintl: 6970 if (visitUnaryFloatCall(I, ISD::FRINT)) 6971 return; 6972 break; 6973 case LibFunc_round: 6974 case LibFunc_roundf: 6975 case LibFunc_roundl: 6976 if (visitUnaryFloatCall(I, ISD::FROUND)) 6977 return; 6978 break; 6979 case LibFunc_trunc: 6980 case LibFunc_truncf: 6981 case LibFunc_truncl: 6982 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6983 return; 6984 break; 6985 case LibFunc_log2: 6986 case LibFunc_log2f: 6987 case LibFunc_log2l: 6988 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6989 return; 6990 break; 6991 case LibFunc_exp2: 6992 case LibFunc_exp2f: 6993 case LibFunc_exp2l: 6994 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6995 return; 6996 break; 6997 case LibFunc_memcmp: 6998 if (visitMemCmpCall(I)) 6999 return; 7000 break; 7001 case LibFunc_mempcpy: 7002 if (visitMemPCpyCall(I)) 7003 return; 7004 break; 7005 case LibFunc_memchr: 7006 if (visitMemChrCall(I)) 7007 return; 7008 break; 7009 case LibFunc_strcpy: 7010 if (visitStrCpyCall(I, false)) 7011 return; 7012 break; 7013 case LibFunc_stpcpy: 7014 if (visitStrCpyCall(I, true)) 7015 return; 7016 break; 7017 case LibFunc_strcmp: 7018 if (visitStrCmpCall(I)) 7019 return; 7020 break; 7021 case LibFunc_strlen: 7022 if (visitStrLenCall(I)) 7023 return; 7024 break; 7025 case LibFunc_strnlen: 7026 if (visitStrNLenCall(I)) 7027 return; 7028 break; 7029 } 7030 } 7031 } 7032 7033 SDValue Callee; 7034 if (!RenameFn) 7035 Callee = getValue(I.getCalledValue()); 7036 else 7037 Callee = DAG.getExternalSymbol( 7038 RenameFn, 7039 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7040 7041 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7042 // have to do anything here to lower funclet bundles. 7043 assert(!I.hasOperandBundlesOtherThan( 7044 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7045 "Cannot lower calls with arbitrary operand bundles!"); 7046 7047 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7048 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7049 else 7050 // Check if we can potentially perform a tail call. More detailed checking 7051 // is be done within LowerCallTo, after more information about the call is 7052 // known. 7053 LowerCallTo(&I, Callee, I.isTailCall()); 7054 } 7055 7056 namespace { 7057 7058 /// AsmOperandInfo - This contains information for each constraint that we are 7059 /// lowering. 7060 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7061 public: 7062 /// CallOperand - If this is the result output operand or a clobber 7063 /// this is null, otherwise it is the incoming operand to the CallInst. 7064 /// This gets modified as the asm is processed. 7065 SDValue CallOperand; 7066 7067 /// AssignedRegs - If this is a register or register class operand, this 7068 /// contains the set of register corresponding to the operand. 7069 RegsForValue AssignedRegs; 7070 7071 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7072 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7073 } 7074 7075 /// Whether or not this operand accesses memory 7076 bool hasMemory(const TargetLowering &TLI) const { 7077 // Indirect operand accesses access memory. 7078 if (isIndirect) 7079 return true; 7080 7081 for (const auto &Code : Codes) 7082 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7083 return true; 7084 7085 return false; 7086 } 7087 7088 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7089 /// corresponds to. If there is no Value* for this operand, it returns 7090 /// MVT::Other. 7091 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7092 const DataLayout &DL) const { 7093 if (!CallOperandVal) return MVT::Other; 7094 7095 if (isa<BasicBlock>(CallOperandVal)) 7096 return TLI.getPointerTy(DL); 7097 7098 llvm::Type *OpTy = CallOperandVal->getType(); 7099 7100 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7101 // If this is an indirect operand, the operand is a pointer to the 7102 // accessed type. 7103 if (isIndirect) { 7104 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7105 if (!PtrTy) 7106 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7107 OpTy = PtrTy->getElementType(); 7108 } 7109 7110 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7111 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7112 if (STy->getNumElements() == 1) 7113 OpTy = STy->getElementType(0); 7114 7115 // If OpTy is not a single value, it may be a struct/union that we 7116 // can tile with integers. 7117 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7118 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7119 switch (BitSize) { 7120 default: break; 7121 case 1: 7122 case 8: 7123 case 16: 7124 case 32: 7125 case 64: 7126 case 128: 7127 OpTy = IntegerType::get(Context, BitSize); 7128 break; 7129 } 7130 } 7131 7132 return TLI.getValueType(DL, OpTy, true); 7133 } 7134 }; 7135 7136 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7137 7138 } // end anonymous namespace 7139 7140 /// Make sure that the output operand \p OpInfo and its corresponding input 7141 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7142 /// out). 7143 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7144 SDISelAsmOperandInfo &MatchingOpInfo, 7145 SelectionDAG &DAG) { 7146 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7147 return; 7148 7149 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7150 const auto &TLI = DAG.getTargetLoweringInfo(); 7151 7152 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7153 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7154 OpInfo.ConstraintVT); 7155 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7156 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7157 MatchingOpInfo.ConstraintVT); 7158 if ((OpInfo.ConstraintVT.isInteger() != 7159 MatchingOpInfo.ConstraintVT.isInteger()) || 7160 (MatchRC.second != InputRC.second)) { 7161 // FIXME: error out in a more elegant fashion 7162 report_fatal_error("Unsupported asm: input constraint" 7163 " with a matching output constraint of" 7164 " incompatible type!"); 7165 } 7166 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7167 } 7168 7169 /// Get a direct memory input to behave well as an indirect operand. 7170 /// This may introduce stores, hence the need for a \p Chain. 7171 /// \return The (possibly updated) chain. 7172 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7173 SDISelAsmOperandInfo &OpInfo, 7174 SelectionDAG &DAG) { 7175 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7176 7177 // If we don't have an indirect input, put it in the constpool if we can, 7178 // otherwise spill it to a stack slot. 7179 // TODO: This isn't quite right. We need to handle these according to 7180 // the addressing mode that the constraint wants. Also, this may take 7181 // an additional register for the computation and we don't want that 7182 // either. 7183 7184 // If the operand is a float, integer, or vector constant, spill to a 7185 // constant pool entry to get its address. 7186 const Value *OpVal = OpInfo.CallOperandVal; 7187 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7188 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7189 OpInfo.CallOperand = DAG.getConstantPool( 7190 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7191 return Chain; 7192 } 7193 7194 // Otherwise, create a stack slot and emit a store to it before the asm. 7195 Type *Ty = OpVal->getType(); 7196 auto &DL = DAG.getDataLayout(); 7197 uint64_t TySize = DL.getTypeAllocSize(Ty); 7198 unsigned Align = DL.getPrefTypeAlignment(Ty); 7199 MachineFunction &MF = DAG.getMachineFunction(); 7200 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7201 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7202 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7203 MachinePointerInfo::getFixedStack(MF, SSFI)); 7204 OpInfo.CallOperand = StackSlot; 7205 7206 return Chain; 7207 } 7208 7209 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7210 /// specified operand. We prefer to assign virtual registers, to allow the 7211 /// register allocator to handle the assignment process. However, if the asm 7212 /// uses features that we can't model on machineinstrs, we have SDISel do the 7213 /// allocation. This produces generally horrible, but correct, code. 7214 /// 7215 /// OpInfo describes the operand 7216 /// RefOpInfo describes the matching operand if any, the operand otherwise 7217 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7218 const SDLoc &DL, SDISelAsmOperandInfo &OpInfo, 7219 SDISelAsmOperandInfo &RefOpInfo) { 7220 LLVMContext &Context = *DAG.getContext(); 7221 7222 MachineFunction &MF = DAG.getMachineFunction(); 7223 SmallVector<unsigned, 4> Regs; 7224 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7225 7226 // If this is a constraint for a single physreg, or a constraint for a 7227 // register class, find it. 7228 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7229 TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode, 7230 RefOpInfo.ConstraintVT); 7231 7232 unsigned NumRegs = 1; 7233 if (OpInfo.ConstraintVT != MVT::Other) { 7234 // If this is an FP operand in an integer register (or visa versa), or more 7235 // generally if the operand value disagrees with the register class we plan 7236 // to stick it in, fix the operand type. 7237 // 7238 // If this is an input value, the bitcast to the new type is done now. 7239 // Bitcast for output value is done at the end of visitInlineAsm(). 7240 if ((OpInfo.Type == InlineAsm::isOutput || 7241 OpInfo.Type == InlineAsm::isInput) && 7242 PhysReg.second && 7243 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7244 // Try to convert to the first EVT that the reg class contains. If the 7245 // types are identical size, use a bitcast to convert (e.g. two differing 7246 // vector types). Note: output bitcast is done at the end of 7247 // visitInlineAsm(). 7248 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7249 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7250 // Exclude indirect inputs while they are unsupported because the code 7251 // to perform the load is missing and thus OpInfo.CallOperand still 7252 // refers to the input address rather than the pointed-to value. 7253 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7254 OpInfo.CallOperand = 7255 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7256 OpInfo.ConstraintVT = RegVT; 7257 // If the operand is an FP value and we want it in integer registers, 7258 // use the corresponding integer type. This turns an f64 value into 7259 // i64, which can be passed with two i32 values on a 32-bit machine. 7260 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7261 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7262 if (OpInfo.Type == InlineAsm::isInput) 7263 OpInfo.CallOperand = 7264 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7265 OpInfo.ConstraintVT = RegVT; 7266 } 7267 } 7268 7269 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7270 } 7271 7272 // No need to allocate a matching input constraint since the constraint it's 7273 // matching to has already been allocated. 7274 if (OpInfo.isMatchingInputConstraint()) 7275 return; 7276 7277 MVT RegVT; 7278 EVT ValueVT = OpInfo.ConstraintVT; 7279 7280 // If this is a constraint for a specific physical register, like {r17}, 7281 // assign it now. 7282 if (unsigned AssignedReg = PhysReg.first) { 7283 const TargetRegisterClass *RC = PhysReg.second; 7284 if (OpInfo.ConstraintVT == MVT::Other) 7285 ValueVT = *TRI.legalclasstypes_begin(*RC); 7286 7287 // Get the actual register value type. This is important, because the user 7288 // may have asked for (e.g.) the AX register in i32 type. We need to 7289 // remember that AX is actually i16 to get the right extension. 7290 RegVT = *TRI.legalclasstypes_begin(*RC); 7291 7292 // This is an explicit reference to a physical register. 7293 Regs.push_back(AssignedReg); 7294 7295 // If this is an expanded reference, add the rest of the regs to Regs. 7296 if (NumRegs != 1) { 7297 TargetRegisterClass::iterator I = RC->begin(); 7298 for (; *I != AssignedReg; ++I) 7299 assert(I != RC->end() && "Didn't find reg!"); 7300 7301 // Already added the first reg. 7302 --NumRegs; ++I; 7303 for (; NumRegs; --NumRegs, ++I) { 7304 assert(I != RC->end() && "Ran out of registers to allocate!"); 7305 Regs.push_back(*I); 7306 } 7307 } 7308 7309 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7310 return; 7311 } 7312 7313 // Otherwise, if this was a reference to an LLVM register class, create vregs 7314 // for this reference. 7315 if (const TargetRegisterClass *RC = PhysReg.second) { 7316 RegVT = *TRI.legalclasstypes_begin(*RC); 7317 if (OpInfo.ConstraintVT == MVT::Other) 7318 ValueVT = RegVT; 7319 7320 // Create the appropriate number of virtual registers. 7321 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7322 for (; NumRegs; --NumRegs) 7323 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7324 7325 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7326 return; 7327 } 7328 7329 // Otherwise, we couldn't allocate enough registers for this. 7330 } 7331 7332 static unsigned 7333 findMatchingInlineAsmOperand(unsigned OperandNo, 7334 const std::vector<SDValue> &AsmNodeOperands) { 7335 // Scan until we find the definition we already emitted of this operand. 7336 unsigned CurOp = InlineAsm::Op_FirstOperand; 7337 for (; OperandNo; --OperandNo) { 7338 // Advance to the next operand. 7339 unsigned OpFlag = 7340 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7341 assert((InlineAsm::isRegDefKind(OpFlag) || 7342 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7343 InlineAsm::isMemKind(OpFlag)) && 7344 "Skipped past definitions?"); 7345 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7346 } 7347 return CurOp; 7348 } 7349 7350 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7351 /// \return true if it has succeeded, false otherwise 7352 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7353 MVT RegVT, SelectionDAG &DAG) { 7354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7355 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7356 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7357 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7358 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7359 else 7360 return false; 7361 } 7362 return true; 7363 } 7364 7365 namespace { 7366 7367 class ExtraFlags { 7368 unsigned Flags = 0; 7369 7370 public: 7371 explicit ExtraFlags(ImmutableCallSite CS) { 7372 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7373 if (IA->hasSideEffects()) 7374 Flags |= InlineAsm::Extra_HasSideEffects; 7375 if (IA->isAlignStack()) 7376 Flags |= InlineAsm::Extra_IsAlignStack; 7377 if (CS.isConvergent()) 7378 Flags |= InlineAsm::Extra_IsConvergent; 7379 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7380 } 7381 7382 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7383 // Ideally, we would only check against memory constraints. However, the 7384 // meaning of an Other constraint can be target-specific and we can't easily 7385 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7386 // for Other constraints as well. 7387 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7388 OpInfo.ConstraintType == TargetLowering::C_Other) { 7389 if (OpInfo.Type == InlineAsm::isInput) 7390 Flags |= InlineAsm::Extra_MayLoad; 7391 else if (OpInfo.Type == InlineAsm::isOutput) 7392 Flags |= InlineAsm::Extra_MayStore; 7393 else if (OpInfo.Type == InlineAsm::isClobber) 7394 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7395 } 7396 } 7397 7398 unsigned get() const { return Flags; } 7399 }; 7400 7401 } // end anonymous namespace 7402 7403 /// visitInlineAsm - Handle a call to an InlineAsm object. 7404 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7405 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7406 7407 /// ConstraintOperands - Information about all of the constraints. 7408 SDISelAsmOperandInfoVector ConstraintOperands; 7409 7410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7411 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7412 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7413 7414 bool hasMemory = false; 7415 7416 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7417 ExtraFlags ExtraInfo(CS); 7418 7419 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7420 unsigned ResNo = 0; // ResNo - The result number of the next output. 7421 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7422 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7423 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7424 7425 MVT OpVT = MVT::Other; 7426 7427 // Compute the value type for each operand. 7428 if (OpInfo.Type == InlineAsm::isInput || 7429 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7430 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7431 7432 // Process the call argument. BasicBlocks are labels, currently appearing 7433 // only in asm's. 7434 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7435 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7436 } else { 7437 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7438 } 7439 7440 OpVT = 7441 OpInfo 7442 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7443 .getSimpleVT(); 7444 } 7445 7446 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7447 // The return value of the call is this value. As such, there is no 7448 // corresponding argument. 7449 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7450 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7451 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7452 STy->getElementType(ResNo)); 7453 } else { 7454 assert(ResNo == 0 && "Asm only has one result!"); 7455 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7456 } 7457 ++ResNo; 7458 } 7459 7460 OpInfo.ConstraintVT = OpVT; 7461 7462 if (!hasMemory) 7463 hasMemory = OpInfo.hasMemory(TLI); 7464 7465 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7466 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7467 auto TargetConstraint = TargetConstraints[i]; 7468 7469 // Compute the constraint code and ConstraintType to use. 7470 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7471 7472 ExtraInfo.update(TargetConstraint); 7473 } 7474 7475 SDValue Chain, Flag; 7476 7477 // We won't need to flush pending loads if this asm doesn't touch 7478 // memory and is nonvolatile. 7479 if (hasMemory || IA->hasSideEffects()) 7480 Chain = getRoot(); 7481 else 7482 Chain = DAG.getRoot(); 7483 7484 // Second pass over the constraints: compute which constraint option to use 7485 // and assign registers to constraints that want a specific physreg. 7486 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7487 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7488 7489 // If this is an output operand with a matching input operand, look up the 7490 // matching input. If their types mismatch, e.g. one is an integer, the 7491 // other is floating point, or their sizes are different, flag it as an 7492 // error. 7493 if (OpInfo.hasMatchingInput()) { 7494 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7495 patchMatchingInput(OpInfo, Input, DAG); 7496 } 7497 7498 // Compute the constraint code and ConstraintType to use. 7499 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7500 7501 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7502 OpInfo.Type == InlineAsm::isClobber) 7503 continue; 7504 7505 // If this is a memory input, and if the operand is not indirect, do what we 7506 // need to provide an address for the memory input. 7507 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7508 !OpInfo.isIndirect) { 7509 assert((OpInfo.isMultipleAlternative || 7510 (OpInfo.Type == InlineAsm::isInput)) && 7511 "Can only indirectify direct input operands!"); 7512 7513 // Memory operands really want the address of the value. 7514 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7515 7516 // There is no longer a Value* corresponding to this operand. 7517 OpInfo.CallOperandVal = nullptr; 7518 7519 // It is now an indirect operand. 7520 OpInfo.isIndirect = true; 7521 } 7522 7523 // If this constraint is for a specific register, allocate it before 7524 // anything else. 7525 SDISelAsmOperandInfo &RefOpInfo = 7526 OpInfo.isMatchingInputConstraint() 7527 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7528 : ConstraintOperands[i]; 7529 if (RefOpInfo.ConstraintType == TargetLowering::C_Register) 7530 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7531 } 7532 7533 // Third pass - Loop over all of the operands, assigning virtual or physregs 7534 // to register class operands. 7535 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7536 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7537 SDISelAsmOperandInfo &RefOpInfo = 7538 OpInfo.isMatchingInputConstraint() 7539 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7540 : ConstraintOperands[i]; 7541 7542 // C_Register operands have already been allocated, Other/Memory don't need 7543 // to be. 7544 if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7545 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7546 } 7547 7548 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7549 std::vector<SDValue> AsmNodeOperands; 7550 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7551 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7552 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7553 7554 // If we have a !srcloc metadata node associated with it, we want to attach 7555 // this to the ultimately generated inline asm machineinstr. To do this, we 7556 // pass in the third operand as this (potentially null) inline asm MDNode. 7557 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7558 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7559 7560 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7561 // bits as operand 3. 7562 AsmNodeOperands.push_back(DAG.getTargetConstant( 7563 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7564 7565 // Loop over all of the inputs, copying the operand values into the 7566 // appropriate registers and processing the output regs. 7567 RegsForValue RetValRegs; 7568 7569 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7570 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7571 7572 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7573 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7574 7575 switch (OpInfo.Type) { 7576 case InlineAsm::isOutput: 7577 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7578 OpInfo.ConstraintType != TargetLowering::C_Register) { 7579 // Memory output, or 'other' output (e.g. 'X' constraint). 7580 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7581 7582 unsigned ConstraintID = 7583 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7584 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7585 "Failed to convert memory constraint code to constraint id."); 7586 7587 // Add information to the INLINEASM node to know about this output. 7588 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7589 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7590 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7591 MVT::i32)); 7592 AsmNodeOperands.push_back(OpInfo.CallOperand); 7593 break; 7594 } 7595 7596 // Otherwise, this is a register or register class output. 7597 7598 // Copy the output from the appropriate register. Find a register that 7599 // we can use. 7600 if (OpInfo.AssignedRegs.Regs.empty()) { 7601 emitInlineAsmError( 7602 CS, "couldn't allocate output register for constraint '" + 7603 Twine(OpInfo.ConstraintCode) + "'"); 7604 return; 7605 } 7606 7607 // If this is an indirect operand, store through the pointer after the 7608 // asm. 7609 if (OpInfo.isIndirect) { 7610 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7611 OpInfo.CallOperandVal)); 7612 } else { 7613 // This is the result value of the call. 7614 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7615 // Concatenate this output onto the outputs list. 7616 RetValRegs.append(OpInfo.AssignedRegs); 7617 } 7618 7619 // Add information to the INLINEASM node to know that this register is 7620 // set. 7621 OpInfo.AssignedRegs 7622 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7623 ? InlineAsm::Kind_RegDefEarlyClobber 7624 : InlineAsm::Kind_RegDef, 7625 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7626 break; 7627 7628 case InlineAsm::isInput: { 7629 SDValue InOperandVal = OpInfo.CallOperand; 7630 7631 if (OpInfo.isMatchingInputConstraint()) { 7632 // If this is required to match an output register we have already set, 7633 // just use its register. 7634 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7635 AsmNodeOperands); 7636 unsigned OpFlag = 7637 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7638 if (InlineAsm::isRegDefKind(OpFlag) || 7639 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7640 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7641 if (OpInfo.isIndirect) { 7642 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7643 emitInlineAsmError(CS, "inline asm not supported yet:" 7644 " don't know how to handle tied " 7645 "indirect register inputs"); 7646 return; 7647 } 7648 7649 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7650 SmallVector<unsigned, 4> Regs; 7651 7652 if (!createVirtualRegs(Regs, 7653 InlineAsm::getNumOperandRegisters(OpFlag), 7654 RegVT, DAG)) { 7655 emitInlineAsmError(CS, "inline asm error: This value type register " 7656 "class is not natively supported!"); 7657 return; 7658 } 7659 7660 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7661 7662 SDLoc dl = getCurSDLoc(); 7663 // Use the produced MatchedRegs object to 7664 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7665 CS.getInstruction()); 7666 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7667 true, OpInfo.getMatchedOperand(), dl, 7668 DAG, AsmNodeOperands); 7669 break; 7670 } 7671 7672 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7673 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7674 "Unexpected number of operands"); 7675 // Add information to the INLINEASM node to know about this input. 7676 // See InlineAsm.h isUseOperandTiedToDef. 7677 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7678 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7679 OpInfo.getMatchedOperand()); 7680 AsmNodeOperands.push_back(DAG.getTargetConstant( 7681 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7682 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7683 break; 7684 } 7685 7686 // Treat indirect 'X' constraint as memory. 7687 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7688 OpInfo.isIndirect) 7689 OpInfo.ConstraintType = TargetLowering::C_Memory; 7690 7691 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7692 std::vector<SDValue> Ops; 7693 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7694 Ops, DAG); 7695 if (Ops.empty()) { 7696 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7697 Twine(OpInfo.ConstraintCode) + "'"); 7698 return; 7699 } 7700 7701 // Add information to the INLINEASM node to know about this input. 7702 unsigned ResOpType = 7703 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7704 AsmNodeOperands.push_back(DAG.getTargetConstant( 7705 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7706 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7707 break; 7708 } 7709 7710 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7711 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7712 assert(InOperandVal.getValueType() == 7713 TLI.getPointerTy(DAG.getDataLayout()) && 7714 "Memory operands expect pointer values"); 7715 7716 unsigned ConstraintID = 7717 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7718 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7719 "Failed to convert memory constraint code to constraint id."); 7720 7721 // Add information to the INLINEASM node to know about this input. 7722 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7723 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7724 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7725 getCurSDLoc(), 7726 MVT::i32)); 7727 AsmNodeOperands.push_back(InOperandVal); 7728 break; 7729 } 7730 7731 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7732 OpInfo.ConstraintType == TargetLowering::C_Register) && 7733 "Unknown constraint type!"); 7734 7735 // TODO: Support this. 7736 if (OpInfo.isIndirect) { 7737 emitInlineAsmError( 7738 CS, "Don't know how to handle indirect register inputs yet " 7739 "for constraint '" + 7740 Twine(OpInfo.ConstraintCode) + "'"); 7741 return; 7742 } 7743 7744 // Copy the input into the appropriate registers. 7745 if (OpInfo.AssignedRegs.Regs.empty()) { 7746 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7747 Twine(OpInfo.ConstraintCode) + "'"); 7748 return; 7749 } 7750 7751 SDLoc dl = getCurSDLoc(); 7752 7753 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7754 Chain, &Flag, CS.getInstruction()); 7755 7756 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7757 dl, DAG, AsmNodeOperands); 7758 break; 7759 } 7760 case InlineAsm::isClobber: 7761 // Add the clobbered value to the operand list, so that the register 7762 // allocator is aware that the physreg got clobbered. 7763 if (!OpInfo.AssignedRegs.Regs.empty()) 7764 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7765 false, 0, getCurSDLoc(), DAG, 7766 AsmNodeOperands); 7767 break; 7768 } 7769 } 7770 7771 // Finish up input operands. Set the input chain and add the flag last. 7772 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7773 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7774 7775 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7776 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7777 Flag = Chain.getValue(1); 7778 7779 // If this asm returns a register value, copy the result from that register 7780 // and set it as the value of the call. 7781 if (!RetValRegs.Regs.empty()) { 7782 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7783 Chain, &Flag, CS.getInstruction()); 7784 7785 llvm::Type *CSResultType = CS.getType(); 7786 unsigned numRet; 7787 ArrayRef<Type *> ResultTypes; 7788 SmallVector<SDValue, 1> ResultValues(1); 7789 if (CSResultType->isSingleValueType()) { 7790 numRet = 1; 7791 ResultValues[0] = Val; 7792 ResultTypes = makeArrayRef(CSResultType); 7793 } else { 7794 numRet = CSResultType->getNumContainedTypes(); 7795 assert(Val->getNumOperands() == numRet && 7796 "Mismatch in number of output operands in asm result"); 7797 ResultTypes = CSResultType->subtypes(); 7798 ArrayRef<SDUse> ValueUses = Val->ops(); 7799 ResultValues.resize(numRet); 7800 std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(), 7801 [](const SDUse &u) -> SDValue { return u.get(); }); 7802 } 7803 SmallVector<EVT, 1> ResultVTs(numRet); 7804 for (unsigned i = 0; i < numRet; i++) { 7805 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]); 7806 SDValue Val = ResultValues[i]; 7807 assert(ResultTypes[i]->isSized() && "Unexpected unsized type"); 7808 // If the type of the inline asm call site return value is different but 7809 // has same size as the type of the asm output bitcast it. One example 7810 // of this is for vectors with different width / number of elements. 7811 // This can happen for register classes that can contain multiple 7812 // different value types. The preg or vreg allocated may not have the 7813 // same VT as was expected. 7814 // 7815 // This can also happen for a return value that disagrees with the 7816 // register class it is put in, eg. a double in a general-purpose 7817 // register on a 32-bit machine. 7818 if (ResultVT != Val.getValueType() && 7819 ResultVT.getSizeInBits() == Val.getValueSizeInBits()) 7820 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val); 7821 else if (ResultVT != Val.getValueType() && ResultVT.isInteger() && 7822 Val.getValueType().isInteger()) { 7823 // If a result value was tied to an input value, the computed result 7824 // may have a wider width than the expected result. Extract the 7825 // relevant portion. 7826 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val); 7827 } 7828 7829 assert(ResultVT == Val.getValueType() && "Asm result value mismatch!"); 7830 ResultVTs[i] = ResultVT; 7831 ResultValues[i] = Val; 7832 } 7833 7834 Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7835 DAG.getVTList(ResultVTs), ResultValues); 7836 setValue(CS.getInstruction(), Val); 7837 // Don't need to use this as a chain in this case. 7838 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7839 return; 7840 } 7841 7842 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7843 7844 // Process indirect outputs, first output all of the flagged copies out of 7845 // physregs. 7846 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7847 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7848 const Value *Ptr = IndirectStoresToEmit[i].second; 7849 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7850 Chain, &Flag, IA); 7851 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7852 } 7853 7854 // Emit the non-flagged stores from the physregs. 7855 SmallVector<SDValue, 8> OutChains; 7856 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7857 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7858 getValue(StoresToEmit[i].second), 7859 MachinePointerInfo(StoresToEmit[i].second)); 7860 OutChains.push_back(Val); 7861 } 7862 7863 if (!OutChains.empty()) 7864 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7865 7866 DAG.setRoot(Chain); 7867 } 7868 7869 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7870 const Twine &Message) { 7871 LLVMContext &Ctx = *DAG.getContext(); 7872 Ctx.emitError(CS.getInstruction(), Message); 7873 7874 // Make sure we leave the DAG in a valid state 7875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7876 SmallVector<EVT, 1> ValueVTs; 7877 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7878 7879 if (ValueVTs.empty()) 7880 return; 7881 7882 SmallVector<SDValue, 1> Ops; 7883 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7884 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7885 7886 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7887 } 7888 7889 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7890 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7891 MVT::Other, getRoot(), 7892 getValue(I.getArgOperand(0)), 7893 DAG.getSrcValue(I.getArgOperand(0)))); 7894 } 7895 7896 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7898 const DataLayout &DL = DAG.getDataLayout(); 7899 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7900 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7901 DAG.getSrcValue(I.getOperand(0)), 7902 DL.getABITypeAlignment(I.getType())); 7903 setValue(&I, V); 7904 DAG.setRoot(V.getValue(1)); 7905 } 7906 7907 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7908 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7909 MVT::Other, getRoot(), 7910 getValue(I.getArgOperand(0)), 7911 DAG.getSrcValue(I.getArgOperand(0)))); 7912 } 7913 7914 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7915 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7916 MVT::Other, getRoot(), 7917 getValue(I.getArgOperand(0)), 7918 getValue(I.getArgOperand(1)), 7919 DAG.getSrcValue(I.getArgOperand(0)), 7920 DAG.getSrcValue(I.getArgOperand(1)))); 7921 } 7922 7923 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7924 const Instruction &I, 7925 SDValue Op) { 7926 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7927 if (!Range) 7928 return Op; 7929 7930 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7931 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7932 return Op; 7933 7934 APInt Lo = CR.getUnsignedMin(); 7935 if (!Lo.isMinValue()) 7936 return Op; 7937 7938 APInt Hi = CR.getUnsignedMax(); 7939 unsigned Bits = Hi.getActiveBits(); 7940 7941 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7942 7943 SDLoc SL = getCurSDLoc(); 7944 7945 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7946 DAG.getValueType(SmallVT)); 7947 unsigned NumVals = Op.getNode()->getNumValues(); 7948 if (NumVals == 1) 7949 return ZExt; 7950 7951 SmallVector<SDValue, 4> Ops; 7952 7953 Ops.push_back(ZExt); 7954 for (unsigned I = 1; I != NumVals; ++I) 7955 Ops.push_back(Op.getValue(I)); 7956 7957 return DAG.getMergeValues(Ops, SL); 7958 } 7959 7960 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 7961 /// the call being lowered. 7962 /// 7963 /// This is a helper for lowering intrinsics that follow a target calling 7964 /// convention or require stack pointer adjustment. Only a subset of the 7965 /// intrinsic's operands need to participate in the calling convention. 7966 void SelectionDAGBuilder::populateCallLoweringInfo( 7967 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7968 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7969 bool IsPatchPoint) { 7970 TargetLowering::ArgListTy Args; 7971 Args.reserve(NumArgs); 7972 7973 // Populate the argument list. 7974 // Attributes for args start at offset 1, after the return attribute. 7975 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7976 ArgI != ArgE; ++ArgI) { 7977 const Value *V = CS->getOperand(ArgI); 7978 7979 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7980 7981 TargetLowering::ArgListEntry Entry; 7982 Entry.Node = getValue(V); 7983 Entry.Ty = V->getType(); 7984 Entry.setAttributes(&CS, ArgI); 7985 Args.push_back(Entry); 7986 } 7987 7988 CLI.setDebugLoc(getCurSDLoc()) 7989 .setChain(getRoot()) 7990 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7991 .setDiscardResult(CS->use_empty()) 7992 .setIsPatchPoint(IsPatchPoint); 7993 } 7994 7995 /// Add a stack map intrinsic call's live variable operands to a stackmap 7996 /// or patchpoint target node's operand list. 7997 /// 7998 /// Constants are converted to TargetConstants purely as an optimization to 7999 /// avoid constant materialization and register allocation. 8000 /// 8001 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8002 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8003 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8004 /// address materialization and register allocation, but may also be required 8005 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8006 /// alloca in the entry block, then the runtime may assume that the alloca's 8007 /// StackMap location can be read immediately after compilation and that the 8008 /// location is valid at any point during execution (this is similar to the 8009 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8010 /// only available in a register, then the runtime would need to trap when 8011 /// execution reaches the StackMap in order to read the alloca's location. 8012 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8013 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8014 SelectionDAGBuilder &Builder) { 8015 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8016 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8018 Ops.push_back( 8019 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8020 Ops.push_back( 8021 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8022 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8023 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8024 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8025 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8026 } else 8027 Ops.push_back(OpVal); 8028 } 8029 } 8030 8031 /// Lower llvm.experimental.stackmap directly to its target opcode. 8032 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8033 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8034 // [live variables...]) 8035 8036 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8037 8038 SDValue Chain, InFlag, Callee, NullPtr; 8039 SmallVector<SDValue, 32> Ops; 8040 8041 SDLoc DL = getCurSDLoc(); 8042 Callee = getValue(CI.getCalledValue()); 8043 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8044 8045 // The stackmap intrinsic only records the live variables (the arguemnts 8046 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8047 // intrinsic, this won't be lowered to a function call. This means we don't 8048 // have to worry about calling conventions and target specific lowering code. 8049 // Instead we perform the call lowering right here. 8050 // 8051 // chain, flag = CALLSEQ_START(chain, 0, 0) 8052 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8053 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8054 // 8055 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8056 InFlag = Chain.getValue(1); 8057 8058 // Add the <id> and <numBytes> constants. 8059 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8060 Ops.push_back(DAG.getTargetConstant( 8061 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8062 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8063 Ops.push_back(DAG.getTargetConstant( 8064 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8065 MVT::i32)); 8066 8067 // Push live variables for the stack map. 8068 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8069 8070 // We are not pushing any register mask info here on the operands list, 8071 // because the stackmap doesn't clobber anything. 8072 8073 // Push the chain and the glue flag. 8074 Ops.push_back(Chain); 8075 Ops.push_back(InFlag); 8076 8077 // Create the STACKMAP node. 8078 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8079 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8080 Chain = SDValue(SM, 0); 8081 InFlag = Chain.getValue(1); 8082 8083 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8084 8085 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8086 8087 // Set the root to the target-lowered call chain. 8088 DAG.setRoot(Chain); 8089 8090 // Inform the Frame Information that we have a stackmap in this function. 8091 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8092 } 8093 8094 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8095 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8096 const BasicBlock *EHPadBB) { 8097 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8098 // i32 <numBytes>, 8099 // i8* <target>, 8100 // i32 <numArgs>, 8101 // [Args...], 8102 // [live variables...]) 8103 8104 CallingConv::ID CC = CS.getCallingConv(); 8105 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8106 bool HasDef = !CS->getType()->isVoidTy(); 8107 SDLoc dl = getCurSDLoc(); 8108 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8109 8110 // Handle immediate and symbolic callees. 8111 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8112 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8113 /*isTarget=*/true); 8114 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8115 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8116 SDLoc(SymbolicCallee), 8117 SymbolicCallee->getValueType(0)); 8118 8119 // Get the real number of arguments participating in the call <numArgs> 8120 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8121 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8122 8123 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8124 // Intrinsics include all meta-operands up to but not including CC. 8125 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8126 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8127 "Not enough arguments provided to the patchpoint intrinsic"); 8128 8129 // For AnyRegCC the arguments are lowered later on manually. 8130 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8131 Type *ReturnTy = 8132 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8133 8134 TargetLowering::CallLoweringInfo CLI(DAG); 8135 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8136 true); 8137 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8138 8139 SDNode *CallEnd = Result.second.getNode(); 8140 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8141 CallEnd = CallEnd->getOperand(0).getNode(); 8142 8143 /// Get a call instruction from the call sequence chain. 8144 /// Tail calls are not allowed. 8145 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8146 "Expected a callseq node."); 8147 SDNode *Call = CallEnd->getOperand(0).getNode(); 8148 bool HasGlue = Call->getGluedNode(); 8149 8150 // Replace the target specific call node with the patchable intrinsic. 8151 SmallVector<SDValue, 8> Ops; 8152 8153 // Add the <id> and <numBytes> constants. 8154 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8155 Ops.push_back(DAG.getTargetConstant( 8156 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8157 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8158 Ops.push_back(DAG.getTargetConstant( 8159 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8160 MVT::i32)); 8161 8162 // Add the callee. 8163 Ops.push_back(Callee); 8164 8165 // Adjust <numArgs> to account for any arguments that have been passed on the 8166 // stack instead. 8167 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8168 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8169 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8170 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8171 8172 // Add the calling convention 8173 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8174 8175 // Add the arguments we omitted previously. The register allocator should 8176 // place these in any free register. 8177 if (IsAnyRegCC) 8178 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8179 Ops.push_back(getValue(CS.getArgument(i))); 8180 8181 // Push the arguments from the call instruction up to the register mask. 8182 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8183 Ops.append(Call->op_begin() + 2, e); 8184 8185 // Push live variables for the stack map. 8186 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8187 8188 // Push the register mask info. 8189 if (HasGlue) 8190 Ops.push_back(*(Call->op_end()-2)); 8191 else 8192 Ops.push_back(*(Call->op_end()-1)); 8193 8194 // Push the chain (this is originally the first operand of the call, but 8195 // becomes now the last or second to last operand). 8196 Ops.push_back(*(Call->op_begin())); 8197 8198 // Push the glue flag (last operand). 8199 if (HasGlue) 8200 Ops.push_back(*(Call->op_end()-1)); 8201 8202 SDVTList NodeTys; 8203 if (IsAnyRegCC && HasDef) { 8204 // Create the return types based on the intrinsic definition 8205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8206 SmallVector<EVT, 3> ValueVTs; 8207 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8208 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8209 8210 // There is always a chain and a glue type at the end 8211 ValueVTs.push_back(MVT::Other); 8212 ValueVTs.push_back(MVT::Glue); 8213 NodeTys = DAG.getVTList(ValueVTs); 8214 } else 8215 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8216 8217 // Replace the target specific call node with a PATCHPOINT node. 8218 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8219 dl, NodeTys, Ops); 8220 8221 // Update the NodeMap. 8222 if (HasDef) { 8223 if (IsAnyRegCC) 8224 setValue(CS.getInstruction(), SDValue(MN, 0)); 8225 else 8226 setValue(CS.getInstruction(), Result.first); 8227 } 8228 8229 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8230 // call sequence. Furthermore the location of the chain and glue can change 8231 // when the AnyReg calling convention is used and the intrinsic returns a 8232 // value. 8233 if (IsAnyRegCC && HasDef) { 8234 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8235 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8236 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8237 } else 8238 DAG.ReplaceAllUsesWith(Call, MN); 8239 DAG.DeleteNode(Call); 8240 8241 // Inform the Frame Information that we have a patchpoint in this function. 8242 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8243 } 8244 8245 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8246 unsigned Intrinsic) { 8247 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8248 SDValue Op1 = getValue(I.getArgOperand(0)); 8249 SDValue Op2; 8250 if (I.getNumArgOperands() > 1) 8251 Op2 = getValue(I.getArgOperand(1)); 8252 SDLoc dl = getCurSDLoc(); 8253 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8254 SDValue Res; 8255 FastMathFlags FMF; 8256 if (isa<FPMathOperator>(I)) 8257 FMF = I.getFastMathFlags(); 8258 8259 switch (Intrinsic) { 8260 case Intrinsic::experimental_vector_reduce_fadd: 8261 if (FMF.isFast()) 8262 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8263 else 8264 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8265 break; 8266 case Intrinsic::experimental_vector_reduce_fmul: 8267 if (FMF.isFast()) 8268 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8269 else 8270 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8271 break; 8272 case Intrinsic::experimental_vector_reduce_add: 8273 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8274 break; 8275 case Intrinsic::experimental_vector_reduce_mul: 8276 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8277 break; 8278 case Intrinsic::experimental_vector_reduce_and: 8279 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8280 break; 8281 case Intrinsic::experimental_vector_reduce_or: 8282 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8283 break; 8284 case Intrinsic::experimental_vector_reduce_xor: 8285 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8286 break; 8287 case Intrinsic::experimental_vector_reduce_smax: 8288 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8289 break; 8290 case Intrinsic::experimental_vector_reduce_smin: 8291 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8292 break; 8293 case Intrinsic::experimental_vector_reduce_umax: 8294 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8295 break; 8296 case Intrinsic::experimental_vector_reduce_umin: 8297 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8298 break; 8299 case Intrinsic::experimental_vector_reduce_fmax: 8300 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8301 break; 8302 case Intrinsic::experimental_vector_reduce_fmin: 8303 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8304 break; 8305 default: 8306 llvm_unreachable("Unhandled vector reduce intrinsic"); 8307 } 8308 setValue(&I, Res); 8309 } 8310 8311 /// Returns an AttributeList representing the attributes applied to the return 8312 /// value of the given call. 8313 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8314 SmallVector<Attribute::AttrKind, 2> Attrs; 8315 if (CLI.RetSExt) 8316 Attrs.push_back(Attribute::SExt); 8317 if (CLI.RetZExt) 8318 Attrs.push_back(Attribute::ZExt); 8319 if (CLI.IsInReg) 8320 Attrs.push_back(Attribute::InReg); 8321 8322 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8323 Attrs); 8324 } 8325 8326 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8327 /// implementation, which just calls LowerCall. 8328 /// FIXME: When all targets are 8329 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8330 std::pair<SDValue, SDValue> 8331 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8332 // Handle the incoming return values from the call. 8333 CLI.Ins.clear(); 8334 Type *OrigRetTy = CLI.RetTy; 8335 SmallVector<EVT, 4> RetTys; 8336 SmallVector<uint64_t, 4> Offsets; 8337 auto &DL = CLI.DAG.getDataLayout(); 8338 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8339 8340 if (CLI.IsPostTypeLegalization) { 8341 // If we are lowering a libcall after legalization, split the return type. 8342 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8343 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8344 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8345 EVT RetVT = OldRetTys[i]; 8346 uint64_t Offset = OldOffsets[i]; 8347 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8348 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8349 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8350 RetTys.append(NumRegs, RegisterVT); 8351 for (unsigned j = 0; j != NumRegs; ++j) 8352 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8353 } 8354 } 8355 8356 SmallVector<ISD::OutputArg, 4> Outs; 8357 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8358 8359 bool CanLowerReturn = 8360 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8361 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8362 8363 SDValue DemoteStackSlot; 8364 int DemoteStackIdx = -100; 8365 if (!CanLowerReturn) { 8366 // FIXME: equivalent assert? 8367 // assert(!CS.hasInAllocaArgument() && 8368 // "sret demotion is incompatible with inalloca"); 8369 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8370 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8371 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8372 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8373 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8374 DL.getAllocaAddrSpace()); 8375 8376 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8377 ArgListEntry Entry; 8378 Entry.Node = DemoteStackSlot; 8379 Entry.Ty = StackSlotPtrType; 8380 Entry.IsSExt = false; 8381 Entry.IsZExt = false; 8382 Entry.IsInReg = false; 8383 Entry.IsSRet = true; 8384 Entry.IsNest = false; 8385 Entry.IsByVal = false; 8386 Entry.IsReturned = false; 8387 Entry.IsSwiftSelf = false; 8388 Entry.IsSwiftError = false; 8389 Entry.Alignment = Align; 8390 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8391 CLI.NumFixedArgs += 1; 8392 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8393 8394 // sret demotion isn't compatible with tail-calls, since the sret argument 8395 // points into the callers stack frame. 8396 CLI.IsTailCall = false; 8397 } else { 8398 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8399 EVT VT = RetTys[I]; 8400 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8401 CLI.CallConv, VT); 8402 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8403 CLI.CallConv, VT); 8404 for (unsigned i = 0; i != NumRegs; ++i) { 8405 ISD::InputArg MyFlags; 8406 MyFlags.VT = RegisterVT; 8407 MyFlags.ArgVT = VT; 8408 MyFlags.Used = CLI.IsReturnValueUsed; 8409 if (CLI.RetSExt) 8410 MyFlags.Flags.setSExt(); 8411 if (CLI.RetZExt) 8412 MyFlags.Flags.setZExt(); 8413 if (CLI.IsInReg) 8414 MyFlags.Flags.setInReg(); 8415 CLI.Ins.push_back(MyFlags); 8416 } 8417 } 8418 } 8419 8420 // We push in swifterror return as the last element of CLI.Ins. 8421 ArgListTy &Args = CLI.getArgs(); 8422 if (supportSwiftError()) { 8423 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8424 if (Args[i].IsSwiftError) { 8425 ISD::InputArg MyFlags; 8426 MyFlags.VT = getPointerTy(DL); 8427 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8428 MyFlags.Flags.setSwiftError(); 8429 CLI.Ins.push_back(MyFlags); 8430 } 8431 } 8432 } 8433 8434 // Handle all of the outgoing arguments. 8435 CLI.Outs.clear(); 8436 CLI.OutVals.clear(); 8437 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8438 SmallVector<EVT, 4> ValueVTs; 8439 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8440 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8441 Type *FinalType = Args[i].Ty; 8442 if (Args[i].IsByVal) 8443 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8444 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8445 FinalType, CLI.CallConv, CLI.IsVarArg); 8446 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8447 ++Value) { 8448 EVT VT = ValueVTs[Value]; 8449 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8450 SDValue Op = SDValue(Args[i].Node.getNode(), 8451 Args[i].Node.getResNo() + Value); 8452 ISD::ArgFlagsTy Flags; 8453 8454 // Certain targets (such as MIPS), may have a different ABI alignment 8455 // for a type depending on the context. Give the target a chance to 8456 // specify the alignment it wants. 8457 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8458 8459 if (Args[i].IsZExt) 8460 Flags.setZExt(); 8461 if (Args[i].IsSExt) 8462 Flags.setSExt(); 8463 if (Args[i].IsInReg) { 8464 // If we are using vectorcall calling convention, a structure that is 8465 // passed InReg - is surely an HVA 8466 if (CLI.CallConv == CallingConv::X86_VectorCall && 8467 isa<StructType>(FinalType)) { 8468 // The first value of a structure is marked 8469 if (0 == Value) 8470 Flags.setHvaStart(); 8471 Flags.setHva(); 8472 } 8473 // Set InReg Flag 8474 Flags.setInReg(); 8475 } 8476 if (Args[i].IsSRet) 8477 Flags.setSRet(); 8478 if (Args[i].IsSwiftSelf) 8479 Flags.setSwiftSelf(); 8480 if (Args[i].IsSwiftError) 8481 Flags.setSwiftError(); 8482 if (Args[i].IsByVal) 8483 Flags.setByVal(); 8484 if (Args[i].IsInAlloca) { 8485 Flags.setInAlloca(); 8486 // Set the byval flag for CCAssignFn callbacks that don't know about 8487 // inalloca. This way we can know how many bytes we should've allocated 8488 // and how many bytes a callee cleanup function will pop. If we port 8489 // inalloca to more targets, we'll have to add custom inalloca handling 8490 // in the various CC lowering callbacks. 8491 Flags.setByVal(); 8492 } 8493 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8494 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8495 Type *ElementTy = Ty->getElementType(); 8496 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8497 // For ByVal, alignment should come from FE. BE will guess if this 8498 // info is not there but there are cases it cannot get right. 8499 unsigned FrameAlign; 8500 if (Args[i].Alignment) 8501 FrameAlign = Args[i].Alignment; 8502 else 8503 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8504 Flags.setByValAlign(FrameAlign); 8505 } 8506 if (Args[i].IsNest) 8507 Flags.setNest(); 8508 if (NeedsRegBlock) 8509 Flags.setInConsecutiveRegs(); 8510 Flags.setOrigAlign(OriginalAlignment); 8511 8512 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8513 CLI.CallConv, VT); 8514 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8515 CLI.CallConv, VT); 8516 SmallVector<SDValue, 4> Parts(NumParts); 8517 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8518 8519 if (Args[i].IsSExt) 8520 ExtendKind = ISD::SIGN_EXTEND; 8521 else if (Args[i].IsZExt) 8522 ExtendKind = ISD::ZERO_EXTEND; 8523 8524 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8525 // for now. 8526 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8527 CanLowerReturn) { 8528 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8529 "unexpected use of 'returned'"); 8530 // Before passing 'returned' to the target lowering code, ensure that 8531 // either the register MVT and the actual EVT are the same size or that 8532 // the return value and argument are extended in the same way; in these 8533 // cases it's safe to pass the argument register value unchanged as the 8534 // return register value (although it's at the target's option whether 8535 // to do so) 8536 // TODO: allow code generation to take advantage of partially preserved 8537 // registers rather than clobbering the entire register when the 8538 // parameter extension method is not compatible with the return 8539 // extension method 8540 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8541 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8542 CLI.RetZExt == Args[i].IsZExt)) 8543 Flags.setReturned(); 8544 } 8545 8546 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8547 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8548 8549 for (unsigned j = 0; j != NumParts; ++j) { 8550 // if it isn't first piece, alignment must be 1 8551 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8552 i < CLI.NumFixedArgs, 8553 i, j*Parts[j].getValueType().getStoreSize()); 8554 if (NumParts > 1 && j == 0) 8555 MyFlags.Flags.setSplit(); 8556 else if (j != 0) { 8557 MyFlags.Flags.setOrigAlign(1); 8558 if (j == NumParts - 1) 8559 MyFlags.Flags.setSplitEnd(); 8560 } 8561 8562 CLI.Outs.push_back(MyFlags); 8563 CLI.OutVals.push_back(Parts[j]); 8564 } 8565 8566 if (NeedsRegBlock && Value == NumValues - 1) 8567 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8568 } 8569 } 8570 8571 SmallVector<SDValue, 4> InVals; 8572 CLI.Chain = LowerCall(CLI, InVals); 8573 8574 // Update CLI.InVals to use outside of this function. 8575 CLI.InVals = InVals; 8576 8577 // Verify that the target's LowerCall behaved as expected. 8578 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8579 "LowerCall didn't return a valid chain!"); 8580 assert((!CLI.IsTailCall || InVals.empty()) && 8581 "LowerCall emitted a return value for a tail call!"); 8582 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8583 "LowerCall didn't emit the correct number of values!"); 8584 8585 // For a tail call, the return value is merely live-out and there aren't 8586 // any nodes in the DAG representing it. Return a special value to 8587 // indicate that a tail call has been emitted and no more Instructions 8588 // should be processed in the current block. 8589 if (CLI.IsTailCall) { 8590 CLI.DAG.setRoot(CLI.Chain); 8591 return std::make_pair(SDValue(), SDValue()); 8592 } 8593 8594 #ifndef NDEBUG 8595 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8596 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8597 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8598 "LowerCall emitted a value with the wrong type!"); 8599 } 8600 #endif 8601 8602 SmallVector<SDValue, 4> ReturnValues; 8603 if (!CanLowerReturn) { 8604 // The instruction result is the result of loading from the 8605 // hidden sret parameter. 8606 SmallVector<EVT, 1> PVTs; 8607 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8608 8609 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8610 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8611 EVT PtrVT = PVTs[0]; 8612 8613 unsigned NumValues = RetTys.size(); 8614 ReturnValues.resize(NumValues); 8615 SmallVector<SDValue, 4> Chains(NumValues); 8616 8617 // An aggregate return value cannot wrap around the address space, so 8618 // offsets to its parts don't wrap either. 8619 SDNodeFlags Flags; 8620 Flags.setNoUnsignedWrap(true); 8621 8622 for (unsigned i = 0; i < NumValues; ++i) { 8623 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8624 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8625 PtrVT), Flags); 8626 SDValue L = CLI.DAG.getLoad( 8627 RetTys[i], CLI.DL, CLI.Chain, Add, 8628 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8629 DemoteStackIdx, Offsets[i]), 8630 /* Alignment = */ 1); 8631 ReturnValues[i] = L; 8632 Chains[i] = L.getValue(1); 8633 } 8634 8635 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8636 } else { 8637 // Collect the legal value parts into potentially illegal values 8638 // that correspond to the original function's return values. 8639 Optional<ISD::NodeType> AssertOp; 8640 if (CLI.RetSExt) 8641 AssertOp = ISD::AssertSext; 8642 else if (CLI.RetZExt) 8643 AssertOp = ISD::AssertZext; 8644 unsigned CurReg = 0; 8645 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8646 EVT VT = RetTys[I]; 8647 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8648 CLI.CallConv, VT); 8649 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8650 CLI.CallConv, VT); 8651 8652 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8653 NumRegs, RegisterVT, VT, nullptr, 8654 CLI.CallConv, AssertOp)); 8655 CurReg += NumRegs; 8656 } 8657 8658 // For a function returning void, there is no return value. We can't create 8659 // such a node, so we just return a null return value in that case. In 8660 // that case, nothing will actually look at the value. 8661 if (ReturnValues.empty()) 8662 return std::make_pair(SDValue(), CLI.Chain); 8663 } 8664 8665 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8666 CLI.DAG.getVTList(RetTys), ReturnValues); 8667 return std::make_pair(Res, CLI.Chain); 8668 } 8669 8670 void TargetLowering::LowerOperationWrapper(SDNode *N, 8671 SmallVectorImpl<SDValue> &Results, 8672 SelectionDAG &DAG) const { 8673 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8674 Results.push_back(Res); 8675 } 8676 8677 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8678 llvm_unreachable("LowerOperation not implemented for this target!"); 8679 } 8680 8681 void 8682 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8683 SDValue Op = getNonRegisterValue(V); 8684 assert((Op.getOpcode() != ISD::CopyFromReg || 8685 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8686 "Copy from a reg to the same reg!"); 8687 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8688 8689 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8690 // If this is an InlineAsm we have to match the registers required, not the 8691 // notional registers required by the type. 8692 8693 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8694 getABIRegCopyCC(V)); 8695 SDValue Chain = DAG.getEntryNode(); 8696 8697 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8698 FuncInfo.PreferredExtendType.end()) 8699 ? ISD::ANY_EXTEND 8700 : FuncInfo.PreferredExtendType[V]; 8701 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8702 PendingExports.push_back(Chain); 8703 } 8704 8705 #include "llvm/CodeGen/SelectionDAGISel.h" 8706 8707 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8708 /// entry block, return true. This includes arguments used by switches, since 8709 /// the switch may expand into multiple basic blocks. 8710 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8711 // With FastISel active, we may be splitting blocks, so force creation 8712 // of virtual registers for all non-dead arguments. 8713 if (FastISel) 8714 return A->use_empty(); 8715 8716 const BasicBlock &Entry = A->getParent()->front(); 8717 for (const User *U : A->users()) 8718 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8719 return false; // Use not in entry block. 8720 8721 return true; 8722 } 8723 8724 using ArgCopyElisionMapTy = 8725 DenseMap<const Argument *, 8726 std::pair<const AllocaInst *, const StoreInst *>>; 8727 8728 /// Scan the entry block of the function in FuncInfo for arguments that look 8729 /// like copies into a local alloca. Record any copied arguments in 8730 /// ArgCopyElisionCandidates. 8731 static void 8732 findArgumentCopyElisionCandidates(const DataLayout &DL, 8733 FunctionLoweringInfo *FuncInfo, 8734 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8735 // Record the state of every static alloca used in the entry block. Argument 8736 // allocas are all used in the entry block, so we need approximately as many 8737 // entries as we have arguments. 8738 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8739 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8740 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8741 StaticAllocas.reserve(NumArgs * 2); 8742 8743 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8744 if (!V) 8745 return nullptr; 8746 V = V->stripPointerCasts(); 8747 const auto *AI = dyn_cast<AllocaInst>(V); 8748 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8749 return nullptr; 8750 auto Iter = StaticAllocas.insert({AI, Unknown}); 8751 return &Iter.first->second; 8752 }; 8753 8754 // Look for stores of arguments to static allocas. Look through bitcasts and 8755 // GEPs to handle type coercions, as long as the alloca is fully initialized 8756 // by the store. Any non-store use of an alloca escapes it and any subsequent 8757 // unanalyzed store might write it. 8758 // FIXME: Handle structs initialized with multiple stores. 8759 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8760 // Look for stores, and handle non-store uses conservatively. 8761 const auto *SI = dyn_cast<StoreInst>(&I); 8762 if (!SI) { 8763 // We will look through cast uses, so ignore them completely. 8764 if (I.isCast()) 8765 continue; 8766 // Ignore debug info intrinsics, they don't escape or store to allocas. 8767 if (isa<DbgInfoIntrinsic>(I)) 8768 continue; 8769 // This is an unknown instruction. Assume it escapes or writes to all 8770 // static alloca operands. 8771 for (const Use &U : I.operands()) { 8772 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8773 *Info = StaticAllocaInfo::Clobbered; 8774 } 8775 continue; 8776 } 8777 8778 // If the stored value is a static alloca, mark it as escaped. 8779 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8780 *Info = StaticAllocaInfo::Clobbered; 8781 8782 // Check if the destination is a static alloca. 8783 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8784 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8785 if (!Info) 8786 continue; 8787 const AllocaInst *AI = cast<AllocaInst>(Dst); 8788 8789 // Skip allocas that have been initialized or clobbered. 8790 if (*Info != StaticAllocaInfo::Unknown) 8791 continue; 8792 8793 // Check if the stored value is an argument, and that this store fully 8794 // initializes the alloca. Don't elide copies from the same argument twice. 8795 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8796 const auto *Arg = dyn_cast<Argument>(Val); 8797 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8798 Arg->getType()->isEmptyTy() || 8799 DL.getTypeStoreSize(Arg->getType()) != 8800 DL.getTypeAllocSize(AI->getAllocatedType()) || 8801 ArgCopyElisionCandidates.count(Arg)) { 8802 *Info = StaticAllocaInfo::Clobbered; 8803 continue; 8804 } 8805 8806 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8807 << '\n'); 8808 8809 // Mark this alloca and store for argument copy elision. 8810 *Info = StaticAllocaInfo::Elidable; 8811 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8812 8813 // Stop scanning if we've seen all arguments. This will happen early in -O0 8814 // builds, which is useful, because -O0 builds have large entry blocks and 8815 // many allocas. 8816 if (ArgCopyElisionCandidates.size() == NumArgs) 8817 break; 8818 } 8819 } 8820 8821 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8822 /// ArgVal is a load from a suitable fixed stack object. 8823 static void tryToElideArgumentCopy( 8824 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8825 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8826 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8827 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8828 SDValue ArgVal, bool &ArgHasUses) { 8829 // Check if this is a load from a fixed stack object. 8830 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8831 if (!LNode) 8832 return; 8833 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8834 if (!FINode) 8835 return; 8836 8837 // Check that the fixed stack object is the right size and alignment. 8838 // Look at the alignment that the user wrote on the alloca instead of looking 8839 // at the stack object. 8840 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8841 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8842 const AllocaInst *AI = ArgCopyIter->second.first; 8843 int FixedIndex = FINode->getIndex(); 8844 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8845 int OldIndex = AllocaIndex; 8846 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8847 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8848 LLVM_DEBUG( 8849 dbgs() << " argument copy elision failed due to bad fixed stack " 8850 "object size\n"); 8851 return; 8852 } 8853 unsigned RequiredAlignment = AI->getAlignment(); 8854 if (!RequiredAlignment) { 8855 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8856 AI->getAllocatedType()); 8857 } 8858 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8859 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8860 "greater than stack argument alignment (" 8861 << RequiredAlignment << " vs " 8862 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8863 return; 8864 } 8865 8866 // Perform the elision. Delete the old stack object and replace its only use 8867 // in the variable info map. Mark the stack object as mutable. 8868 LLVM_DEBUG({ 8869 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8870 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8871 << '\n'; 8872 }); 8873 MFI.RemoveStackObject(OldIndex); 8874 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8875 AllocaIndex = FixedIndex; 8876 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8877 Chains.push_back(ArgVal.getValue(1)); 8878 8879 // Avoid emitting code for the store implementing the copy. 8880 const StoreInst *SI = ArgCopyIter->second.second; 8881 ElidedArgCopyInstrs.insert(SI); 8882 8883 // Check for uses of the argument again so that we can avoid exporting ArgVal 8884 // if it is't used by anything other than the store. 8885 for (const Value *U : Arg.users()) { 8886 if (U != SI) { 8887 ArgHasUses = true; 8888 break; 8889 } 8890 } 8891 } 8892 8893 void SelectionDAGISel::LowerArguments(const Function &F) { 8894 SelectionDAG &DAG = SDB->DAG; 8895 SDLoc dl = SDB->getCurSDLoc(); 8896 const DataLayout &DL = DAG.getDataLayout(); 8897 SmallVector<ISD::InputArg, 16> Ins; 8898 8899 if (!FuncInfo->CanLowerReturn) { 8900 // Put in an sret pointer parameter before all the other parameters. 8901 SmallVector<EVT, 1> ValueVTs; 8902 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8903 F.getReturnType()->getPointerTo( 8904 DAG.getDataLayout().getAllocaAddrSpace()), 8905 ValueVTs); 8906 8907 // NOTE: Assuming that a pointer will never break down to more than one VT 8908 // or one register. 8909 ISD::ArgFlagsTy Flags; 8910 Flags.setSRet(); 8911 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8912 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8913 ISD::InputArg::NoArgIndex, 0); 8914 Ins.push_back(RetArg); 8915 } 8916 8917 // Look for stores of arguments to static allocas. Mark such arguments with a 8918 // flag to ask the target to give us the memory location of that argument if 8919 // available. 8920 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8921 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8922 8923 // Set up the incoming argument description vector. 8924 for (const Argument &Arg : F.args()) { 8925 unsigned ArgNo = Arg.getArgNo(); 8926 SmallVector<EVT, 4> ValueVTs; 8927 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8928 bool isArgValueUsed = !Arg.use_empty(); 8929 unsigned PartBase = 0; 8930 Type *FinalType = Arg.getType(); 8931 if (Arg.hasAttribute(Attribute::ByVal)) 8932 FinalType = cast<PointerType>(FinalType)->getElementType(); 8933 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8934 FinalType, F.getCallingConv(), F.isVarArg()); 8935 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8936 Value != NumValues; ++Value) { 8937 EVT VT = ValueVTs[Value]; 8938 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8939 ISD::ArgFlagsTy Flags; 8940 8941 // Certain targets (such as MIPS), may have a different ABI alignment 8942 // for a type depending on the context. Give the target a chance to 8943 // specify the alignment it wants. 8944 unsigned OriginalAlignment = 8945 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8946 8947 if (Arg.hasAttribute(Attribute::ZExt)) 8948 Flags.setZExt(); 8949 if (Arg.hasAttribute(Attribute::SExt)) 8950 Flags.setSExt(); 8951 if (Arg.hasAttribute(Attribute::InReg)) { 8952 // If we are using vectorcall calling convention, a structure that is 8953 // passed InReg - is surely an HVA 8954 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8955 isa<StructType>(Arg.getType())) { 8956 // The first value of a structure is marked 8957 if (0 == Value) 8958 Flags.setHvaStart(); 8959 Flags.setHva(); 8960 } 8961 // Set InReg Flag 8962 Flags.setInReg(); 8963 } 8964 if (Arg.hasAttribute(Attribute::StructRet)) 8965 Flags.setSRet(); 8966 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8967 Flags.setSwiftSelf(); 8968 if (Arg.hasAttribute(Attribute::SwiftError)) 8969 Flags.setSwiftError(); 8970 if (Arg.hasAttribute(Attribute::ByVal)) 8971 Flags.setByVal(); 8972 if (Arg.hasAttribute(Attribute::InAlloca)) { 8973 Flags.setInAlloca(); 8974 // Set the byval flag for CCAssignFn callbacks that don't know about 8975 // inalloca. This way we can know how many bytes we should've allocated 8976 // and how many bytes a callee cleanup function will pop. If we port 8977 // inalloca to more targets, we'll have to add custom inalloca handling 8978 // in the various CC lowering callbacks. 8979 Flags.setByVal(); 8980 } 8981 if (F.getCallingConv() == CallingConv::X86_INTR) { 8982 // IA Interrupt passes frame (1st parameter) by value in the stack. 8983 if (ArgNo == 0) 8984 Flags.setByVal(); 8985 } 8986 if (Flags.isByVal() || Flags.isInAlloca()) { 8987 PointerType *Ty = cast<PointerType>(Arg.getType()); 8988 Type *ElementTy = Ty->getElementType(); 8989 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8990 // For ByVal, alignment should be passed from FE. BE will guess if 8991 // this info is not there but there are cases it cannot get right. 8992 unsigned FrameAlign; 8993 if (Arg.getParamAlignment()) 8994 FrameAlign = Arg.getParamAlignment(); 8995 else 8996 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8997 Flags.setByValAlign(FrameAlign); 8998 } 8999 if (Arg.hasAttribute(Attribute::Nest)) 9000 Flags.setNest(); 9001 if (NeedsRegBlock) 9002 Flags.setInConsecutiveRegs(); 9003 Flags.setOrigAlign(OriginalAlignment); 9004 if (ArgCopyElisionCandidates.count(&Arg)) 9005 Flags.setCopyElisionCandidate(); 9006 9007 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9008 *CurDAG->getContext(), F.getCallingConv(), VT); 9009 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9010 *CurDAG->getContext(), F.getCallingConv(), VT); 9011 for (unsigned i = 0; i != NumRegs; ++i) { 9012 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9013 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9014 if (NumRegs > 1 && i == 0) 9015 MyFlags.Flags.setSplit(); 9016 // if it isn't first piece, alignment must be 1 9017 else if (i > 0) { 9018 MyFlags.Flags.setOrigAlign(1); 9019 if (i == NumRegs - 1) 9020 MyFlags.Flags.setSplitEnd(); 9021 } 9022 Ins.push_back(MyFlags); 9023 } 9024 if (NeedsRegBlock && Value == NumValues - 1) 9025 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9026 PartBase += VT.getStoreSize(); 9027 } 9028 } 9029 9030 // Call the target to set up the argument values. 9031 SmallVector<SDValue, 8> InVals; 9032 SDValue NewRoot = TLI->LowerFormalArguments( 9033 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9034 9035 // Verify that the target's LowerFormalArguments behaved as expected. 9036 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9037 "LowerFormalArguments didn't return a valid chain!"); 9038 assert(InVals.size() == Ins.size() && 9039 "LowerFormalArguments didn't emit the correct number of values!"); 9040 LLVM_DEBUG({ 9041 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9042 assert(InVals[i].getNode() && 9043 "LowerFormalArguments emitted a null value!"); 9044 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9045 "LowerFormalArguments emitted a value with the wrong type!"); 9046 } 9047 }); 9048 9049 // Update the DAG with the new chain value resulting from argument lowering. 9050 DAG.setRoot(NewRoot); 9051 9052 // Set up the argument values. 9053 unsigned i = 0; 9054 if (!FuncInfo->CanLowerReturn) { 9055 // Create a virtual register for the sret pointer, and put in a copy 9056 // from the sret argument into it. 9057 SmallVector<EVT, 1> ValueVTs; 9058 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9059 F.getReturnType()->getPointerTo( 9060 DAG.getDataLayout().getAllocaAddrSpace()), 9061 ValueVTs); 9062 MVT VT = ValueVTs[0].getSimpleVT(); 9063 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9064 Optional<ISD::NodeType> AssertOp = None; 9065 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9066 nullptr, F.getCallingConv(), AssertOp); 9067 9068 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9069 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9070 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9071 FuncInfo->DemoteRegister = SRetReg; 9072 NewRoot = 9073 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9074 DAG.setRoot(NewRoot); 9075 9076 // i indexes lowered arguments. Bump it past the hidden sret argument. 9077 ++i; 9078 } 9079 9080 SmallVector<SDValue, 4> Chains; 9081 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9082 for (const Argument &Arg : F.args()) { 9083 SmallVector<SDValue, 4> ArgValues; 9084 SmallVector<EVT, 4> ValueVTs; 9085 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9086 unsigned NumValues = ValueVTs.size(); 9087 if (NumValues == 0) 9088 continue; 9089 9090 bool ArgHasUses = !Arg.use_empty(); 9091 9092 // Elide the copying store if the target loaded this argument from a 9093 // suitable fixed stack object. 9094 if (Ins[i].Flags.isCopyElisionCandidate()) { 9095 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9096 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9097 InVals[i], ArgHasUses); 9098 } 9099 9100 // If this argument is unused then remember its value. It is used to generate 9101 // debugging information. 9102 bool isSwiftErrorArg = 9103 TLI->supportSwiftError() && 9104 Arg.hasAttribute(Attribute::SwiftError); 9105 if (!ArgHasUses && !isSwiftErrorArg) { 9106 SDB->setUnusedArgValue(&Arg, InVals[i]); 9107 9108 // Also remember any frame index for use in FastISel. 9109 if (FrameIndexSDNode *FI = 9110 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9111 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9112 } 9113 9114 for (unsigned Val = 0; Val != NumValues; ++Val) { 9115 EVT VT = ValueVTs[Val]; 9116 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9117 F.getCallingConv(), VT); 9118 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9119 *CurDAG->getContext(), F.getCallingConv(), VT); 9120 9121 // Even an apparant 'unused' swifterror argument needs to be returned. So 9122 // we do generate a copy for it that can be used on return from the 9123 // function. 9124 if (ArgHasUses || isSwiftErrorArg) { 9125 Optional<ISD::NodeType> AssertOp; 9126 if (Arg.hasAttribute(Attribute::SExt)) 9127 AssertOp = ISD::AssertSext; 9128 else if (Arg.hasAttribute(Attribute::ZExt)) 9129 AssertOp = ISD::AssertZext; 9130 9131 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9132 PartVT, VT, nullptr, 9133 F.getCallingConv(), AssertOp)); 9134 } 9135 9136 i += NumParts; 9137 } 9138 9139 // We don't need to do anything else for unused arguments. 9140 if (ArgValues.empty()) 9141 continue; 9142 9143 // Note down frame index. 9144 if (FrameIndexSDNode *FI = 9145 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9146 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9147 9148 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9149 SDB->getCurSDLoc()); 9150 9151 SDB->setValue(&Arg, Res); 9152 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9153 // We want to associate the argument with the frame index, among 9154 // involved operands, that correspond to the lowest address. The 9155 // getCopyFromParts function, called earlier, is swapping the order of 9156 // the operands to BUILD_PAIR depending on endianness. The result of 9157 // that swapping is that the least significant bits of the argument will 9158 // be in the first operand of the BUILD_PAIR node, and the most 9159 // significant bits will be in the second operand. 9160 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9161 if (LoadSDNode *LNode = 9162 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9163 if (FrameIndexSDNode *FI = 9164 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9165 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9166 } 9167 9168 // Update the SwiftErrorVRegDefMap. 9169 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9170 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9171 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9172 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9173 FuncInfo->SwiftErrorArg, Reg); 9174 } 9175 9176 // If this argument is live outside of the entry block, insert a copy from 9177 // wherever we got it to the vreg that other BB's will reference it as. 9178 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9179 // If we can, though, try to skip creating an unnecessary vreg. 9180 // FIXME: This isn't very clean... it would be nice to make this more 9181 // general. It's also subtly incompatible with the hacks FastISel 9182 // uses with vregs. 9183 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9184 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9185 FuncInfo->ValueMap[&Arg] = Reg; 9186 continue; 9187 } 9188 } 9189 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9190 FuncInfo->InitializeRegForValue(&Arg); 9191 SDB->CopyToExportRegsIfNeeded(&Arg); 9192 } 9193 } 9194 9195 if (!Chains.empty()) { 9196 Chains.push_back(NewRoot); 9197 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9198 } 9199 9200 DAG.setRoot(NewRoot); 9201 9202 assert(i == InVals.size() && "Argument register count mismatch!"); 9203 9204 // If any argument copy elisions occurred and we have debug info, update the 9205 // stale frame indices used in the dbg.declare variable info table. 9206 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9207 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9208 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9209 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9210 if (I != ArgCopyElisionFrameIndexMap.end()) 9211 VI.Slot = I->second; 9212 } 9213 } 9214 9215 // Finally, if the target has anything special to do, allow it to do so. 9216 EmitFunctionEntryCode(); 9217 } 9218 9219 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9220 /// ensure constants are generated when needed. Remember the virtual registers 9221 /// that need to be added to the Machine PHI nodes as input. We cannot just 9222 /// directly add them, because expansion might result in multiple MBB's for one 9223 /// BB. As such, the start of the BB might correspond to a different MBB than 9224 /// the end. 9225 void 9226 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9227 const TerminatorInst *TI = LLVMBB->getTerminator(); 9228 9229 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9230 9231 // Check PHI nodes in successors that expect a value to be available from this 9232 // block. 9233 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9234 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9235 if (!isa<PHINode>(SuccBB->begin())) continue; 9236 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9237 9238 // If this terminator has multiple identical successors (common for 9239 // switches), only handle each succ once. 9240 if (!SuccsHandled.insert(SuccMBB).second) 9241 continue; 9242 9243 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9244 9245 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9246 // nodes and Machine PHI nodes, but the incoming operands have not been 9247 // emitted yet. 9248 for (const PHINode &PN : SuccBB->phis()) { 9249 // Ignore dead phi's. 9250 if (PN.use_empty()) 9251 continue; 9252 9253 // Skip empty types 9254 if (PN.getType()->isEmptyTy()) 9255 continue; 9256 9257 unsigned Reg; 9258 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9259 9260 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9261 unsigned &RegOut = ConstantsOut[C]; 9262 if (RegOut == 0) { 9263 RegOut = FuncInfo.CreateRegs(C->getType()); 9264 CopyValueToVirtualRegister(C, RegOut); 9265 } 9266 Reg = RegOut; 9267 } else { 9268 DenseMap<const Value *, unsigned>::iterator I = 9269 FuncInfo.ValueMap.find(PHIOp); 9270 if (I != FuncInfo.ValueMap.end()) 9271 Reg = I->second; 9272 else { 9273 assert(isa<AllocaInst>(PHIOp) && 9274 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9275 "Didn't codegen value into a register!??"); 9276 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9277 CopyValueToVirtualRegister(PHIOp, Reg); 9278 } 9279 } 9280 9281 // Remember that this register needs to added to the machine PHI node as 9282 // the input for this MBB. 9283 SmallVector<EVT, 4> ValueVTs; 9284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9285 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9286 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9287 EVT VT = ValueVTs[vti]; 9288 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9289 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9290 FuncInfo.PHINodesToUpdate.push_back( 9291 std::make_pair(&*MBBI++, Reg + i)); 9292 Reg += NumRegisters; 9293 } 9294 } 9295 } 9296 9297 ConstantsOut.clear(); 9298 } 9299 9300 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9301 /// is 0. 9302 MachineBasicBlock * 9303 SelectionDAGBuilder::StackProtectorDescriptor:: 9304 AddSuccessorMBB(const BasicBlock *BB, 9305 MachineBasicBlock *ParentMBB, 9306 bool IsLikely, 9307 MachineBasicBlock *SuccMBB) { 9308 // If SuccBB has not been created yet, create it. 9309 if (!SuccMBB) { 9310 MachineFunction *MF = ParentMBB->getParent(); 9311 MachineFunction::iterator BBI(ParentMBB); 9312 SuccMBB = MF->CreateMachineBasicBlock(BB); 9313 MF->insert(++BBI, SuccMBB); 9314 } 9315 // Add it as a successor of ParentMBB. 9316 ParentMBB->addSuccessor( 9317 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9318 return SuccMBB; 9319 } 9320 9321 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9322 MachineFunction::iterator I(MBB); 9323 if (++I == FuncInfo.MF->end()) 9324 return nullptr; 9325 return &*I; 9326 } 9327 9328 /// During lowering new call nodes can be created (such as memset, etc.). 9329 /// Those will become new roots of the current DAG, but complications arise 9330 /// when they are tail calls. In such cases, the call lowering will update 9331 /// the root, but the builder still needs to know that a tail call has been 9332 /// lowered in order to avoid generating an additional return. 9333 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9334 // If the node is null, we do have a tail call. 9335 if (MaybeTC.getNode() != nullptr) 9336 DAG.setRoot(MaybeTC); 9337 else 9338 HasTailCall = true; 9339 } 9340 9341 uint64_t 9342 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9343 unsigned First, unsigned Last) const { 9344 assert(Last >= First); 9345 const APInt &LowCase = Clusters[First].Low->getValue(); 9346 const APInt &HighCase = Clusters[Last].High->getValue(); 9347 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9348 9349 // FIXME: A range of consecutive cases has 100% density, but only requires one 9350 // comparison to lower. We should discriminate against such consecutive ranges 9351 // in jump tables. 9352 9353 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9354 } 9355 9356 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9357 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9358 unsigned Last) const { 9359 assert(Last >= First); 9360 assert(TotalCases[Last] >= TotalCases[First]); 9361 uint64_t NumCases = 9362 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9363 return NumCases; 9364 } 9365 9366 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9367 unsigned First, unsigned Last, 9368 const SwitchInst *SI, 9369 MachineBasicBlock *DefaultMBB, 9370 CaseCluster &JTCluster) { 9371 assert(First <= Last); 9372 9373 auto Prob = BranchProbability::getZero(); 9374 unsigned NumCmps = 0; 9375 std::vector<MachineBasicBlock*> Table; 9376 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9377 9378 // Initialize probabilities in JTProbs. 9379 for (unsigned I = First; I <= Last; ++I) 9380 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9381 9382 for (unsigned I = First; I <= Last; ++I) { 9383 assert(Clusters[I].Kind == CC_Range); 9384 Prob += Clusters[I].Prob; 9385 const APInt &Low = Clusters[I].Low->getValue(); 9386 const APInt &High = Clusters[I].High->getValue(); 9387 NumCmps += (Low == High) ? 1 : 2; 9388 if (I != First) { 9389 // Fill the gap between this and the previous cluster. 9390 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9391 assert(PreviousHigh.slt(Low)); 9392 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9393 for (uint64_t J = 0; J < Gap; J++) 9394 Table.push_back(DefaultMBB); 9395 } 9396 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9397 for (uint64_t J = 0; J < ClusterSize; ++J) 9398 Table.push_back(Clusters[I].MBB); 9399 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9400 } 9401 9402 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9403 unsigned NumDests = JTProbs.size(); 9404 if (TLI.isSuitableForBitTests( 9405 NumDests, NumCmps, Clusters[First].Low->getValue(), 9406 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9407 // Clusters[First..Last] should be lowered as bit tests instead. 9408 return false; 9409 } 9410 9411 // Create the MBB that will load from and jump through the table. 9412 // Note: We create it here, but it's not inserted into the function yet. 9413 MachineFunction *CurMF = FuncInfo.MF; 9414 MachineBasicBlock *JumpTableMBB = 9415 CurMF->CreateMachineBasicBlock(SI->getParent()); 9416 9417 // Add successors. Note: use table order for determinism. 9418 SmallPtrSet<MachineBasicBlock *, 8> Done; 9419 for (MachineBasicBlock *Succ : Table) { 9420 if (Done.count(Succ)) 9421 continue; 9422 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9423 Done.insert(Succ); 9424 } 9425 JumpTableMBB->normalizeSuccProbs(); 9426 9427 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9428 ->createJumpTableIndex(Table); 9429 9430 // Set up the jump table info. 9431 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9432 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9433 Clusters[Last].High->getValue(), SI->getCondition(), 9434 nullptr, false); 9435 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9436 9437 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9438 JTCases.size() - 1, Prob); 9439 return true; 9440 } 9441 9442 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9443 const SwitchInst *SI, 9444 MachineBasicBlock *DefaultMBB) { 9445 #ifndef NDEBUG 9446 // Clusters must be non-empty, sorted, and only contain Range clusters. 9447 assert(!Clusters.empty()); 9448 for (CaseCluster &C : Clusters) 9449 assert(C.Kind == CC_Range); 9450 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9451 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9452 #endif 9453 9454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9455 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9456 return; 9457 9458 const int64_t N = Clusters.size(); 9459 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9460 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9461 9462 if (N < 2 || N < MinJumpTableEntries) 9463 return; 9464 9465 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9466 SmallVector<unsigned, 8> TotalCases(N); 9467 for (unsigned i = 0; i < N; ++i) { 9468 const APInt &Hi = Clusters[i].High->getValue(); 9469 const APInt &Lo = Clusters[i].Low->getValue(); 9470 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9471 if (i != 0) 9472 TotalCases[i] += TotalCases[i - 1]; 9473 } 9474 9475 // Cheap case: the whole range may be suitable for jump table. 9476 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9477 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9478 assert(NumCases < UINT64_MAX / 100); 9479 assert(Range >= NumCases); 9480 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9481 CaseCluster JTCluster; 9482 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9483 Clusters[0] = JTCluster; 9484 Clusters.resize(1); 9485 return; 9486 } 9487 } 9488 9489 // The algorithm below is not suitable for -O0. 9490 if (TM.getOptLevel() == CodeGenOpt::None) 9491 return; 9492 9493 // Split Clusters into minimum number of dense partitions. The algorithm uses 9494 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9495 // for the Case Statement'" (1994), but builds the MinPartitions array in 9496 // reverse order to make it easier to reconstruct the partitions in ascending 9497 // order. In the choice between two optimal partitionings, it picks the one 9498 // which yields more jump tables. 9499 9500 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9501 SmallVector<unsigned, 8> MinPartitions(N); 9502 // LastElement[i] is the last element of the partition starting at i. 9503 SmallVector<unsigned, 8> LastElement(N); 9504 // PartitionsScore[i] is used to break ties when choosing between two 9505 // partitionings resulting in the same number of partitions. 9506 SmallVector<unsigned, 8> PartitionsScore(N); 9507 // For PartitionsScore, a small number of comparisons is considered as good as 9508 // a jump table and a single comparison is considered better than a jump 9509 // table. 9510 enum PartitionScores : unsigned { 9511 NoTable = 0, 9512 Table = 1, 9513 FewCases = 1, 9514 SingleCase = 2 9515 }; 9516 9517 // Base case: There is only one way to partition Clusters[N-1]. 9518 MinPartitions[N - 1] = 1; 9519 LastElement[N - 1] = N - 1; 9520 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9521 9522 // Note: loop indexes are signed to avoid underflow. 9523 for (int64_t i = N - 2; i >= 0; i--) { 9524 // Find optimal partitioning of Clusters[i..N-1]. 9525 // Baseline: Put Clusters[i] into a partition on its own. 9526 MinPartitions[i] = MinPartitions[i + 1] + 1; 9527 LastElement[i] = i; 9528 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9529 9530 // Search for a solution that results in fewer partitions. 9531 for (int64_t j = N - 1; j > i; j--) { 9532 // Try building a partition from Clusters[i..j]. 9533 uint64_t Range = getJumpTableRange(Clusters, i, j); 9534 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9535 assert(NumCases < UINT64_MAX / 100); 9536 assert(Range >= NumCases); 9537 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9538 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9539 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9540 int64_t NumEntries = j - i + 1; 9541 9542 if (NumEntries == 1) 9543 Score += PartitionScores::SingleCase; 9544 else if (NumEntries <= SmallNumberOfEntries) 9545 Score += PartitionScores::FewCases; 9546 else if (NumEntries >= MinJumpTableEntries) 9547 Score += PartitionScores::Table; 9548 9549 // If this leads to fewer partitions, or to the same number of 9550 // partitions with better score, it is a better partitioning. 9551 if (NumPartitions < MinPartitions[i] || 9552 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9553 MinPartitions[i] = NumPartitions; 9554 LastElement[i] = j; 9555 PartitionsScore[i] = Score; 9556 } 9557 } 9558 } 9559 } 9560 9561 // Iterate over the partitions, replacing some with jump tables in-place. 9562 unsigned DstIndex = 0; 9563 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9564 Last = LastElement[First]; 9565 assert(Last >= First); 9566 assert(DstIndex <= First); 9567 unsigned NumClusters = Last - First + 1; 9568 9569 CaseCluster JTCluster; 9570 if (NumClusters >= MinJumpTableEntries && 9571 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9572 Clusters[DstIndex++] = JTCluster; 9573 } else { 9574 for (unsigned I = First; I <= Last; ++I) 9575 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9576 } 9577 } 9578 Clusters.resize(DstIndex); 9579 } 9580 9581 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9582 unsigned First, unsigned Last, 9583 const SwitchInst *SI, 9584 CaseCluster &BTCluster) { 9585 assert(First <= Last); 9586 if (First == Last) 9587 return false; 9588 9589 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9590 unsigned NumCmps = 0; 9591 for (int64_t I = First; I <= Last; ++I) { 9592 assert(Clusters[I].Kind == CC_Range); 9593 Dests.set(Clusters[I].MBB->getNumber()); 9594 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9595 } 9596 unsigned NumDests = Dests.count(); 9597 9598 APInt Low = Clusters[First].Low->getValue(); 9599 APInt High = Clusters[Last].High->getValue(); 9600 assert(Low.slt(High)); 9601 9602 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9603 const DataLayout &DL = DAG.getDataLayout(); 9604 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9605 return false; 9606 9607 APInt LowBound; 9608 APInt CmpRange; 9609 9610 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9611 assert(TLI.rangeFitsInWord(Low, High, DL) && 9612 "Case range must fit in bit mask!"); 9613 9614 // Check if the clusters cover a contiguous range such that no value in the 9615 // range will jump to the default statement. 9616 bool ContiguousRange = true; 9617 for (int64_t I = First + 1; I <= Last; ++I) { 9618 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9619 ContiguousRange = false; 9620 break; 9621 } 9622 } 9623 9624 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9625 // Optimize the case where all the case values fit in a word without having 9626 // to subtract minValue. In this case, we can optimize away the subtraction. 9627 LowBound = APInt::getNullValue(Low.getBitWidth()); 9628 CmpRange = High; 9629 ContiguousRange = false; 9630 } else { 9631 LowBound = Low; 9632 CmpRange = High - Low; 9633 } 9634 9635 CaseBitsVector CBV; 9636 auto TotalProb = BranchProbability::getZero(); 9637 for (unsigned i = First; i <= Last; ++i) { 9638 // Find the CaseBits for this destination. 9639 unsigned j; 9640 for (j = 0; j < CBV.size(); ++j) 9641 if (CBV[j].BB == Clusters[i].MBB) 9642 break; 9643 if (j == CBV.size()) 9644 CBV.push_back( 9645 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9646 CaseBits *CB = &CBV[j]; 9647 9648 // Update Mask, Bits and ExtraProb. 9649 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9650 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9651 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9652 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9653 CB->Bits += Hi - Lo + 1; 9654 CB->ExtraProb += Clusters[i].Prob; 9655 TotalProb += Clusters[i].Prob; 9656 } 9657 9658 BitTestInfo BTI; 9659 llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9660 // Sort by probability first, number of bits second, bit mask third. 9661 if (a.ExtraProb != b.ExtraProb) 9662 return a.ExtraProb > b.ExtraProb; 9663 if (a.Bits != b.Bits) 9664 return a.Bits > b.Bits; 9665 return a.Mask < b.Mask; 9666 }); 9667 9668 for (auto &CB : CBV) { 9669 MachineBasicBlock *BitTestBB = 9670 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9671 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9672 } 9673 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9674 SI->getCondition(), -1U, MVT::Other, false, 9675 ContiguousRange, nullptr, nullptr, std::move(BTI), 9676 TotalProb); 9677 9678 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9679 BitTestCases.size() - 1, TotalProb); 9680 return true; 9681 } 9682 9683 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9684 const SwitchInst *SI) { 9685 // Partition Clusters into as few subsets as possible, where each subset has a 9686 // range that fits in a machine word and has <= 3 unique destinations. 9687 9688 #ifndef NDEBUG 9689 // Clusters must be sorted and contain Range or JumpTable clusters. 9690 assert(!Clusters.empty()); 9691 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9692 for (const CaseCluster &C : Clusters) 9693 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9694 for (unsigned i = 1; i < Clusters.size(); ++i) 9695 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9696 #endif 9697 9698 // The algorithm below is not suitable for -O0. 9699 if (TM.getOptLevel() == CodeGenOpt::None) 9700 return; 9701 9702 // If target does not have legal shift left, do not emit bit tests at all. 9703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9704 const DataLayout &DL = DAG.getDataLayout(); 9705 9706 EVT PTy = TLI.getPointerTy(DL); 9707 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9708 return; 9709 9710 int BitWidth = PTy.getSizeInBits(); 9711 const int64_t N = Clusters.size(); 9712 9713 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9714 SmallVector<unsigned, 8> MinPartitions(N); 9715 // LastElement[i] is the last element of the partition starting at i. 9716 SmallVector<unsigned, 8> LastElement(N); 9717 9718 // FIXME: This might not be the best algorithm for finding bit test clusters. 9719 9720 // Base case: There is only one way to partition Clusters[N-1]. 9721 MinPartitions[N - 1] = 1; 9722 LastElement[N - 1] = N - 1; 9723 9724 // Note: loop indexes are signed to avoid underflow. 9725 for (int64_t i = N - 2; i >= 0; --i) { 9726 // Find optimal partitioning of Clusters[i..N-1]. 9727 // Baseline: Put Clusters[i] into a partition on its own. 9728 MinPartitions[i] = MinPartitions[i + 1] + 1; 9729 LastElement[i] = i; 9730 9731 // Search for a solution that results in fewer partitions. 9732 // Note: the search is limited by BitWidth, reducing time complexity. 9733 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9734 // Try building a partition from Clusters[i..j]. 9735 9736 // Check the range. 9737 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9738 Clusters[j].High->getValue(), DL)) 9739 continue; 9740 9741 // Check nbr of destinations and cluster types. 9742 // FIXME: This works, but doesn't seem very efficient. 9743 bool RangesOnly = true; 9744 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9745 for (int64_t k = i; k <= j; k++) { 9746 if (Clusters[k].Kind != CC_Range) { 9747 RangesOnly = false; 9748 break; 9749 } 9750 Dests.set(Clusters[k].MBB->getNumber()); 9751 } 9752 if (!RangesOnly || Dests.count() > 3) 9753 break; 9754 9755 // Check if it's a better partition. 9756 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9757 if (NumPartitions < MinPartitions[i]) { 9758 // Found a better partition. 9759 MinPartitions[i] = NumPartitions; 9760 LastElement[i] = j; 9761 } 9762 } 9763 } 9764 9765 // Iterate over the partitions, replacing with bit-test clusters in-place. 9766 unsigned DstIndex = 0; 9767 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9768 Last = LastElement[First]; 9769 assert(First <= Last); 9770 assert(DstIndex <= First); 9771 9772 CaseCluster BitTestCluster; 9773 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9774 Clusters[DstIndex++] = BitTestCluster; 9775 } else { 9776 size_t NumClusters = Last - First + 1; 9777 std::memmove(&Clusters[DstIndex], &Clusters[First], 9778 sizeof(Clusters[0]) * NumClusters); 9779 DstIndex += NumClusters; 9780 } 9781 } 9782 Clusters.resize(DstIndex); 9783 } 9784 9785 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9786 MachineBasicBlock *SwitchMBB, 9787 MachineBasicBlock *DefaultMBB) { 9788 MachineFunction *CurMF = FuncInfo.MF; 9789 MachineBasicBlock *NextMBB = nullptr; 9790 MachineFunction::iterator BBI(W.MBB); 9791 if (++BBI != FuncInfo.MF->end()) 9792 NextMBB = &*BBI; 9793 9794 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9795 9796 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9797 9798 if (Size == 2 && W.MBB == SwitchMBB) { 9799 // If any two of the cases has the same destination, and if one value 9800 // is the same as the other, but has one bit unset that the other has set, 9801 // use bit manipulation to do two compares at once. For example: 9802 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9803 // TODO: This could be extended to merge any 2 cases in switches with 3 9804 // cases. 9805 // TODO: Handle cases where W.CaseBB != SwitchBB. 9806 CaseCluster &Small = *W.FirstCluster; 9807 CaseCluster &Big = *W.LastCluster; 9808 9809 if (Small.Low == Small.High && Big.Low == Big.High && 9810 Small.MBB == Big.MBB) { 9811 const APInt &SmallValue = Small.Low->getValue(); 9812 const APInt &BigValue = Big.Low->getValue(); 9813 9814 // Check that there is only one bit different. 9815 APInt CommonBit = BigValue ^ SmallValue; 9816 if (CommonBit.isPowerOf2()) { 9817 SDValue CondLHS = getValue(Cond); 9818 EVT VT = CondLHS.getValueType(); 9819 SDLoc DL = getCurSDLoc(); 9820 9821 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9822 DAG.getConstant(CommonBit, DL, VT)); 9823 SDValue Cond = DAG.getSetCC( 9824 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9825 ISD::SETEQ); 9826 9827 // Update successor info. 9828 // Both Small and Big will jump to Small.BB, so we sum up the 9829 // probabilities. 9830 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9831 if (BPI) 9832 addSuccessorWithProb( 9833 SwitchMBB, DefaultMBB, 9834 // The default destination is the first successor in IR. 9835 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9836 else 9837 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9838 9839 // Insert the true branch. 9840 SDValue BrCond = 9841 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9842 DAG.getBasicBlock(Small.MBB)); 9843 // Insert the false branch. 9844 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9845 DAG.getBasicBlock(DefaultMBB)); 9846 9847 DAG.setRoot(BrCond); 9848 return; 9849 } 9850 } 9851 } 9852 9853 if (TM.getOptLevel() != CodeGenOpt::None) { 9854 // Here, we order cases by probability so the most likely case will be 9855 // checked first. However, two clusters can have the same probability in 9856 // which case their relative ordering is non-deterministic. So we use Low 9857 // as a tie-breaker as clusters are guaranteed to never overlap. 9858 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9859 [](const CaseCluster &a, const CaseCluster &b) { 9860 return a.Prob != b.Prob ? 9861 a.Prob > b.Prob : 9862 a.Low->getValue().slt(b.Low->getValue()); 9863 }); 9864 9865 // Rearrange the case blocks so that the last one falls through if possible 9866 // without changing the order of probabilities. 9867 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9868 --I; 9869 if (I->Prob > W.LastCluster->Prob) 9870 break; 9871 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9872 std::swap(*I, *W.LastCluster); 9873 break; 9874 } 9875 } 9876 } 9877 9878 // Compute total probability. 9879 BranchProbability DefaultProb = W.DefaultProb; 9880 BranchProbability UnhandledProbs = DefaultProb; 9881 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9882 UnhandledProbs += I->Prob; 9883 9884 MachineBasicBlock *CurMBB = W.MBB; 9885 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9886 MachineBasicBlock *Fallthrough; 9887 if (I == W.LastCluster) { 9888 // For the last cluster, fall through to the default destination. 9889 Fallthrough = DefaultMBB; 9890 } else { 9891 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9892 CurMF->insert(BBI, Fallthrough); 9893 // Put Cond in a virtual register to make it available from the new blocks. 9894 ExportFromCurrentBlock(Cond); 9895 } 9896 UnhandledProbs -= I->Prob; 9897 9898 switch (I->Kind) { 9899 case CC_JumpTable: { 9900 // FIXME: Optimize away range check based on pivot comparisons. 9901 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9902 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9903 9904 // The jump block hasn't been inserted yet; insert it here. 9905 MachineBasicBlock *JumpMBB = JT->MBB; 9906 CurMF->insert(BBI, JumpMBB); 9907 9908 auto JumpProb = I->Prob; 9909 auto FallthroughProb = UnhandledProbs; 9910 9911 // If the default statement is a target of the jump table, we evenly 9912 // distribute the default probability to successors of CurMBB. Also 9913 // update the probability on the edge from JumpMBB to Fallthrough. 9914 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9915 SE = JumpMBB->succ_end(); 9916 SI != SE; ++SI) { 9917 if (*SI == DefaultMBB) { 9918 JumpProb += DefaultProb / 2; 9919 FallthroughProb -= DefaultProb / 2; 9920 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9921 JumpMBB->normalizeSuccProbs(); 9922 break; 9923 } 9924 } 9925 9926 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9927 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9928 CurMBB->normalizeSuccProbs(); 9929 9930 // The jump table header will be inserted in our current block, do the 9931 // range check, and fall through to our fallthrough block. 9932 JTH->HeaderBB = CurMBB; 9933 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9934 9935 // If we're in the right place, emit the jump table header right now. 9936 if (CurMBB == SwitchMBB) { 9937 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9938 JTH->Emitted = true; 9939 } 9940 break; 9941 } 9942 case CC_BitTests: { 9943 // FIXME: Optimize away range check based on pivot comparisons. 9944 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9945 9946 // The bit test blocks haven't been inserted yet; insert them here. 9947 for (BitTestCase &BTC : BTB->Cases) 9948 CurMF->insert(BBI, BTC.ThisBB); 9949 9950 // Fill in fields of the BitTestBlock. 9951 BTB->Parent = CurMBB; 9952 BTB->Default = Fallthrough; 9953 9954 BTB->DefaultProb = UnhandledProbs; 9955 // If the cases in bit test don't form a contiguous range, we evenly 9956 // distribute the probability on the edge to Fallthrough to two 9957 // successors of CurMBB. 9958 if (!BTB->ContiguousRange) { 9959 BTB->Prob += DefaultProb / 2; 9960 BTB->DefaultProb -= DefaultProb / 2; 9961 } 9962 9963 // If we're in the right place, emit the bit test header right now. 9964 if (CurMBB == SwitchMBB) { 9965 visitBitTestHeader(*BTB, SwitchMBB); 9966 BTB->Emitted = true; 9967 } 9968 break; 9969 } 9970 case CC_Range: { 9971 const Value *RHS, *LHS, *MHS; 9972 ISD::CondCode CC; 9973 if (I->Low == I->High) { 9974 // Check Cond == I->Low. 9975 CC = ISD::SETEQ; 9976 LHS = Cond; 9977 RHS=I->Low; 9978 MHS = nullptr; 9979 } else { 9980 // Check I->Low <= Cond <= I->High. 9981 CC = ISD::SETLE; 9982 LHS = I->Low; 9983 MHS = Cond; 9984 RHS = I->High; 9985 } 9986 9987 // The false probability is the sum of all unhandled cases. 9988 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9989 getCurSDLoc(), I->Prob, UnhandledProbs); 9990 9991 if (CurMBB == SwitchMBB) 9992 visitSwitchCase(CB, SwitchMBB); 9993 else 9994 SwitchCases.push_back(CB); 9995 9996 break; 9997 } 9998 } 9999 CurMBB = Fallthrough; 10000 } 10001 } 10002 10003 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10004 CaseClusterIt First, 10005 CaseClusterIt Last) { 10006 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10007 if (X.Prob != CC.Prob) 10008 return X.Prob > CC.Prob; 10009 10010 // Ties are broken by comparing the case value. 10011 return X.Low->getValue().slt(CC.Low->getValue()); 10012 }); 10013 } 10014 10015 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10016 const SwitchWorkListItem &W, 10017 Value *Cond, 10018 MachineBasicBlock *SwitchMBB) { 10019 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10020 "Clusters not sorted?"); 10021 10022 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10023 10024 // Balance the tree based on branch probabilities to create a near-optimal (in 10025 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10026 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10027 CaseClusterIt LastLeft = W.FirstCluster; 10028 CaseClusterIt FirstRight = W.LastCluster; 10029 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10030 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10031 10032 // Move LastLeft and FirstRight towards each other from opposite directions to 10033 // find a partitioning of the clusters which balances the probability on both 10034 // sides. If LeftProb and RightProb are equal, alternate which side is 10035 // taken to ensure 0-probability nodes are distributed evenly. 10036 unsigned I = 0; 10037 while (LastLeft + 1 < FirstRight) { 10038 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10039 LeftProb += (++LastLeft)->Prob; 10040 else 10041 RightProb += (--FirstRight)->Prob; 10042 I++; 10043 } 10044 10045 while (true) { 10046 // Our binary search tree differs from a typical BST in that ours can have up 10047 // to three values in each leaf. The pivot selection above doesn't take that 10048 // into account, which means the tree might require more nodes and be less 10049 // efficient. We compensate for this here. 10050 10051 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10052 unsigned NumRight = W.LastCluster - FirstRight + 1; 10053 10054 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10055 // If one side has less than 3 clusters, and the other has more than 3, 10056 // consider taking a cluster from the other side. 10057 10058 if (NumLeft < NumRight) { 10059 // Consider moving the first cluster on the right to the left side. 10060 CaseCluster &CC = *FirstRight; 10061 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10062 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10063 if (LeftSideRank <= RightSideRank) { 10064 // Moving the cluster to the left does not demote it. 10065 ++LastLeft; 10066 ++FirstRight; 10067 continue; 10068 } 10069 } else { 10070 assert(NumRight < NumLeft); 10071 // Consider moving the last element on the left to the right side. 10072 CaseCluster &CC = *LastLeft; 10073 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10074 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10075 if (RightSideRank <= LeftSideRank) { 10076 // Moving the cluster to the right does not demot it. 10077 --LastLeft; 10078 --FirstRight; 10079 continue; 10080 } 10081 } 10082 } 10083 break; 10084 } 10085 10086 assert(LastLeft + 1 == FirstRight); 10087 assert(LastLeft >= W.FirstCluster); 10088 assert(FirstRight <= W.LastCluster); 10089 10090 // Use the first element on the right as pivot since we will make less-than 10091 // comparisons against it. 10092 CaseClusterIt PivotCluster = FirstRight; 10093 assert(PivotCluster > W.FirstCluster); 10094 assert(PivotCluster <= W.LastCluster); 10095 10096 CaseClusterIt FirstLeft = W.FirstCluster; 10097 CaseClusterIt LastRight = W.LastCluster; 10098 10099 const ConstantInt *Pivot = PivotCluster->Low; 10100 10101 // New blocks will be inserted immediately after the current one. 10102 MachineFunction::iterator BBI(W.MBB); 10103 ++BBI; 10104 10105 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10106 // we can branch to its destination directly if it's squeezed exactly in 10107 // between the known lower bound and Pivot - 1. 10108 MachineBasicBlock *LeftMBB; 10109 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10110 FirstLeft->Low == W.GE && 10111 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10112 LeftMBB = FirstLeft->MBB; 10113 } else { 10114 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10115 FuncInfo.MF->insert(BBI, LeftMBB); 10116 WorkList.push_back( 10117 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10118 // Put Cond in a virtual register to make it available from the new blocks. 10119 ExportFromCurrentBlock(Cond); 10120 } 10121 10122 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10123 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10124 // directly if RHS.High equals the current upper bound. 10125 MachineBasicBlock *RightMBB; 10126 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10127 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10128 RightMBB = FirstRight->MBB; 10129 } else { 10130 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10131 FuncInfo.MF->insert(BBI, RightMBB); 10132 WorkList.push_back( 10133 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10134 // Put Cond in a virtual register to make it available from the new blocks. 10135 ExportFromCurrentBlock(Cond); 10136 } 10137 10138 // Create the CaseBlock record that will be used to lower the branch. 10139 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10140 getCurSDLoc(), LeftProb, RightProb); 10141 10142 if (W.MBB == SwitchMBB) 10143 visitSwitchCase(CB, SwitchMBB); 10144 else 10145 SwitchCases.push_back(CB); 10146 } 10147 10148 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10149 // from the swith statement. 10150 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10151 BranchProbability PeeledCaseProb) { 10152 if (PeeledCaseProb == BranchProbability::getOne()) 10153 return BranchProbability::getZero(); 10154 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10155 10156 uint32_t Numerator = CaseProb.getNumerator(); 10157 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10158 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10159 } 10160 10161 // Try to peel the top probability case if it exceeds the threshold. 10162 // Return current MachineBasicBlock for the switch statement if the peeling 10163 // does not occur. 10164 // If the peeling is performed, return the newly created MachineBasicBlock 10165 // for the peeled switch statement. Also update Clusters to remove the peeled 10166 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10167 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10168 const SwitchInst &SI, CaseClusterVector &Clusters, 10169 BranchProbability &PeeledCaseProb) { 10170 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10171 // Don't perform if there is only one cluster or optimizing for size. 10172 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10173 TM.getOptLevel() == CodeGenOpt::None || 10174 SwitchMBB->getParent()->getFunction().optForMinSize()) 10175 return SwitchMBB; 10176 10177 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10178 unsigned PeeledCaseIndex = 0; 10179 bool SwitchPeeled = false; 10180 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10181 CaseCluster &CC = Clusters[Index]; 10182 if (CC.Prob < TopCaseProb) 10183 continue; 10184 TopCaseProb = CC.Prob; 10185 PeeledCaseIndex = Index; 10186 SwitchPeeled = true; 10187 } 10188 if (!SwitchPeeled) 10189 return SwitchMBB; 10190 10191 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10192 << TopCaseProb << "\n"); 10193 10194 // Record the MBB for the peeled switch statement. 10195 MachineFunction::iterator BBI(SwitchMBB); 10196 ++BBI; 10197 MachineBasicBlock *PeeledSwitchMBB = 10198 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10199 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10200 10201 ExportFromCurrentBlock(SI.getCondition()); 10202 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10203 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10204 nullptr, nullptr, TopCaseProb.getCompl()}; 10205 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10206 10207 Clusters.erase(PeeledCaseIt); 10208 for (CaseCluster &CC : Clusters) { 10209 LLVM_DEBUG( 10210 dbgs() << "Scale the probablity for one cluster, before scaling: " 10211 << CC.Prob << "\n"); 10212 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10213 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10214 } 10215 PeeledCaseProb = TopCaseProb; 10216 return PeeledSwitchMBB; 10217 } 10218 10219 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10220 // Extract cases from the switch. 10221 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10222 CaseClusterVector Clusters; 10223 Clusters.reserve(SI.getNumCases()); 10224 for (auto I : SI.cases()) { 10225 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10226 const ConstantInt *CaseVal = I.getCaseValue(); 10227 BranchProbability Prob = 10228 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10229 : BranchProbability(1, SI.getNumCases() + 1); 10230 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10231 } 10232 10233 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10234 10235 // Cluster adjacent cases with the same destination. We do this at all 10236 // optimization levels because it's cheap to do and will make codegen faster 10237 // if there are many clusters. 10238 sortAndRangeify(Clusters); 10239 10240 if (TM.getOptLevel() != CodeGenOpt::None) { 10241 // Replace an unreachable default with the most popular destination. 10242 // FIXME: Exploit unreachable default more aggressively. 10243 bool UnreachableDefault = 10244 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10245 if (UnreachableDefault && !Clusters.empty()) { 10246 DenseMap<const BasicBlock *, unsigned> Popularity; 10247 unsigned MaxPop = 0; 10248 const BasicBlock *MaxBB = nullptr; 10249 for (auto I : SI.cases()) { 10250 const BasicBlock *BB = I.getCaseSuccessor(); 10251 if (++Popularity[BB] > MaxPop) { 10252 MaxPop = Popularity[BB]; 10253 MaxBB = BB; 10254 } 10255 } 10256 // Set new default. 10257 assert(MaxPop > 0 && MaxBB); 10258 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10259 10260 // Remove cases that were pointing to the destination that is now the 10261 // default. 10262 CaseClusterVector New; 10263 New.reserve(Clusters.size()); 10264 for (CaseCluster &CC : Clusters) { 10265 if (CC.MBB != DefaultMBB) 10266 New.push_back(CC); 10267 } 10268 Clusters = std::move(New); 10269 } 10270 } 10271 10272 // The branch probablity of the peeled case. 10273 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10274 MachineBasicBlock *PeeledSwitchMBB = 10275 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10276 10277 // If there is only the default destination, jump there directly. 10278 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10279 if (Clusters.empty()) { 10280 assert(PeeledSwitchMBB == SwitchMBB); 10281 SwitchMBB->addSuccessor(DefaultMBB); 10282 if (DefaultMBB != NextBlock(SwitchMBB)) { 10283 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10284 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10285 } 10286 return; 10287 } 10288 10289 findJumpTables(Clusters, &SI, DefaultMBB); 10290 findBitTestClusters(Clusters, &SI); 10291 10292 LLVM_DEBUG({ 10293 dbgs() << "Case clusters: "; 10294 for (const CaseCluster &C : Clusters) { 10295 if (C.Kind == CC_JumpTable) 10296 dbgs() << "JT:"; 10297 if (C.Kind == CC_BitTests) 10298 dbgs() << "BT:"; 10299 10300 C.Low->getValue().print(dbgs(), true); 10301 if (C.Low != C.High) { 10302 dbgs() << '-'; 10303 C.High->getValue().print(dbgs(), true); 10304 } 10305 dbgs() << ' '; 10306 } 10307 dbgs() << '\n'; 10308 }); 10309 10310 assert(!Clusters.empty()); 10311 SwitchWorkList WorkList; 10312 CaseClusterIt First = Clusters.begin(); 10313 CaseClusterIt Last = Clusters.end() - 1; 10314 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10315 // Scale the branchprobability for DefaultMBB if the peel occurs and 10316 // DefaultMBB is not replaced. 10317 if (PeeledCaseProb != BranchProbability::getZero() && 10318 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10319 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10320 WorkList.push_back( 10321 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10322 10323 while (!WorkList.empty()) { 10324 SwitchWorkListItem W = WorkList.back(); 10325 WorkList.pop_back(); 10326 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10327 10328 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10329 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10330 // For optimized builds, lower large range as a balanced binary tree. 10331 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10332 continue; 10333 } 10334 10335 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10336 } 10337 } 10338