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 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 2197 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2198 MachineMemOperand::MODereferenceable; 2199 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8, 2200 DAG.getEVTAlignment(PtrTy)); 2201 Node->setMemRefs(MemRefs, MemRefs + 1); 2202 } 2203 return SDValue(Node, 0); 2204 } 2205 2206 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2207 /// tail spliced into a stack protector check success bb. 2208 /// 2209 /// For a high level explanation of how this fits into the stack protector 2210 /// generation see the comment on the declaration of class 2211 /// StackProtectorDescriptor. 2212 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2213 MachineBasicBlock *ParentBB) { 2214 2215 // First create the loads to the guard/stack slot for the comparison. 2216 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2217 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2218 2219 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2220 int FI = MFI.getStackProtectorIndex(); 2221 2222 SDValue Guard; 2223 SDLoc dl = getCurSDLoc(); 2224 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2225 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2226 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2227 2228 // Generate code to load the content of the guard slot. 2229 SDValue GuardVal = DAG.getLoad( 2230 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2231 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2232 MachineMemOperand::MOVolatile); 2233 2234 if (TLI.useStackGuardXorFP()) 2235 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2236 2237 // Retrieve guard check function, nullptr if instrumentation is inlined. 2238 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2239 // The target provides a guard check function to validate the guard value. 2240 // Generate a call to that function with the content of the guard slot as 2241 // argument. 2242 auto *Fn = cast<Function>(GuardCheck); 2243 FunctionType *FnTy = Fn->getFunctionType(); 2244 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2245 2246 TargetLowering::ArgListTy Args; 2247 TargetLowering::ArgListEntry Entry; 2248 Entry.Node = GuardVal; 2249 Entry.Ty = FnTy->getParamType(0); 2250 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2251 Entry.IsInReg = true; 2252 Args.push_back(Entry); 2253 2254 TargetLowering::CallLoweringInfo CLI(DAG); 2255 CLI.setDebugLoc(getCurSDLoc()) 2256 .setChain(DAG.getEntryNode()) 2257 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2258 getValue(GuardCheck), std::move(Args)); 2259 2260 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2261 DAG.setRoot(Result.second); 2262 return; 2263 } 2264 2265 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2266 // Otherwise, emit a volatile load to retrieve the stack guard value. 2267 SDValue Chain = DAG.getEntryNode(); 2268 if (TLI.useLoadStackGuardNode()) { 2269 Guard = getLoadStackGuard(DAG, dl, Chain); 2270 } else { 2271 const Value *IRGuard = TLI.getSDagStackGuard(M); 2272 SDValue GuardPtr = getValue(IRGuard); 2273 2274 Guard = 2275 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2276 Align, MachineMemOperand::MOVolatile); 2277 } 2278 2279 // Perform the comparison via a subtract/getsetcc. 2280 EVT VT = Guard.getValueType(); 2281 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2282 2283 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2284 *DAG.getContext(), 2285 Sub.getValueType()), 2286 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2287 2288 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2289 // branch to failure MBB. 2290 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2291 MVT::Other, GuardVal.getOperand(0), 2292 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2293 // Otherwise branch to success MBB. 2294 SDValue Br = DAG.getNode(ISD::BR, dl, 2295 MVT::Other, BrCond, 2296 DAG.getBasicBlock(SPD.getSuccessMBB())); 2297 2298 DAG.setRoot(Br); 2299 } 2300 2301 /// Codegen the failure basic block for a stack protector check. 2302 /// 2303 /// A failure stack protector machine basic block consists simply of a call to 2304 /// __stack_chk_fail(). 2305 /// 2306 /// For a high level explanation of how this fits into the stack protector 2307 /// generation see the comment on the declaration of class 2308 /// StackProtectorDescriptor. 2309 void 2310 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2311 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2312 SDValue Chain = 2313 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2314 None, false, getCurSDLoc(), false, false).second; 2315 DAG.setRoot(Chain); 2316 } 2317 2318 /// visitBitTestHeader - This function emits necessary code to produce value 2319 /// suitable for "bit tests" 2320 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2321 MachineBasicBlock *SwitchBB) { 2322 SDLoc dl = getCurSDLoc(); 2323 2324 // Subtract the minimum value 2325 SDValue SwitchOp = getValue(B.SValue); 2326 EVT VT = SwitchOp.getValueType(); 2327 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2328 DAG.getConstant(B.First, dl, VT)); 2329 2330 // Check range 2331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2332 SDValue RangeCmp = DAG.getSetCC( 2333 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2334 Sub.getValueType()), 2335 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2336 2337 // Determine the type of the test operands. 2338 bool UsePtrType = false; 2339 if (!TLI.isTypeLegal(VT)) 2340 UsePtrType = true; 2341 else { 2342 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2343 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2344 // Switch table case range are encoded into series of masks. 2345 // Just use pointer type, it's guaranteed to fit. 2346 UsePtrType = true; 2347 break; 2348 } 2349 } 2350 if (UsePtrType) { 2351 VT = TLI.getPointerTy(DAG.getDataLayout()); 2352 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2353 } 2354 2355 B.RegVT = VT.getSimpleVT(); 2356 B.Reg = FuncInfo.CreateReg(B.RegVT); 2357 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2358 2359 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2360 2361 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2362 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2363 SwitchBB->normalizeSuccProbs(); 2364 2365 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2366 MVT::Other, CopyTo, RangeCmp, 2367 DAG.getBasicBlock(B.Default)); 2368 2369 // Avoid emitting unnecessary branches to the next block. 2370 if (MBB != NextBlock(SwitchBB)) 2371 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2372 DAG.getBasicBlock(MBB)); 2373 2374 DAG.setRoot(BrRange); 2375 } 2376 2377 /// visitBitTestCase - this function produces one "bit test" 2378 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2379 MachineBasicBlock* NextMBB, 2380 BranchProbability BranchProbToNext, 2381 unsigned Reg, 2382 BitTestCase &B, 2383 MachineBasicBlock *SwitchBB) { 2384 SDLoc dl = getCurSDLoc(); 2385 MVT VT = BB.RegVT; 2386 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2387 SDValue Cmp; 2388 unsigned PopCount = countPopulation(B.Mask); 2389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2390 if (PopCount == 1) { 2391 // Testing for a single bit; just compare the shift count with what it 2392 // would need to be to shift a 1 bit in that position. 2393 Cmp = DAG.getSetCC( 2394 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2395 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2396 ISD::SETEQ); 2397 } else if (PopCount == BB.Range) { 2398 // There is only one zero bit in the range, test for it directly. 2399 Cmp = DAG.getSetCC( 2400 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2401 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2402 ISD::SETNE); 2403 } else { 2404 // Make desired shift 2405 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2406 DAG.getConstant(1, dl, VT), ShiftOp); 2407 2408 // Emit bit tests and jumps 2409 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2410 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2411 Cmp = DAG.getSetCC( 2412 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2413 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2414 } 2415 2416 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2417 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2418 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2419 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2420 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2421 // one as they are relative probabilities (and thus work more like weights), 2422 // and hence we need to normalize them to let the sum of them become one. 2423 SwitchBB->normalizeSuccProbs(); 2424 2425 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2426 MVT::Other, getControlRoot(), 2427 Cmp, DAG.getBasicBlock(B.TargetBB)); 2428 2429 // Avoid emitting unnecessary branches to the next block. 2430 if (NextMBB != NextBlock(SwitchBB)) 2431 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2432 DAG.getBasicBlock(NextMBB)); 2433 2434 DAG.setRoot(BrAnd); 2435 } 2436 2437 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2438 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2439 2440 // Retrieve successors. Look through artificial IR level blocks like 2441 // catchswitch for successors. 2442 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2443 const BasicBlock *EHPadBB = I.getSuccessor(1); 2444 2445 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2446 // have to do anything here to lower funclet bundles. 2447 assert(!I.hasOperandBundlesOtherThan( 2448 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2449 "Cannot lower invokes with arbitrary operand bundles yet!"); 2450 2451 const Value *Callee(I.getCalledValue()); 2452 const Function *Fn = dyn_cast<Function>(Callee); 2453 if (isa<InlineAsm>(Callee)) 2454 visitInlineAsm(&I); 2455 else if (Fn && Fn->isIntrinsic()) { 2456 switch (Fn->getIntrinsicID()) { 2457 default: 2458 llvm_unreachable("Cannot invoke this intrinsic"); 2459 case Intrinsic::donothing: 2460 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2461 break; 2462 case Intrinsic::experimental_patchpoint_void: 2463 case Intrinsic::experimental_patchpoint_i64: 2464 visitPatchpoint(&I, EHPadBB); 2465 break; 2466 case Intrinsic::experimental_gc_statepoint: 2467 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2468 break; 2469 } 2470 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2471 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2472 // Eventually we will support lowering the @llvm.experimental.deoptimize 2473 // intrinsic, and right now there are no plans to support other intrinsics 2474 // with deopt state. 2475 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2476 } else { 2477 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2478 } 2479 2480 // If the value of the invoke is used outside of its defining block, make it 2481 // available as a virtual register. 2482 // We already took care of the exported value for the statepoint instruction 2483 // during call to the LowerStatepoint. 2484 if (!isStatepoint(I)) { 2485 CopyToExportRegsIfNeeded(&I); 2486 } 2487 2488 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2489 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2490 BranchProbability EHPadBBProb = 2491 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2492 : BranchProbability::getZero(); 2493 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2494 2495 // Update successor info. 2496 addSuccessorWithProb(InvokeMBB, Return); 2497 for (auto &UnwindDest : UnwindDests) { 2498 UnwindDest.first->setIsEHPad(); 2499 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2500 } 2501 InvokeMBB->normalizeSuccProbs(); 2502 2503 // Drop into normal successor. 2504 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2505 MVT::Other, getControlRoot(), 2506 DAG.getBasicBlock(Return))); 2507 } 2508 2509 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2510 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2511 } 2512 2513 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2514 assert(FuncInfo.MBB->isEHPad() && 2515 "Call to landingpad not in landing pad!"); 2516 2517 MachineBasicBlock *MBB = FuncInfo.MBB; 2518 addLandingPadInfo(LP, *MBB); 2519 2520 // If there aren't registers to copy the values into (e.g., during SjLj 2521 // exceptions), then don't bother to create these DAG nodes. 2522 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2523 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2524 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2525 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2526 return; 2527 2528 // If landingpad's return type is token type, we don't create DAG nodes 2529 // for its exception pointer and selector value. The extraction of exception 2530 // pointer or selector value from token type landingpads is not currently 2531 // supported. 2532 if (LP.getType()->isTokenTy()) 2533 return; 2534 2535 SmallVector<EVT, 2> ValueVTs; 2536 SDLoc dl = getCurSDLoc(); 2537 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2538 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2539 2540 // Get the two live-in registers as SDValues. The physregs have already been 2541 // copied into virtual registers. 2542 SDValue Ops[2]; 2543 if (FuncInfo.ExceptionPointerVirtReg) { 2544 Ops[0] = DAG.getZExtOrTrunc( 2545 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2546 FuncInfo.ExceptionPointerVirtReg, 2547 TLI.getPointerTy(DAG.getDataLayout())), 2548 dl, ValueVTs[0]); 2549 } else { 2550 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2551 } 2552 Ops[1] = DAG.getZExtOrTrunc( 2553 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2554 FuncInfo.ExceptionSelectorVirtReg, 2555 TLI.getPointerTy(DAG.getDataLayout())), 2556 dl, ValueVTs[1]); 2557 2558 // Merge into one. 2559 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2560 DAG.getVTList(ValueVTs), Ops); 2561 setValue(&LP, Res); 2562 } 2563 2564 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2565 #ifndef NDEBUG 2566 for (const CaseCluster &CC : Clusters) 2567 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2568 #endif 2569 2570 llvm::sort(Clusters.begin(), Clusters.end(), 2571 [](const CaseCluster &a, const CaseCluster &b) { 2572 return a.Low->getValue().slt(b.Low->getValue()); 2573 }); 2574 2575 // Merge adjacent clusters with the same destination. 2576 const unsigned N = Clusters.size(); 2577 unsigned DstIndex = 0; 2578 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2579 CaseCluster &CC = Clusters[SrcIndex]; 2580 const ConstantInt *CaseVal = CC.Low; 2581 MachineBasicBlock *Succ = CC.MBB; 2582 2583 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2584 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2585 // If this case has the same successor and is a neighbour, merge it into 2586 // the previous cluster. 2587 Clusters[DstIndex - 1].High = CaseVal; 2588 Clusters[DstIndex - 1].Prob += CC.Prob; 2589 } else { 2590 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2591 sizeof(Clusters[SrcIndex])); 2592 } 2593 } 2594 Clusters.resize(DstIndex); 2595 } 2596 2597 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2598 MachineBasicBlock *Last) { 2599 // Update JTCases. 2600 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2601 if (JTCases[i].first.HeaderBB == First) 2602 JTCases[i].first.HeaderBB = Last; 2603 2604 // Update BitTestCases. 2605 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2606 if (BitTestCases[i].Parent == First) 2607 BitTestCases[i].Parent = Last; 2608 } 2609 2610 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2611 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2612 2613 // Update machine-CFG edges with unique successors. 2614 SmallSet<BasicBlock*, 32> Done; 2615 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2616 BasicBlock *BB = I.getSuccessor(i); 2617 bool Inserted = Done.insert(BB).second; 2618 if (!Inserted) 2619 continue; 2620 2621 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2622 addSuccessorWithProb(IndirectBrMBB, Succ); 2623 } 2624 IndirectBrMBB->normalizeSuccProbs(); 2625 2626 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2627 MVT::Other, getControlRoot(), 2628 getValue(I.getAddress()))); 2629 } 2630 2631 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2632 if (!DAG.getTarget().Options.TrapUnreachable) 2633 return; 2634 2635 // We may be able to ignore unreachable behind a noreturn call. 2636 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2637 const BasicBlock &BB = *I.getParent(); 2638 if (&I != &BB.front()) { 2639 BasicBlock::const_iterator PredI = 2640 std::prev(BasicBlock::const_iterator(&I)); 2641 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2642 if (Call->doesNotReturn()) 2643 return; 2644 } 2645 } 2646 } 2647 2648 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2649 } 2650 2651 void SelectionDAGBuilder::visitFSub(const User &I) { 2652 // -0.0 - X --> fneg 2653 Type *Ty = I.getType(); 2654 if (isa<Constant>(I.getOperand(0)) && 2655 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2656 SDValue Op2 = getValue(I.getOperand(1)); 2657 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2658 Op2.getValueType(), Op2)); 2659 return; 2660 } 2661 2662 visitBinary(I, ISD::FSUB); 2663 } 2664 2665 /// Checks if the given instruction performs a vector reduction, in which case 2666 /// we have the freedom to alter the elements in the result as long as the 2667 /// reduction of them stays unchanged. 2668 static bool isVectorReductionOp(const User *I) { 2669 const Instruction *Inst = dyn_cast<Instruction>(I); 2670 if (!Inst || !Inst->getType()->isVectorTy()) 2671 return false; 2672 2673 auto OpCode = Inst->getOpcode(); 2674 switch (OpCode) { 2675 case Instruction::Add: 2676 case Instruction::Mul: 2677 case Instruction::And: 2678 case Instruction::Or: 2679 case Instruction::Xor: 2680 break; 2681 case Instruction::FAdd: 2682 case Instruction::FMul: 2683 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2684 if (FPOp->getFastMathFlags().isFast()) 2685 break; 2686 LLVM_FALLTHROUGH; 2687 default: 2688 return false; 2689 } 2690 2691 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2692 // Ensure the reduction size is a power of 2. 2693 if (!isPowerOf2_32(ElemNum)) 2694 return false; 2695 2696 unsigned ElemNumToReduce = ElemNum; 2697 2698 // Do DFS search on the def-use chain from the given instruction. We only 2699 // allow four kinds of operations during the search until we reach the 2700 // instruction that extracts the first element from the vector: 2701 // 2702 // 1. The reduction operation of the same opcode as the given instruction. 2703 // 2704 // 2. PHI node. 2705 // 2706 // 3. ShuffleVector instruction together with a reduction operation that 2707 // does a partial reduction. 2708 // 2709 // 4. ExtractElement that extracts the first element from the vector, and we 2710 // stop searching the def-use chain here. 2711 // 2712 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2713 // from 1-3 to the stack to continue the DFS. The given instruction is not 2714 // a reduction operation if we meet any other instructions other than those 2715 // listed above. 2716 2717 SmallVector<const User *, 16> UsersToVisit{Inst}; 2718 SmallPtrSet<const User *, 16> Visited; 2719 bool ReduxExtracted = false; 2720 2721 while (!UsersToVisit.empty()) { 2722 auto User = UsersToVisit.back(); 2723 UsersToVisit.pop_back(); 2724 if (!Visited.insert(User).second) 2725 continue; 2726 2727 for (const auto &U : User->users()) { 2728 auto Inst = dyn_cast<Instruction>(U); 2729 if (!Inst) 2730 return false; 2731 2732 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2733 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2734 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2735 return false; 2736 UsersToVisit.push_back(U); 2737 } else if (const ShuffleVectorInst *ShufInst = 2738 dyn_cast<ShuffleVectorInst>(U)) { 2739 // Detect the following pattern: A ShuffleVector instruction together 2740 // with a reduction that do partial reduction on the first and second 2741 // ElemNumToReduce / 2 elements, and store the result in 2742 // ElemNumToReduce / 2 elements in another vector. 2743 2744 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2745 if (ResultElements < ElemNum) 2746 return false; 2747 2748 if (ElemNumToReduce == 1) 2749 return false; 2750 if (!isa<UndefValue>(U->getOperand(1))) 2751 return false; 2752 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2753 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2754 return false; 2755 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2756 if (ShufInst->getMaskValue(i) != -1) 2757 return false; 2758 2759 // There is only one user of this ShuffleVector instruction, which 2760 // must be a reduction operation. 2761 if (!U->hasOneUse()) 2762 return false; 2763 2764 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2765 if (!U2 || U2->getOpcode() != OpCode) 2766 return false; 2767 2768 // Check operands of the reduction operation. 2769 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2770 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2771 UsersToVisit.push_back(U2); 2772 ElemNumToReduce /= 2; 2773 } else 2774 return false; 2775 } else if (isa<ExtractElementInst>(U)) { 2776 // At this moment we should have reduced all elements in the vector. 2777 if (ElemNumToReduce != 1) 2778 return false; 2779 2780 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2781 if (!Val || !Val->isZero()) 2782 return false; 2783 2784 ReduxExtracted = true; 2785 } else 2786 return false; 2787 } 2788 } 2789 return ReduxExtracted; 2790 } 2791 2792 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2793 SDNodeFlags Flags; 2794 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2795 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2796 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2797 } 2798 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2799 Flags.setExact(ExactOp->isExact()); 2800 } 2801 if (isVectorReductionOp(&I)) { 2802 Flags.setVectorReduction(true); 2803 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2804 } 2805 2806 SDValue Op1 = getValue(I.getOperand(0)); 2807 SDValue Op2 = getValue(I.getOperand(1)); 2808 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2809 Op1, Op2, Flags); 2810 setValue(&I, BinNodeValue); 2811 } 2812 2813 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2814 SDValue Op1 = getValue(I.getOperand(0)); 2815 SDValue Op2 = getValue(I.getOperand(1)); 2816 2817 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2818 Op2.getValueType(), DAG.getDataLayout()); 2819 2820 // Coerce the shift amount to the right type if we can. 2821 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2822 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2823 unsigned Op2Size = Op2.getValueSizeInBits(); 2824 SDLoc DL = getCurSDLoc(); 2825 2826 // If the operand is smaller than the shift count type, promote it. 2827 if (ShiftSize > Op2Size) 2828 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2829 2830 // If the operand is larger than the shift count type but the shift 2831 // count type has enough bits to represent any shift value, truncate 2832 // it now. This is a common case and it exposes the truncate to 2833 // optimization early. 2834 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2835 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2836 // Otherwise we'll need to temporarily settle for some other convenient 2837 // type. Type legalization will make adjustments once the shiftee is split. 2838 else 2839 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2840 } 2841 2842 bool nuw = false; 2843 bool nsw = false; 2844 bool exact = false; 2845 2846 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2847 2848 if (const OverflowingBinaryOperator *OFBinOp = 2849 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2850 nuw = OFBinOp->hasNoUnsignedWrap(); 2851 nsw = OFBinOp->hasNoSignedWrap(); 2852 } 2853 if (const PossiblyExactOperator *ExactOp = 2854 dyn_cast<const PossiblyExactOperator>(&I)) 2855 exact = ExactOp->isExact(); 2856 } 2857 SDNodeFlags Flags; 2858 Flags.setExact(exact); 2859 Flags.setNoSignedWrap(nsw); 2860 Flags.setNoUnsignedWrap(nuw); 2861 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2862 Flags); 2863 setValue(&I, Res); 2864 } 2865 2866 void SelectionDAGBuilder::visitSDiv(const User &I) { 2867 SDValue Op1 = getValue(I.getOperand(0)); 2868 SDValue Op2 = getValue(I.getOperand(1)); 2869 2870 SDNodeFlags Flags; 2871 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2872 cast<PossiblyExactOperator>(&I)->isExact()); 2873 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2874 Op2, Flags)); 2875 } 2876 2877 void SelectionDAGBuilder::visitICmp(const User &I) { 2878 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2879 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2880 predicate = IC->getPredicate(); 2881 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2882 predicate = ICmpInst::Predicate(IC->getPredicate()); 2883 SDValue Op1 = getValue(I.getOperand(0)); 2884 SDValue Op2 = getValue(I.getOperand(1)); 2885 ISD::CondCode Opcode = getICmpCondCode(predicate); 2886 2887 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2888 I.getType()); 2889 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2890 } 2891 2892 void SelectionDAGBuilder::visitFCmp(const User &I) { 2893 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2894 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2895 predicate = FC->getPredicate(); 2896 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2897 predicate = FCmpInst::Predicate(FC->getPredicate()); 2898 SDValue Op1 = getValue(I.getOperand(0)); 2899 SDValue Op2 = getValue(I.getOperand(1)); 2900 2901 ISD::CondCode Condition = getFCmpCondCode(predicate); 2902 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2903 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2904 Condition = getFCmpCodeWithoutNaN(Condition); 2905 2906 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2907 I.getType()); 2908 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2909 } 2910 2911 // Check if the condition of the select has one use or two users that are both 2912 // selects with the same condition. 2913 static bool hasOnlySelectUsers(const Value *Cond) { 2914 return llvm::all_of(Cond->users(), [](const Value *V) { 2915 return isa<SelectInst>(V); 2916 }); 2917 } 2918 2919 void SelectionDAGBuilder::visitSelect(const User &I) { 2920 SmallVector<EVT, 4> ValueVTs; 2921 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2922 ValueVTs); 2923 unsigned NumValues = ValueVTs.size(); 2924 if (NumValues == 0) return; 2925 2926 SmallVector<SDValue, 4> Values(NumValues); 2927 SDValue Cond = getValue(I.getOperand(0)); 2928 SDValue LHSVal = getValue(I.getOperand(1)); 2929 SDValue RHSVal = getValue(I.getOperand(2)); 2930 auto BaseOps = {Cond}; 2931 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2932 ISD::VSELECT : ISD::SELECT; 2933 2934 // Min/max matching is only viable if all output VTs are the same. 2935 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2936 EVT VT = ValueVTs[0]; 2937 LLVMContext &Ctx = *DAG.getContext(); 2938 auto &TLI = DAG.getTargetLoweringInfo(); 2939 2940 // We care about the legality of the operation after it has been type 2941 // legalized. 2942 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2943 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2944 VT = TLI.getTypeToTransformTo(Ctx, VT); 2945 2946 // If the vselect is legal, assume we want to leave this as a vector setcc + 2947 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2948 // min/max is legal on the scalar type. 2949 bool UseScalarMinMax = VT.isVector() && 2950 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2951 2952 Value *LHS, *RHS; 2953 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2954 ISD::NodeType Opc = ISD::DELETED_NODE; 2955 switch (SPR.Flavor) { 2956 case SPF_UMAX: Opc = ISD::UMAX; break; 2957 case SPF_UMIN: Opc = ISD::UMIN; break; 2958 case SPF_SMAX: Opc = ISD::SMAX; break; 2959 case SPF_SMIN: Opc = ISD::SMIN; break; 2960 case SPF_FMINNUM: 2961 switch (SPR.NaNBehavior) { 2962 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2963 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2964 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2965 case SPNB_RETURNS_ANY: { 2966 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2967 Opc = ISD::FMINNUM; 2968 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2969 Opc = ISD::FMINNAN; 2970 else if (UseScalarMinMax) 2971 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2972 ISD::FMINNUM : ISD::FMINNAN; 2973 break; 2974 } 2975 } 2976 break; 2977 case SPF_FMAXNUM: 2978 switch (SPR.NaNBehavior) { 2979 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2980 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2981 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2982 case SPNB_RETURNS_ANY: 2983 2984 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2985 Opc = ISD::FMAXNUM; 2986 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2987 Opc = ISD::FMAXNAN; 2988 else if (UseScalarMinMax) 2989 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2990 ISD::FMAXNUM : ISD::FMAXNAN; 2991 break; 2992 } 2993 break; 2994 default: break; 2995 } 2996 2997 if (Opc != ISD::DELETED_NODE && 2998 (TLI.isOperationLegalOrCustom(Opc, VT) || 2999 (UseScalarMinMax && 3000 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3001 // If the underlying comparison instruction is used by any other 3002 // instruction, the consumed instructions won't be destroyed, so it is 3003 // not profitable to convert to a min/max. 3004 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3005 OpCode = Opc; 3006 LHSVal = getValue(LHS); 3007 RHSVal = getValue(RHS); 3008 BaseOps = {}; 3009 } 3010 } 3011 3012 for (unsigned i = 0; i != NumValues; ++i) { 3013 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3014 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3015 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3016 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3017 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3018 Ops); 3019 } 3020 3021 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3022 DAG.getVTList(ValueVTs), Values)); 3023 } 3024 3025 void SelectionDAGBuilder::visitTrunc(const User &I) { 3026 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3027 SDValue N = getValue(I.getOperand(0)); 3028 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3029 I.getType()); 3030 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3031 } 3032 3033 void SelectionDAGBuilder::visitZExt(const User &I) { 3034 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3035 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3036 SDValue N = getValue(I.getOperand(0)); 3037 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3038 I.getType()); 3039 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3040 } 3041 3042 void SelectionDAGBuilder::visitSExt(const User &I) { 3043 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3044 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3045 SDValue N = getValue(I.getOperand(0)); 3046 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3047 I.getType()); 3048 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3049 } 3050 3051 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3052 // FPTrunc is never a no-op cast, no need to check 3053 SDValue N = getValue(I.getOperand(0)); 3054 SDLoc dl = getCurSDLoc(); 3055 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3056 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3057 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3058 DAG.getTargetConstant( 3059 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3060 } 3061 3062 void SelectionDAGBuilder::visitFPExt(const User &I) { 3063 // FPExt is never a no-op cast, no need to check 3064 SDValue N = getValue(I.getOperand(0)); 3065 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3066 I.getType()); 3067 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3068 } 3069 3070 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3071 // FPToUI is never a no-op cast, no need to check 3072 SDValue N = getValue(I.getOperand(0)); 3073 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3074 I.getType()); 3075 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3076 } 3077 3078 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3079 // FPToSI is never a no-op cast, no need to check 3080 SDValue N = getValue(I.getOperand(0)); 3081 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3082 I.getType()); 3083 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3084 } 3085 3086 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3087 // UIToFP is never a no-op cast, no need to check 3088 SDValue N = getValue(I.getOperand(0)); 3089 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3090 I.getType()); 3091 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3092 } 3093 3094 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3095 // SIToFP is never a no-op cast, no need to check 3096 SDValue N = getValue(I.getOperand(0)); 3097 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3098 I.getType()); 3099 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3100 } 3101 3102 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3103 // What to do depends on the size of the integer and the size of the pointer. 3104 // We can either truncate, zero extend, or no-op, accordingly. 3105 SDValue N = getValue(I.getOperand(0)); 3106 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3107 I.getType()); 3108 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3109 } 3110 3111 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3112 // What to do depends on the size of the integer and the size of the pointer. 3113 // We can either truncate, zero extend, or no-op, accordingly. 3114 SDValue N = getValue(I.getOperand(0)); 3115 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3116 I.getType()); 3117 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3118 } 3119 3120 void SelectionDAGBuilder::visitBitCast(const User &I) { 3121 SDValue N = getValue(I.getOperand(0)); 3122 SDLoc dl = getCurSDLoc(); 3123 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3124 I.getType()); 3125 3126 // BitCast assures us that source and destination are the same size so this is 3127 // either a BITCAST or a no-op. 3128 if (DestVT != N.getValueType()) 3129 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3130 DestVT, N)); // convert types. 3131 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3132 // might fold any kind of constant expression to an integer constant and that 3133 // is not what we are looking for. Only recognize a bitcast of a genuine 3134 // constant integer as an opaque constant. 3135 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3136 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3137 /*isOpaque*/true)); 3138 else 3139 setValue(&I, N); // noop cast. 3140 } 3141 3142 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3144 const Value *SV = I.getOperand(0); 3145 SDValue N = getValue(SV); 3146 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3147 3148 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3149 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3150 3151 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3152 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3153 3154 setValue(&I, N); 3155 } 3156 3157 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3159 SDValue InVec = getValue(I.getOperand(0)); 3160 SDValue InVal = getValue(I.getOperand(1)); 3161 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3162 TLI.getVectorIdxTy(DAG.getDataLayout())); 3163 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3164 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3165 InVec, InVal, InIdx)); 3166 } 3167 3168 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3170 SDValue InVec = getValue(I.getOperand(0)); 3171 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3172 TLI.getVectorIdxTy(DAG.getDataLayout())); 3173 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3174 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3175 InVec, InIdx)); 3176 } 3177 3178 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3179 SDValue Src1 = getValue(I.getOperand(0)); 3180 SDValue Src2 = getValue(I.getOperand(1)); 3181 SDLoc DL = getCurSDLoc(); 3182 3183 SmallVector<int, 8> Mask; 3184 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3185 unsigned MaskNumElts = Mask.size(); 3186 3187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3188 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3189 EVT SrcVT = Src1.getValueType(); 3190 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3191 3192 if (SrcNumElts == MaskNumElts) { 3193 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3194 return; 3195 } 3196 3197 // Normalize the shuffle vector since mask and vector length don't match. 3198 if (SrcNumElts < MaskNumElts) { 3199 // Mask is longer than the source vectors. We can use concatenate vector to 3200 // make the mask and vectors lengths match. 3201 3202 if (MaskNumElts % SrcNumElts == 0) { 3203 // Mask length is a multiple of the source vector length. 3204 // Check if the shuffle is some kind of concatenation of the input 3205 // vectors. 3206 unsigned NumConcat = MaskNumElts / SrcNumElts; 3207 bool IsConcat = true; 3208 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3209 for (unsigned i = 0; i != MaskNumElts; ++i) { 3210 int Idx = Mask[i]; 3211 if (Idx < 0) 3212 continue; 3213 // Ensure the indices in each SrcVT sized piece are sequential and that 3214 // the same source is used for the whole piece. 3215 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3216 (ConcatSrcs[i / SrcNumElts] >= 0 && 3217 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3218 IsConcat = false; 3219 break; 3220 } 3221 // Remember which source this index came from. 3222 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3223 } 3224 3225 // The shuffle is concatenating multiple vectors together. Just emit 3226 // a CONCAT_VECTORS operation. 3227 if (IsConcat) { 3228 SmallVector<SDValue, 8> ConcatOps; 3229 for (auto Src : ConcatSrcs) { 3230 if (Src < 0) 3231 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3232 else if (Src == 0) 3233 ConcatOps.push_back(Src1); 3234 else 3235 ConcatOps.push_back(Src2); 3236 } 3237 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3238 return; 3239 } 3240 } 3241 3242 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3243 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3244 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3245 PaddedMaskNumElts); 3246 3247 // Pad both vectors with undefs to make them the same length as the mask. 3248 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3249 3250 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3251 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3252 MOps1[0] = Src1; 3253 MOps2[0] = Src2; 3254 3255 Src1 = Src1.isUndef() 3256 ? DAG.getUNDEF(PaddedVT) 3257 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3258 Src2 = Src2.isUndef() 3259 ? DAG.getUNDEF(PaddedVT) 3260 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3261 3262 // Readjust mask for new input vector length. 3263 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3264 for (unsigned i = 0; i != MaskNumElts; ++i) { 3265 int Idx = Mask[i]; 3266 if (Idx >= (int)SrcNumElts) 3267 Idx -= SrcNumElts - PaddedMaskNumElts; 3268 MappedOps[i] = Idx; 3269 } 3270 3271 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3272 3273 // If the concatenated vector was padded, extract a subvector with the 3274 // correct number of elements. 3275 if (MaskNumElts != PaddedMaskNumElts) 3276 Result = DAG.getNode( 3277 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3278 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3279 3280 setValue(&I, Result); 3281 return; 3282 } 3283 3284 if (SrcNumElts > MaskNumElts) { 3285 // Analyze the access pattern of the vector to see if we can extract 3286 // two subvectors and do the shuffle. 3287 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3288 bool CanExtract = true; 3289 for (int Idx : Mask) { 3290 unsigned Input = 0; 3291 if (Idx < 0) 3292 continue; 3293 3294 if (Idx >= (int)SrcNumElts) { 3295 Input = 1; 3296 Idx -= SrcNumElts; 3297 } 3298 3299 // If all the indices come from the same MaskNumElts sized portion of 3300 // the sources we can use extract. Also make sure the extract wouldn't 3301 // extract past the end of the source. 3302 int NewStartIdx = alignDown(Idx, MaskNumElts); 3303 if (NewStartIdx + MaskNumElts > SrcNumElts || 3304 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3305 CanExtract = false; 3306 // Make sure we always update StartIdx as we use it to track if all 3307 // elements are undef. 3308 StartIdx[Input] = NewStartIdx; 3309 } 3310 3311 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3312 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3313 return; 3314 } 3315 if (CanExtract) { 3316 // Extract appropriate subvector and generate a vector shuffle 3317 for (unsigned Input = 0; Input < 2; ++Input) { 3318 SDValue &Src = Input == 0 ? Src1 : Src2; 3319 if (StartIdx[Input] < 0) 3320 Src = DAG.getUNDEF(VT); 3321 else { 3322 Src = DAG.getNode( 3323 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3324 DAG.getConstant(StartIdx[Input], DL, 3325 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3326 } 3327 } 3328 3329 // Calculate new mask. 3330 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3331 for (int &Idx : MappedOps) { 3332 if (Idx >= (int)SrcNumElts) 3333 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3334 else if (Idx >= 0) 3335 Idx -= StartIdx[0]; 3336 } 3337 3338 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3339 return; 3340 } 3341 } 3342 3343 // We can't use either concat vectors or extract subvectors so fall back to 3344 // replacing the shuffle with extract and build vector. 3345 // to insert and build vector. 3346 EVT EltVT = VT.getVectorElementType(); 3347 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3348 SmallVector<SDValue,8> Ops; 3349 for (int Idx : Mask) { 3350 SDValue Res; 3351 3352 if (Idx < 0) { 3353 Res = DAG.getUNDEF(EltVT); 3354 } else { 3355 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3356 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3357 3358 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3359 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3360 } 3361 3362 Ops.push_back(Res); 3363 } 3364 3365 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3366 } 3367 3368 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3369 ArrayRef<unsigned> Indices; 3370 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3371 Indices = IV->getIndices(); 3372 else 3373 Indices = cast<ConstantExpr>(&I)->getIndices(); 3374 3375 const Value *Op0 = I.getOperand(0); 3376 const Value *Op1 = I.getOperand(1); 3377 Type *AggTy = I.getType(); 3378 Type *ValTy = Op1->getType(); 3379 bool IntoUndef = isa<UndefValue>(Op0); 3380 bool FromUndef = isa<UndefValue>(Op1); 3381 3382 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3383 3384 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3385 SmallVector<EVT, 4> AggValueVTs; 3386 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3387 SmallVector<EVT, 4> ValValueVTs; 3388 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3389 3390 unsigned NumAggValues = AggValueVTs.size(); 3391 unsigned NumValValues = ValValueVTs.size(); 3392 SmallVector<SDValue, 4> Values(NumAggValues); 3393 3394 // Ignore an insertvalue that produces an empty object 3395 if (!NumAggValues) { 3396 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3397 return; 3398 } 3399 3400 SDValue Agg = getValue(Op0); 3401 unsigned i = 0; 3402 // Copy the beginning value(s) from the original aggregate. 3403 for (; i != LinearIndex; ++i) 3404 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3405 SDValue(Agg.getNode(), Agg.getResNo() + i); 3406 // Copy values from the inserted value(s). 3407 if (NumValValues) { 3408 SDValue Val = getValue(Op1); 3409 for (; i != LinearIndex + NumValValues; ++i) 3410 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3411 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3412 } 3413 // Copy remaining value(s) from the original aggregate. 3414 for (; i != NumAggValues; ++i) 3415 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3416 SDValue(Agg.getNode(), Agg.getResNo() + i); 3417 3418 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3419 DAG.getVTList(AggValueVTs), Values)); 3420 } 3421 3422 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3423 ArrayRef<unsigned> Indices; 3424 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3425 Indices = EV->getIndices(); 3426 else 3427 Indices = cast<ConstantExpr>(&I)->getIndices(); 3428 3429 const Value *Op0 = I.getOperand(0); 3430 Type *AggTy = Op0->getType(); 3431 Type *ValTy = I.getType(); 3432 bool OutOfUndef = isa<UndefValue>(Op0); 3433 3434 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3435 3436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3437 SmallVector<EVT, 4> ValValueVTs; 3438 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3439 3440 unsigned NumValValues = ValValueVTs.size(); 3441 3442 // Ignore a extractvalue that produces an empty object 3443 if (!NumValValues) { 3444 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3445 return; 3446 } 3447 3448 SmallVector<SDValue, 4> Values(NumValValues); 3449 3450 SDValue Agg = getValue(Op0); 3451 // Copy out the selected value(s). 3452 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3453 Values[i - LinearIndex] = 3454 OutOfUndef ? 3455 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3456 SDValue(Agg.getNode(), Agg.getResNo() + i); 3457 3458 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3459 DAG.getVTList(ValValueVTs), Values)); 3460 } 3461 3462 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3463 Value *Op0 = I.getOperand(0); 3464 // Note that the pointer operand may be a vector of pointers. Take the scalar 3465 // element which holds a pointer. 3466 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3467 SDValue N = getValue(Op0); 3468 SDLoc dl = getCurSDLoc(); 3469 3470 // Normalize Vector GEP - all scalar operands should be converted to the 3471 // splat vector. 3472 unsigned VectorWidth = I.getType()->isVectorTy() ? 3473 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3474 3475 if (VectorWidth && !N.getValueType().isVector()) { 3476 LLVMContext &Context = *DAG.getContext(); 3477 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3478 N = DAG.getSplatBuildVector(VT, dl, N); 3479 } 3480 3481 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3482 GTI != E; ++GTI) { 3483 const Value *Idx = GTI.getOperand(); 3484 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3485 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3486 if (Field) { 3487 // N = N + Offset 3488 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3489 3490 // In an inbounds GEP with an offset that is nonnegative even when 3491 // interpreted as signed, assume there is no unsigned overflow. 3492 SDNodeFlags Flags; 3493 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3494 Flags.setNoUnsignedWrap(true); 3495 3496 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3497 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3498 } 3499 } else { 3500 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3501 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3502 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3503 3504 // If this is a scalar constant or a splat vector of constants, 3505 // handle it quickly. 3506 const auto *CI = dyn_cast<ConstantInt>(Idx); 3507 if (!CI && isa<ConstantDataVector>(Idx) && 3508 cast<ConstantDataVector>(Idx)->getSplatValue()) 3509 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3510 3511 if (CI) { 3512 if (CI->isZero()) 3513 continue; 3514 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3515 LLVMContext &Context = *DAG.getContext(); 3516 SDValue OffsVal = VectorWidth ? 3517 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3518 DAG.getConstant(Offs, dl, IdxTy); 3519 3520 // In an inbouds GEP with an offset that is nonnegative even when 3521 // interpreted as signed, assume there is no unsigned overflow. 3522 SDNodeFlags Flags; 3523 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3524 Flags.setNoUnsignedWrap(true); 3525 3526 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3527 continue; 3528 } 3529 3530 // N = N + Idx * ElementSize; 3531 SDValue IdxN = getValue(Idx); 3532 3533 if (!IdxN.getValueType().isVector() && VectorWidth) { 3534 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3535 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3536 } 3537 3538 // If the index is smaller or larger than intptr_t, truncate or extend 3539 // it. 3540 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3541 3542 // If this is a multiply by a power of two, turn it into a shl 3543 // immediately. This is a very common case. 3544 if (ElementSize != 1) { 3545 if (ElementSize.isPowerOf2()) { 3546 unsigned Amt = ElementSize.logBase2(); 3547 IdxN = DAG.getNode(ISD::SHL, dl, 3548 N.getValueType(), IdxN, 3549 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3550 } else { 3551 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3552 IdxN = DAG.getNode(ISD::MUL, dl, 3553 N.getValueType(), IdxN, Scale); 3554 } 3555 } 3556 3557 N = DAG.getNode(ISD::ADD, dl, 3558 N.getValueType(), N, IdxN); 3559 } 3560 } 3561 3562 setValue(&I, N); 3563 } 3564 3565 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3566 // If this is a fixed sized alloca in the entry block of the function, 3567 // allocate it statically on the stack. 3568 if (FuncInfo.StaticAllocaMap.count(&I)) 3569 return; // getValue will auto-populate this. 3570 3571 SDLoc dl = getCurSDLoc(); 3572 Type *Ty = I.getAllocatedType(); 3573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3574 auto &DL = DAG.getDataLayout(); 3575 uint64_t TySize = DL.getTypeAllocSize(Ty); 3576 unsigned Align = 3577 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3578 3579 SDValue AllocSize = getValue(I.getArraySize()); 3580 3581 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3582 if (AllocSize.getValueType() != IntPtr) 3583 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3584 3585 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3586 AllocSize, 3587 DAG.getConstant(TySize, dl, IntPtr)); 3588 3589 // Handle alignment. If the requested alignment is less than or equal to 3590 // the stack alignment, ignore it. If the size is greater than or equal to 3591 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3592 unsigned StackAlign = 3593 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3594 if (Align <= StackAlign) 3595 Align = 0; 3596 3597 // Round the size of the allocation up to the stack alignment size 3598 // by add SA-1 to the size. This doesn't overflow because we're computing 3599 // an address inside an alloca. 3600 SDNodeFlags Flags; 3601 Flags.setNoUnsignedWrap(true); 3602 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3603 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3604 3605 // Mask out the low bits for alignment purposes. 3606 AllocSize = 3607 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3608 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3609 3610 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3611 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3612 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3613 setValue(&I, DSA); 3614 DAG.setRoot(DSA.getValue(1)); 3615 3616 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3617 } 3618 3619 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3620 if (I.isAtomic()) 3621 return visitAtomicLoad(I); 3622 3623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3624 const Value *SV = I.getOperand(0); 3625 if (TLI.supportSwiftError()) { 3626 // Swifterror values can come from either a function parameter with 3627 // swifterror attribute or an alloca with swifterror attribute. 3628 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3629 if (Arg->hasSwiftErrorAttr()) 3630 return visitLoadFromSwiftError(I); 3631 } 3632 3633 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3634 if (Alloca->isSwiftError()) 3635 return visitLoadFromSwiftError(I); 3636 } 3637 } 3638 3639 SDValue Ptr = getValue(SV); 3640 3641 Type *Ty = I.getType(); 3642 3643 bool isVolatile = I.isVolatile(); 3644 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3645 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3646 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3647 unsigned Alignment = I.getAlignment(); 3648 3649 AAMDNodes AAInfo; 3650 I.getAAMetadata(AAInfo); 3651 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3652 3653 SmallVector<EVT, 4> ValueVTs; 3654 SmallVector<uint64_t, 4> Offsets; 3655 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3656 unsigned NumValues = ValueVTs.size(); 3657 if (NumValues == 0) 3658 return; 3659 3660 SDValue Root; 3661 bool ConstantMemory = false; 3662 if (isVolatile || NumValues > MaxParallelChains) 3663 // Serialize volatile loads with other side effects. 3664 Root = getRoot(); 3665 else if (AA && AA->pointsToConstantMemory(MemoryLocation( 3666 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3667 // Do not serialize (non-volatile) loads of constant memory with anything. 3668 Root = DAG.getEntryNode(); 3669 ConstantMemory = true; 3670 } else { 3671 // Do not serialize non-volatile loads against each other. 3672 Root = DAG.getRoot(); 3673 } 3674 3675 SDLoc dl = getCurSDLoc(); 3676 3677 if (isVolatile) 3678 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3679 3680 // An aggregate load cannot wrap around the address space, so offsets to its 3681 // parts don't wrap either. 3682 SDNodeFlags Flags; 3683 Flags.setNoUnsignedWrap(true); 3684 3685 SmallVector<SDValue, 4> Values(NumValues); 3686 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3687 EVT PtrVT = Ptr.getValueType(); 3688 unsigned ChainI = 0; 3689 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3690 // Serializing loads here may result in excessive register pressure, and 3691 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3692 // could recover a bit by hoisting nodes upward in the chain by recognizing 3693 // they are side-effect free or do not alias. The optimizer should really 3694 // avoid this case by converting large object/array copies to llvm.memcpy 3695 // (MaxParallelChains should always remain as failsafe). 3696 if (ChainI == MaxParallelChains) { 3697 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3698 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3699 makeArrayRef(Chains.data(), ChainI)); 3700 Root = Chain; 3701 ChainI = 0; 3702 } 3703 SDValue A = DAG.getNode(ISD::ADD, dl, 3704 PtrVT, Ptr, 3705 DAG.getConstant(Offsets[i], dl, PtrVT), 3706 Flags); 3707 auto MMOFlags = MachineMemOperand::MONone; 3708 if (isVolatile) 3709 MMOFlags |= MachineMemOperand::MOVolatile; 3710 if (isNonTemporal) 3711 MMOFlags |= MachineMemOperand::MONonTemporal; 3712 if (isInvariant) 3713 MMOFlags |= MachineMemOperand::MOInvariant; 3714 if (isDereferenceable) 3715 MMOFlags |= MachineMemOperand::MODereferenceable; 3716 MMOFlags |= TLI.getMMOFlags(I); 3717 3718 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3719 MachinePointerInfo(SV, Offsets[i]), Alignment, 3720 MMOFlags, AAInfo, Ranges); 3721 3722 Values[i] = L; 3723 Chains[ChainI] = L.getValue(1); 3724 } 3725 3726 if (!ConstantMemory) { 3727 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3728 makeArrayRef(Chains.data(), ChainI)); 3729 if (isVolatile) 3730 DAG.setRoot(Chain); 3731 else 3732 PendingLoads.push_back(Chain); 3733 } 3734 3735 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3736 DAG.getVTList(ValueVTs), Values)); 3737 } 3738 3739 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3740 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3741 "call visitStoreToSwiftError when backend supports swifterror"); 3742 3743 SmallVector<EVT, 4> ValueVTs; 3744 SmallVector<uint64_t, 4> Offsets; 3745 const Value *SrcV = I.getOperand(0); 3746 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3747 SrcV->getType(), ValueVTs, &Offsets); 3748 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3749 "expect a single EVT for swifterror"); 3750 3751 SDValue Src = getValue(SrcV); 3752 // Create a virtual register, then update the virtual register. 3753 unsigned VReg; bool CreatedVReg; 3754 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3755 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3756 // Chain can be getRoot or getControlRoot. 3757 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3758 SDValue(Src.getNode(), Src.getResNo())); 3759 DAG.setRoot(CopyNode); 3760 if (CreatedVReg) 3761 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3762 } 3763 3764 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3765 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3766 "call visitLoadFromSwiftError when backend supports swifterror"); 3767 3768 assert(!I.isVolatile() && 3769 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3770 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3771 "Support volatile, non temporal, invariant for load_from_swift_error"); 3772 3773 const Value *SV = I.getOperand(0); 3774 Type *Ty = I.getType(); 3775 AAMDNodes AAInfo; 3776 I.getAAMetadata(AAInfo); 3777 assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( 3778 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && 3779 "load_from_swift_error should not be constant memory"); 3780 3781 SmallVector<EVT, 4> ValueVTs; 3782 SmallVector<uint64_t, 4> Offsets; 3783 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3784 ValueVTs, &Offsets); 3785 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3786 "expect a single EVT for swifterror"); 3787 3788 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3789 SDValue L = DAG.getCopyFromReg( 3790 getRoot(), getCurSDLoc(), 3791 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3792 ValueVTs[0]); 3793 3794 setValue(&I, L); 3795 } 3796 3797 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3798 if (I.isAtomic()) 3799 return visitAtomicStore(I); 3800 3801 const Value *SrcV = I.getOperand(0); 3802 const Value *PtrV = I.getOperand(1); 3803 3804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3805 if (TLI.supportSwiftError()) { 3806 // Swifterror values can come from either a function parameter with 3807 // swifterror attribute or an alloca with swifterror attribute. 3808 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3809 if (Arg->hasSwiftErrorAttr()) 3810 return visitStoreToSwiftError(I); 3811 } 3812 3813 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3814 if (Alloca->isSwiftError()) 3815 return visitStoreToSwiftError(I); 3816 } 3817 } 3818 3819 SmallVector<EVT, 4> ValueVTs; 3820 SmallVector<uint64_t, 4> Offsets; 3821 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3822 SrcV->getType(), ValueVTs, &Offsets); 3823 unsigned NumValues = ValueVTs.size(); 3824 if (NumValues == 0) 3825 return; 3826 3827 // Get the lowered operands. Note that we do this after 3828 // checking if NumResults is zero, because with zero results 3829 // the operands won't have values in the map. 3830 SDValue Src = getValue(SrcV); 3831 SDValue Ptr = getValue(PtrV); 3832 3833 SDValue Root = getRoot(); 3834 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3835 SDLoc dl = getCurSDLoc(); 3836 EVT PtrVT = Ptr.getValueType(); 3837 unsigned Alignment = I.getAlignment(); 3838 AAMDNodes AAInfo; 3839 I.getAAMetadata(AAInfo); 3840 3841 auto MMOFlags = MachineMemOperand::MONone; 3842 if (I.isVolatile()) 3843 MMOFlags |= MachineMemOperand::MOVolatile; 3844 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3845 MMOFlags |= MachineMemOperand::MONonTemporal; 3846 MMOFlags |= TLI.getMMOFlags(I); 3847 3848 // An aggregate load cannot wrap around the address space, so offsets to its 3849 // parts don't wrap either. 3850 SDNodeFlags Flags; 3851 Flags.setNoUnsignedWrap(true); 3852 3853 unsigned ChainI = 0; 3854 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3855 // See visitLoad comments. 3856 if (ChainI == MaxParallelChains) { 3857 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3858 makeArrayRef(Chains.data(), ChainI)); 3859 Root = Chain; 3860 ChainI = 0; 3861 } 3862 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3863 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3864 SDValue St = DAG.getStore( 3865 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3866 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3867 Chains[ChainI] = St; 3868 } 3869 3870 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3871 makeArrayRef(Chains.data(), ChainI)); 3872 DAG.setRoot(StoreNode); 3873 } 3874 3875 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3876 bool IsCompressing) { 3877 SDLoc sdl = getCurSDLoc(); 3878 3879 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3880 unsigned& Alignment) { 3881 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3882 Src0 = I.getArgOperand(0); 3883 Ptr = I.getArgOperand(1); 3884 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3885 Mask = I.getArgOperand(3); 3886 }; 3887 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3888 unsigned& Alignment) { 3889 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3890 Src0 = I.getArgOperand(0); 3891 Ptr = I.getArgOperand(1); 3892 Mask = I.getArgOperand(2); 3893 Alignment = 0; 3894 }; 3895 3896 Value *PtrOperand, *MaskOperand, *Src0Operand; 3897 unsigned Alignment; 3898 if (IsCompressing) 3899 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3900 else 3901 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3902 3903 SDValue Ptr = getValue(PtrOperand); 3904 SDValue Src0 = getValue(Src0Operand); 3905 SDValue Mask = getValue(MaskOperand); 3906 3907 EVT VT = Src0.getValueType(); 3908 if (!Alignment) 3909 Alignment = DAG.getEVTAlignment(VT); 3910 3911 AAMDNodes AAInfo; 3912 I.getAAMetadata(AAInfo); 3913 3914 MachineMemOperand *MMO = 3915 DAG.getMachineFunction(). 3916 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3917 MachineMemOperand::MOStore, VT.getStoreSize(), 3918 Alignment, AAInfo); 3919 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3920 MMO, false /* Truncating */, 3921 IsCompressing); 3922 DAG.setRoot(StoreNode); 3923 setValue(&I, StoreNode); 3924 } 3925 3926 // Get a uniform base for the Gather/Scatter intrinsic. 3927 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3928 // We try to represent it as a base pointer + vector of indices. 3929 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3930 // The first operand of the GEP may be a single pointer or a vector of pointers 3931 // Example: 3932 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3933 // or 3934 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3935 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3936 // 3937 // When the first GEP operand is a single pointer - it is the uniform base we 3938 // are looking for. If first operand of the GEP is a splat vector - we 3939 // extract the splat value and use it as a uniform base. 3940 // In all other cases the function returns 'false'. 3941 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3942 SDValue &Scale, SelectionDAGBuilder* SDB) { 3943 SelectionDAG& DAG = SDB->DAG; 3944 LLVMContext &Context = *DAG.getContext(); 3945 3946 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3947 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3948 if (!GEP) 3949 return false; 3950 3951 const Value *GEPPtr = GEP->getPointerOperand(); 3952 if (!GEPPtr->getType()->isVectorTy()) 3953 Ptr = GEPPtr; 3954 else if (!(Ptr = getSplatValue(GEPPtr))) 3955 return false; 3956 3957 unsigned FinalIndex = GEP->getNumOperands() - 1; 3958 Value *IndexVal = GEP->getOperand(FinalIndex); 3959 3960 // Ensure all the other indices are 0. 3961 for (unsigned i = 1; i < FinalIndex; ++i) { 3962 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3963 if (!C || !C->isZero()) 3964 return false; 3965 } 3966 3967 // The operands of the GEP may be defined in another basic block. 3968 // In this case we'll not find nodes for the operands. 3969 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3970 return false; 3971 3972 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3973 const DataLayout &DL = DAG.getDataLayout(); 3974 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 3975 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 3976 Base = SDB->getValue(Ptr); 3977 Index = SDB->getValue(IndexVal); 3978 3979 if (!Index.getValueType().isVector()) { 3980 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3981 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3982 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 3983 } 3984 return true; 3985 } 3986 3987 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3988 SDLoc sdl = getCurSDLoc(); 3989 3990 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3991 const Value *Ptr = I.getArgOperand(1); 3992 SDValue Src0 = getValue(I.getArgOperand(0)); 3993 SDValue Mask = getValue(I.getArgOperand(3)); 3994 EVT VT = Src0.getValueType(); 3995 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3996 if (!Alignment) 3997 Alignment = DAG.getEVTAlignment(VT); 3998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3999 4000 AAMDNodes AAInfo; 4001 I.getAAMetadata(AAInfo); 4002 4003 SDValue Base; 4004 SDValue Index; 4005 SDValue Scale; 4006 const Value *BasePtr = Ptr; 4007 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4008 4009 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4010 MachineMemOperand *MMO = DAG.getMachineFunction(). 4011 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4012 MachineMemOperand::MOStore, VT.getStoreSize(), 4013 Alignment, AAInfo); 4014 if (!UniformBase) { 4015 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4016 Index = getValue(Ptr); 4017 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4018 } 4019 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4020 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4021 Ops, MMO); 4022 DAG.setRoot(Scatter); 4023 setValue(&I, Scatter); 4024 } 4025 4026 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4027 SDLoc sdl = getCurSDLoc(); 4028 4029 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4030 unsigned& Alignment) { 4031 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4032 Ptr = I.getArgOperand(0); 4033 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4034 Mask = I.getArgOperand(2); 4035 Src0 = I.getArgOperand(3); 4036 }; 4037 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4038 unsigned& Alignment) { 4039 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4040 Ptr = I.getArgOperand(0); 4041 Alignment = 0; 4042 Mask = I.getArgOperand(1); 4043 Src0 = I.getArgOperand(2); 4044 }; 4045 4046 Value *PtrOperand, *MaskOperand, *Src0Operand; 4047 unsigned Alignment; 4048 if (IsExpanding) 4049 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4050 else 4051 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4052 4053 SDValue Ptr = getValue(PtrOperand); 4054 SDValue Src0 = getValue(Src0Operand); 4055 SDValue Mask = getValue(MaskOperand); 4056 4057 EVT VT = Src0.getValueType(); 4058 if (!Alignment) 4059 Alignment = DAG.getEVTAlignment(VT); 4060 4061 AAMDNodes AAInfo; 4062 I.getAAMetadata(AAInfo); 4063 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4064 4065 // Do not serialize masked loads of constant memory with anything. 4066 bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( 4067 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 4068 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4069 4070 MachineMemOperand *MMO = 4071 DAG.getMachineFunction(). 4072 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4073 MachineMemOperand::MOLoad, VT.getStoreSize(), 4074 Alignment, AAInfo, Ranges); 4075 4076 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4077 ISD::NON_EXTLOAD, IsExpanding); 4078 if (AddToChain) 4079 PendingLoads.push_back(Load.getValue(1)); 4080 setValue(&I, Load); 4081 } 4082 4083 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4084 SDLoc sdl = getCurSDLoc(); 4085 4086 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4087 const Value *Ptr = I.getArgOperand(0); 4088 SDValue Src0 = getValue(I.getArgOperand(3)); 4089 SDValue Mask = getValue(I.getArgOperand(2)); 4090 4091 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4092 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4093 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4094 if (!Alignment) 4095 Alignment = DAG.getEVTAlignment(VT); 4096 4097 AAMDNodes AAInfo; 4098 I.getAAMetadata(AAInfo); 4099 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4100 4101 SDValue Root = DAG.getRoot(); 4102 SDValue Base; 4103 SDValue Index; 4104 SDValue Scale; 4105 const Value *BasePtr = Ptr; 4106 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4107 bool ConstantMemory = false; 4108 if (UniformBase && 4109 AA && AA->pointsToConstantMemory(MemoryLocation( 4110 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 4111 AAInfo))) { 4112 // Do not serialize (non-volatile) loads of constant memory with anything. 4113 Root = DAG.getEntryNode(); 4114 ConstantMemory = true; 4115 } 4116 4117 MachineMemOperand *MMO = 4118 DAG.getMachineFunction(). 4119 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4120 MachineMemOperand::MOLoad, VT.getStoreSize(), 4121 Alignment, AAInfo, Ranges); 4122 4123 if (!UniformBase) { 4124 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4125 Index = getValue(Ptr); 4126 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4127 } 4128 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4129 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4130 Ops, MMO); 4131 4132 SDValue OutChain = Gather.getValue(1); 4133 if (!ConstantMemory) 4134 PendingLoads.push_back(OutChain); 4135 setValue(&I, Gather); 4136 } 4137 4138 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4139 SDLoc dl = getCurSDLoc(); 4140 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4141 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4142 SyncScope::ID SSID = I.getSyncScopeID(); 4143 4144 SDValue InChain = getRoot(); 4145 4146 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4147 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4148 SDValue L = DAG.getAtomicCmpSwap( 4149 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4150 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4151 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4152 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4153 4154 SDValue OutChain = L.getValue(2); 4155 4156 setValue(&I, L); 4157 DAG.setRoot(OutChain); 4158 } 4159 4160 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4161 SDLoc dl = getCurSDLoc(); 4162 ISD::NodeType NT; 4163 switch (I.getOperation()) { 4164 default: llvm_unreachable("Unknown atomicrmw operation"); 4165 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4166 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4167 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4168 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4169 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4170 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4171 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4172 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4173 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4174 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4175 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4176 } 4177 AtomicOrdering Order = I.getOrdering(); 4178 SyncScope::ID SSID = I.getSyncScopeID(); 4179 4180 SDValue InChain = getRoot(); 4181 4182 SDValue L = 4183 DAG.getAtomic(NT, dl, 4184 getValue(I.getValOperand()).getSimpleValueType(), 4185 InChain, 4186 getValue(I.getPointerOperand()), 4187 getValue(I.getValOperand()), 4188 I.getPointerOperand(), 4189 /* Alignment=*/ 0, Order, SSID); 4190 4191 SDValue OutChain = L.getValue(1); 4192 4193 setValue(&I, L); 4194 DAG.setRoot(OutChain); 4195 } 4196 4197 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4198 SDLoc dl = getCurSDLoc(); 4199 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4200 SDValue Ops[3]; 4201 Ops[0] = getRoot(); 4202 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4203 TLI.getFenceOperandTy(DAG.getDataLayout())); 4204 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4205 TLI.getFenceOperandTy(DAG.getDataLayout())); 4206 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4207 } 4208 4209 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4210 SDLoc dl = getCurSDLoc(); 4211 AtomicOrdering Order = I.getOrdering(); 4212 SyncScope::ID SSID = I.getSyncScopeID(); 4213 4214 SDValue InChain = getRoot(); 4215 4216 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4217 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4218 4219 if (!TLI.supportsUnalignedAtomics() && 4220 I.getAlignment() < VT.getStoreSize()) 4221 report_fatal_error("Cannot generate unaligned atomic load"); 4222 4223 MachineMemOperand *MMO = 4224 DAG.getMachineFunction(). 4225 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4226 MachineMemOperand::MOVolatile | 4227 MachineMemOperand::MOLoad, 4228 VT.getStoreSize(), 4229 I.getAlignment() ? I.getAlignment() : 4230 DAG.getEVTAlignment(VT), 4231 AAMDNodes(), nullptr, SSID, Order); 4232 4233 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4234 SDValue L = 4235 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4236 getValue(I.getPointerOperand()), MMO); 4237 4238 SDValue OutChain = L.getValue(1); 4239 4240 setValue(&I, L); 4241 DAG.setRoot(OutChain); 4242 } 4243 4244 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4245 SDLoc dl = getCurSDLoc(); 4246 4247 AtomicOrdering Order = I.getOrdering(); 4248 SyncScope::ID SSID = I.getSyncScopeID(); 4249 4250 SDValue InChain = getRoot(); 4251 4252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4253 EVT VT = 4254 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4255 4256 if (I.getAlignment() < VT.getStoreSize()) 4257 report_fatal_error("Cannot generate unaligned atomic store"); 4258 4259 SDValue OutChain = 4260 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4261 InChain, 4262 getValue(I.getPointerOperand()), 4263 getValue(I.getValueOperand()), 4264 I.getPointerOperand(), I.getAlignment(), 4265 Order, SSID); 4266 4267 DAG.setRoot(OutChain); 4268 } 4269 4270 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4271 /// node. 4272 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4273 unsigned Intrinsic) { 4274 // Ignore the callsite's attributes. A specific call site may be marked with 4275 // readnone, but the lowering code will expect the chain based on the 4276 // definition. 4277 const Function *F = I.getCalledFunction(); 4278 bool HasChain = !F->doesNotAccessMemory(); 4279 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4280 4281 // Build the operand list. 4282 SmallVector<SDValue, 8> Ops; 4283 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4284 if (OnlyLoad) { 4285 // We don't need to serialize loads against other loads. 4286 Ops.push_back(DAG.getRoot()); 4287 } else { 4288 Ops.push_back(getRoot()); 4289 } 4290 } 4291 4292 // Info is set by getTgtMemInstrinsic 4293 TargetLowering::IntrinsicInfo Info; 4294 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4295 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4296 DAG.getMachineFunction(), 4297 Intrinsic); 4298 4299 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4300 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4301 Info.opc == ISD::INTRINSIC_W_CHAIN) 4302 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4303 TLI.getPointerTy(DAG.getDataLayout()))); 4304 4305 // Add all operands of the call to the operand list. 4306 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4307 SDValue Op = getValue(I.getArgOperand(i)); 4308 Ops.push_back(Op); 4309 } 4310 4311 SmallVector<EVT, 4> ValueVTs; 4312 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4313 4314 if (HasChain) 4315 ValueVTs.push_back(MVT::Other); 4316 4317 SDVTList VTs = DAG.getVTList(ValueVTs); 4318 4319 // Create the node. 4320 SDValue Result; 4321 if (IsTgtIntrinsic) { 4322 // This is target intrinsic that touches memory 4323 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4324 Ops, Info.memVT, 4325 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4326 Info.flags, Info.size); 4327 } else if (!HasChain) { 4328 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4329 } else if (!I.getType()->isVoidTy()) { 4330 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4331 } else { 4332 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4333 } 4334 4335 if (HasChain) { 4336 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4337 if (OnlyLoad) 4338 PendingLoads.push_back(Chain); 4339 else 4340 DAG.setRoot(Chain); 4341 } 4342 4343 if (!I.getType()->isVoidTy()) { 4344 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4345 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4346 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4347 } else 4348 Result = lowerRangeToAssertZExt(DAG, I, Result); 4349 4350 setValue(&I, Result); 4351 } 4352 } 4353 4354 /// GetSignificand - Get the significand and build it into a floating-point 4355 /// number with exponent of 1: 4356 /// 4357 /// Op = (Op & 0x007fffff) | 0x3f800000; 4358 /// 4359 /// where Op is the hexadecimal representation of floating point value. 4360 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4361 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4362 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4363 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4364 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4365 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4366 } 4367 4368 /// GetExponent - Get the exponent: 4369 /// 4370 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4371 /// 4372 /// where Op is the hexadecimal representation of floating point value. 4373 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4374 const TargetLowering &TLI, const SDLoc &dl) { 4375 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4376 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4377 SDValue t1 = DAG.getNode( 4378 ISD::SRL, dl, MVT::i32, t0, 4379 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4380 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4381 DAG.getConstant(127, dl, MVT::i32)); 4382 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4383 } 4384 4385 /// getF32Constant - Get 32-bit floating point constant. 4386 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4387 const SDLoc &dl) { 4388 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4389 MVT::f32); 4390 } 4391 4392 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4393 SelectionDAG &DAG) { 4394 // TODO: What fast-math-flags should be set on the floating-point nodes? 4395 4396 // IntegerPartOfX = ((int32_t)(t0); 4397 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4398 4399 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4400 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4401 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4402 4403 // IntegerPartOfX <<= 23; 4404 IntegerPartOfX = DAG.getNode( 4405 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4406 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4407 DAG.getDataLayout()))); 4408 4409 SDValue TwoToFractionalPartOfX; 4410 if (LimitFloatPrecision <= 6) { 4411 // For floating-point precision of 6: 4412 // 4413 // TwoToFractionalPartOfX = 4414 // 0.997535578f + 4415 // (0.735607626f + 0.252464424f * x) * x; 4416 // 4417 // error 0.0144103317, which is 6 bits 4418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4419 getF32Constant(DAG, 0x3e814304, dl)); 4420 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4421 getF32Constant(DAG, 0x3f3c50c8, dl)); 4422 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4423 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4424 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4425 } else if (LimitFloatPrecision <= 12) { 4426 // For floating-point precision of 12: 4427 // 4428 // TwoToFractionalPartOfX = 4429 // 0.999892986f + 4430 // (0.696457318f + 4431 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4432 // 4433 // error 0.000107046256, which is 13 to 14 bits 4434 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4435 getF32Constant(DAG, 0x3da235e3, dl)); 4436 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4437 getF32Constant(DAG, 0x3e65b8f3, dl)); 4438 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4439 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4440 getF32Constant(DAG, 0x3f324b07, dl)); 4441 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4442 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4443 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4444 } else { // LimitFloatPrecision <= 18 4445 // For floating-point precision of 18: 4446 // 4447 // TwoToFractionalPartOfX = 4448 // 0.999999982f + 4449 // (0.693148872f + 4450 // (0.240227044f + 4451 // (0.554906021e-1f + 4452 // (0.961591928e-2f + 4453 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4454 // error 2.47208000*10^(-7), which is better than 18 bits 4455 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4456 getF32Constant(DAG, 0x3924b03e, dl)); 4457 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4458 getF32Constant(DAG, 0x3ab24b87, dl)); 4459 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4460 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4461 getF32Constant(DAG, 0x3c1d8c17, dl)); 4462 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4463 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4464 getF32Constant(DAG, 0x3d634a1d, dl)); 4465 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4466 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4467 getF32Constant(DAG, 0x3e75fe14, dl)); 4468 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4469 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4470 getF32Constant(DAG, 0x3f317234, dl)); 4471 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4472 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4473 getF32Constant(DAG, 0x3f800000, dl)); 4474 } 4475 4476 // Add the exponent into the result in integer domain. 4477 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4478 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4479 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4480 } 4481 4482 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4483 /// limited-precision mode. 4484 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4485 const TargetLowering &TLI) { 4486 if (Op.getValueType() == MVT::f32 && 4487 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4488 4489 // Put the exponent in the right bit position for later addition to the 4490 // final result: 4491 // 4492 // #define LOG2OFe 1.4426950f 4493 // t0 = Op * LOG2OFe 4494 4495 // TODO: What fast-math-flags should be set here? 4496 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4497 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4498 return getLimitedPrecisionExp2(t0, dl, DAG); 4499 } 4500 4501 // No special expansion. 4502 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4503 } 4504 4505 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4506 /// limited-precision mode. 4507 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4508 const TargetLowering &TLI) { 4509 // TODO: What fast-math-flags should be set on the floating-point nodes? 4510 4511 if (Op.getValueType() == MVT::f32 && 4512 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4513 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4514 4515 // Scale the exponent by log(2) [0.69314718f]. 4516 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4517 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4518 getF32Constant(DAG, 0x3f317218, dl)); 4519 4520 // Get the significand and build it into a floating-point number with 4521 // exponent of 1. 4522 SDValue X = GetSignificand(DAG, Op1, dl); 4523 4524 SDValue LogOfMantissa; 4525 if (LimitFloatPrecision <= 6) { 4526 // For floating-point precision of 6: 4527 // 4528 // LogofMantissa = 4529 // -1.1609546f + 4530 // (1.4034025f - 0.23903021f * x) * x; 4531 // 4532 // error 0.0034276066, which is better than 8 bits 4533 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4534 getF32Constant(DAG, 0xbe74c456, dl)); 4535 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4536 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4537 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4538 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4539 getF32Constant(DAG, 0x3f949a29, dl)); 4540 } else if (LimitFloatPrecision <= 12) { 4541 // For floating-point precision of 12: 4542 // 4543 // LogOfMantissa = 4544 // -1.7417939f + 4545 // (2.8212026f + 4546 // (-1.4699568f + 4547 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4548 // 4549 // error 0.000061011436, which is 14 bits 4550 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4551 getF32Constant(DAG, 0xbd67b6d6, dl)); 4552 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4553 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4554 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4555 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4556 getF32Constant(DAG, 0x3fbc278b, dl)); 4557 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4558 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4559 getF32Constant(DAG, 0x40348e95, dl)); 4560 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4561 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4562 getF32Constant(DAG, 0x3fdef31a, dl)); 4563 } else { // LimitFloatPrecision <= 18 4564 // For floating-point precision of 18: 4565 // 4566 // LogOfMantissa = 4567 // -2.1072184f + 4568 // (4.2372794f + 4569 // (-3.7029485f + 4570 // (2.2781945f + 4571 // (-0.87823314f + 4572 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4573 // 4574 // error 0.0000023660568, which is better than 18 bits 4575 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4576 getF32Constant(DAG, 0xbc91e5ac, dl)); 4577 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4578 getF32Constant(DAG, 0x3e4350aa, dl)); 4579 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4580 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4581 getF32Constant(DAG, 0x3f60d3e3, dl)); 4582 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4583 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4584 getF32Constant(DAG, 0x4011cdf0, dl)); 4585 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4586 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4587 getF32Constant(DAG, 0x406cfd1c, dl)); 4588 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4589 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4590 getF32Constant(DAG, 0x408797cb, dl)); 4591 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4592 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4593 getF32Constant(DAG, 0x4006dcab, dl)); 4594 } 4595 4596 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4597 } 4598 4599 // No special expansion. 4600 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4601 } 4602 4603 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4604 /// limited-precision mode. 4605 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4606 const TargetLowering &TLI) { 4607 // TODO: What fast-math-flags should be set on the floating-point nodes? 4608 4609 if (Op.getValueType() == MVT::f32 && 4610 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4611 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4612 4613 // Get the exponent. 4614 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4615 4616 // Get the significand and build it into a floating-point number with 4617 // exponent of 1. 4618 SDValue X = GetSignificand(DAG, Op1, dl); 4619 4620 // Different possible minimax approximations of significand in 4621 // floating-point for various degrees of accuracy over [1,2]. 4622 SDValue Log2ofMantissa; 4623 if (LimitFloatPrecision <= 6) { 4624 // For floating-point precision of 6: 4625 // 4626 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4627 // 4628 // error 0.0049451742, which is more than 7 bits 4629 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4630 getF32Constant(DAG, 0xbeb08fe0, dl)); 4631 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4632 getF32Constant(DAG, 0x40019463, dl)); 4633 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4634 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4635 getF32Constant(DAG, 0x3fd6633d, dl)); 4636 } else if (LimitFloatPrecision <= 12) { 4637 // For floating-point precision of 12: 4638 // 4639 // Log2ofMantissa = 4640 // -2.51285454f + 4641 // (4.07009056f + 4642 // (-2.12067489f + 4643 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4644 // 4645 // error 0.0000876136000, which is better than 13 bits 4646 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4647 getF32Constant(DAG, 0xbda7262e, dl)); 4648 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4649 getF32Constant(DAG, 0x3f25280b, dl)); 4650 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4651 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4652 getF32Constant(DAG, 0x4007b923, dl)); 4653 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4654 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4655 getF32Constant(DAG, 0x40823e2f, dl)); 4656 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4657 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4658 getF32Constant(DAG, 0x4020d29c, dl)); 4659 } else { // LimitFloatPrecision <= 18 4660 // For floating-point precision of 18: 4661 // 4662 // Log2ofMantissa = 4663 // -3.0400495f + 4664 // (6.1129976f + 4665 // (-5.3420409f + 4666 // (3.2865683f + 4667 // (-1.2669343f + 4668 // (0.27515199f - 4669 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4670 // 4671 // error 0.0000018516, which is better than 18 bits 4672 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4673 getF32Constant(DAG, 0xbcd2769e, dl)); 4674 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4675 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4676 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4677 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4678 getF32Constant(DAG, 0x3fa22ae7, dl)); 4679 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4680 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4681 getF32Constant(DAG, 0x40525723, dl)); 4682 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4683 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4684 getF32Constant(DAG, 0x40aaf200, dl)); 4685 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4686 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4687 getF32Constant(DAG, 0x40c39dad, dl)); 4688 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4689 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4690 getF32Constant(DAG, 0x4042902c, dl)); 4691 } 4692 4693 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4694 } 4695 4696 // No special expansion. 4697 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4698 } 4699 4700 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4701 /// limited-precision mode. 4702 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4703 const TargetLowering &TLI) { 4704 // TODO: What fast-math-flags should be set on the floating-point nodes? 4705 4706 if (Op.getValueType() == MVT::f32 && 4707 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4708 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4709 4710 // Scale the exponent by log10(2) [0.30102999f]. 4711 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4712 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4713 getF32Constant(DAG, 0x3e9a209a, dl)); 4714 4715 // Get the significand and build it into a floating-point number with 4716 // exponent of 1. 4717 SDValue X = GetSignificand(DAG, Op1, dl); 4718 4719 SDValue Log10ofMantissa; 4720 if (LimitFloatPrecision <= 6) { 4721 // For floating-point precision of 6: 4722 // 4723 // Log10ofMantissa = 4724 // -0.50419619f + 4725 // (0.60948995f - 0.10380950f * x) * x; 4726 // 4727 // error 0.0014886165, which is 6 bits 4728 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4729 getF32Constant(DAG, 0xbdd49a13, dl)); 4730 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4731 getF32Constant(DAG, 0x3f1c0789, dl)); 4732 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4733 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4734 getF32Constant(DAG, 0x3f011300, dl)); 4735 } else if (LimitFloatPrecision <= 12) { 4736 // For floating-point precision of 12: 4737 // 4738 // Log10ofMantissa = 4739 // -0.64831180f + 4740 // (0.91751397f + 4741 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4742 // 4743 // error 0.00019228036, which is better than 12 bits 4744 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4745 getF32Constant(DAG, 0x3d431f31, dl)); 4746 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4747 getF32Constant(DAG, 0x3ea21fb2, dl)); 4748 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4749 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4750 getF32Constant(DAG, 0x3f6ae232, dl)); 4751 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4752 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4753 getF32Constant(DAG, 0x3f25f7c3, dl)); 4754 } else { // LimitFloatPrecision <= 18 4755 // For floating-point precision of 18: 4756 // 4757 // Log10ofMantissa = 4758 // -0.84299375f + 4759 // (1.5327582f + 4760 // (-1.0688956f + 4761 // (0.49102474f + 4762 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4763 // 4764 // error 0.0000037995730, which is better than 18 bits 4765 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4766 getF32Constant(DAG, 0x3c5d51ce, dl)); 4767 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4768 getF32Constant(DAG, 0x3e00685a, dl)); 4769 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4770 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4771 getF32Constant(DAG, 0x3efb6798, dl)); 4772 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4773 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4774 getF32Constant(DAG, 0x3f88d192, dl)); 4775 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4776 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4777 getF32Constant(DAG, 0x3fc4316c, dl)); 4778 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4779 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4780 getF32Constant(DAG, 0x3f57ce70, dl)); 4781 } 4782 4783 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4784 } 4785 4786 // No special expansion. 4787 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4788 } 4789 4790 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4791 /// limited-precision mode. 4792 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4793 const TargetLowering &TLI) { 4794 if (Op.getValueType() == MVT::f32 && 4795 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4796 return getLimitedPrecisionExp2(Op, dl, DAG); 4797 4798 // No special expansion. 4799 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4800 } 4801 4802 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4803 /// limited-precision mode with x == 10.0f. 4804 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4805 SelectionDAG &DAG, const TargetLowering &TLI) { 4806 bool IsExp10 = false; 4807 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4808 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4809 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4810 APFloat Ten(10.0f); 4811 IsExp10 = LHSC->isExactlyValue(Ten); 4812 } 4813 } 4814 4815 // TODO: What fast-math-flags should be set on the FMUL node? 4816 if (IsExp10) { 4817 // Put the exponent in the right bit position for later addition to the 4818 // final result: 4819 // 4820 // #define LOG2OF10 3.3219281f 4821 // t0 = Op * LOG2OF10; 4822 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4823 getF32Constant(DAG, 0x40549a78, dl)); 4824 return getLimitedPrecisionExp2(t0, dl, DAG); 4825 } 4826 4827 // No special expansion. 4828 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4829 } 4830 4831 /// ExpandPowI - Expand a llvm.powi intrinsic. 4832 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4833 SelectionDAG &DAG) { 4834 // If RHS is a constant, we can expand this out to a multiplication tree, 4835 // otherwise we end up lowering to a call to __powidf2 (for example). When 4836 // optimizing for size, we only want to do this if the expansion would produce 4837 // a small number of multiplies, otherwise we do the full expansion. 4838 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4839 // Get the exponent as a positive value. 4840 unsigned Val = RHSC->getSExtValue(); 4841 if ((int)Val < 0) Val = -Val; 4842 4843 // powi(x, 0) -> 1.0 4844 if (Val == 0) 4845 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4846 4847 const Function &F = DAG.getMachineFunction().getFunction(); 4848 if (!F.optForSize() || 4849 // If optimizing for size, don't insert too many multiplies. 4850 // This inserts up to 5 multiplies. 4851 countPopulation(Val) + Log2_32(Val) < 7) { 4852 // We use the simple binary decomposition method to generate the multiply 4853 // sequence. There are more optimal ways to do this (for example, 4854 // powi(x,15) generates one more multiply than it should), but this has 4855 // the benefit of being both really simple and much better than a libcall. 4856 SDValue Res; // Logically starts equal to 1.0 4857 SDValue CurSquare = LHS; 4858 // TODO: Intrinsics should have fast-math-flags that propagate to these 4859 // nodes. 4860 while (Val) { 4861 if (Val & 1) { 4862 if (Res.getNode()) 4863 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4864 else 4865 Res = CurSquare; // 1.0*CurSquare. 4866 } 4867 4868 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4869 CurSquare, CurSquare); 4870 Val >>= 1; 4871 } 4872 4873 // If the original was negative, invert the result, producing 1/(x*x*x). 4874 if (RHSC->getSExtValue() < 0) 4875 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4876 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4877 return Res; 4878 } 4879 } 4880 4881 // Otherwise, expand to a libcall. 4882 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4883 } 4884 4885 // getUnderlyingArgReg - Find underlying register used for a truncated or 4886 // bitcasted argument. 4887 static unsigned getUnderlyingArgReg(const SDValue &N) { 4888 switch (N.getOpcode()) { 4889 case ISD::CopyFromReg: 4890 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4891 case ISD::BITCAST: 4892 case ISD::AssertZext: 4893 case ISD::AssertSext: 4894 case ISD::TRUNCATE: 4895 return getUnderlyingArgReg(N.getOperand(0)); 4896 default: 4897 return 0; 4898 } 4899 } 4900 4901 /// If the DbgValueInst is a dbg_value of a function argument, create the 4902 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4903 /// instruction selection, they will be inserted to the entry BB. 4904 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4905 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4906 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4907 const Argument *Arg = dyn_cast<Argument>(V); 4908 if (!Arg) 4909 return false; 4910 4911 MachineFunction &MF = DAG.getMachineFunction(); 4912 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4913 4914 bool IsIndirect = false; 4915 Optional<MachineOperand> Op; 4916 // Some arguments' frame index is recorded during argument lowering. 4917 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4918 if (FI != std::numeric_limits<int>::max()) 4919 Op = MachineOperand::CreateFI(FI); 4920 4921 if (!Op && N.getNode()) { 4922 unsigned Reg = getUnderlyingArgReg(N); 4923 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4924 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4925 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4926 if (PR) 4927 Reg = PR; 4928 } 4929 if (Reg) { 4930 Op = MachineOperand::CreateReg(Reg, false); 4931 IsIndirect = IsDbgDeclare; 4932 } 4933 } 4934 4935 if (!Op && N.getNode()) 4936 // Check if frame index is available. 4937 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4938 if (FrameIndexSDNode *FINode = 4939 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4940 Op = MachineOperand::CreateFI(FINode->getIndex()); 4941 4942 if (!Op) { 4943 // Check if ValueMap has reg number. 4944 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4945 if (VMI != FuncInfo.ValueMap.end()) { 4946 const auto &TLI = DAG.getTargetLoweringInfo(); 4947 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4948 V->getType(), getABIRegCopyCC(V)); 4949 if (RFV.occupiesMultipleRegs()) { 4950 unsigned Offset = 0; 4951 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4952 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4953 auto FragmentExpr = DIExpression::createFragmentExpression( 4954 Expr, Offset, RegAndSize.second); 4955 if (!FragmentExpr) 4956 continue; 4957 FuncInfo.ArgDbgValues.push_back( 4958 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4959 Op->getReg(), Variable, *FragmentExpr)); 4960 Offset += RegAndSize.second; 4961 } 4962 return true; 4963 } 4964 Op = MachineOperand::CreateReg(VMI->second, false); 4965 IsIndirect = IsDbgDeclare; 4966 } 4967 } 4968 4969 if (!Op) 4970 return false; 4971 4972 assert(Variable->isValidLocationForIntrinsic(DL) && 4973 "Expected inlined-at fields to agree"); 4974 IsIndirect = (Op->isReg()) ? IsIndirect : true; 4975 FuncInfo.ArgDbgValues.push_back( 4976 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4977 *Op, Variable, Expr)); 4978 4979 return true; 4980 } 4981 4982 /// Return the appropriate SDDbgValue based on N. 4983 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4984 DILocalVariable *Variable, 4985 DIExpression *Expr, 4986 const DebugLoc &dl, 4987 unsigned DbgSDNodeOrder) { 4988 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 4989 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4990 // stack slot locations. 4991 // 4992 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 4993 // debug values here after optimization: 4994 // 4995 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 4996 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 4997 // 4998 // Both describe the direct values of their associated variables. 4999 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5000 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5001 } 5002 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5003 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5004 } 5005 5006 // VisualStudio defines setjmp as _setjmp 5007 #if defined(_MSC_VER) && defined(setjmp) && \ 5008 !defined(setjmp_undefined_for_msvc) 5009 # pragma push_macro("setjmp") 5010 # undef setjmp 5011 # define setjmp_undefined_for_msvc 5012 #endif 5013 5014 /// Lower the call to the specified intrinsic function. If we want to emit this 5015 /// as a call to a named external function, return the name. Otherwise, lower it 5016 /// and return null. 5017 const char * 5018 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5019 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5020 SDLoc sdl = getCurSDLoc(); 5021 DebugLoc dl = getCurDebugLoc(); 5022 SDValue Res; 5023 5024 switch (Intrinsic) { 5025 default: 5026 // By default, turn this into a target intrinsic node. 5027 visitTargetIntrinsic(I, Intrinsic); 5028 return nullptr; 5029 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5030 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5031 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5032 case Intrinsic::returnaddress: 5033 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5034 TLI.getPointerTy(DAG.getDataLayout()), 5035 getValue(I.getArgOperand(0)))); 5036 return nullptr; 5037 case Intrinsic::addressofreturnaddress: 5038 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5039 TLI.getPointerTy(DAG.getDataLayout()))); 5040 return nullptr; 5041 case Intrinsic::frameaddress: 5042 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5043 TLI.getPointerTy(DAG.getDataLayout()), 5044 getValue(I.getArgOperand(0)))); 5045 return nullptr; 5046 case Intrinsic::read_register: { 5047 Value *Reg = I.getArgOperand(0); 5048 SDValue Chain = getRoot(); 5049 SDValue RegName = 5050 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5051 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5052 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5053 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5054 setValue(&I, Res); 5055 DAG.setRoot(Res.getValue(1)); 5056 return nullptr; 5057 } 5058 case Intrinsic::write_register: { 5059 Value *Reg = I.getArgOperand(0); 5060 Value *RegValue = I.getArgOperand(1); 5061 SDValue Chain = getRoot(); 5062 SDValue RegName = 5063 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5064 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5065 RegName, getValue(RegValue))); 5066 return nullptr; 5067 } 5068 case Intrinsic::setjmp: 5069 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5070 case Intrinsic::longjmp: 5071 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5072 case Intrinsic::memcpy: { 5073 const auto &MCI = cast<MemCpyInst>(I); 5074 SDValue Op1 = getValue(I.getArgOperand(0)); 5075 SDValue Op2 = getValue(I.getArgOperand(1)); 5076 SDValue Op3 = getValue(I.getArgOperand(2)); 5077 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5078 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5079 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5080 unsigned Align = MinAlign(DstAlign, SrcAlign); 5081 bool isVol = MCI.isVolatile(); 5082 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5083 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5084 // node. 5085 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5086 false, isTC, 5087 MachinePointerInfo(I.getArgOperand(0)), 5088 MachinePointerInfo(I.getArgOperand(1))); 5089 updateDAGForMaybeTailCall(MC); 5090 return nullptr; 5091 } 5092 case Intrinsic::memset: { 5093 const auto &MSI = cast<MemSetInst>(I); 5094 SDValue Op1 = getValue(I.getArgOperand(0)); 5095 SDValue Op2 = getValue(I.getArgOperand(1)); 5096 SDValue Op3 = getValue(I.getArgOperand(2)); 5097 // @llvm.memset defines 0 and 1 to both mean no alignment. 5098 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5099 bool isVol = MSI.isVolatile(); 5100 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5101 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5102 isTC, MachinePointerInfo(I.getArgOperand(0))); 5103 updateDAGForMaybeTailCall(MS); 5104 return nullptr; 5105 } 5106 case Intrinsic::memmove: { 5107 const auto &MMI = cast<MemMoveInst>(I); 5108 SDValue Op1 = getValue(I.getArgOperand(0)); 5109 SDValue Op2 = getValue(I.getArgOperand(1)); 5110 SDValue Op3 = getValue(I.getArgOperand(2)); 5111 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5112 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5113 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5114 unsigned Align = MinAlign(DstAlign, SrcAlign); 5115 bool isVol = MMI.isVolatile(); 5116 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5117 // FIXME: Support passing different dest/src alignments to the memmove DAG 5118 // node. 5119 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5120 isTC, MachinePointerInfo(I.getArgOperand(0)), 5121 MachinePointerInfo(I.getArgOperand(1))); 5122 updateDAGForMaybeTailCall(MM); 5123 return nullptr; 5124 } 5125 case Intrinsic::memcpy_element_unordered_atomic: { 5126 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5127 SDValue Dst = getValue(MI.getRawDest()); 5128 SDValue Src = getValue(MI.getRawSource()); 5129 SDValue Length = getValue(MI.getLength()); 5130 5131 unsigned DstAlign = MI.getDestAlignment(); 5132 unsigned SrcAlign = MI.getSourceAlignment(); 5133 Type *LengthTy = MI.getLength()->getType(); 5134 unsigned ElemSz = MI.getElementSizeInBytes(); 5135 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5136 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5137 SrcAlign, Length, LengthTy, ElemSz, isTC, 5138 MachinePointerInfo(MI.getRawDest()), 5139 MachinePointerInfo(MI.getRawSource())); 5140 updateDAGForMaybeTailCall(MC); 5141 return nullptr; 5142 } 5143 case Intrinsic::memmove_element_unordered_atomic: { 5144 auto &MI = cast<AtomicMemMoveInst>(I); 5145 SDValue Dst = getValue(MI.getRawDest()); 5146 SDValue Src = getValue(MI.getRawSource()); 5147 SDValue Length = getValue(MI.getLength()); 5148 5149 unsigned DstAlign = MI.getDestAlignment(); 5150 unsigned SrcAlign = MI.getSourceAlignment(); 5151 Type *LengthTy = MI.getLength()->getType(); 5152 unsigned ElemSz = MI.getElementSizeInBytes(); 5153 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5154 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5155 SrcAlign, Length, LengthTy, ElemSz, isTC, 5156 MachinePointerInfo(MI.getRawDest()), 5157 MachinePointerInfo(MI.getRawSource())); 5158 updateDAGForMaybeTailCall(MC); 5159 return nullptr; 5160 } 5161 case Intrinsic::memset_element_unordered_atomic: { 5162 auto &MI = cast<AtomicMemSetInst>(I); 5163 SDValue Dst = getValue(MI.getRawDest()); 5164 SDValue Val = getValue(MI.getValue()); 5165 SDValue Length = getValue(MI.getLength()); 5166 5167 unsigned DstAlign = MI.getDestAlignment(); 5168 Type *LengthTy = MI.getLength()->getType(); 5169 unsigned ElemSz = MI.getElementSizeInBytes(); 5170 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5171 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5172 LengthTy, ElemSz, isTC, 5173 MachinePointerInfo(MI.getRawDest())); 5174 updateDAGForMaybeTailCall(MC); 5175 return nullptr; 5176 } 5177 case Intrinsic::dbg_addr: 5178 case Intrinsic::dbg_declare: { 5179 const auto &DI = cast<DbgVariableIntrinsic>(I); 5180 DILocalVariable *Variable = DI.getVariable(); 5181 DIExpression *Expression = DI.getExpression(); 5182 dropDanglingDebugInfo(Variable, Expression); 5183 assert(Variable && "Missing variable"); 5184 5185 // Check if address has undef value. 5186 const Value *Address = DI.getVariableLocation(); 5187 if (!Address || isa<UndefValue>(Address) || 5188 (Address->use_empty() && !isa<Argument>(Address))) { 5189 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5190 return nullptr; 5191 } 5192 5193 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5194 5195 // Check if this variable can be described by a frame index, typically 5196 // either as a static alloca or a byval parameter. 5197 int FI = std::numeric_limits<int>::max(); 5198 if (const auto *AI = 5199 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5200 if (AI->isStaticAlloca()) { 5201 auto I = FuncInfo.StaticAllocaMap.find(AI); 5202 if (I != FuncInfo.StaticAllocaMap.end()) 5203 FI = I->second; 5204 } 5205 } else if (const auto *Arg = dyn_cast<Argument>( 5206 Address->stripInBoundsConstantOffsets())) { 5207 FI = FuncInfo.getArgumentFrameIndex(Arg); 5208 } 5209 5210 // llvm.dbg.addr is control dependent and always generates indirect 5211 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5212 // the MachineFunction variable table. 5213 if (FI != std::numeric_limits<int>::max()) { 5214 if (Intrinsic == Intrinsic::dbg_addr) { 5215 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5216 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5217 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5218 } 5219 return nullptr; 5220 } 5221 5222 SDValue &N = NodeMap[Address]; 5223 if (!N.getNode() && isa<Argument>(Address)) 5224 // Check unused arguments map. 5225 N = UnusedArgNodeMap[Address]; 5226 SDDbgValue *SDV; 5227 if (N.getNode()) { 5228 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5229 Address = BCI->getOperand(0); 5230 // Parameters are handled specially. 5231 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5232 if (isParameter && FINode) { 5233 // Byval parameter. We have a frame index at this point. 5234 SDV = 5235 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5236 /*IsIndirect*/ true, dl, SDNodeOrder); 5237 } else if (isa<Argument>(Address)) { 5238 // Address is an argument, so try to emit its dbg value using 5239 // virtual register info from the FuncInfo.ValueMap. 5240 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5241 return nullptr; 5242 } else { 5243 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5244 true, dl, SDNodeOrder); 5245 } 5246 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5247 } else { 5248 // If Address is an argument then try to emit its dbg value using 5249 // virtual register info from the FuncInfo.ValueMap. 5250 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5251 N)) { 5252 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5253 } 5254 } 5255 return nullptr; 5256 } 5257 case Intrinsic::dbg_label: { 5258 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5259 DILabel *Label = DI.getLabel(); 5260 assert(Label && "Missing label"); 5261 5262 SDDbgLabel *SDV; 5263 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5264 DAG.AddDbgLabel(SDV); 5265 return nullptr; 5266 } 5267 case Intrinsic::dbg_value: { 5268 const DbgValueInst &DI = cast<DbgValueInst>(I); 5269 assert(DI.getVariable() && "Missing variable"); 5270 5271 DILocalVariable *Variable = DI.getVariable(); 5272 DIExpression *Expression = DI.getExpression(); 5273 dropDanglingDebugInfo(Variable, Expression); 5274 const Value *V = DI.getValue(); 5275 if (!V) 5276 return nullptr; 5277 5278 SDDbgValue *SDV; 5279 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5280 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5281 DAG.AddDbgValue(SDV, nullptr, false); 5282 return nullptr; 5283 } 5284 5285 // Do not use getValue() in here; we don't want to generate code at 5286 // this point if it hasn't been done yet. 5287 SDValue N = NodeMap[V]; 5288 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5289 N = UnusedArgNodeMap[V]; 5290 if (N.getNode()) { 5291 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5292 return nullptr; 5293 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5294 DAG.AddDbgValue(SDV, N.getNode(), false); 5295 return nullptr; 5296 } 5297 5298 // PHI nodes have already been selected, so we should know which VReg that 5299 // is assigns to already. 5300 if (isa<PHINode>(V)) { 5301 auto VMI = FuncInfo.ValueMap.find(V); 5302 if (VMI != FuncInfo.ValueMap.end()) { 5303 unsigned Reg = VMI->second; 5304 // The PHI node may be split up into several MI PHI nodes (in 5305 // FunctionLoweringInfo::set). 5306 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5307 V->getType(), None); 5308 if (RFV.occupiesMultipleRegs()) { 5309 unsigned Offset = 0; 5310 unsigned BitsToDescribe = 0; 5311 if (auto VarSize = Variable->getSizeInBits()) 5312 BitsToDescribe = *VarSize; 5313 if (auto Fragment = Expression->getFragmentInfo()) 5314 BitsToDescribe = Fragment->SizeInBits; 5315 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5316 unsigned RegisterSize = RegAndSize.second; 5317 // Bail out if all bits are described already. 5318 if (Offset >= BitsToDescribe) 5319 break; 5320 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5321 ? BitsToDescribe - Offset 5322 : RegisterSize; 5323 auto FragmentExpr = DIExpression::createFragmentExpression( 5324 Expression, Offset, FragmentSize); 5325 if (!FragmentExpr) 5326 continue; 5327 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5328 false, dl, SDNodeOrder); 5329 DAG.AddDbgValue(SDV, nullptr, false); 5330 Offset += RegisterSize; 5331 } 5332 } else { 5333 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5334 SDNodeOrder); 5335 DAG.AddDbgValue(SDV, nullptr, false); 5336 } 5337 return nullptr; 5338 } 5339 } 5340 5341 // TODO: When we get here we will either drop the dbg.value completely, or 5342 // we try to move it forward by letting it dangle for awhile. So we should 5343 // probably add an extra DbgValue to the DAG here, with a reference to 5344 // "noreg", to indicate that we have lost the debug location for the 5345 // variable. 5346 5347 if (!V->use_empty() ) { 5348 // Do not call getValue(V) yet, as we don't want to generate code. 5349 // Remember it for later. 5350 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5351 return nullptr; 5352 } 5353 5354 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5355 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5356 return nullptr; 5357 } 5358 5359 case Intrinsic::eh_typeid_for: { 5360 // Find the type id for the given typeinfo. 5361 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5362 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5363 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5364 setValue(&I, Res); 5365 return nullptr; 5366 } 5367 5368 case Intrinsic::eh_return_i32: 5369 case Intrinsic::eh_return_i64: 5370 DAG.getMachineFunction().setCallsEHReturn(true); 5371 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5372 MVT::Other, 5373 getControlRoot(), 5374 getValue(I.getArgOperand(0)), 5375 getValue(I.getArgOperand(1)))); 5376 return nullptr; 5377 case Intrinsic::eh_unwind_init: 5378 DAG.getMachineFunction().setCallsUnwindInit(true); 5379 return nullptr; 5380 case Intrinsic::eh_dwarf_cfa: 5381 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5382 TLI.getPointerTy(DAG.getDataLayout()), 5383 getValue(I.getArgOperand(0)))); 5384 return nullptr; 5385 case Intrinsic::eh_sjlj_callsite: { 5386 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5387 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5388 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5389 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5390 5391 MMI.setCurrentCallSite(CI->getZExtValue()); 5392 return nullptr; 5393 } 5394 case Intrinsic::eh_sjlj_functioncontext: { 5395 // Get and store the index of the function context. 5396 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5397 AllocaInst *FnCtx = 5398 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5399 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5400 MFI.setFunctionContextIndex(FI); 5401 return nullptr; 5402 } 5403 case Intrinsic::eh_sjlj_setjmp: { 5404 SDValue Ops[2]; 5405 Ops[0] = getRoot(); 5406 Ops[1] = getValue(I.getArgOperand(0)); 5407 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5408 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5409 setValue(&I, Op.getValue(0)); 5410 DAG.setRoot(Op.getValue(1)); 5411 return nullptr; 5412 } 5413 case Intrinsic::eh_sjlj_longjmp: 5414 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5415 getRoot(), getValue(I.getArgOperand(0)))); 5416 return nullptr; 5417 case Intrinsic::eh_sjlj_setup_dispatch: 5418 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5419 getRoot())); 5420 return nullptr; 5421 case Intrinsic::masked_gather: 5422 visitMaskedGather(I); 5423 return nullptr; 5424 case Intrinsic::masked_load: 5425 visitMaskedLoad(I); 5426 return nullptr; 5427 case Intrinsic::masked_scatter: 5428 visitMaskedScatter(I); 5429 return nullptr; 5430 case Intrinsic::masked_store: 5431 visitMaskedStore(I); 5432 return nullptr; 5433 case Intrinsic::masked_expandload: 5434 visitMaskedLoad(I, true /* IsExpanding */); 5435 return nullptr; 5436 case Intrinsic::masked_compressstore: 5437 visitMaskedStore(I, true /* IsCompressing */); 5438 return nullptr; 5439 case Intrinsic::x86_mmx_pslli_w: 5440 case Intrinsic::x86_mmx_pslli_d: 5441 case Intrinsic::x86_mmx_pslli_q: 5442 case Intrinsic::x86_mmx_psrli_w: 5443 case Intrinsic::x86_mmx_psrli_d: 5444 case Intrinsic::x86_mmx_psrli_q: 5445 case Intrinsic::x86_mmx_psrai_w: 5446 case Intrinsic::x86_mmx_psrai_d: { 5447 SDValue ShAmt = getValue(I.getArgOperand(1)); 5448 if (isa<ConstantSDNode>(ShAmt)) { 5449 visitTargetIntrinsic(I, Intrinsic); 5450 return nullptr; 5451 } 5452 unsigned NewIntrinsic = 0; 5453 EVT ShAmtVT = MVT::v2i32; 5454 switch (Intrinsic) { 5455 case Intrinsic::x86_mmx_pslli_w: 5456 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5457 break; 5458 case Intrinsic::x86_mmx_pslli_d: 5459 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5460 break; 5461 case Intrinsic::x86_mmx_pslli_q: 5462 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5463 break; 5464 case Intrinsic::x86_mmx_psrli_w: 5465 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5466 break; 5467 case Intrinsic::x86_mmx_psrli_d: 5468 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5469 break; 5470 case Intrinsic::x86_mmx_psrli_q: 5471 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5472 break; 5473 case Intrinsic::x86_mmx_psrai_w: 5474 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5475 break; 5476 case Intrinsic::x86_mmx_psrai_d: 5477 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5478 break; 5479 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5480 } 5481 5482 // The vector shift intrinsics with scalars uses 32b shift amounts but 5483 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5484 // to be zero. 5485 // We must do this early because v2i32 is not a legal type. 5486 SDValue ShOps[2]; 5487 ShOps[0] = ShAmt; 5488 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5489 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5490 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5491 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5492 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5493 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5494 getValue(I.getArgOperand(0)), ShAmt); 5495 setValue(&I, Res); 5496 return nullptr; 5497 } 5498 case Intrinsic::powi: 5499 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5500 getValue(I.getArgOperand(1)), DAG)); 5501 return nullptr; 5502 case Intrinsic::log: 5503 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5504 return nullptr; 5505 case Intrinsic::log2: 5506 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5507 return nullptr; 5508 case Intrinsic::log10: 5509 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5510 return nullptr; 5511 case Intrinsic::exp: 5512 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5513 return nullptr; 5514 case Intrinsic::exp2: 5515 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5516 return nullptr; 5517 case Intrinsic::pow: 5518 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5519 getValue(I.getArgOperand(1)), DAG, TLI)); 5520 return nullptr; 5521 case Intrinsic::sqrt: 5522 case Intrinsic::fabs: 5523 case Intrinsic::sin: 5524 case Intrinsic::cos: 5525 case Intrinsic::floor: 5526 case Intrinsic::ceil: 5527 case Intrinsic::trunc: 5528 case Intrinsic::rint: 5529 case Intrinsic::nearbyint: 5530 case Intrinsic::round: 5531 case Intrinsic::canonicalize: { 5532 unsigned Opcode; 5533 switch (Intrinsic) { 5534 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5535 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5536 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5537 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5538 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5539 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5540 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5541 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5542 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5543 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5544 case Intrinsic::round: Opcode = ISD::FROUND; break; 5545 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5546 } 5547 5548 setValue(&I, DAG.getNode(Opcode, sdl, 5549 getValue(I.getArgOperand(0)).getValueType(), 5550 getValue(I.getArgOperand(0)))); 5551 return nullptr; 5552 } 5553 case Intrinsic::minnum: { 5554 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5555 unsigned Opc = 5556 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5557 ? ISD::FMINNAN 5558 : ISD::FMINNUM; 5559 setValue(&I, DAG.getNode(Opc, sdl, VT, 5560 getValue(I.getArgOperand(0)), 5561 getValue(I.getArgOperand(1)))); 5562 return nullptr; 5563 } 5564 case Intrinsic::maxnum: { 5565 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5566 unsigned Opc = 5567 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5568 ? ISD::FMAXNAN 5569 : ISD::FMAXNUM; 5570 setValue(&I, DAG.getNode(Opc, sdl, VT, 5571 getValue(I.getArgOperand(0)), 5572 getValue(I.getArgOperand(1)))); 5573 return nullptr; 5574 } 5575 case Intrinsic::copysign: 5576 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5577 getValue(I.getArgOperand(0)).getValueType(), 5578 getValue(I.getArgOperand(0)), 5579 getValue(I.getArgOperand(1)))); 5580 return nullptr; 5581 case Intrinsic::fma: 5582 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5583 getValue(I.getArgOperand(0)).getValueType(), 5584 getValue(I.getArgOperand(0)), 5585 getValue(I.getArgOperand(1)), 5586 getValue(I.getArgOperand(2)))); 5587 return nullptr; 5588 case Intrinsic::experimental_constrained_fadd: 5589 case Intrinsic::experimental_constrained_fsub: 5590 case Intrinsic::experimental_constrained_fmul: 5591 case Intrinsic::experimental_constrained_fdiv: 5592 case Intrinsic::experimental_constrained_frem: 5593 case Intrinsic::experimental_constrained_fma: 5594 case Intrinsic::experimental_constrained_sqrt: 5595 case Intrinsic::experimental_constrained_pow: 5596 case Intrinsic::experimental_constrained_powi: 5597 case Intrinsic::experimental_constrained_sin: 5598 case Intrinsic::experimental_constrained_cos: 5599 case Intrinsic::experimental_constrained_exp: 5600 case Intrinsic::experimental_constrained_exp2: 5601 case Intrinsic::experimental_constrained_log: 5602 case Intrinsic::experimental_constrained_log10: 5603 case Intrinsic::experimental_constrained_log2: 5604 case Intrinsic::experimental_constrained_rint: 5605 case Intrinsic::experimental_constrained_nearbyint: 5606 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5607 return nullptr; 5608 case Intrinsic::fmuladd: { 5609 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5610 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5611 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5612 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5613 getValue(I.getArgOperand(0)).getValueType(), 5614 getValue(I.getArgOperand(0)), 5615 getValue(I.getArgOperand(1)), 5616 getValue(I.getArgOperand(2)))); 5617 } else { 5618 // TODO: Intrinsic calls should have fast-math-flags. 5619 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5620 getValue(I.getArgOperand(0)).getValueType(), 5621 getValue(I.getArgOperand(0)), 5622 getValue(I.getArgOperand(1))); 5623 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5624 getValue(I.getArgOperand(0)).getValueType(), 5625 Mul, 5626 getValue(I.getArgOperand(2))); 5627 setValue(&I, Add); 5628 } 5629 return nullptr; 5630 } 5631 case Intrinsic::convert_to_fp16: 5632 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5633 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5634 getValue(I.getArgOperand(0)), 5635 DAG.getTargetConstant(0, sdl, 5636 MVT::i32)))); 5637 return nullptr; 5638 case Intrinsic::convert_from_fp16: 5639 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5640 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5641 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5642 getValue(I.getArgOperand(0))))); 5643 return nullptr; 5644 case Intrinsic::pcmarker: { 5645 SDValue Tmp = getValue(I.getArgOperand(0)); 5646 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5647 return nullptr; 5648 } 5649 case Intrinsic::readcyclecounter: { 5650 SDValue Op = getRoot(); 5651 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5652 DAG.getVTList(MVT::i64, MVT::Other), Op); 5653 setValue(&I, Res); 5654 DAG.setRoot(Res.getValue(1)); 5655 return nullptr; 5656 } 5657 case Intrinsic::bitreverse: 5658 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5659 getValue(I.getArgOperand(0)).getValueType(), 5660 getValue(I.getArgOperand(0)))); 5661 return nullptr; 5662 case Intrinsic::bswap: 5663 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5664 getValue(I.getArgOperand(0)).getValueType(), 5665 getValue(I.getArgOperand(0)))); 5666 return nullptr; 5667 case Intrinsic::cttz: { 5668 SDValue Arg = getValue(I.getArgOperand(0)); 5669 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5670 EVT Ty = Arg.getValueType(); 5671 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5672 sdl, Ty, Arg)); 5673 return nullptr; 5674 } 5675 case Intrinsic::ctlz: { 5676 SDValue Arg = getValue(I.getArgOperand(0)); 5677 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5678 EVT Ty = Arg.getValueType(); 5679 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5680 sdl, Ty, Arg)); 5681 return nullptr; 5682 } 5683 case Intrinsic::ctpop: { 5684 SDValue Arg = getValue(I.getArgOperand(0)); 5685 EVT Ty = Arg.getValueType(); 5686 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5687 return nullptr; 5688 } 5689 case Intrinsic::fshl: 5690 case Intrinsic::fshr: { 5691 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5692 SDValue X = getValue(I.getArgOperand(0)); 5693 SDValue Y = getValue(I.getArgOperand(1)); 5694 SDValue Z = getValue(I.getArgOperand(2)); 5695 EVT VT = X.getValueType(); 5696 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5697 SDValue Zero = DAG.getConstant(0, sdl, VT); 5698 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5699 5700 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5701 // avoid the select that is necessary in the general case to filter out 5702 // the 0-shift possibility that leads to UB. 5703 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5704 // TODO: This should also be done if the operation is custom, but we have 5705 // to make sure targets are handling the modulo shift amount as expected. 5706 // TODO: If the rotate direction (left or right) corresponding to the 5707 // shift is not available, adjust the shift value and invert the 5708 // direction. 5709 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5710 if (TLI.isOperationLegal(RotateOpcode, VT)) { 5711 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5712 return nullptr; 5713 } 5714 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5715 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5716 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5717 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5718 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5719 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5720 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5721 return nullptr; 5722 } 5723 5724 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5725 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5726 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5727 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5728 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5729 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5730 5731 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5732 // and that is undefined. We must compare and select to avoid UB. 5733 EVT CCVT = MVT::i1; 5734 if (VT.isVector()) 5735 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5736 5737 // For fshl, 0-shift returns the 1st arg (X). 5738 // For fshr, 0-shift returns the 2nd arg (Y). 5739 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5740 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5741 return nullptr; 5742 } 5743 case Intrinsic::stacksave: { 5744 SDValue Op = getRoot(); 5745 Res = DAG.getNode( 5746 ISD::STACKSAVE, sdl, 5747 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5748 setValue(&I, Res); 5749 DAG.setRoot(Res.getValue(1)); 5750 return nullptr; 5751 } 5752 case Intrinsic::stackrestore: 5753 Res = getValue(I.getArgOperand(0)); 5754 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5755 return nullptr; 5756 case Intrinsic::get_dynamic_area_offset: { 5757 SDValue Op = getRoot(); 5758 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5759 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5760 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5761 // target. 5762 if (PtrTy != ResTy) 5763 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5764 " intrinsic!"); 5765 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5766 Op); 5767 DAG.setRoot(Op); 5768 setValue(&I, Res); 5769 return nullptr; 5770 } 5771 case Intrinsic::stackguard: { 5772 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5773 MachineFunction &MF = DAG.getMachineFunction(); 5774 const Module &M = *MF.getFunction().getParent(); 5775 SDValue Chain = getRoot(); 5776 if (TLI.useLoadStackGuardNode()) { 5777 Res = getLoadStackGuard(DAG, sdl, Chain); 5778 } else { 5779 const Value *Global = TLI.getSDagStackGuard(M); 5780 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5781 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5782 MachinePointerInfo(Global, 0), Align, 5783 MachineMemOperand::MOVolatile); 5784 } 5785 if (TLI.useStackGuardXorFP()) 5786 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5787 DAG.setRoot(Chain); 5788 setValue(&I, Res); 5789 return nullptr; 5790 } 5791 case Intrinsic::stackprotector: { 5792 // Emit code into the DAG to store the stack guard onto the stack. 5793 MachineFunction &MF = DAG.getMachineFunction(); 5794 MachineFrameInfo &MFI = MF.getFrameInfo(); 5795 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5796 SDValue Src, Chain = getRoot(); 5797 5798 if (TLI.useLoadStackGuardNode()) 5799 Src = getLoadStackGuard(DAG, sdl, Chain); 5800 else 5801 Src = getValue(I.getArgOperand(0)); // The guard's value. 5802 5803 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5804 5805 int FI = FuncInfo.StaticAllocaMap[Slot]; 5806 MFI.setStackProtectorIndex(FI); 5807 5808 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5809 5810 // Store the stack protector onto the stack. 5811 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5812 DAG.getMachineFunction(), FI), 5813 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5814 setValue(&I, Res); 5815 DAG.setRoot(Res); 5816 return nullptr; 5817 } 5818 case Intrinsic::objectsize: { 5819 // If we don't know by now, we're never going to know. 5820 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5821 5822 assert(CI && "Non-constant type in __builtin_object_size?"); 5823 5824 SDValue Arg = getValue(I.getCalledValue()); 5825 EVT Ty = Arg.getValueType(); 5826 5827 if (CI->isZero()) 5828 Res = DAG.getConstant(-1ULL, sdl, Ty); 5829 else 5830 Res = DAG.getConstant(0, sdl, Ty); 5831 5832 setValue(&I, Res); 5833 return nullptr; 5834 } 5835 case Intrinsic::annotation: 5836 case Intrinsic::ptr_annotation: 5837 case Intrinsic::launder_invariant_group: 5838 case Intrinsic::strip_invariant_group: 5839 // Drop the intrinsic, but forward the value 5840 setValue(&I, getValue(I.getOperand(0))); 5841 return nullptr; 5842 case Intrinsic::assume: 5843 case Intrinsic::var_annotation: 5844 case Intrinsic::sideeffect: 5845 // Discard annotate attributes, assumptions, and artificial side-effects. 5846 return nullptr; 5847 5848 case Intrinsic::codeview_annotation: { 5849 // Emit a label associated with this metadata. 5850 MachineFunction &MF = DAG.getMachineFunction(); 5851 MCSymbol *Label = 5852 MF.getMMI().getContext().createTempSymbol("annotation", true); 5853 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5854 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5855 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5856 DAG.setRoot(Res); 5857 return nullptr; 5858 } 5859 5860 case Intrinsic::init_trampoline: { 5861 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5862 5863 SDValue Ops[6]; 5864 Ops[0] = getRoot(); 5865 Ops[1] = getValue(I.getArgOperand(0)); 5866 Ops[2] = getValue(I.getArgOperand(1)); 5867 Ops[3] = getValue(I.getArgOperand(2)); 5868 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5869 Ops[5] = DAG.getSrcValue(F); 5870 5871 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5872 5873 DAG.setRoot(Res); 5874 return nullptr; 5875 } 5876 case Intrinsic::adjust_trampoline: 5877 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5878 TLI.getPointerTy(DAG.getDataLayout()), 5879 getValue(I.getArgOperand(0)))); 5880 return nullptr; 5881 case Intrinsic::gcroot: { 5882 assert(DAG.getMachineFunction().getFunction().hasGC() && 5883 "only valid in functions with gc specified, enforced by Verifier"); 5884 assert(GFI && "implied by previous"); 5885 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5886 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5887 5888 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5889 GFI->addStackRoot(FI->getIndex(), TypeMap); 5890 return nullptr; 5891 } 5892 case Intrinsic::gcread: 5893 case Intrinsic::gcwrite: 5894 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5895 case Intrinsic::flt_rounds: 5896 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5897 return nullptr; 5898 5899 case Intrinsic::expect: 5900 // Just replace __builtin_expect(exp, c) with EXP. 5901 setValue(&I, getValue(I.getArgOperand(0))); 5902 return nullptr; 5903 5904 case Intrinsic::debugtrap: 5905 case Intrinsic::trap: { 5906 StringRef TrapFuncName = 5907 I.getAttributes() 5908 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5909 .getValueAsString(); 5910 if (TrapFuncName.empty()) { 5911 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5912 ISD::TRAP : ISD::DEBUGTRAP; 5913 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5914 return nullptr; 5915 } 5916 TargetLowering::ArgListTy Args; 5917 5918 TargetLowering::CallLoweringInfo CLI(DAG); 5919 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5920 CallingConv::C, I.getType(), 5921 DAG.getExternalSymbol(TrapFuncName.data(), 5922 TLI.getPointerTy(DAG.getDataLayout())), 5923 std::move(Args)); 5924 5925 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5926 DAG.setRoot(Result.second); 5927 return nullptr; 5928 } 5929 5930 case Intrinsic::uadd_with_overflow: 5931 case Intrinsic::sadd_with_overflow: 5932 case Intrinsic::usub_with_overflow: 5933 case Intrinsic::ssub_with_overflow: 5934 case Intrinsic::umul_with_overflow: 5935 case Intrinsic::smul_with_overflow: { 5936 ISD::NodeType Op; 5937 switch (Intrinsic) { 5938 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5939 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5940 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5941 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5942 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5943 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5944 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5945 } 5946 SDValue Op1 = getValue(I.getArgOperand(0)); 5947 SDValue Op2 = getValue(I.getArgOperand(1)); 5948 5949 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5950 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5951 return nullptr; 5952 } 5953 case Intrinsic::prefetch: { 5954 SDValue Ops[5]; 5955 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5956 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 5957 Ops[0] = DAG.getRoot(); 5958 Ops[1] = getValue(I.getArgOperand(0)); 5959 Ops[2] = getValue(I.getArgOperand(1)); 5960 Ops[3] = getValue(I.getArgOperand(2)); 5961 Ops[4] = getValue(I.getArgOperand(3)); 5962 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5963 DAG.getVTList(MVT::Other), Ops, 5964 EVT::getIntegerVT(*Context, 8), 5965 MachinePointerInfo(I.getArgOperand(0)), 5966 0, /* align */ 5967 Flags); 5968 5969 // Chain the prefetch in parallell with any pending loads, to stay out of 5970 // the way of later optimizations. 5971 PendingLoads.push_back(Result); 5972 Result = getRoot(); 5973 DAG.setRoot(Result); 5974 return nullptr; 5975 } 5976 case Intrinsic::lifetime_start: 5977 case Intrinsic::lifetime_end: { 5978 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5979 // Stack coloring is not enabled in O0, discard region information. 5980 if (TM.getOptLevel() == CodeGenOpt::None) 5981 return nullptr; 5982 5983 SmallVector<Value *, 4> Allocas; 5984 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5985 5986 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5987 E = Allocas.end(); Object != E; ++Object) { 5988 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5989 5990 // Could not find an Alloca. 5991 if (!LifetimeObject) 5992 continue; 5993 5994 // First check that the Alloca is static, otherwise it won't have a 5995 // valid frame index. 5996 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5997 if (SI == FuncInfo.StaticAllocaMap.end()) 5998 return nullptr; 5999 6000 int FI = SI->second; 6001 6002 SDValue Ops[2]; 6003 Ops[0] = getRoot(); 6004 Ops[1] = 6005 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6006 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6007 6008 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6009 DAG.setRoot(Res); 6010 } 6011 return nullptr; 6012 } 6013 case Intrinsic::invariant_start: 6014 // Discard region information. 6015 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6016 return nullptr; 6017 case Intrinsic::invariant_end: 6018 // Discard region information. 6019 return nullptr; 6020 case Intrinsic::clear_cache: 6021 return TLI.getClearCacheBuiltinName(); 6022 case Intrinsic::donothing: 6023 // ignore 6024 return nullptr; 6025 case Intrinsic::experimental_stackmap: 6026 visitStackmap(I); 6027 return nullptr; 6028 case Intrinsic::experimental_patchpoint_void: 6029 case Intrinsic::experimental_patchpoint_i64: 6030 visitPatchpoint(&I); 6031 return nullptr; 6032 case Intrinsic::experimental_gc_statepoint: 6033 LowerStatepoint(ImmutableStatepoint(&I)); 6034 return nullptr; 6035 case Intrinsic::experimental_gc_result: 6036 visitGCResult(cast<GCResultInst>(I)); 6037 return nullptr; 6038 case Intrinsic::experimental_gc_relocate: 6039 visitGCRelocate(cast<GCRelocateInst>(I)); 6040 return nullptr; 6041 case Intrinsic::instrprof_increment: 6042 llvm_unreachable("instrprof failed to lower an increment"); 6043 case Intrinsic::instrprof_value_profile: 6044 llvm_unreachable("instrprof failed to lower a value profiling call"); 6045 case Intrinsic::localescape: { 6046 MachineFunction &MF = DAG.getMachineFunction(); 6047 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6048 6049 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6050 // is the same on all targets. 6051 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6052 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6053 if (isa<ConstantPointerNull>(Arg)) 6054 continue; // Skip null pointers. They represent a hole in index space. 6055 AllocaInst *Slot = cast<AllocaInst>(Arg); 6056 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6057 "can only escape static allocas"); 6058 int FI = FuncInfo.StaticAllocaMap[Slot]; 6059 MCSymbol *FrameAllocSym = 6060 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6061 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6062 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6063 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6064 .addSym(FrameAllocSym) 6065 .addFrameIndex(FI); 6066 } 6067 6068 return nullptr; 6069 } 6070 6071 case Intrinsic::localrecover: { 6072 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6073 MachineFunction &MF = DAG.getMachineFunction(); 6074 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6075 6076 // Get the symbol that defines the frame offset. 6077 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6078 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6079 unsigned IdxVal = 6080 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6081 MCSymbol *FrameAllocSym = 6082 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6083 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6084 6085 // Create a MCSymbol for the label to avoid any target lowering 6086 // that would make this PC relative. 6087 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6088 SDValue OffsetVal = 6089 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6090 6091 // Add the offset to the FP. 6092 Value *FP = I.getArgOperand(1); 6093 SDValue FPVal = getValue(FP); 6094 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6095 setValue(&I, Add); 6096 6097 return nullptr; 6098 } 6099 6100 case Intrinsic::eh_exceptionpointer: 6101 case Intrinsic::eh_exceptioncode: { 6102 // Get the exception pointer vreg, copy from it, and resize it to fit. 6103 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6104 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6105 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6106 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6107 SDValue N = 6108 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6109 if (Intrinsic == Intrinsic::eh_exceptioncode) 6110 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6111 setValue(&I, N); 6112 return nullptr; 6113 } 6114 case Intrinsic::xray_customevent: { 6115 // Here we want to make sure that the intrinsic behaves as if it has a 6116 // specific calling convention, and only for x86_64. 6117 // FIXME: Support other platforms later. 6118 const auto &Triple = DAG.getTarget().getTargetTriple(); 6119 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6120 return nullptr; 6121 6122 SDLoc DL = getCurSDLoc(); 6123 SmallVector<SDValue, 8> Ops; 6124 6125 // We want to say that we always want the arguments in registers. 6126 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6127 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6128 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6129 SDValue Chain = getRoot(); 6130 Ops.push_back(LogEntryVal); 6131 Ops.push_back(StrSizeVal); 6132 Ops.push_back(Chain); 6133 6134 // We need to enforce the calling convention for the callsite, so that 6135 // argument ordering is enforced correctly, and that register allocation can 6136 // see that some registers may be assumed clobbered and have to preserve 6137 // them across calls to the intrinsic. 6138 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6139 DL, NodeTys, Ops); 6140 SDValue patchableNode = SDValue(MN, 0); 6141 DAG.setRoot(patchableNode); 6142 setValue(&I, patchableNode); 6143 return nullptr; 6144 } 6145 case Intrinsic::xray_typedevent: { 6146 // Here we want to make sure that the intrinsic behaves as if it has a 6147 // specific calling convention, and only for x86_64. 6148 // FIXME: Support other platforms later. 6149 const auto &Triple = DAG.getTarget().getTargetTriple(); 6150 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6151 return nullptr; 6152 6153 SDLoc DL = getCurSDLoc(); 6154 SmallVector<SDValue, 8> Ops; 6155 6156 // We want to say that we always want the arguments in registers. 6157 // It's unclear to me how manipulating the selection DAG here forces callers 6158 // to provide arguments in registers instead of on the stack. 6159 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6160 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6161 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6162 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6163 SDValue Chain = getRoot(); 6164 Ops.push_back(LogTypeId); 6165 Ops.push_back(LogEntryVal); 6166 Ops.push_back(StrSizeVal); 6167 Ops.push_back(Chain); 6168 6169 // We need to enforce the calling convention for the callsite, so that 6170 // argument ordering is enforced correctly, and that register allocation can 6171 // see that some registers may be assumed clobbered and have to preserve 6172 // them across calls to the intrinsic. 6173 MachineSDNode *MN = DAG.getMachineNode( 6174 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6175 SDValue patchableNode = SDValue(MN, 0); 6176 DAG.setRoot(patchableNode); 6177 setValue(&I, patchableNode); 6178 return nullptr; 6179 } 6180 case Intrinsic::experimental_deoptimize: 6181 LowerDeoptimizeCall(&I); 6182 return nullptr; 6183 6184 case Intrinsic::experimental_vector_reduce_fadd: 6185 case Intrinsic::experimental_vector_reduce_fmul: 6186 case Intrinsic::experimental_vector_reduce_add: 6187 case Intrinsic::experimental_vector_reduce_mul: 6188 case Intrinsic::experimental_vector_reduce_and: 6189 case Intrinsic::experimental_vector_reduce_or: 6190 case Intrinsic::experimental_vector_reduce_xor: 6191 case Intrinsic::experimental_vector_reduce_smax: 6192 case Intrinsic::experimental_vector_reduce_smin: 6193 case Intrinsic::experimental_vector_reduce_umax: 6194 case Intrinsic::experimental_vector_reduce_umin: 6195 case Intrinsic::experimental_vector_reduce_fmax: 6196 case Intrinsic::experimental_vector_reduce_fmin: 6197 visitVectorReduce(I, Intrinsic); 6198 return nullptr; 6199 6200 case Intrinsic::icall_branch_funnel: { 6201 SmallVector<SDValue, 16> Ops; 6202 Ops.push_back(DAG.getRoot()); 6203 Ops.push_back(getValue(I.getArgOperand(0))); 6204 6205 int64_t Offset; 6206 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6207 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6208 if (!Base) 6209 report_fatal_error( 6210 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6211 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6212 6213 struct BranchFunnelTarget { 6214 int64_t Offset; 6215 SDValue Target; 6216 }; 6217 SmallVector<BranchFunnelTarget, 8> Targets; 6218 6219 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6220 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6221 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6222 if (ElemBase != Base) 6223 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6224 "to the same GlobalValue"); 6225 6226 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6227 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6228 if (!GA) 6229 report_fatal_error( 6230 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6231 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6232 GA->getGlobal(), getCurSDLoc(), 6233 Val.getValueType(), GA->getOffset())}); 6234 } 6235 llvm::sort(Targets.begin(), Targets.end(), 6236 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6237 return T1.Offset < T2.Offset; 6238 }); 6239 6240 for (auto &T : Targets) { 6241 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6242 Ops.push_back(T.Target); 6243 } 6244 6245 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6246 getCurSDLoc(), MVT::Other, Ops), 6247 0); 6248 DAG.setRoot(N); 6249 setValue(&I, N); 6250 HasTailCall = true; 6251 return nullptr; 6252 } 6253 6254 case Intrinsic::wasm_landingpad_index: { 6255 // TODO store landing pad index in a map, which will be used when generating 6256 // LSDA information 6257 return nullptr; 6258 } 6259 } 6260 } 6261 6262 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6263 const ConstrainedFPIntrinsic &FPI) { 6264 SDLoc sdl = getCurSDLoc(); 6265 unsigned Opcode; 6266 switch (FPI.getIntrinsicID()) { 6267 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6268 case Intrinsic::experimental_constrained_fadd: 6269 Opcode = ISD::STRICT_FADD; 6270 break; 6271 case Intrinsic::experimental_constrained_fsub: 6272 Opcode = ISD::STRICT_FSUB; 6273 break; 6274 case Intrinsic::experimental_constrained_fmul: 6275 Opcode = ISD::STRICT_FMUL; 6276 break; 6277 case Intrinsic::experimental_constrained_fdiv: 6278 Opcode = ISD::STRICT_FDIV; 6279 break; 6280 case Intrinsic::experimental_constrained_frem: 6281 Opcode = ISD::STRICT_FREM; 6282 break; 6283 case Intrinsic::experimental_constrained_fma: 6284 Opcode = ISD::STRICT_FMA; 6285 break; 6286 case Intrinsic::experimental_constrained_sqrt: 6287 Opcode = ISD::STRICT_FSQRT; 6288 break; 6289 case Intrinsic::experimental_constrained_pow: 6290 Opcode = ISD::STRICT_FPOW; 6291 break; 6292 case Intrinsic::experimental_constrained_powi: 6293 Opcode = ISD::STRICT_FPOWI; 6294 break; 6295 case Intrinsic::experimental_constrained_sin: 6296 Opcode = ISD::STRICT_FSIN; 6297 break; 6298 case Intrinsic::experimental_constrained_cos: 6299 Opcode = ISD::STRICT_FCOS; 6300 break; 6301 case Intrinsic::experimental_constrained_exp: 6302 Opcode = ISD::STRICT_FEXP; 6303 break; 6304 case Intrinsic::experimental_constrained_exp2: 6305 Opcode = ISD::STRICT_FEXP2; 6306 break; 6307 case Intrinsic::experimental_constrained_log: 6308 Opcode = ISD::STRICT_FLOG; 6309 break; 6310 case Intrinsic::experimental_constrained_log10: 6311 Opcode = ISD::STRICT_FLOG10; 6312 break; 6313 case Intrinsic::experimental_constrained_log2: 6314 Opcode = ISD::STRICT_FLOG2; 6315 break; 6316 case Intrinsic::experimental_constrained_rint: 6317 Opcode = ISD::STRICT_FRINT; 6318 break; 6319 case Intrinsic::experimental_constrained_nearbyint: 6320 Opcode = ISD::STRICT_FNEARBYINT; 6321 break; 6322 } 6323 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6324 SDValue Chain = getRoot(); 6325 SmallVector<EVT, 4> ValueVTs; 6326 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6327 ValueVTs.push_back(MVT::Other); // Out chain 6328 6329 SDVTList VTs = DAG.getVTList(ValueVTs); 6330 SDValue Result; 6331 if (FPI.isUnaryOp()) 6332 Result = DAG.getNode(Opcode, sdl, VTs, 6333 { Chain, getValue(FPI.getArgOperand(0)) }); 6334 else if (FPI.isTernaryOp()) 6335 Result = DAG.getNode(Opcode, sdl, VTs, 6336 { Chain, getValue(FPI.getArgOperand(0)), 6337 getValue(FPI.getArgOperand(1)), 6338 getValue(FPI.getArgOperand(2)) }); 6339 else 6340 Result = DAG.getNode(Opcode, sdl, VTs, 6341 { Chain, getValue(FPI.getArgOperand(0)), 6342 getValue(FPI.getArgOperand(1)) }); 6343 6344 assert(Result.getNode()->getNumValues() == 2); 6345 SDValue OutChain = Result.getValue(1); 6346 DAG.setRoot(OutChain); 6347 SDValue FPResult = Result.getValue(0); 6348 setValue(&FPI, FPResult); 6349 } 6350 6351 std::pair<SDValue, SDValue> 6352 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6353 const BasicBlock *EHPadBB) { 6354 MachineFunction &MF = DAG.getMachineFunction(); 6355 MachineModuleInfo &MMI = MF.getMMI(); 6356 MCSymbol *BeginLabel = nullptr; 6357 6358 if (EHPadBB) { 6359 // Insert a label before the invoke call to mark the try range. This can be 6360 // used to detect deletion of the invoke via the MachineModuleInfo. 6361 BeginLabel = MMI.getContext().createTempSymbol(); 6362 6363 // For SjLj, keep track of which landing pads go with which invokes 6364 // so as to maintain the ordering of pads in the LSDA. 6365 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6366 if (CallSiteIndex) { 6367 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6368 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6369 6370 // Now that the call site is handled, stop tracking it. 6371 MMI.setCurrentCallSite(0); 6372 } 6373 6374 // Both PendingLoads and PendingExports must be flushed here; 6375 // this call might not return. 6376 (void)getRoot(); 6377 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6378 6379 CLI.setChain(getRoot()); 6380 } 6381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6382 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6383 6384 assert((CLI.IsTailCall || Result.second.getNode()) && 6385 "Non-null chain expected with non-tail call!"); 6386 assert((Result.second.getNode() || !Result.first.getNode()) && 6387 "Null value expected with tail call!"); 6388 6389 if (!Result.second.getNode()) { 6390 // As a special case, a null chain means that a tail call has been emitted 6391 // and the DAG root is already updated. 6392 HasTailCall = true; 6393 6394 // Since there's no actual continuation from this block, nothing can be 6395 // relying on us setting vregs for them. 6396 PendingExports.clear(); 6397 } else { 6398 DAG.setRoot(Result.second); 6399 } 6400 6401 if (EHPadBB) { 6402 // Insert a label at the end of the invoke call to mark the try range. This 6403 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6404 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6405 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6406 6407 // Inform MachineModuleInfo of range. 6408 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6409 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6410 // actually use outlined funclets and their LSDA info style. 6411 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6412 assert(CLI.CS); 6413 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6414 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6415 BeginLabel, EndLabel); 6416 } else { 6417 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6418 } 6419 } 6420 6421 return Result; 6422 } 6423 6424 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6425 bool isTailCall, 6426 const BasicBlock *EHPadBB) { 6427 auto &DL = DAG.getDataLayout(); 6428 FunctionType *FTy = CS.getFunctionType(); 6429 Type *RetTy = CS.getType(); 6430 6431 TargetLowering::ArgListTy Args; 6432 Args.reserve(CS.arg_size()); 6433 6434 const Value *SwiftErrorVal = nullptr; 6435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6436 6437 // We can't tail call inside a function with a swifterror argument. Lowering 6438 // does not support this yet. It would have to move into the swifterror 6439 // register before the call. 6440 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6441 if (TLI.supportSwiftError() && 6442 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6443 isTailCall = false; 6444 6445 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6446 i != e; ++i) { 6447 TargetLowering::ArgListEntry Entry; 6448 const Value *V = *i; 6449 6450 // Skip empty types 6451 if (V->getType()->isEmptyTy()) 6452 continue; 6453 6454 SDValue ArgNode = getValue(V); 6455 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6456 6457 Entry.setAttributes(&CS, i - CS.arg_begin()); 6458 6459 // Use swifterror virtual register as input to the call. 6460 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6461 SwiftErrorVal = V; 6462 // We find the virtual register for the actual swifterror argument. 6463 // Instead of using the Value, we use the virtual register instead. 6464 Entry.Node = DAG.getRegister(FuncInfo 6465 .getOrCreateSwiftErrorVRegUseAt( 6466 CS.getInstruction(), FuncInfo.MBB, V) 6467 .first, 6468 EVT(TLI.getPointerTy(DL))); 6469 } 6470 6471 Args.push_back(Entry); 6472 6473 // If we have an explicit sret argument that is an Instruction, (i.e., it 6474 // might point to function-local memory), we can't meaningfully tail-call. 6475 if (Entry.IsSRet && isa<Instruction>(V)) 6476 isTailCall = false; 6477 } 6478 6479 // Check if target-independent constraints permit a tail call here. 6480 // Target-dependent constraints are checked within TLI->LowerCallTo. 6481 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6482 isTailCall = false; 6483 6484 // Disable tail calls if there is an swifterror argument. Targets have not 6485 // been updated to support tail calls. 6486 if (TLI.supportSwiftError() && SwiftErrorVal) 6487 isTailCall = false; 6488 6489 TargetLowering::CallLoweringInfo CLI(DAG); 6490 CLI.setDebugLoc(getCurSDLoc()) 6491 .setChain(getRoot()) 6492 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6493 .setTailCall(isTailCall) 6494 .setConvergent(CS.isConvergent()); 6495 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6496 6497 if (Result.first.getNode()) { 6498 const Instruction *Inst = CS.getInstruction(); 6499 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6500 setValue(Inst, Result.first); 6501 } 6502 6503 // The last element of CLI.InVals has the SDValue for swifterror return. 6504 // Here we copy it to a virtual register and update SwiftErrorMap for 6505 // book-keeping. 6506 if (SwiftErrorVal && TLI.supportSwiftError()) { 6507 // Get the last element of InVals. 6508 SDValue Src = CLI.InVals.back(); 6509 unsigned VReg; bool CreatedVReg; 6510 std::tie(VReg, CreatedVReg) = 6511 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6512 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6513 // We update the virtual register for the actual swifterror argument. 6514 if (CreatedVReg) 6515 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6516 DAG.setRoot(CopyNode); 6517 } 6518 } 6519 6520 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6521 SelectionDAGBuilder &Builder) { 6522 // Check to see if this load can be trivially constant folded, e.g. if the 6523 // input is from a string literal. 6524 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6525 // Cast pointer to the type we really want to load. 6526 Type *LoadTy = 6527 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6528 if (LoadVT.isVector()) 6529 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6530 6531 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6532 PointerType::getUnqual(LoadTy)); 6533 6534 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6535 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6536 return Builder.getValue(LoadCst); 6537 } 6538 6539 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6540 // still constant memory, the input chain can be the entry node. 6541 SDValue Root; 6542 bool ConstantMemory = false; 6543 6544 // Do not serialize (non-volatile) loads of constant memory with anything. 6545 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6546 Root = Builder.DAG.getEntryNode(); 6547 ConstantMemory = true; 6548 } else { 6549 // Do not serialize non-volatile loads against each other. 6550 Root = Builder.DAG.getRoot(); 6551 } 6552 6553 SDValue Ptr = Builder.getValue(PtrVal); 6554 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6555 Ptr, MachinePointerInfo(PtrVal), 6556 /* Alignment = */ 1); 6557 6558 if (!ConstantMemory) 6559 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6560 return LoadVal; 6561 } 6562 6563 /// Record the value for an instruction that produces an integer result, 6564 /// converting the type where necessary. 6565 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6566 SDValue Value, 6567 bool IsSigned) { 6568 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6569 I.getType(), true); 6570 if (IsSigned) 6571 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6572 else 6573 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6574 setValue(&I, Value); 6575 } 6576 6577 /// See if we can lower a memcmp call into an optimized form. If so, return 6578 /// true and lower it. Otherwise return false, and it will be lowered like a 6579 /// normal call. 6580 /// The caller already checked that \p I calls the appropriate LibFunc with a 6581 /// correct prototype. 6582 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6583 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6584 const Value *Size = I.getArgOperand(2); 6585 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6586 if (CSize && CSize->getZExtValue() == 0) { 6587 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6588 I.getType(), true); 6589 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6590 return true; 6591 } 6592 6593 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6594 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6595 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6596 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6597 if (Res.first.getNode()) { 6598 processIntegerCallValue(I, Res.first, true); 6599 PendingLoads.push_back(Res.second); 6600 return true; 6601 } 6602 6603 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6604 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6605 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6606 return false; 6607 6608 // If the target has a fast compare for the given size, it will return a 6609 // preferred load type for that size. Require that the load VT is legal and 6610 // that the target supports unaligned loads of that type. Otherwise, return 6611 // INVALID. 6612 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6613 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6614 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6615 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6616 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6617 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6618 // TODO: Check alignment of src and dest ptrs. 6619 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6620 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6621 if (!TLI.isTypeLegal(LVT) || 6622 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6623 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6624 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6625 } 6626 6627 return LVT; 6628 }; 6629 6630 // This turns into unaligned loads. We only do this if the target natively 6631 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6632 // we'll only produce a small number of byte loads. 6633 MVT LoadVT; 6634 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6635 switch (NumBitsToCompare) { 6636 default: 6637 return false; 6638 case 16: 6639 LoadVT = MVT::i16; 6640 break; 6641 case 32: 6642 LoadVT = MVT::i32; 6643 break; 6644 case 64: 6645 case 128: 6646 case 256: 6647 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6648 break; 6649 } 6650 6651 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6652 return false; 6653 6654 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6655 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6656 6657 // Bitcast to a wide integer type if the loads are vectors. 6658 if (LoadVT.isVector()) { 6659 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6660 LoadL = DAG.getBitcast(CmpVT, LoadL); 6661 LoadR = DAG.getBitcast(CmpVT, LoadR); 6662 } 6663 6664 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6665 processIntegerCallValue(I, Cmp, false); 6666 return true; 6667 } 6668 6669 /// See if we can lower a memchr call into an optimized form. If so, return 6670 /// true and lower it. Otherwise return false, and it will be lowered like a 6671 /// normal call. 6672 /// The caller already checked that \p I calls the appropriate LibFunc with a 6673 /// correct prototype. 6674 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6675 const Value *Src = I.getArgOperand(0); 6676 const Value *Char = I.getArgOperand(1); 6677 const Value *Length = I.getArgOperand(2); 6678 6679 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6680 std::pair<SDValue, SDValue> Res = 6681 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6682 getValue(Src), getValue(Char), getValue(Length), 6683 MachinePointerInfo(Src)); 6684 if (Res.first.getNode()) { 6685 setValue(&I, Res.first); 6686 PendingLoads.push_back(Res.second); 6687 return true; 6688 } 6689 6690 return false; 6691 } 6692 6693 /// See if we can lower a mempcpy call into an optimized form. If so, return 6694 /// true and lower it. Otherwise return false, and it will be lowered like a 6695 /// normal call. 6696 /// The caller already checked that \p I calls the appropriate LibFunc with a 6697 /// correct prototype. 6698 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6699 SDValue Dst = getValue(I.getArgOperand(0)); 6700 SDValue Src = getValue(I.getArgOperand(1)); 6701 SDValue Size = getValue(I.getArgOperand(2)); 6702 6703 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6704 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6705 unsigned Align = std::min(DstAlign, SrcAlign); 6706 if (Align == 0) // Alignment of one or both could not be inferred. 6707 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6708 6709 bool isVol = false; 6710 SDLoc sdl = getCurSDLoc(); 6711 6712 // In the mempcpy context we need to pass in a false value for isTailCall 6713 // because the return pointer needs to be adjusted by the size of 6714 // the copied memory. 6715 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6716 false, /*isTailCall=*/false, 6717 MachinePointerInfo(I.getArgOperand(0)), 6718 MachinePointerInfo(I.getArgOperand(1))); 6719 assert(MC.getNode() != nullptr && 6720 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6721 DAG.setRoot(MC); 6722 6723 // Check if Size needs to be truncated or extended. 6724 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6725 6726 // Adjust return pointer to point just past the last dst byte. 6727 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6728 Dst, Size); 6729 setValue(&I, DstPlusSize); 6730 return true; 6731 } 6732 6733 /// See if we can lower a strcpy call into an optimized form. If so, return 6734 /// true and lower it, otherwise return false and it will be lowered like a 6735 /// normal call. 6736 /// The caller already checked that \p I calls the appropriate LibFunc with a 6737 /// correct prototype. 6738 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6739 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6740 6741 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6742 std::pair<SDValue, SDValue> Res = 6743 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6744 getValue(Arg0), getValue(Arg1), 6745 MachinePointerInfo(Arg0), 6746 MachinePointerInfo(Arg1), isStpcpy); 6747 if (Res.first.getNode()) { 6748 setValue(&I, Res.first); 6749 DAG.setRoot(Res.second); 6750 return true; 6751 } 6752 6753 return false; 6754 } 6755 6756 /// See if we can lower a strcmp call into an optimized form. If so, return 6757 /// true and lower it, otherwise return false and it will be lowered like a 6758 /// normal call. 6759 /// The caller already checked that \p I calls the appropriate LibFunc with a 6760 /// correct prototype. 6761 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6762 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6763 6764 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6765 std::pair<SDValue, SDValue> Res = 6766 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6767 getValue(Arg0), getValue(Arg1), 6768 MachinePointerInfo(Arg0), 6769 MachinePointerInfo(Arg1)); 6770 if (Res.first.getNode()) { 6771 processIntegerCallValue(I, Res.first, true); 6772 PendingLoads.push_back(Res.second); 6773 return true; 6774 } 6775 6776 return false; 6777 } 6778 6779 /// See if we can lower a strlen call into an optimized form. If so, return 6780 /// true and lower it, otherwise return false and it will be lowered like a 6781 /// normal call. 6782 /// The caller already checked that \p I calls the appropriate LibFunc with a 6783 /// correct prototype. 6784 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6785 const Value *Arg0 = I.getArgOperand(0); 6786 6787 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6788 std::pair<SDValue, SDValue> Res = 6789 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6790 getValue(Arg0), MachinePointerInfo(Arg0)); 6791 if (Res.first.getNode()) { 6792 processIntegerCallValue(I, Res.first, false); 6793 PendingLoads.push_back(Res.second); 6794 return true; 6795 } 6796 6797 return false; 6798 } 6799 6800 /// See if we can lower a strnlen call into an optimized form. If so, return 6801 /// true and lower it, otherwise return false and it will be lowered like a 6802 /// normal call. 6803 /// The caller already checked that \p I calls the appropriate LibFunc with a 6804 /// correct prototype. 6805 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6806 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6807 6808 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6809 std::pair<SDValue, SDValue> Res = 6810 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6811 getValue(Arg0), getValue(Arg1), 6812 MachinePointerInfo(Arg0)); 6813 if (Res.first.getNode()) { 6814 processIntegerCallValue(I, Res.first, false); 6815 PendingLoads.push_back(Res.second); 6816 return true; 6817 } 6818 6819 return false; 6820 } 6821 6822 /// See if we can lower a unary floating-point operation into an SDNode with 6823 /// the specified Opcode. If so, return true and lower it, otherwise return 6824 /// false and it will be lowered like a normal call. 6825 /// The caller already checked that \p I calls the appropriate LibFunc with a 6826 /// correct prototype. 6827 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6828 unsigned Opcode) { 6829 // We already checked this call's prototype; verify it doesn't modify errno. 6830 if (!I.onlyReadsMemory()) 6831 return false; 6832 6833 SDValue Tmp = getValue(I.getArgOperand(0)); 6834 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6835 return true; 6836 } 6837 6838 /// See if we can lower a binary floating-point operation into an SDNode with 6839 /// the specified Opcode. If so, return true and lower it. Otherwise return 6840 /// false, and it will be lowered like a normal call. 6841 /// The caller already checked that \p I calls the appropriate LibFunc with a 6842 /// correct prototype. 6843 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6844 unsigned Opcode) { 6845 // We already checked this call's prototype; verify it doesn't modify errno. 6846 if (!I.onlyReadsMemory()) 6847 return false; 6848 6849 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6850 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6851 EVT VT = Tmp0.getValueType(); 6852 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6853 return true; 6854 } 6855 6856 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6857 // Handle inline assembly differently. 6858 if (isa<InlineAsm>(I.getCalledValue())) { 6859 visitInlineAsm(&I); 6860 return; 6861 } 6862 6863 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6864 computeUsesVAFloatArgument(I, MMI); 6865 6866 const char *RenameFn = nullptr; 6867 if (Function *F = I.getCalledFunction()) { 6868 if (F->isDeclaration()) { 6869 // Is this an LLVM intrinsic or a target-specific intrinsic? 6870 unsigned IID = F->getIntrinsicID(); 6871 if (!IID) 6872 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6873 IID = II->getIntrinsicID(F); 6874 6875 if (IID) { 6876 RenameFn = visitIntrinsicCall(I, IID); 6877 if (!RenameFn) 6878 return; 6879 } 6880 } 6881 6882 // Check for well-known libc/libm calls. If the function is internal, it 6883 // can't be a library call. Don't do the check if marked as nobuiltin for 6884 // some reason or the call site requires strict floating point semantics. 6885 LibFunc Func; 6886 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6887 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6888 LibInfo->hasOptimizedCodeGen(Func)) { 6889 switch (Func) { 6890 default: break; 6891 case LibFunc_copysign: 6892 case LibFunc_copysignf: 6893 case LibFunc_copysignl: 6894 // We already checked this call's prototype; verify it doesn't modify 6895 // errno. 6896 if (I.onlyReadsMemory()) { 6897 SDValue LHS = getValue(I.getArgOperand(0)); 6898 SDValue RHS = getValue(I.getArgOperand(1)); 6899 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6900 LHS.getValueType(), LHS, RHS)); 6901 return; 6902 } 6903 break; 6904 case LibFunc_fabs: 6905 case LibFunc_fabsf: 6906 case LibFunc_fabsl: 6907 if (visitUnaryFloatCall(I, ISD::FABS)) 6908 return; 6909 break; 6910 case LibFunc_fmin: 6911 case LibFunc_fminf: 6912 case LibFunc_fminl: 6913 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6914 return; 6915 break; 6916 case LibFunc_fmax: 6917 case LibFunc_fmaxf: 6918 case LibFunc_fmaxl: 6919 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6920 return; 6921 break; 6922 case LibFunc_sin: 6923 case LibFunc_sinf: 6924 case LibFunc_sinl: 6925 if (visitUnaryFloatCall(I, ISD::FSIN)) 6926 return; 6927 break; 6928 case LibFunc_cos: 6929 case LibFunc_cosf: 6930 case LibFunc_cosl: 6931 if (visitUnaryFloatCall(I, ISD::FCOS)) 6932 return; 6933 break; 6934 case LibFunc_sqrt: 6935 case LibFunc_sqrtf: 6936 case LibFunc_sqrtl: 6937 case LibFunc_sqrt_finite: 6938 case LibFunc_sqrtf_finite: 6939 case LibFunc_sqrtl_finite: 6940 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6941 return; 6942 break; 6943 case LibFunc_floor: 6944 case LibFunc_floorf: 6945 case LibFunc_floorl: 6946 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6947 return; 6948 break; 6949 case LibFunc_nearbyint: 6950 case LibFunc_nearbyintf: 6951 case LibFunc_nearbyintl: 6952 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6953 return; 6954 break; 6955 case LibFunc_ceil: 6956 case LibFunc_ceilf: 6957 case LibFunc_ceill: 6958 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6959 return; 6960 break; 6961 case LibFunc_rint: 6962 case LibFunc_rintf: 6963 case LibFunc_rintl: 6964 if (visitUnaryFloatCall(I, ISD::FRINT)) 6965 return; 6966 break; 6967 case LibFunc_round: 6968 case LibFunc_roundf: 6969 case LibFunc_roundl: 6970 if (visitUnaryFloatCall(I, ISD::FROUND)) 6971 return; 6972 break; 6973 case LibFunc_trunc: 6974 case LibFunc_truncf: 6975 case LibFunc_truncl: 6976 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6977 return; 6978 break; 6979 case LibFunc_log2: 6980 case LibFunc_log2f: 6981 case LibFunc_log2l: 6982 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6983 return; 6984 break; 6985 case LibFunc_exp2: 6986 case LibFunc_exp2f: 6987 case LibFunc_exp2l: 6988 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6989 return; 6990 break; 6991 case LibFunc_memcmp: 6992 if (visitMemCmpCall(I)) 6993 return; 6994 break; 6995 case LibFunc_mempcpy: 6996 if (visitMemPCpyCall(I)) 6997 return; 6998 break; 6999 case LibFunc_memchr: 7000 if (visitMemChrCall(I)) 7001 return; 7002 break; 7003 case LibFunc_strcpy: 7004 if (visitStrCpyCall(I, false)) 7005 return; 7006 break; 7007 case LibFunc_stpcpy: 7008 if (visitStrCpyCall(I, true)) 7009 return; 7010 break; 7011 case LibFunc_strcmp: 7012 if (visitStrCmpCall(I)) 7013 return; 7014 break; 7015 case LibFunc_strlen: 7016 if (visitStrLenCall(I)) 7017 return; 7018 break; 7019 case LibFunc_strnlen: 7020 if (visitStrNLenCall(I)) 7021 return; 7022 break; 7023 } 7024 } 7025 } 7026 7027 SDValue Callee; 7028 if (!RenameFn) 7029 Callee = getValue(I.getCalledValue()); 7030 else 7031 Callee = DAG.getExternalSymbol( 7032 RenameFn, 7033 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7034 7035 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7036 // have to do anything here to lower funclet bundles. 7037 assert(!I.hasOperandBundlesOtherThan( 7038 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7039 "Cannot lower calls with arbitrary operand bundles!"); 7040 7041 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7042 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7043 else 7044 // Check if we can potentially perform a tail call. More detailed checking 7045 // is be done within LowerCallTo, after more information about the call is 7046 // known. 7047 LowerCallTo(&I, Callee, I.isTailCall()); 7048 } 7049 7050 namespace { 7051 7052 /// AsmOperandInfo - This contains information for each constraint that we are 7053 /// lowering. 7054 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7055 public: 7056 /// CallOperand - If this is the result output operand or a clobber 7057 /// this is null, otherwise it is the incoming operand to the CallInst. 7058 /// This gets modified as the asm is processed. 7059 SDValue CallOperand; 7060 7061 /// AssignedRegs - If this is a register or register class operand, this 7062 /// contains the set of register corresponding to the operand. 7063 RegsForValue AssignedRegs; 7064 7065 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7066 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7067 } 7068 7069 /// Whether or not this operand accesses memory 7070 bool hasMemory(const TargetLowering &TLI) const { 7071 // Indirect operand accesses access memory. 7072 if (isIndirect) 7073 return true; 7074 7075 for (const auto &Code : Codes) 7076 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7077 return true; 7078 7079 return false; 7080 } 7081 7082 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7083 /// corresponds to. If there is no Value* for this operand, it returns 7084 /// MVT::Other. 7085 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7086 const DataLayout &DL) const { 7087 if (!CallOperandVal) return MVT::Other; 7088 7089 if (isa<BasicBlock>(CallOperandVal)) 7090 return TLI.getPointerTy(DL); 7091 7092 llvm::Type *OpTy = CallOperandVal->getType(); 7093 7094 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7095 // If this is an indirect operand, the operand is a pointer to the 7096 // accessed type. 7097 if (isIndirect) { 7098 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7099 if (!PtrTy) 7100 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7101 OpTy = PtrTy->getElementType(); 7102 } 7103 7104 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7105 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7106 if (STy->getNumElements() == 1) 7107 OpTy = STy->getElementType(0); 7108 7109 // If OpTy is not a single value, it may be a struct/union that we 7110 // can tile with integers. 7111 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7112 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7113 switch (BitSize) { 7114 default: break; 7115 case 1: 7116 case 8: 7117 case 16: 7118 case 32: 7119 case 64: 7120 case 128: 7121 OpTy = IntegerType::get(Context, BitSize); 7122 break; 7123 } 7124 } 7125 7126 return TLI.getValueType(DL, OpTy, true); 7127 } 7128 }; 7129 7130 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7131 7132 } // end anonymous namespace 7133 7134 /// Make sure that the output operand \p OpInfo and its corresponding input 7135 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7136 /// out). 7137 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7138 SDISelAsmOperandInfo &MatchingOpInfo, 7139 SelectionDAG &DAG) { 7140 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7141 return; 7142 7143 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7144 const auto &TLI = DAG.getTargetLoweringInfo(); 7145 7146 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7147 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7148 OpInfo.ConstraintVT); 7149 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7150 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7151 MatchingOpInfo.ConstraintVT); 7152 if ((OpInfo.ConstraintVT.isInteger() != 7153 MatchingOpInfo.ConstraintVT.isInteger()) || 7154 (MatchRC.second != InputRC.second)) { 7155 // FIXME: error out in a more elegant fashion 7156 report_fatal_error("Unsupported asm: input constraint" 7157 " with a matching output constraint of" 7158 " incompatible type!"); 7159 } 7160 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7161 } 7162 7163 /// Get a direct memory input to behave well as an indirect operand. 7164 /// This may introduce stores, hence the need for a \p Chain. 7165 /// \return The (possibly updated) chain. 7166 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7167 SDISelAsmOperandInfo &OpInfo, 7168 SelectionDAG &DAG) { 7169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7170 7171 // If we don't have an indirect input, put it in the constpool if we can, 7172 // otherwise spill it to a stack slot. 7173 // TODO: This isn't quite right. We need to handle these according to 7174 // the addressing mode that the constraint wants. Also, this may take 7175 // an additional register for the computation and we don't want that 7176 // either. 7177 7178 // If the operand is a float, integer, or vector constant, spill to a 7179 // constant pool entry to get its address. 7180 const Value *OpVal = OpInfo.CallOperandVal; 7181 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7182 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7183 OpInfo.CallOperand = DAG.getConstantPool( 7184 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7185 return Chain; 7186 } 7187 7188 // Otherwise, create a stack slot and emit a store to it before the asm. 7189 Type *Ty = OpVal->getType(); 7190 auto &DL = DAG.getDataLayout(); 7191 uint64_t TySize = DL.getTypeAllocSize(Ty); 7192 unsigned Align = DL.getPrefTypeAlignment(Ty); 7193 MachineFunction &MF = DAG.getMachineFunction(); 7194 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7195 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7196 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7197 MachinePointerInfo::getFixedStack(MF, SSFI)); 7198 OpInfo.CallOperand = StackSlot; 7199 7200 return Chain; 7201 } 7202 7203 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7204 /// specified operand. We prefer to assign virtual registers, to allow the 7205 /// register allocator to handle the assignment process. However, if the asm 7206 /// uses features that we can't model on machineinstrs, we have SDISel do the 7207 /// allocation. This produces generally horrible, but correct, code. 7208 /// 7209 /// OpInfo describes the operand 7210 /// RefOpInfo describes the matching operand if any, the operand otherwise 7211 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7212 const SDLoc &DL, SDISelAsmOperandInfo &OpInfo, 7213 SDISelAsmOperandInfo &RefOpInfo) { 7214 LLVMContext &Context = *DAG.getContext(); 7215 7216 MachineFunction &MF = DAG.getMachineFunction(); 7217 SmallVector<unsigned, 4> Regs; 7218 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7219 7220 // If this is a constraint for a single physreg, or a constraint for a 7221 // register class, find it. 7222 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7223 TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode, 7224 RefOpInfo.ConstraintVT); 7225 7226 unsigned NumRegs = 1; 7227 if (OpInfo.ConstraintVT != MVT::Other) { 7228 // If this is a FP operand in an integer register (or visa versa), or more 7229 // generally if the operand value disagrees with the register class we plan 7230 // to stick it in, fix the operand type. 7231 // 7232 // If this is an input value, the bitcast to the new type is done now. 7233 // Bitcast for output value is done at the end of visitInlineAsm(). 7234 if ((OpInfo.Type == InlineAsm::isOutput || 7235 OpInfo.Type == InlineAsm::isInput) && 7236 PhysReg.second && 7237 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7238 // Try to convert to the first EVT that the reg class contains. If the 7239 // types are identical size, use a bitcast to convert (e.g. two differing 7240 // vector types). Note: output bitcast is done at the end of 7241 // visitInlineAsm(). 7242 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7243 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7244 // Exclude indirect inputs while they are unsupported because the code 7245 // to perform the load is missing and thus OpInfo.CallOperand still 7246 // refer to the input address rather than the pointed-to value. 7247 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7248 OpInfo.CallOperand = 7249 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7250 OpInfo.ConstraintVT = RegVT; 7251 // If the operand is a FP value and we want it in integer registers, 7252 // use the corresponding integer type. This turns an f64 value into 7253 // i64, which can be passed with two i32 values on a 32-bit machine. 7254 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7255 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7256 if (OpInfo.Type == InlineAsm::isInput) 7257 OpInfo.CallOperand = 7258 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7259 OpInfo.ConstraintVT = RegVT; 7260 } 7261 } 7262 7263 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7264 } 7265 7266 // No need to allocate a matching input constraint since the constraint it's 7267 // matching to has already been allocated. 7268 if (OpInfo.isMatchingInputConstraint()) 7269 return; 7270 7271 MVT RegVT; 7272 EVT ValueVT = OpInfo.ConstraintVT; 7273 7274 // If this is a constraint for a specific physical register, like {r17}, 7275 // assign it now. 7276 if (unsigned AssignedReg = PhysReg.first) { 7277 const TargetRegisterClass *RC = PhysReg.second; 7278 if (OpInfo.ConstraintVT == MVT::Other) 7279 ValueVT = *TRI.legalclasstypes_begin(*RC); 7280 7281 // Get the actual register value type. This is important, because the user 7282 // may have asked for (e.g.) the AX register in i32 type. We need to 7283 // remember that AX is actually i16 to get the right extension. 7284 RegVT = *TRI.legalclasstypes_begin(*RC); 7285 7286 // This is a explicit reference to a physical register. 7287 Regs.push_back(AssignedReg); 7288 7289 // If this is an expanded reference, add the rest of the regs to Regs. 7290 if (NumRegs != 1) { 7291 TargetRegisterClass::iterator I = RC->begin(); 7292 for (; *I != AssignedReg; ++I) 7293 assert(I != RC->end() && "Didn't find reg!"); 7294 7295 // Already added the first reg. 7296 --NumRegs; ++I; 7297 for (; NumRegs; --NumRegs, ++I) { 7298 assert(I != RC->end() && "Ran out of registers to allocate!"); 7299 Regs.push_back(*I); 7300 } 7301 } 7302 7303 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7304 return; 7305 } 7306 7307 // Otherwise, if this was a reference to an LLVM register class, create vregs 7308 // for this reference. 7309 if (const TargetRegisterClass *RC = PhysReg.second) { 7310 RegVT = *TRI.legalclasstypes_begin(*RC); 7311 if (OpInfo.ConstraintVT == MVT::Other) 7312 ValueVT = RegVT; 7313 7314 // Create the appropriate number of virtual registers. 7315 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7316 for (; NumRegs; --NumRegs) 7317 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7318 7319 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7320 return; 7321 } 7322 7323 // Otherwise, we couldn't allocate enough registers for this. 7324 } 7325 7326 static unsigned 7327 findMatchingInlineAsmOperand(unsigned OperandNo, 7328 const std::vector<SDValue> &AsmNodeOperands) { 7329 // Scan until we find the definition we already emitted of this operand. 7330 unsigned CurOp = InlineAsm::Op_FirstOperand; 7331 for (; OperandNo; --OperandNo) { 7332 // Advance to the next operand. 7333 unsigned OpFlag = 7334 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7335 assert((InlineAsm::isRegDefKind(OpFlag) || 7336 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7337 InlineAsm::isMemKind(OpFlag)) && 7338 "Skipped past definitions?"); 7339 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7340 } 7341 return CurOp; 7342 } 7343 7344 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7345 /// \return true if it has succeeded, false otherwise 7346 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7347 MVT RegVT, SelectionDAG &DAG) { 7348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7349 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7350 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7351 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7352 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7353 else 7354 return false; 7355 } 7356 return true; 7357 } 7358 7359 namespace { 7360 7361 class ExtraFlags { 7362 unsigned Flags = 0; 7363 7364 public: 7365 explicit ExtraFlags(ImmutableCallSite CS) { 7366 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7367 if (IA->hasSideEffects()) 7368 Flags |= InlineAsm::Extra_HasSideEffects; 7369 if (IA->isAlignStack()) 7370 Flags |= InlineAsm::Extra_IsAlignStack; 7371 if (CS.isConvergent()) 7372 Flags |= InlineAsm::Extra_IsConvergent; 7373 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7374 } 7375 7376 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7377 // Ideally, we would only check against memory constraints. However, the 7378 // meaning of an Other constraint can be target-specific and we can't easily 7379 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7380 // for Other constraints as well. 7381 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7382 OpInfo.ConstraintType == TargetLowering::C_Other) { 7383 if (OpInfo.Type == InlineAsm::isInput) 7384 Flags |= InlineAsm::Extra_MayLoad; 7385 else if (OpInfo.Type == InlineAsm::isOutput) 7386 Flags |= InlineAsm::Extra_MayStore; 7387 else if (OpInfo.Type == InlineAsm::isClobber) 7388 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7389 } 7390 } 7391 7392 unsigned get() const { return Flags; } 7393 }; 7394 7395 } // end anonymous namespace 7396 7397 /// visitInlineAsm - Handle a call to an InlineAsm object. 7398 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7399 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7400 7401 /// ConstraintOperands - Information about all of the constraints. 7402 SDISelAsmOperandInfoVector ConstraintOperands; 7403 7404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7405 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7406 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7407 7408 bool hasMemory = false; 7409 7410 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7411 ExtraFlags ExtraInfo(CS); 7412 7413 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7414 unsigned ResNo = 0; // ResNo - The result number of the next output. 7415 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7416 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7417 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7418 7419 MVT OpVT = MVT::Other; 7420 7421 // Compute the value type for each operand. 7422 if (OpInfo.Type == InlineAsm::isInput || 7423 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7424 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7425 7426 // Process the call argument. BasicBlocks are labels, currently appearing 7427 // only in asm's. 7428 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7429 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7430 } else { 7431 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7432 } 7433 7434 OpVT = 7435 OpInfo 7436 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7437 .getSimpleVT(); 7438 } 7439 7440 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7441 // The return value of the call is this value. As such, there is no 7442 // corresponding argument. 7443 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7444 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7445 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7446 STy->getElementType(ResNo)); 7447 } else { 7448 assert(ResNo == 0 && "Asm only has one result!"); 7449 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7450 } 7451 ++ResNo; 7452 } 7453 7454 OpInfo.ConstraintVT = OpVT; 7455 7456 if (!hasMemory) 7457 hasMemory = OpInfo.hasMemory(TLI); 7458 7459 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7460 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7461 auto TargetConstraint = TargetConstraints[i]; 7462 7463 // Compute the constraint code and ConstraintType to use. 7464 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7465 7466 ExtraInfo.update(TargetConstraint); 7467 } 7468 7469 SDValue Chain, Flag; 7470 7471 // We won't need to flush pending loads if this asm doesn't touch 7472 // memory and is nonvolatile. 7473 if (hasMemory || IA->hasSideEffects()) 7474 Chain = getRoot(); 7475 else 7476 Chain = DAG.getRoot(); 7477 7478 // Second pass over the constraints: compute which constraint option to use 7479 // and assign registers to constraints that want a specific physreg. 7480 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7481 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7482 7483 // If this is an output operand with a matching input operand, look up the 7484 // matching input. If their types mismatch, e.g. one is an integer, the 7485 // other is floating point, or their sizes are different, flag it as an 7486 // error. 7487 if (OpInfo.hasMatchingInput()) { 7488 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7489 patchMatchingInput(OpInfo, Input, DAG); 7490 } 7491 7492 // Compute the constraint code and ConstraintType to use. 7493 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7494 7495 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7496 OpInfo.Type == InlineAsm::isClobber) 7497 continue; 7498 7499 // If this is a memory input, and if the operand is not indirect, do what we 7500 // need to provide an address for the memory input. 7501 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7502 !OpInfo.isIndirect) { 7503 assert((OpInfo.isMultipleAlternative || 7504 (OpInfo.Type == InlineAsm::isInput)) && 7505 "Can only indirectify direct input operands!"); 7506 7507 // Memory operands really want the address of the value. 7508 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7509 7510 // There is no longer a Value* corresponding to this operand. 7511 OpInfo.CallOperandVal = nullptr; 7512 7513 // It is now an indirect operand. 7514 OpInfo.isIndirect = true; 7515 } 7516 7517 // If this constraint is for a specific register, allocate it before 7518 // anything else. 7519 SDISelAsmOperandInfo &RefOpInfo = 7520 OpInfo.isMatchingInputConstraint() 7521 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7522 : ConstraintOperands[i]; 7523 if (RefOpInfo.ConstraintType == TargetLowering::C_Register) 7524 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7525 } 7526 7527 // Third pass - Loop over all of the operands, assigning virtual or physregs 7528 // to register class operands. 7529 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7530 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7531 SDISelAsmOperandInfo &RefOpInfo = 7532 OpInfo.isMatchingInputConstraint() 7533 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7534 : ConstraintOperands[i]; 7535 7536 // C_Register operands have already been allocated, Other/Memory don't need 7537 // to be. 7538 if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7539 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo); 7540 } 7541 7542 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7543 std::vector<SDValue> AsmNodeOperands; 7544 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7545 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7546 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7547 7548 // If we have a !srcloc metadata node associated with it, we want to attach 7549 // this to the ultimately generated inline asm machineinstr. To do this, we 7550 // pass in the third operand as this (potentially null) inline asm MDNode. 7551 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7552 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7553 7554 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7555 // bits as operand 3. 7556 AsmNodeOperands.push_back(DAG.getTargetConstant( 7557 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7558 7559 // Loop over all of the inputs, copying the operand values into the 7560 // appropriate registers and processing the output regs. 7561 RegsForValue RetValRegs; 7562 7563 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7564 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7565 7566 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7567 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7568 7569 switch (OpInfo.Type) { 7570 case InlineAsm::isOutput: 7571 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7572 OpInfo.ConstraintType != TargetLowering::C_Register) { 7573 // Memory output, or 'other' output (e.g. 'X' constraint). 7574 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7575 7576 unsigned ConstraintID = 7577 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7578 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7579 "Failed to convert memory constraint code to constraint id."); 7580 7581 // Add information to the INLINEASM node to know about this output. 7582 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7583 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7584 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7585 MVT::i32)); 7586 AsmNodeOperands.push_back(OpInfo.CallOperand); 7587 break; 7588 } 7589 7590 // Otherwise, this is a register or register class output. 7591 7592 // Copy the output from the appropriate register. Find a register that 7593 // we can use. 7594 if (OpInfo.AssignedRegs.Regs.empty()) { 7595 emitInlineAsmError( 7596 CS, "couldn't allocate output register for constraint '" + 7597 Twine(OpInfo.ConstraintCode) + "'"); 7598 return; 7599 } 7600 7601 // If this is an indirect operand, store through the pointer after the 7602 // asm. 7603 if (OpInfo.isIndirect) { 7604 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7605 OpInfo.CallOperandVal)); 7606 } else { 7607 // This is the result value of the call. 7608 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7609 // Concatenate this output onto the outputs list. 7610 RetValRegs.append(OpInfo.AssignedRegs); 7611 } 7612 7613 // Add information to the INLINEASM node to know that this register is 7614 // set. 7615 OpInfo.AssignedRegs 7616 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7617 ? InlineAsm::Kind_RegDefEarlyClobber 7618 : InlineAsm::Kind_RegDef, 7619 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7620 break; 7621 7622 case InlineAsm::isInput: { 7623 SDValue InOperandVal = OpInfo.CallOperand; 7624 7625 if (OpInfo.isMatchingInputConstraint()) { 7626 // If this is required to match an output register we have already set, 7627 // just use its register. 7628 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7629 AsmNodeOperands); 7630 unsigned OpFlag = 7631 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7632 if (InlineAsm::isRegDefKind(OpFlag) || 7633 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7634 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7635 if (OpInfo.isIndirect) { 7636 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7637 emitInlineAsmError(CS, "inline asm not supported yet:" 7638 " don't know how to handle tied " 7639 "indirect register inputs"); 7640 return; 7641 } 7642 7643 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7644 SmallVector<unsigned, 4> Regs; 7645 7646 if (!createVirtualRegs(Regs, 7647 InlineAsm::getNumOperandRegisters(OpFlag), 7648 RegVT, DAG)) { 7649 emitInlineAsmError(CS, "inline asm error: This value type register " 7650 "class is not natively supported!"); 7651 return; 7652 } 7653 7654 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7655 7656 SDLoc dl = getCurSDLoc(); 7657 // Use the produced MatchedRegs object to 7658 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7659 CS.getInstruction()); 7660 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7661 true, OpInfo.getMatchedOperand(), dl, 7662 DAG, AsmNodeOperands); 7663 break; 7664 } 7665 7666 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7667 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7668 "Unexpected number of operands"); 7669 // Add information to the INLINEASM node to know about this input. 7670 // See InlineAsm.h isUseOperandTiedToDef. 7671 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7672 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7673 OpInfo.getMatchedOperand()); 7674 AsmNodeOperands.push_back(DAG.getTargetConstant( 7675 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7676 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7677 break; 7678 } 7679 7680 // Treat indirect 'X' constraint as memory. 7681 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7682 OpInfo.isIndirect) 7683 OpInfo.ConstraintType = TargetLowering::C_Memory; 7684 7685 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7686 std::vector<SDValue> Ops; 7687 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7688 Ops, DAG); 7689 if (Ops.empty()) { 7690 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7691 Twine(OpInfo.ConstraintCode) + "'"); 7692 return; 7693 } 7694 7695 // Add information to the INLINEASM node to know about this input. 7696 unsigned ResOpType = 7697 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7698 AsmNodeOperands.push_back(DAG.getTargetConstant( 7699 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7700 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7701 break; 7702 } 7703 7704 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7705 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7706 assert(InOperandVal.getValueType() == 7707 TLI.getPointerTy(DAG.getDataLayout()) && 7708 "Memory operands expect pointer values"); 7709 7710 unsigned ConstraintID = 7711 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7712 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7713 "Failed to convert memory constraint code to constraint id."); 7714 7715 // Add information to the INLINEASM node to know about this input. 7716 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7717 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7718 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7719 getCurSDLoc(), 7720 MVT::i32)); 7721 AsmNodeOperands.push_back(InOperandVal); 7722 break; 7723 } 7724 7725 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7726 OpInfo.ConstraintType == TargetLowering::C_Register) && 7727 "Unknown constraint type!"); 7728 7729 // TODO: Support this. 7730 if (OpInfo.isIndirect) { 7731 emitInlineAsmError( 7732 CS, "Don't know how to handle indirect register inputs yet " 7733 "for constraint '" + 7734 Twine(OpInfo.ConstraintCode) + "'"); 7735 return; 7736 } 7737 7738 // Copy the input into the appropriate registers. 7739 if (OpInfo.AssignedRegs.Regs.empty()) { 7740 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7741 Twine(OpInfo.ConstraintCode) + "'"); 7742 return; 7743 } 7744 7745 SDLoc dl = getCurSDLoc(); 7746 7747 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7748 Chain, &Flag, CS.getInstruction()); 7749 7750 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7751 dl, DAG, AsmNodeOperands); 7752 break; 7753 } 7754 case InlineAsm::isClobber: 7755 // Add the clobbered value to the operand list, so that the register 7756 // allocator is aware that the physreg got clobbered. 7757 if (!OpInfo.AssignedRegs.Regs.empty()) 7758 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7759 false, 0, getCurSDLoc(), DAG, 7760 AsmNodeOperands); 7761 break; 7762 } 7763 } 7764 7765 // Finish up input operands. Set the input chain and add the flag last. 7766 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7767 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7768 7769 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7770 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7771 Flag = Chain.getValue(1); 7772 7773 // If this asm returns a register value, copy the result from that register 7774 // and set it as the value of the call. 7775 if (!RetValRegs.Regs.empty()) { 7776 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7777 Chain, &Flag, CS.getInstruction()); 7778 7779 // FIXME: Why don't we do this for inline asms with MRVs? 7780 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7781 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7782 7783 // If the type of the inline asm call site return value is different but 7784 // has same size as the type of the asm output bitcast it. One example 7785 // of this is for vectors with different width / number of elements. 7786 // This can happen for register classes that can contain multiple 7787 // different value types. The preg or vreg allocated may not have the 7788 // same VT as was expected. 7789 // 7790 // This can also happen for a return value that disagrees with the 7791 // register class it is put in, eg. a double in a general-purpose 7792 // register on a 32-bit machine. 7793 if (ResultType != Val.getValueType() && 7794 ResultType.getSizeInBits() == Val.getValueSizeInBits()) { 7795 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7796 ResultType, Val); 7797 7798 } else if (ResultType != Val.getValueType() && 7799 ResultType.isInteger() && Val.getValueType().isInteger()) { 7800 // If a result value was tied to an input value, the computed result may 7801 // have a wider width than the expected result. Extract the relevant 7802 // portion. 7803 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7804 } 7805 7806 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7807 } 7808 7809 setValue(CS.getInstruction(), Val); 7810 // Don't need to use this as a chain in this case. 7811 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7812 return; 7813 } 7814 7815 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7816 7817 // Process indirect outputs, first output all of the flagged copies out of 7818 // physregs. 7819 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7820 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7821 const Value *Ptr = IndirectStoresToEmit[i].second; 7822 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7823 Chain, &Flag, IA); 7824 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7825 } 7826 7827 // Emit the non-flagged stores from the physregs. 7828 SmallVector<SDValue, 8> OutChains; 7829 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7830 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7831 getValue(StoresToEmit[i].second), 7832 MachinePointerInfo(StoresToEmit[i].second)); 7833 OutChains.push_back(Val); 7834 } 7835 7836 if (!OutChains.empty()) 7837 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7838 7839 DAG.setRoot(Chain); 7840 } 7841 7842 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7843 const Twine &Message) { 7844 LLVMContext &Ctx = *DAG.getContext(); 7845 Ctx.emitError(CS.getInstruction(), Message); 7846 7847 // Make sure we leave the DAG in a valid state 7848 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7849 SmallVector<EVT, 1> ValueVTs; 7850 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7851 7852 if (ValueVTs.empty()) 7853 return; 7854 7855 SmallVector<SDValue, 1> Ops; 7856 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7857 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7858 7859 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7860 } 7861 7862 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7863 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7864 MVT::Other, getRoot(), 7865 getValue(I.getArgOperand(0)), 7866 DAG.getSrcValue(I.getArgOperand(0)))); 7867 } 7868 7869 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7870 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7871 const DataLayout &DL = DAG.getDataLayout(); 7872 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7873 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7874 DAG.getSrcValue(I.getOperand(0)), 7875 DL.getABITypeAlignment(I.getType())); 7876 setValue(&I, V); 7877 DAG.setRoot(V.getValue(1)); 7878 } 7879 7880 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7881 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7882 MVT::Other, getRoot(), 7883 getValue(I.getArgOperand(0)), 7884 DAG.getSrcValue(I.getArgOperand(0)))); 7885 } 7886 7887 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7888 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7889 MVT::Other, getRoot(), 7890 getValue(I.getArgOperand(0)), 7891 getValue(I.getArgOperand(1)), 7892 DAG.getSrcValue(I.getArgOperand(0)), 7893 DAG.getSrcValue(I.getArgOperand(1)))); 7894 } 7895 7896 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7897 const Instruction &I, 7898 SDValue Op) { 7899 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7900 if (!Range) 7901 return Op; 7902 7903 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7904 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7905 return Op; 7906 7907 APInt Lo = CR.getUnsignedMin(); 7908 if (!Lo.isMinValue()) 7909 return Op; 7910 7911 APInt Hi = CR.getUnsignedMax(); 7912 unsigned Bits = Hi.getActiveBits(); 7913 7914 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7915 7916 SDLoc SL = getCurSDLoc(); 7917 7918 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7919 DAG.getValueType(SmallVT)); 7920 unsigned NumVals = Op.getNode()->getNumValues(); 7921 if (NumVals == 1) 7922 return ZExt; 7923 7924 SmallVector<SDValue, 4> Ops; 7925 7926 Ops.push_back(ZExt); 7927 for (unsigned I = 1; I != NumVals; ++I) 7928 Ops.push_back(Op.getValue(I)); 7929 7930 return DAG.getMergeValues(Ops, SL); 7931 } 7932 7933 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 7934 /// the call being lowered. 7935 /// 7936 /// This is a helper for lowering intrinsics that follow a target calling 7937 /// convention or require stack pointer adjustment. Only a subset of the 7938 /// intrinsic's operands need to participate in the calling convention. 7939 void SelectionDAGBuilder::populateCallLoweringInfo( 7940 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7941 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7942 bool IsPatchPoint) { 7943 TargetLowering::ArgListTy Args; 7944 Args.reserve(NumArgs); 7945 7946 // Populate the argument list. 7947 // Attributes for args start at offset 1, after the return attribute. 7948 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7949 ArgI != ArgE; ++ArgI) { 7950 const Value *V = CS->getOperand(ArgI); 7951 7952 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7953 7954 TargetLowering::ArgListEntry Entry; 7955 Entry.Node = getValue(V); 7956 Entry.Ty = V->getType(); 7957 Entry.setAttributes(&CS, ArgI); 7958 Args.push_back(Entry); 7959 } 7960 7961 CLI.setDebugLoc(getCurSDLoc()) 7962 .setChain(getRoot()) 7963 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7964 .setDiscardResult(CS->use_empty()) 7965 .setIsPatchPoint(IsPatchPoint); 7966 } 7967 7968 /// Add a stack map intrinsic call's live variable operands to a stackmap 7969 /// or patchpoint target node's operand list. 7970 /// 7971 /// Constants are converted to TargetConstants purely as an optimization to 7972 /// avoid constant materialization and register allocation. 7973 /// 7974 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7975 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7976 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7977 /// address materialization and register allocation, but may also be required 7978 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7979 /// alloca in the entry block, then the runtime may assume that the alloca's 7980 /// StackMap location can be read immediately after compilation and that the 7981 /// location is valid at any point during execution (this is similar to the 7982 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7983 /// only available in a register, then the runtime would need to trap when 7984 /// execution reaches the StackMap in order to read the alloca's location. 7985 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7986 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7987 SelectionDAGBuilder &Builder) { 7988 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7989 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7990 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7991 Ops.push_back( 7992 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7993 Ops.push_back( 7994 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7995 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7996 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7997 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7998 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 7999 } else 8000 Ops.push_back(OpVal); 8001 } 8002 } 8003 8004 /// Lower llvm.experimental.stackmap directly to its target opcode. 8005 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8006 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8007 // [live variables...]) 8008 8009 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8010 8011 SDValue Chain, InFlag, Callee, NullPtr; 8012 SmallVector<SDValue, 32> Ops; 8013 8014 SDLoc DL = getCurSDLoc(); 8015 Callee = getValue(CI.getCalledValue()); 8016 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8017 8018 // The stackmap intrinsic only records the live variables (the arguemnts 8019 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8020 // intrinsic, this won't be lowered to a function call. This means we don't 8021 // have to worry about calling conventions and target specific lowering code. 8022 // Instead we perform the call lowering right here. 8023 // 8024 // chain, flag = CALLSEQ_START(chain, 0, 0) 8025 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8026 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8027 // 8028 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8029 InFlag = Chain.getValue(1); 8030 8031 // Add the <id> and <numBytes> constants. 8032 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8033 Ops.push_back(DAG.getTargetConstant( 8034 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8035 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8036 Ops.push_back(DAG.getTargetConstant( 8037 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8038 MVT::i32)); 8039 8040 // Push live variables for the stack map. 8041 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8042 8043 // We are not pushing any register mask info here on the operands list, 8044 // because the stackmap doesn't clobber anything. 8045 8046 // Push the chain and the glue flag. 8047 Ops.push_back(Chain); 8048 Ops.push_back(InFlag); 8049 8050 // Create the STACKMAP node. 8051 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8052 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8053 Chain = SDValue(SM, 0); 8054 InFlag = Chain.getValue(1); 8055 8056 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8057 8058 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8059 8060 // Set the root to the target-lowered call chain. 8061 DAG.setRoot(Chain); 8062 8063 // Inform the Frame Information that we have a stackmap in this function. 8064 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8065 } 8066 8067 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8068 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8069 const BasicBlock *EHPadBB) { 8070 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8071 // i32 <numBytes>, 8072 // i8* <target>, 8073 // i32 <numArgs>, 8074 // [Args...], 8075 // [live variables...]) 8076 8077 CallingConv::ID CC = CS.getCallingConv(); 8078 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8079 bool HasDef = !CS->getType()->isVoidTy(); 8080 SDLoc dl = getCurSDLoc(); 8081 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8082 8083 // Handle immediate and symbolic callees. 8084 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8085 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8086 /*isTarget=*/true); 8087 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8088 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8089 SDLoc(SymbolicCallee), 8090 SymbolicCallee->getValueType(0)); 8091 8092 // Get the real number of arguments participating in the call <numArgs> 8093 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8094 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8095 8096 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8097 // Intrinsics include all meta-operands up to but not including CC. 8098 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8099 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8100 "Not enough arguments provided to the patchpoint intrinsic"); 8101 8102 // For AnyRegCC the arguments are lowered later on manually. 8103 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8104 Type *ReturnTy = 8105 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8106 8107 TargetLowering::CallLoweringInfo CLI(DAG); 8108 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8109 true); 8110 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8111 8112 SDNode *CallEnd = Result.second.getNode(); 8113 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8114 CallEnd = CallEnd->getOperand(0).getNode(); 8115 8116 /// Get a call instruction from the call sequence chain. 8117 /// Tail calls are not allowed. 8118 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8119 "Expected a callseq node."); 8120 SDNode *Call = CallEnd->getOperand(0).getNode(); 8121 bool HasGlue = Call->getGluedNode(); 8122 8123 // Replace the target specific call node with the patchable intrinsic. 8124 SmallVector<SDValue, 8> Ops; 8125 8126 // Add the <id> and <numBytes> constants. 8127 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8128 Ops.push_back(DAG.getTargetConstant( 8129 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8130 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8131 Ops.push_back(DAG.getTargetConstant( 8132 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8133 MVT::i32)); 8134 8135 // Add the callee. 8136 Ops.push_back(Callee); 8137 8138 // Adjust <numArgs> to account for any arguments that have been passed on the 8139 // stack instead. 8140 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8141 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8142 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8143 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8144 8145 // Add the calling convention 8146 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8147 8148 // Add the arguments we omitted previously. The register allocator should 8149 // place these in any free register. 8150 if (IsAnyRegCC) 8151 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8152 Ops.push_back(getValue(CS.getArgument(i))); 8153 8154 // Push the arguments from the call instruction up to the register mask. 8155 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8156 Ops.append(Call->op_begin() + 2, e); 8157 8158 // Push live variables for the stack map. 8159 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8160 8161 // Push the register mask info. 8162 if (HasGlue) 8163 Ops.push_back(*(Call->op_end()-2)); 8164 else 8165 Ops.push_back(*(Call->op_end()-1)); 8166 8167 // Push the chain (this is originally the first operand of the call, but 8168 // becomes now the last or second to last operand). 8169 Ops.push_back(*(Call->op_begin())); 8170 8171 // Push the glue flag (last operand). 8172 if (HasGlue) 8173 Ops.push_back(*(Call->op_end()-1)); 8174 8175 SDVTList NodeTys; 8176 if (IsAnyRegCC && HasDef) { 8177 // Create the return types based on the intrinsic definition 8178 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8179 SmallVector<EVT, 3> ValueVTs; 8180 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8181 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8182 8183 // There is always a chain and a glue type at the end 8184 ValueVTs.push_back(MVT::Other); 8185 ValueVTs.push_back(MVT::Glue); 8186 NodeTys = DAG.getVTList(ValueVTs); 8187 } else 8188 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8189 8190 // Replace the target specific call node with a PATCHPOINT node. 8191 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8192 dl, NodeTys, Ops); 8193 8194 // Update the NodeMap. 8195 if (HasDef) { 8196 if (IsAnyRegCC) 8197 setValue(CS.getInstruction(), SDValue(MN, 0)); 8198 else 8199 setValue(CS.getInstruction(), Result.first); 8200 } 8201 8202 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8203 // call sequence. Furthermore the location of the chain and glue can change 8204 // when the AnyReg calling convention is used and the intrinsic returns a 8205 // value. 8206 if (IsAnyRegCC && HasDef) { 8207 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8208 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8209 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8210 } else 8211 DAG.ReplaceAllUsesWith(Call, MN); 8212 DAG.DeleteNode(Call); 8213 8214 // Inform the Frame Information that we have a patchpoint in this function. 8215 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8216 } 8217 8218 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8219 unsigned Intrinsic) { 8220 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8221 SDValue Op1 = getValue(I.getArgOperand(0)); 8222 SDValue Op2; 8223 if (I.getNumArgOperands() > 1) 8224 Op2 = getValue(I.getArgOperand(1)); 8225 SDLoc dl = getCurSDLoc(); 8226 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8227 SDValue Res; 8228 FastMathFlags FMF; 8229 if (isa<FPMathOperator>(I)) 8230 FMF = I.getFastMathFlags(); 8231 8232 switch (Intrinsic) { 8233 case Intrinsic::experimental_vector_reduce_fadd: 8234 if (FMF.isFast()) 8235 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8236 else 8237 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8238 break; 8239 case Intrinsic::experimental_vector_reduce_fmul: 8240 if (FMF.isFast()) 8241 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8242 else 8243 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8244 break; 8245 case Intrinsic::experimental_vector_reduce_add: 8246 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8247 break; 8248 case Intrinsic::experimental_vector_reduce_mul: 8249 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8250 break; 8251 case Intrinsic::experimental_vector_reduce_and: 8252 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8253 break; 8254 case Intrinsic::experimental_vector_reduce_or: 8255 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8256 break; 8257 case Intrinsic::experimental_vector_reduce_xor: 8258 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8259 break; 8260 case Intrinsic::experimental_vector_reduce_smax: 8261 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8262 break; 8263 case Intrinsic::experimental_vector_reduce_smin: 8264 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8265 break; 8266 case Intrinsic::experimental_vector_reduce_umax: 8267 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8268 break; 8269 case Intrinsic::experimental_vector_reduce_umin: 8270 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8271 break; 8272 case Intrinsic::experimental_vector_reduce_fmax: 8273 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8274 break; 8275 case Intrinsic::experimental_vector_reduce_fmin: 8276 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8277 break; 8278 default: 8279 llvm_unreachable("Unhandled vector reduce intrinsic"); 8280 } 8281 setValue(&I, Res); 8282 } 8283 8284 /// Returns an AttributeList representing the attributes applied to the return 8285 /// value of the given call. 8286 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8287 SmallVector<Attribute::AttrKind, 2> Attrs; 8288 if (CLI.RetSExt) 8289 Attrs.push_back(Attribute::SExt); 8290 if (CLI.RetZExt) 8291 Attrs.push_back(Attribute::ZExt); 8292 if (CLI.IsInReg) 8293 Attrs.push_back(Attribute::InReg); 8294 8295 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8296 Attrs); 8297 } 8298 8299 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8300 /// implementation, which just calls LowerCall. 8301 /// FIXME: When all targets are 8302 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8303 std::pair<SDValue, SDValue> 8304 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8305 // Handle the incoming return values from the call. 8306 CLI.Ins.clear(); 8307 Type *OrigRetTy = CLI.RetTy; 8308 SmallVector<EVT, 4> RetTys; 8309 SmallVector<uint64_t, 4> Offsets; 8310 auto &DL = CLI.DAG.getDataLayout(); 8311 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8312 8313 if (CLI.IsPostTypeLegalization) { 8314 // If we are lowering a libcall after legalization, split the return type. 8315 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8316 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8317 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8318 EVT RetVT = OldRetTys[i]; 8319 uint64_t Offset = OldOffsets[i]; 8320 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8321 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8322 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8323 RetTys.append(NumRegs, RegisterVT); 8324 for (unsigned j = 0; j != NumRegs; ++j) 8325 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8326 } 8327 } 8328 8329 SmallVector<ISD::OutputArg, 4> Outs; 8330 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8331 8332 bool CanLowerReturn = 8333 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8334 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8335 8336 SDValue DemoteStackSlot; 8337 int DemoteStackIdx = -100; 8338 if (!CanLowerReturn) { 8339 // FIXME: equivalent assert? 8340 // assert(!CS.hasInAllocaArgument() && 8341 // "sret demotion is incompatible with inalloca"); 8342 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8343 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8344 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8345 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8346 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8347 DL.getAllocaAddrSpace()); 8348 8349 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8350 ArgListEntry Entry; 8351 Entry.Node = DemoteStackSlot; 8352 Entry.Ty = StackSlotPtrType; 8353 Entry.IsSExt = false; 8354 Entry.IsZExt = false; 8355 Entry.IsInReg = false; 8356 Entry.IsSRet = true; 8357 Entry.IsNest = false; 8358 Entry.IsByVal = false; 8359 Entry.IsReturned = false; 8360 Entry.IsSwiftSelf = false; 8361 Entry.IsSwiftError = false; 8362 Entry.Alignment = Align; 8363 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8364 CLI.NumFixedArgs += 1; 8365 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8366 8367 // sret demotion isn't compatible with tail-calls, since the sret argument 8368 // points into the callers stack frame. 8369 CLI.IsTailCall = false; 8370 } else { 8371 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8372 EVT VT = RetTys[I]; 8373 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8374 CLI.CallConv, VT); 8375 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8376 CLI.CallConv, VT); 8377 for (unsigned i = 0; i != NumRegs; ++i) { 8378 ISD::InputArg MyFlags; 8379 MyFlags.VT = RegisterVT; 8380 MyFlags.ArgVT = VT; 8381 MyFlags.Used = CLI.IsReturnValueUsed; 8382 if (CLI.RetSExt) 8383 MyFlags.Flags.setSExt(); 8384 if (CLI.RetZExt) 8385 MyFlags.Flags.setZExt(); 8386 if (CLI.IsInReg) 8387 MyFlags.Flags.setInReg(); 8388 CLI.Ins.push_back(MyFlags); 8389 } 8390 } 8391 } 8392 8393 // We push in swifterror return as the last element of CLI.Ins. 8394 ArgListTy &Args = CLI.getArgs(); 8395 if (supportSwiftError()) { 8396 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8397 if (Args[i].IsSwiftError) { 8398 ISD::InputArg MyFlags; 8399 MyFlags.VT = getPointerTy(DL); 8400 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8401 MyFlags.Flags.setSwiftError(); 8402 CLI.Ins.push_back(MyFlags); 8403 } 8404 } 8405 } 8406 8407 // Handle all of the outgoing arguments. 8408 CLI.Outs.clear(); 8409 CLI.OutVals.clear(); 8410 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8411 SmallVector<EVT, 4> ValueVTs; 8412 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8413 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8414 Type *FinalType = Args[i].Ty; 8415 if (Args[i].IsByVal) 8416 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8417 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8418 FinalType, CLI.CallConv, CLI.IsVarArg); 8419 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8420 ++Value) { 8421 EVT VT = ValueVTs[Value]; 8422 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8423 SDValue Op = SDValue(Args[i].Node.getNode(), 8424 Args[i].Node.getResNo() + Value); 8425 ISD::ArgFlagsTy Flags; 8426 8427 // Certain targets (such as MIPS), may have a different ABI alignment 8428 // for a type depending on the context. Give the target a chance to 8429 // specify the alignment it wants. 8430 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8431 8432 if (Args[i].IsZExt) 8433 Flags.setZExt(); 8434 if (Args[i].IsSExt) 8435 Flags.setSExt(); 8436 if (Args[i].IsInReg) { 8437 // If we are using vectorcall calling convention, a structure that is 8438 // passed InReg - is surely an HVA 8439 if (CLI.CallConv == CallingConv::X86_VectorCall && 8440 isa<StructType>(FinalType)) { 8441 // The first value of a structure is marked 8442 if (0 == Value) 8443 Flags.setHvaStart(); 8444 Flags.setHva(); 8445 } 8446 // Set InReg Flag 8447 Flags.setInReg(); 8448 } 8449 if (Args[i].IsSRet) 8450 Flags.setSRet(); 8451 if (Args[i].IsSwiftSelf) 8452 Flags.setSwiftSelf(); 8453 if (Args[i].IsSwiftError) 8454 Flags.setSwiftError(); 8455 if (Args[i].IsByVal) 8456 Flags.setByVal(); 8457 if (Args[i].IsInAlloca) { 8458 Flags.setInAlloca(); 8459 // Set the byval flag for CCAssignFn callbacks that don't know about 8460 // inalloca. This way we can know how many bytes we should've allocated 8461 // and how many bytes a callee cleanup function will pop. If we port 8462 // inalloca to more targets, we'll have to add custom inalloca handling 8463 // in the various CC lowering callbacks. 8464 Flags.setByVal(); 8465 } 8466 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8467 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8468 Type *ElementTy = Ty->getElementType(); 8469 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8470 // For ByVal, alignment should come from FE. BE will guess if this 8471 // info is not there but there are cases it cannot get right. 8472 unsigned FrameAlign; 8473 if (Args[i].Alignment) 8474 FrameAlign = Args[i].Alignment; 8475 else 8476 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8477 Flags.setByValAlign(FrameAlign); 8478 } 8479 if (Args[i].IsNest) 8480 Flags.setNest(); 8481 if (NeedsRegBlock) 8482 Flags.setInConsecutiveRegs(); 8483 Flags.setOrigAlign(OriginalAlignment); 8484 8485 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8486 CLI.CallConv, VT); 8487 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8488 CLI.CallConv, VT); 8489 SmallVector<SDValue, 4> Parts(NumParts); 8490 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8491 8492 if (Args[i].IsSExt) 8493 ExtendKind = ISD::SIGN_EXTEND; 8494 else if (Args[i].IsZExt) 8495 ExtendKind = ISD::ZERO_EXTEND; 8496 8497 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8498 // for now. 8499 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8500 CanLowerReturn) { 8501 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8502 "unexpected use of 'returned'"); 8503 // Before passing 'returned' to the target lowering code, ensure that 8504 // either the register MVT and the actual EVT are the same size or that 8505 // the return value and argument are extended in the same way; in these 8506 // cases it's safe to pass the argument register value unchanged as the 8507 // return register value (although it's at the target's option whether 8508 // to do so) 8509 // TODO: allow code generation to take advantage of partially preserved 8510 // registers rather than clobbering the entire register when the 8511 // parameter extension method is not compatible with the return 8512 // extension method 8513 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8514 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8515 CLI.RetZExt == Args[i].IsZExt)) 8516 Flags.setReturned(); 8517 } 8518 8519 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8520 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8521 8522 for (unsigned j = 0; j != NumParts; ++j) { 8523 // if it isn't first piece, alignment must be 1 8524 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8525 i < CLI.NumFixedArgs, 8526 i, j*Parts[j].getValueType().getStoreSize()); 8527 if (NumParts > 1 && j == 0) 8528 MyFlags.Flags.setSplit(); 8529 else if (j != 0) { 8530 MyFlags.Flags.setOrigAlign(1); 8531 if (j == NumParts - 1) 8532 MyFlags.Flags.setSplitEnd(); 8533 } 8534 8535 CLI.Outs.push_back(MyFlags); 8536 CLI.OutVals.push_back(Parts[j]); 8537 } 8538 8539 if (NeedsRegBlock && Value == NumValues - 1) 8540 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8541 } 8542 } 8543 8544 SmallVector<SDValue, 4> InVals; 8545 CLI.Chain = LowerCall(CLI, InVals); 8546 8547 // Update CLI.InVals to use outside of this function. 8548 CLI.InVals = InVals; 8549 8550 // Verify that the target's LowerCall behaved as expected. 8551 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8552 "LowerCall didn't return a valid chain!"); 8553 assert((!CLI.IsTailCall || InVals.empty()) && 8554 "LowerCall emitted a return value for a tail call!"); 8555 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8556 "LowerCall didn't emit the correct number of values!"); 8557 8558 // For a tail call, the return value is merely live-out and there aren't 8559 // any nodes in the DAG representing it. Return a special value to 8560 // indicate that a tail call has been emitted and no more Instructions 8561 // should be processed in the current block. 8562 if (CLI.IsTailCall) { 8563 CLI.DAG.setRoot(CLI.Chain); 8564 return std::make_pair(SDValue(), SDValue()); 8565 } 8566 8567 #ifndef NDEBUG 8568 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8569 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8570 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8571 "LowerCall emitted a value with the wrong type!"); 8572 } 8573 #endif 8574 8575 SmallVector<SDValue, 4> ReturnValues; 8576 if (!CanLowerReturn) { 8577 // The instruction result is the result of loading from the 8578 // hidden sret parameter. 8579 SmallVector<EVT, 1> PVTs; 8580 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8581 8582 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8583 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8584 EVT PtrVT = PVTs[0]; 8585 8586 unsigned NumValues = RetTys.size(); 8587 ReturnValues.resize(NumValues); 8588 SmallVector<SDValue, 4> Chains(NumValues); 8589 8590 // An aggregate return value cannot wrap around the address space, so 8591 // offsets to its parts don't wrap either. 8592 SDNodeFlags Flags; 8593 Flags.setNoUnsignedWrap(true); 8594 8595 for (unsigned i = 0; i < NumValues; ++i) { 8596 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8597 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8598 PtrVT), Flags); 8599 SDValue L = CLI.DAG.getLoad( 8600 RetTys[i], CLI.DL, CLI.Chain, Add, 8601 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8602 DemoteStackIdx, Offsets[i]), 8603 /* Alignment = */ 1); 8604 ReturnValues[i] = L; 8605 Chains[i] = L.getValue(1); 8606 } 8607 8608 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8609 } else { 8610 // Collect the legal value parts into potentially illegal values 8611 // that correspond to the original function's return values. 8612 Optional<ISD::NodeType> AssertOp; 8613 if (CLI.RetSExt) 8614 AssertOp = ISD::AssertSext; 8615 else if (CLI.RetZExt) 8616 AssertOp = ISD::AssertZext; 8617 unsigned CurReg = 0; 8618 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8619 EVT VT = RetTys[I]; 8620 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8621 CLI.CallConv, VT); 8622 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8623 CLI.CallConv, VT); 8624 8625 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8626 NumRegs, RegisterVT, VT, nullptr, 8627 CLI.CallConv, AssertOp)); 8628 CurReg += NumRegs; 8629 } 8630 8631 // For a function returning void, there is no return value. We can't create 8632 // such a node, so we just return a null return value in that case. In 8633 // that case, nothing will actually look at the value. 8634 if (ReturnValues.empty()) 8635 return std::make_pair(SDValue(), CLI.Chain); 8636 } 8637 8638 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8639 CLI.DAG.getVTList(RetTys), ReturnValues); 8640 return std::make_pair(Res, CLI.Chain); 8641 } 8642 8643 void TargetLowering::LowerOperationWrapper(SDNode *N, 8644 SmallVectorImpl<SDValue> &Results, 8645 SelectionDAG &DAG) const { 8646 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8647 Results.push_back(Res); 8648 } 8649 8650 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8651 llvm_unreachable("LowerOperation not implemented for this target!"); 8652 } 8653 8654 void 8655 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8656 SDValue Op = getNonRegisterValue(V); 8657 assert((Op.getOpcode() != ISD::CopyFromReg || 8658 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8659 "Copy from a reg to the same reg!"); 8660 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8661 8662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8663 // If this is an InlineAsm we have to match the registers required, not the 8664 // notional registers required by the type. 8665 8666 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8667 getABIRegCopyCC(V)); 8668 SDValue Chain = DAG.getEntryNode(); 8669 8670 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8671 FuncInfo.PreferredExtendType.end()) 8672 ? ISD::ANY_EXTEND 8673 : FuncInfo.PreferredExtendType[V]; 8674 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8675 PendingExports.push_back(Chain); 8676 } 8677 8678 #include "llvm/CodeGen/SelectionDAGISel.h" 8679 8680 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8681 /// entry block, return true. This includes arguments used by switches, since 8682 /// the switch may expand into multiple basic blocks. 8683 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8684 // With FastISel active, we may be splitting blocks, so force creation 8685 // of virtual registers for all non-dead arguments. 8686 if (FastISel) 8687 return A->use_empty(); 8688 8689 const BasicBlock &Entry = A->getParent()->front(); 8690 for (const User *U : A->users()) 8691 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8692 return false; // Use not in entry block. 8693 8694 return true; 8695 } 8696 8697 using ArgCopyElisionMapTy = 8698 DenseMap<const Argument *, 8699 std::pair<const AllocaInst *, const StoreInst *>>; 8700 8701 /// Scan the entry block of the function in FuncInfo for arguments that look 8702 /// like copies into a local alloca. Record any copied arguments in 8703 /// ArgCopyElisionCandidates. 8704 static void 8705 findArgumentCopyElisionCandidates(const DataLayout &DL, 8706 FunctionLoweringInfo *FuncInfo, 8707 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8708 // Record the state of every static alloca used in the entry block. Argument 8709 // allocas are all used in the entry block, so we need approximately as many 8710 // entries as we have arguments. 8711 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8712 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8713 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8714 StaticAllocas.reserve(NumArgs * 2); 8715 8716 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8717 if (!V) 8718 return nullptr; 8719 V = V->stripPointerCasts(); 8720 const auto *AI = dyn_cast<AllocaInst>(V); 8721 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8722 return nullptr; 8723 auto Iter = StaticAllocas.insert({AI, Unknown}); 8724 return &Iter.first->second; 8725 }; 8726 8727 // Look for stores of arguments to static allocas. Look through bitcasts and 8728 // GEPs to handle type coercions, as long as the alloca is fully initialized 8729 // by the store. Any non-store use of an alloca escapes it and any subsequent 8730 // unanalyzed store might write it. 8731 // FIXME: Handle structs initialized with multiple stores. 8732 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8733 // Look for stores, and handle non-store uses conservatively. 8734 const auto *SI = dyn_cast<StoreInst>(&I); 8735 if (!SI) { 8736 // We will look through cast uses, so ignore them completely. 8737 if (I.isCast()) 8738 continue; 8739 // Ignore debug info intrinsics, they don't escape or store to allocas. 8740 if (isa<DbgInfoIntrinsic>(I)) 8741 continue; 8742 // This is an unknown instruction. Assume it escapes or writes to all 8743 // static alloca operands. 8744 for (const Use &U : I.operands()) { 8745 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8746 *Info = StaticAllocaInfo::Clobbered; 8747 } 8748 continue; 8749 } 8750 8751 // If the stored value is a static alloca, mark it as escaped. 8752 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8753 *Info = StaticAllocaInfo::Clobbered; 8754 8755 // Check if the destination is a static alloca. 8756 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8757 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8758 if (!Info) 8759 continue; 8760 const AllocaInst *AI = cast<AllocaInst>(Dst); 8761 8762 // Skip allocas that have been initialized or clobbered. 8763 if (*Info != StaticAllocaInfo::Unknown) 8764 continue; 8765 8766 // Check if the stored value is an argument, and that this store fully 8767 // initializes the alloca. Don't elide copies from the same argument twice. 8768 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8769 const auto *Arg = dyn_cast<Argument>(Val); 8770 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8771 Arg->getType()->isEmptyTy() || 8772 DL.getTypeStoreSize(Arg->getType()) != 8773 DL.getTypeAllocSize(AI->getAllocatedType()) || 8774 ArgCopyElisionCandidates.count(Arg)) { 8775 *Info = StaticAllocaInfo::Clobbered; 8776 continue; 8777 } 8778 8779 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8780 << '\n'); 8781 8782 // Mark this alloca and store for argument copy elision. 8783 *Info = StaticAllocaInfo::Elidable; 8784 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8785 8786 // Stop scanning if we've seen all arguments. This will happen early in -O0 8787 // builds, which is useful, because -O0 builds have large entry blocks and 8788 // many allocas. 8789 if (ArgCopyElisionCandidates.size() == NumArgs) 8790 break; 8791 } 8792 } 8793 8794 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8795 /// ArgVal is a load from a suitable fixed stack object. 8796 static void tryToElideArgumentCopy( 8797 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8798 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8799 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8800 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8801 SDValue ArgVal, bool &ArgHasUses) { 8802 // Check if this is a load from a fixed stack object. 8803 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8804 if (!LNode) 8805 return; 8806 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8807 if (!FINode) 8808 return; 8809 8810 // Check that the fixed stack object is the right size and alignment. 8811 // Look at the alignment that the user wrote on the alloca instead of looking 8812 // at the stack object. 8813 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8814 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8815 const AllocaInst *AI = ArgCopyIter->second.first; 8816 int FixedIndex = FINode->getIndex(); 8817 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8818 int OldIndex = AllocaIndex; 8819 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8820 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8821 LLVM_DEBUG( 8822 dbgs() << " argument copy elision failed due to bad fixed stack " 8823 "object size\n"); 8824 return; 8825 } 8826 unsigned RequiredAlignment = AI->getAlignment(); 8827 if (!RequiredAlignment) { 8828 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8829 AI->getAllocatedType()); 8830 } 8831 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8832 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8833 "greater than stack argument alignment (" 8834 << RequiredAlignment << " vs " 8835 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8836 return; 8837 } 8838 8839 // Perform the elision. Delete the old stack object and replace its only use 8840 // in the variable info map. Mark the stack object as mutable. 8841 LLVM_DEBUG({ 8842 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8843 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8844 << '\n'; 8845 }); 8846 MFI.RemoveStackObject(OldIndex); 8847 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8848 AllocaIndex = FixedIndex; 8849 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8850 Chains.push_back(ArgVal.getValue(1)); 8851 8852 // Avoid emitting code for the store implementing the copy. 8853 const StoreInst *SI = ArgCopyIter->second.second; 8854 ElidedArgCopyInstrs.insert(SI); 8855 8856 // Check for uses of the argument again so that we can avoid exporting ArgVal 8857 // if it is't used by anything other than the store. 8858 for (const Value *U : Arg.users()) { 8859 if (U != SI) { 8860 ArgHasUses = true; 8861 break; 8862 } 8863 } 8864 } 8865 8866 void SelectionDAGISel::LowerArguments(const Function &F) { 8867 SelectionDAG &DAG = SDB->DAG; 8868 SDLoc dl = SDB->getCurSDLoc(); 8869 const DataLayout &DL = DAG.getDataLayout(); 8870 SmallVector<ISD::InputArg, 16> Ins; 8871 8872 if (!FuncInfo->CanLowerReturn) { 8873 // Put in an sret pointer parameter before all the other parameters. 8874 SmallVector<EVT, 1> ValueVTs; 8875 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8876 F.getReturnType()->getPointerTo( 8877 DAG.getDataLayout().getAllocaAddrSpace()), 8878 ValueVTs); 8879 8880 // NOTE: Assuming that a pointer will never break down to more than one VT 8881 // or one register. 8882 ISD::ArgFlagsTy Flags; 8883 Flags.setSRet(); 8884 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8885 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8886 ISD::InputArg::NoArgIndex, 0); 8887 Ins.push_back(RetArg); 8888 } 8889 8890 // Look for stores of arguments to static allocas. Mark such arguments with a 8891 // flag to ask the target to give us the memory location of that argument if 8892 // available. 8893 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8894 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8895 8896 // Set up the incoming argument description vector. 8897 for (const Argument &Arg : F.args()) { 8898 unsigned ArgNo = Arg.getArgNo(); 8899 SmallVector<EVT, 4> ValueVTs; 8900 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8901 bool isArgValueUsed = !Arg.use_empty(); 8902 unsigned PartBase = 0; 8903 Type *FinalType = Arg.getType(); 8904 if (Arg.hasAttribute(Attribute::ByVal)) 8905 FinalType = cast<PointerType>(FinalType)->getElementType(); 8906 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8907 FinalType, F.getCallingConv(), F.isVarArg()); 8908 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8909 Value != NumValues; ++Value) { 8910 EVT VT = ValueVTs[Value]; 8911 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8912 ISD::ArgFlagsTy Flags; 8913 8914 // Certain targets (such as MIPS), may have a different ABI alignment 8915 // for a type depending on the context. Give the target a chance to 8916 // specify the alignment it wants. 8917 unsigned OriginalAlignment = 8918 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8919 8920 if (Arg.hasAttribute(Attribute::ZExt)) 8921 Flags.setZExt(); 8922 if (Arg.hasAttribute(Attribute::SExt)) 8923 Flags.setSExt(); 8924 if (Arg.hasAttribute(Attribute::InReg)) { 8925 // If we are using vectorcall calling convention, a structure that is 8926 // passed InReg - is surely an HVA 8927 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8928 isa<StructType>(Arg.getType())) { 8929 // The first value of a structure is marked 8930 if (0 == Value) 8931 Flags.setHvaStart(); 8932 Flags.setHva(); 8933 } 8934 // Set InReg Flag 8935 Flags.setInReg(); 8936 } 8937 if (Arg.hasAttribute(Attribute::StructRet)) 8938 Flags.setSRet(); 8939 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8940 Flags.setSwiftSelf(); 8941 if (Arg.hasAttribute(Attribute::SwiftError)) 8942 Flags.setSwiftError(); 8943 if (Arg.hasAttribute(Attribute::ByVal)) 8944 Flags.setByVal(); 8945 if (Arg.hasAttribute(Attribute::InAlloca)) { 8946 Flags.setInAlloca(); 8947 // Set the byval flag for CCAssignFn callbacks that don't know about 8948 // inalloca. This way we can know how many bytes we should've allocated 8949 // and how many bytes a callee cleanup function will pop. If we port 8950 // inalloca to more targets, we'll have to add custom inalloca handling 8951 // in the various CC lowering callbacks. 8952 Flags.setByVal(); 8953 } 8954 if (F.getCallingConv() == CallingConv::X86_INTR) { 8955 // IA Interrupt passes frame (1st parameter) by value in the stack. 8956 if (ArgNo == 0) 8957 Flags.setByVal(); 8958 } 8959 if (Flags.isByVal() || Flags.isInAlloca()) { 8960 PointerType *Ty = cast<PointerType>(Arg.getType()); 8961 Type *ElementTy = Ty->getElementType(); 8962 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8963 // For ByVal, alignment should be passed from FE. BE will guess if 8964 // this info is not there but there are cases it cannot get right. 8965 unsigned FrameAlign; 8966 if (Arg.getParamAlignment()) 8967 FrameAlign = Arg.getParamAlignment(); 8968 else 8969 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8970 Flags.setByValAlign(FrameAlign); 8971 } 8972 if (Arg.hasAttribute(Attribute::Nest)) 8973 Flags.setNest(); 8974 if (NeedsRegBlock) 8975 Flags.setInConsecutiveRegs(); 8976 Flags.setOrigAlign(OriginalAlignment); 8977 if (ArgCopyElisionCandidates.count(&Arg)) 8978 Flags.setCopyElisionCandidate(); 8979 8980 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 8981 *CurDAG->getContext(), F.getCallingConv(), VT); 8982 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 8983 *CurDAG->getContext(), F.getCallingConv(), VT); 8984 for (unsigned i = 0; i != NumRegs; ++i) { 8985 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8986 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 8987 if (NumRegs > 1 && i == 0) 8988 MyFlags.Flags.setSplit(); 8989 // if it isn't first piece, alignment must be 1 8990 else if (i > 0) { 8991 MyFlags.Flags.setOrigAlign(1); 8992 if (i == NumRegs - 1) 8993 MyFlags.Flags.setSplitEnd(); 8994 } 8995 Ins.push_back(MyFlags); 8996 } 8997 if (NeedsRegBlock && Value == NumValues - 1) 8998 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8999 PartBase += VT.getStoreSize(); 9000 } 9001 } 9002 9003 // Call the target to set up the argument values. 9004 SmallVector<SDValue, 8> InVals; 9005 SDValue NewRoot = TLI->LowerFormalArguments( 9006 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9007 9008 // Verify that the target's LowerFormalArguments behaved as expected. 9009 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9010 "LowerFormalArguments didn't return a valid chain!"); 9011 assert(InVals.size() == Ins.size() && 9012 "LowerFormalArguments didn't emit the correct number of values!"); 9013 LLVM_DEBUG({ 9014 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9015 assert(InVals[i].getNode() && 9016 "LowerFormalArguments emitted a null value!"); 9017 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9018 "LowerFormalArguments emitted a value with the wrong type!"); 9019 } 9020 }); 9021 9022 // Update the DAG with the new chain value resulting from argument lowering. 9023 DAG.setRoot(NewRoot); 9024 9025 // Set up the argument values. 9026 unsigned i = 0; 9027 if (!FuncInfo->CanLowerReturn) { 9028 // Create a virtual register for the sret pointer, and put in a copy 9029 // from the sret argument into it. 9030 SmallVector<EVT, 1> ValueVTs; 9031 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9032 F.getReturnType()->getPointerTo( 9033 DAG.getDataLayout().getAllocaAddrSpace()), 9034 ValueVTs); 9035 MVT VT = ValueVTs[0].getSimpleVT(); 9036 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9037 Optional<ISD::NodeType> AssertOp = None; 9038 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9039 nullptr, F.getCallingConv(), AssertOp); 9040 9041 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9042 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9043 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9044 FuncInfo->DemoteRegister = SRetReg; 9045 NewRoot = 9046 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9047 DAG.setRoot(NewRoot); 9048 9049 // i indexes lowered arguments. Bump it past the hidden sret argument. 9050 ++i; 9051 } 9052 9053 SmallVector<SDValue, 4> Chains; 9054 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9055 for (const Argument &Arg : F.args()) { 9056 SmallVector<SDValue, 4> ArgValues; 9057 SmallVector<EVT, 4> ValueVTs; 9058 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9059 unsigned NumValues = ValueVTs.size(); 9060 if (NumValues == 0) 9061 continue; 9062 9063 bool ArgHasUses = !Arg.use_empty(); 9064 9065 // Elide the copying store if the target loaded this argument from a 9066 // suitable fixed stack object. 9067 if (Ins[i].Flags.isCopyElisionCandidate()) { 9068 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9069 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9070 InVals[i], ArgHasUses); 9071 } 9072 9073 // If this argument is unused then remember its value. It is used to generate 9074 // debugging information. 9075 bool isSwiftErrorArg = 9076 TLI->supportSwiftError() && 9077 Arg.hasAttribute(Attribute::SwiftError); 9078 if (!ArgHasUses && !isSwiftErrorArg) { 9079 SDB->setUnusedArgValue(&Arg, InVals[i]); 9080 9081 // Also remember any frame index for use in FastISel. 9082 if (FrameIndexSDNode *FI = 9083 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9084 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9085 } 9086 9087 for (unsigned Val = 0; Val != NumValues; ++Val) { 9088 EVT VT = ValueVTs[Val]; 9089 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9090 F.getCallingConv(), VT); 9091 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9092 *CurDAG->getContext(), F.getCallingConv(), VT); 9093 9094 // Even an apparant 'unused' swifterror argument needs to be returned. So 9095 // we do generate a copy for it that can be used on return from the 9096 // function. 9097 if (ArgHasUses || isSwiftErrorArg) { 9098 Optional<ISD::NodeType> AssertOp; 9099 if (Arg.hasAttribute(Attribute::SExt)) 9100 AssertOp = ISD::AssertSext; 9101 else if (Arg.hasAttribute(Attribute::ZExt)) 9102 AssertOp = ISD::AssertZext; 9103 9104 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9105 PartVT, VT, nullptr, 9106 F.getCallingConv(), AssertOp)); 9107 } 9108 9109 i += NumParts; 9110 } 9111 9112 // We don't need to do anything else for unused arguments. 9113 if (ArgValues.empty()) 9114 continue; 9115 9116 // Note down frame index. 9117 if (FrameIndexSDNode *FI = 9118 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9119 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9120 9121 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9122 SDB->getCurSDLoc()); 9123 9124 SDB->setValue(&Arg, Res); 9125 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9126 // We want to associate the argument with the frame index, among 9127 // involved operands, that correspond to the lowest address. The 9128 // getCopyFromParts function, called earlier, is swapping the order of 9129 // the operands to BUILD_PAIR depending on endianness. The result of 9130 // that swapping is that the least significant bits of the argument will 9131 // be in the first operand of the BUILD_PAIR node, and the most 9132 // significant bits will be in the second operand. 9133 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9134 if (LoadSDNode *LNode = 9135 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9136 if (FrameIndexSDNode *FI = 9137 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9138 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9139 } 9140 9141 // Update the SwiftErrorVRegDefMap. 9142 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9143 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9144 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9145 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9146 FuncInfo->SwiftErrorArg, Reg); 9147 } 9148 9149 // If this argument is live outside of the entry block, insert a copy from 9150 // wherever we got it to the vreg that other BB's will reference it as. 9151 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9152 // If we can, though, try to skip creating an unnecessary vreg. 9153 // FIXME: This isn't very clean... it would be nice to make this more 9154 // general. It's also subtly incompatible with the hacks FastISel 9155 // uses with vregs. 9156 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9157 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9158 FuncInfo->ValueMap[&Arg] = Reg; 9159 continue; 9160 } 9161 } 9162 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9163 FuncInfo->InitializeRegForValue(&Arg); 9164 SDB->CopyToExportRegsIfNeeded(&Arg); 9165 } 9166 } 9167 9168 if (!Chains.empty()) { 9169 Chains.push_back(NewRoot); 9170 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9171 } 9172 9173 DAG.setRoot(NewRoot); 9174 9175 assert(i == InVals.size() && "Argument register count mismatch!"); 9176 9177 // If any argument copy elisions occurred and we have debug info, update the 9178 // stale frame indices used in the dbg.declare variable info table. 9179 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9180 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9181 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9182 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9183 if (I != ArgCopyElisionFrameIndexMap.end()) 9184 VI.Slot = I->second; 9185 } 9186 } 9187 9188 // Finally, if the target has anything special to do, allow it to do so. 9189 EmitFunctionEntryCode(); 9190 } 9191 9192 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9193 /// ensure constants are generated when needed. Remember the virtual registers 9194 /// that need to be added to the Machine PHI nodes as input. We cannot just 9195 /// directly add them, because expansion might result in multiple MBB's for one 9196 /// BB. As such, the start of the BB might correspond to a different MBB than 9197 /// the end. 9198 void 9199 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9200 const TerminatorInst *TI = LLVMBB->getTerminator(); 9201 9202 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9203 9204 // Check PHI nodes in successors that expect a value to be available from this 9205 // block. 9206 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9207 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9208 if (!isa<PHINode>(SuccBB->begin())) continue; 9209 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9210 9211 // If this terminator has multiple identical successors (common for 9212 // switches), only handle each succ once. 9213 if (!SuccsHandled.insert(SuccMBB).second) 9214 continue; 9215 9216 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9217 9218 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9219 // nodes and Machine PHI nodes, but the incoming operands have not been 9220 // emitted yet. 9221 for (const PHINode &PN : SuccBB->phis()) { 9222 // Ignore dead phi's. 9223 if (PN.use_empty()) 9224 continue; 9225 9226 // Skip empty types 9227 if (PN.getType()->isEmptyTy()) 9228 continue; 9229 9230 unsigned Reg; 9231 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9232 9233 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9234 unsigned &RegOut = ConstantsOut[C]; 9235 if (RegOut == 0) { 9236 RegOut = FuncInfo.CreateRegs(C->getType()); 9237 CopyValueToVirtualRegister(C, RegOut); 9238 } 9239 Reg = RegOut; 9240 } else { 9241 DenseMap<const Value *, unsigned>::iterator I = 9242 FuncInfo.ValueMap.find(PHIOp); 9243 if (I != FuncInfo.ValueMap.end()) 9244 Reg = I->second; 9245 else { 9246 assert(isa<AllocaInst>(PHIOp) && 9247 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9248 "Didn't codegen value into a register!??"); 9249 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9250 CopyValueToVirtualRegister(PHIOp, Reg); 9251 } 9252 } 9253 9254 // Remember that this register needs to added to the machine PHI node as 9255 // the input for this MBB. 9256 SmallVector<EVT, 4> ValueVTs; 9257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9258 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9259 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9260 EVT VT = ValueVTs[vti]; 9261 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9262 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9263 FuncInfo.PHINodesToUpdate.push_back( 9264 std::make_pair(&*MBBI++, Reg + i)); 9265 Reg += NumRegisters; 9266 } 9267 } 9268 } 9269 9270 ConstantsOut.clear(); 9271 } 9272 9273 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9274 /// is 0. 9275 MachineBasicBlock * 9276 SelectionDAGBuilder::StackProtectorDescriptor:: 9277 AddSuccessorMBB(const BasicBlock *BB, 9278 MachineBasicBlock *ParentMBB, 9279 bool IsLikely, 9280 MachineBasicBlock *SuccMBB) { 9281 // If SuccBB has not been created yet, create it. 9282 if (!SuccMBB) { 9283 MachineFunction *MF = ParentMBB->getParent(); 9284 MachineFunction::iterator BBI(ParentMBB); 9285 SuccMBB = MF->CreateMachineBasicBlock(BB); 9286 MF->insert(++BBI, SuccMBB); 9287 } 9288 // Add it as a successor of ParentMBB. 9289 ParentMBB->addSuccessor( 9290 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9291 return SuccMBB; 9292 } 9293 9294 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9295 MachineFunction::iterator I(MBB); 9296 if (++I == FuncInfo.MF->end()) 9297 return nullptr; 9298 return &*I; 9299 } 9300 9301 /// During lowering new call nodes can be created (such as memset, etc.). 9302 /// Those will become new roots of the current DAG, but complications arise 9303 /// when they are tail calls. In such cases, the call lowering will update 9304 /// the root, but the builder still needs to know that a tail call has been 9305 /// lowered in order to avoid generating an additional return. 9306 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9307 // If the node is null, we do have a tail call. 9308 if (MaybeTC.getNode() != nullptr) 9309 DAG.setRoot(MaybeTC); 9310 else 9311 HasTailCall = true; 9312 } 9313 9314 uint64_t 9315 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9316 unsigned First, unsigned Last) const { 9317 assert(Last >= First); 9318 const APInt &LowCase = Clusters[First].Low->getValue(); 9319 const APInt &HighCase = Clusters[Last].High->getValue(); 9320 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9321 9322 // FIXME: A range of consecutive cases has 100% density, but only requires one 9323 // comparison to lower. We should discriminate against such consecutive ranges 9324 // in jump tables. 9325 9326 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9327 } 9328 9329 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9330 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9331 unsigned Last) const { 9332 assert(Last >= First); 9333 assert(TotalCases[Last] >= TotalCases[First]); 9334 uint64_t NumCases = 9335 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9336 return NumCases; 9337 } 9338 9339 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9340 unsigned First, unsigned Last, 9341 const SwitchInst *SI, 9342 MachineBasicBlock *DefaultMBB, 9343 CaseCluster &JTCluster) { 9344 assert(First <= Last); 9345 9346 auto Prob = BranchProbability::getZero(); 9347 unsigned NumCmps = 0; 9348 std::vector<MachineBasicBlock*> Table; 9349 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9350 9351 // Initialize probabilities in JTProbs. 9352 for (unsigned I = First; I <= Last; ++I) 9353 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9354 9355 for (unsigned I = First; I <= Last; ++I) { 9356 assert(Clusters[I].Kind == CC_Range); 9357 Prob += Clusters[I].Prob; 9358 const APInt &Low = Clusters[I].Low->getValue(); 9359 const APInt &High = Clusters[I].High->getValue(); 9360 NumCmps += (Low == High) ? 1 : 2; 9361 if (I != First) { 9362 // Fill the gap between this and the previous cluster. 9363 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9364 assert(PreviousHigh.slt(Low)); 9365 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9366 for (uint64_t J = 0; J < Gap; J++) 9367 Table.push_back(DefaultMBB); 9368 } 9369 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9370 for (uint64_t J = 0; J < ClusterSize; ++J) 9371 Table.push_back(Clusters[I].MBB); 9372 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9373 } 9374 9375 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9376 unsigned NumDests = JTProbs.size(); 9377 if (TLI.isSuitableForBitTests( 9378 NumDests, NumCmps, Clusters[First].Low->getValue(), 9379 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9380 // Clusters[First..Last] should be lowered as bit tests instead. 9381 return false; 9382 } 9383 9384 // Create the MBB that will load from and jump through the table. 9385 // Note: We create it here, but it's not inserted into the function yet. 9386 MachineFunction *CurMF = FuncInfo.MF; 9387 MachineBasicBlock *JumpTableMBB = 9388 CurMF->CreateMachineBasicBlock(SI->getParent()); 9389 9390 // Add successors. Note: use table order for determinism. 9391 SmallPtrSet<MachineBasicBlock *, 8> Done; 9392 for (MachineBasicBlock *Succ : Table) { 9393 if (Done.count(Succ)) 9394 continue; 9395 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9396 Done.insert(Succ); 9397 } 9398 JumpTableMBB->normalizeSuccProbs(); 9399 9400 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9401 ->createJumpTableIndex(Table); 9402 9403 // Set up the jump table info. 9404 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9405 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9406 Clusters[Last].High->getValue(), SI->getCondition(), 9407 nullptr, false); 9408 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9409 9410 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9411 JTCases.size() - 1, Prob); 9412 return true; 9413 } 9414 9415 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9416 const SwitchInst *SI, 9417 MachineBasicBlock *DefaultMBB) { 9418 #ifndef NDEBUG 9419 // Clusters must be non-empty, sorted, and only contain Range clusters. 9420 assert(!Clusters.empty()); 9421 for (CaseCluster &C : Clusters) 9422 assert(C.Kind == CC_Range); 9423 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9424 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9425 #endif 9426 9427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9428 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9429 return; 9430 9431 const int64_t N = Clusters.size(); 9432 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9433 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9434 9435 if (N < 2 || N < MinJumpTableEntries) 9436 return; 9437 9438 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9439 SmallVector<unsigned, 8> TotalCases(N); 9440 for (unsigned i = 0; i < N; ++i) { 9441 const APInt &Hi = Clusters[i].High->getValue(); 9442 const APInt &Lo = Clusters[i].Low->getValue(); 9443 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9444 if (i != 0) 9445 TotalCases[i] += TotalCases[i - 1]; 9446 } 9447 9448 // Cheap case: the whole range may be suitable for jump table. 9449 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9450 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9451 assert(NumCases < UINT64_MAX / 100); 9452 assert(Range >= NumCases); 9453 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9454 CaseCluster JTCluster; 9455 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9456 Clusters[0] = JTCluster; 9457 Clusters.resize(1); 9458 return; 9459 } 9460 } 9461 9462 // The algorithm below is not suitable for -O0. 9463 if (TM.getOptLevel() == CodeGenOpt::None) 9464 return; 9465 9466 // Split Clusters into minimum number of dense partitions. The algorithm uses 9467 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9468 // for the Case Statement'" (1994), but builds the MinPartitions array in 9469 // reverse order to make it easier to reconstruct the partitions in ascending 9470 // order. In the choice between two optimal partitionings, it picks the one 9471 // which yields more jump tables. 9472 9473 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9474 SmallVector<unsigned, 8> MinPartitions(N); 9475 // LastElement[i] is the last element of the partition starting at i. 9476 SmallVector<unsigned, 8> LastElement(N); 9477 // PartitionsScore[i] is used to break ties when choosing between two 9478 // partitionings resulting in the same number of partitions. 9479 SmallVector<unsigned, 8> PartitionsScore(N); 9480 // For PartitionsScore, a small number of comparisons is considered as good as 9481 // a jump table and a single comparison is considered better than a jump 9482 // table. 9483 enum PartitionScores : unsigned { 9484 NoTable = 0, 9485 Table = 1, 9486 FewCases = 1, 9487 SingleCase = 2 9488 }; 9489 9490 // Base case: There is only one way to partition Clusters[N-1]. 9491 MinPartitions[N - 1] = 1; 9492 LastElement[N - 1] = N - 1; 9493 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9494 9495 // Note: loop indexes are signed to avoid underflow. 9496 for (int64_t i = N - 2; i >= 0; i--) { 9497 // Find optimal partitioning of Clusters[i..N-1]. 9498 // Baseline: Put Clusters[i] into a partition on its own. 9499 MinPartitions[i] = MinPartitions[i + 1] + 1; 9500 LastElement[i] = i; 9501 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9502 9503 // Search for a solution that results in fewer partitions. 9504 for (int64_t j = N - 1; j > i; j--) { 9505 // Try building a partition from Clusters[i..j]. 9506 uint64_t Range = getJumpTableRange(Clusters, i, j); 9507 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9508 assert(NumCases < UINT64_MAX / 100); 9509 assert(Range >= NumCases); 9510 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9511 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9512 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9513 int64_t NumEntries = j - i + 1; 9514 9515 if (NumEntries == 1) 9516 Score += PartitionScores::SingleCase; 9517 else if (NumEntries <= SmallNumberOfEntries) 9518 Score += PartitionScores::FewCases; 9519 else if (NumEntries >= MinJumpTableEntries) 9520 Score += PartitionScores::Table; 9521 9522 // If this leads to fewer partitions, or to the same number of 9523 // partitions with better score, it is a better partitioning. 9524 if (NumPartitions < MinPartitions[i] || 9525 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9526 MinPartitions[i] = NumPartitions; 9527 LastElement[i] = j; 9528 PartitionsScore[i] = Score; 9529 } 9530 } 9531 } 9532 } 9533 9534 // Iterate over the partitions, replacing some with jump tables in-place. 9535 unsigned DstIndex = 0; 9536 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9537 Last = LastElement[First]; 9538 assert(Last >= First); 9539 assert(DstIndex <= First); 9540 unsigned NumClusters = Last - First + 1; 9541 9542 CaseCluster JTCluster; 9543 if (NumClusters >= MinJumpTableEntries && 9544 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9545 Clusters[DstIndex++] = JTCluster; 9546 } else { 9547 for (unsigned I = First; I <= Last; ++I) 9548 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9549 } 9550 } 9551 Clusters.resize(DstIndex); 9552 } 9553 9554 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9555 unsigned First, unsigned Last, 9556 const SwitchInst *SI, 9557 CaseCluster &BTCluster) { 9558 assert(First <= Last); 9559 if (First == Last) 9560 return false; 9561 9562 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9563 unsigned NumCmps = 0; 9564 for (int64_t I = First; I <= Last; ++I) { 9565 assert(Clusters[I].Kind == CC_Range); 9566 Dests.set(Clusters[I].MBB->getNumber()); 9567 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9568 } 9569 unsigned NumDests = Dests.count(); 9570 9571 APInt Low = Clusters[First].Low->getValue(); 9572 APInt High = Clusters[Last].High->getValue(); 9573 assert(Low.slt(High)); 9574 9575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9576 const DataLayout &DL = DAG.getDataLayout(); 9577 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9578 return false; 9579 9580 APInt LowBound; 9581 APInt CmpRange; 9582 9583 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9584 assert(TLI.rangeFitsInWord(Low, High, DL) && 9585 "Case range must fit in bit mask!"); 9586 9587 // Check if the clusters cover a contiguous range such that no value in the 9588 // range will jump to the default statement. 9589 bool ContiguousRange = true; 9590 for (int64_t I = First + 1; I <= Last; ++I) { 9591 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9592 ContiguousRange = false; 9593 break; 9594 } 9595 } 9596 9597 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9598 // Optimize the case where all the case values fit in a word without having 9599 // to subtract minValue. In this case, we can optimize away the subtraction. 9600 LowBound = APInt::getNullValue(Low.getBitWidth()); 9601 CmpRange = High; 9602 ContiguousRange = false; 9603 } else { 9604 LowBound = Low; 9605 CmpRange = High - Low; 9606 } 9607 9608 CaseBitsVector CBV; 9609 auto TotalProb = BranchProbability::getZero(); 9610 for (unsigned i = First; i <= Last; ++i) { 9611 // Find the CaseBits for this destination. 9612 unsigned j; 9613 for (j = 0; j < CBV.size(); ++j) 9614 if (CBV[j].BB == Clusters[i].MBB) 9615 break; 9616 if (j == CBV.size()) 9617 CBV.push_back( 9618 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9619 CaseBits *CB = &CBV[j]; 9620 9621 // Update Mask, Bits and ExtraProb. 9622 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9623 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9624 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9625 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9626 CB->Bits += Hi - Lo + 1; 9627 CB->ExtraProb += Clusters[i].Prob; 9628 TotalProb += Clusters[i].Prob; 9629 } 9630 9631 BitTestInfo BTI; 9632 llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9633 // Sort by probability first, number of bits second, bit mask third. 9634 if (a.ExtraProb != b.ExtraProb) 9635 return a.ExtraProb > b.ExtraProb; 9636 if (a.Bits != b.Bits) 9637 return a.Bits > b.Bits; 9638 return a.Mask < b.Mask; 9639 }); 9640 9641 for (auto &CB : CBV) { 9642 MachineBasicBlock *BitTestBB = 9643 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9644 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9645 } 9646 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9647 SI->getCondition(), -1U, MVT::Other, false, 9648 ContiguousRange, nullptr, nullptr, std::move(BTI), 9649 TotalProb); 9650 9651 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9652 BitTestCases.size() - 1, TotalProb); 9653 return true; 9654 } 9655 9656 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9657 const SwitchInst *SI) { 9658 // Partition Clusters into as few subsets as possible, where each subset has a 9659 // range that fits in a machine word and has <= 3 unique destinations. 9660 9661 #ifndef NDEBUG 9662 // Clusters must be sorted and contain Range or JumpTable clusters. 9663 assert(!Clusters.empty()); 9664 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9665 for (const CaseCluster &C : Clusters) 9666 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9667 for (unsigned i = 1; i < Clusters.size(); ++i) 9668 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9669 #endif 9670 9671 // The algorithm below is not suitable for -O0. 9672 if (TM.getOptLevel() == CodeGenOpt::None) 9673 return; 9674 9675 // If target does not have legal shift left, do not emit bit tests at all. 9676 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9677 const DataLayout &DL = DAG.getDataLayout(); 9678 9679 EVT PTy = TLI.getPointerTy(DL); 9680 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9681 return; 9682 9683 int BitWidth = PTy.getSizeInBits(); 9684 const int64_t N = Clusters.size(); 9685 9686 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9687 SmallVector<unsigned, 8> MinPartitions(N); 9688 // LastElement[i] is the last element of the partition starting at i. 9689 SmallVector<unsigned, 8> LastElement(N); 9690 9691 // FIXME: This might not be the best algorithm for finding bit test clusters. 9692 9693 // Base case: There is only one way to partition Clusters[N-1]. 9694 MinPartitions[N - 1] = 1; 9695 LastElement[N - 1] = N - 1; 9696 9697 // Note: loop indexes are signed to avoid underflow. 9698 for (int64_t i = N - 2; i >= 0; --i) { 9699 // Find optimal partitioning of Clusters[i..N-1]. 9700 // Baseline: Put Clusters[i] into a partition on its own. 9701 MinPartitions[i] = MinPartitions[i + 1] + 1; 9702 LastElement[i] = i; 9703 9704 // Search for a solution that results in fewer partitions. 9705 // Note: the search is limited by BitWidth, reducing time complexity. 9706 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9707 // Try building a partition from Clusters[i..j]. 9708 9709 // Check the range. 9710 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9711 Clusters[j].High->getValue(), DL)) 9712 continue; 9713 9714 // Check nbr of destinations and cluster types. 9715 // FIXME: This works, but doesn't seem very efficient. 9716 bool RangesOnly = true; 9717 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9718 for (int64_t k = i; k <= j; k++) { 9719 if (Clusters[k].Kind != CC_Range) { 9720 RangesOnly = false; 9721 break; 9722 } 9723 Dests.set(Clusters[k].MBB->getNumber()); 9724 } 9725 if (!RangesOnly || Dests.count() > 3) 9726 break; 9727 9728 // Check if it's a better partition. 9729 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9730 if (NumPartitions < MinPartitions[i]) { 9731 // Found a better partition. 9732 MinPartitions[i] = NumPartitions; 9733 LastElement[i] = j; 9734 } 9735 } 9736 } 9737 9738 // Iterate over the partitions, replacing with bit-test clusters in-place. 9739 unsigned DstIndex = 0; 9740 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9741 Last = LastElement[First]; 9742 assert(First <= Last); 9743 assert(DstIndex <= First); 9744 9745 CaseCluster BitTestCluster; 9746 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9747 Clusters[DstIndex++] = BitTestCluster; 9748 } else { 9749 size_t NumClusters = Last - First + 1; 9750 std::memmove(&Clusters[DstIndex], &Clusters[First], 9751 sizeof(Clusters[0]) * NumClusters); 9752 DstIndex += NumClusters; 9753 } 9754 } 9755 Clusters.resize(DstIndex); 9756 } 9757 9758 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9759 MachineBasicBlock *SwitchMBB, 9760 MachineBasicBlock *DefaultMBB) { 9761 MachineFunction *CurMF = FuncInfo.MF; 9762 MachineBasicBlock *NextMBB = nullptr; 9763 MachineFunction::iterator BBI(W.MBB); 9764 if (++BBI != FuncInfo.MF->end()) 9765 NextMBB = &*BBI; 9766 9767 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9768 9769 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9770 9771 if (Size == 2 && W.MBB == SwitchMBB) { 9772 // If any two of the cases has the same destination, and if one value 9773 // is the same as the other, but has one bit unset that the other has set, 9774 // use bit manipulation to do two compares at once. For example: 9775 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9776 // TODO: This could be extended to merge any 2 cases in switches with 3 9777 // cases. 9778 // TODO: Handle cases where W.CaseBB != SwitchBB. 9779 CaseCluster &Small = *W.FirstCluster; 9780 CaseCluster &Big = *W.LastCluster; 9781 9782 if (Small.Low == Small.High && Big.Low == Big.High && 9783 Small.MBB == Big.MBB) { 9784 const APInt &SmallValue = Small.Low->getValue(); 9785 const APInt &BigValue = Big.Low->getValue(); 9786 9787 // Check that there is only one bit different. 9788 APInt CommonBit = BigValue ^ SmallValue; 9789 if (CommonBit.isPowerOf2()) { 9790 SDValue CondLHS = getValue(Cond); 9791 EVT VT = CondLHS.getValueType(); 9792 SDLoc DL = getCurSDLoc(); 9793 9794 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9795 DAG.getConstant(CommonBit, DL, VT)); 9796 SDValue Cond = DAG.getSetCC( 9797 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9798 ISD::SETEQ); 9799 9800 // Update successor info. 9801 // Both Small and Big will jump to Small.BB, so we sum up the 9802 // probabilities. 9803 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9804 if (BPI) 9805 addSuccessorWithProb( 9806 SwitchMBB, DefaultMBB, 9807 // The default destination is the first successor in IR. 9808 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9809 else 9810 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9811 9812 // Insert the true branch. 9813 SDValue BrCond = 9814 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9815 DAG.getBasicBlock(Small.MBB)); 9816 // Insert the false branch. 9817 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9818 DAG.getBasicBlock(DefaultMBB)); 9819 9820 DAG.setRoot(BrCond); 9821 return; 9822 } 9823 } 9824 } 9825 9826 if (TM.getOptLevel() != CodeGenOpt::None) { 9827 // Here, we order cases by probability so the most likely case will be 9828 // checked first. However, two clusters can have the same probability in 9829 // which case their relative ordering is non-deterministic. So we use Low 9830 // as a tie-breaker as clusters are guaranteed to never overlap. 9831 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9832 [](const CaseCluster &a, const CaseCluster &b) { 9833 return a.Prob != b.Prob ? 9834 a.Prob > b.Prob : 9835 a.Low->getValue().slt(b.Low->getValue()); 9836 }); 9837 9838 // Rearrange the case blocks so that the last one falls through if possible 9839 // without changing the order of probabilities. 9840 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9841 --I; 9842 if (I->Prob > W.LastCluster->Prob) 9843 break; 9844 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9845 std::swap(*I, *W.LastCluster); 9846 break; 9847 } 9848 } 9849 } 9850 9851 // Compute total probability. 9852 BranchProbability DefaultProb = W.DefaultProb; 9853 BranchProbability UnhandledProbs = DefaultProb; 9854 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9855 UnhandledProbs += I->Prob; 9856 9857 MachineBasicBlock *CurMBB = W.MBB; 9858 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9859 MachineBasicBlock *Fallthrough; 9860 if (I == W.LastCluster) { 9861 // For the last cluster, fall through to the default destination. 9862 Fallthrough = DefaultMBB; 9863 } else { 9864 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9865 CurMF->insert(BBI, Fallthrough); 9866 // Put Cond in a virtual register to make it available from the new blocks. 9867 ExportFromCurrentBlock(Cond); 9868 } 9869 UnhandledProbs -= I->Prob; 9870 9871 switch (I->Kind) { 9872 case CC_JumpTable: { 9873 // FIXME: Optimize away range check based on pivot comparisons. 9874 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9875 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9876 9877 // The jump block hasn't been inserted yet; insert it here. 9878 MachineBasicBlock *JumpMBB = JT->MBB; 9879 CurMF->insert(BBI, JumpMBB); 9880 9881 auto JumpProb = I->Prob; 9882 auto FallthroughProb = UnhandledProbs; 9883 9884 // If the default statement is a target of the jump table, we evenly 9885 // distribute the default probability to successors of CurMBB. Also 9886 // update the probability on the edge from JumpMBB to Fallthrough. 9887 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9888 SE = JumpMBB->succ_end(); 9889 SI != SE; ++SI) { 9890 if (*SI == DefaultMBB) { 9891 JumpProb += DefaultProb / 2; 9892 FallthroughProb -= DefaultProb / 2; 9893 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9894 JumpMBB->normalizeSuccProbs(); 9895 break; 9896 } 9897 } 9898 9899 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9900 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9901 CurMBB->normalizeSuccProbs(); 9902 9903 // The jump table header will be inserted in our current block, do the 9904 // range check, and fall through to our fallthrough block. 9905 JTH->HeaderBB = CurMBB; 9906 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9907 9908 // If we're in the right place, emit the jump table header right now. 9909 if (CurMBB == SwitchMBB) { 9910 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9911 JTH->Emitted = true; 9912 } 9913 break; 9914 } 9915 case CC_BitTests: { 9916 // FIXME: Optimize away range check based on pivot comparisons. 9917 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9918 9919 // The bit test blocks haven't been inserted yet; insert them here. 9920 for (BitTestCase &BTC : BTB->Cases) 9921 CurMF->insert(BBI, BTC.ThisBB); 9922 9923 // Fill in fields of the BitTestBlock. 9924 BTB->Parent = CurMBB; 9925 BTB->Default = Fallthrough; 9926 9927 BTB->DefaultProb = UnhandledProbs; 9928 // If the cases in bit test don't form a contiguous range, we evenly 9929 // distribute the probability on the edge to Fallthrough to two 9930 // successors of CurMBB. 9931 if (!BTB->ContiguousRange) { 9932 BTB->Prob += DefaultProb / 2; 9933 BTB->DefaultProb -= DefaultProb / 2; 9934 } 9935 9936 // If we're in the right place, emit the bit test header right now. 9937 if (CurMBB == SwitchMBB) { 9938 visitBitTestHeader(*BTB, SwitchMBB); 9939 BTB->Emitted = true; 9940 } 9941 break; 9942 } 9943 case CC_Range: { 9944 const Value *RHS, *LHS, *MHS; 9945 ISD::CondCode CC; 9946 if (I->Low == I->High) { 9947 // Check Cond == I->Low. 9948 CC = ISD::SETEQ; 9949 LHS = Cond; 9950 RHS=I->Low; 9951 MHS = nullptr; 9952 } else { 9953 // Check I->Low <= Cond <= I->High. 9954 CC = ISD::SETLE; 9955 LHS = I->Low; 9956 MHS = Cond; 9957 RHS = I->High; 9958 } 9959 9960 // The false probability is the sum of all unhandled cases. 9961 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9962 getCurSDLoc(), I->Prob, UnhandledProbs); 9963 9964 if (CurMBB == SwitchMBB) 9965 visitSwitchCase(CB, SwitchMBB); 9966 else 9967 SwitchCases.push_back(CB); 9968 9969 break; 9970 } 9971 } 9972 CurMBB = Fallthrough; 9973 } 9974 } 9975 9976 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 9977 CaseClusterIt First, 9978 CaseClusterIt Last) { 9979 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 9980 if (X.Prob != CC.Prob) 9981 return X.Prob > CC.Prob; 9982 9983 // Ties are broken by comparing the case value. 9984 return X.Low->getValue().slt(CC.Low->getValue()); 9985 }); 9986 } 9987 9988 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9989 const SwitchWorkListItem &W, 9990 Value *Cond, 9991 MachineBasicBlock *SwitchMBB) { 9992 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9993 "Clusters not sorted?"); 9994 9995 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9996 9997 // Balance the tree based on branch probabilities to create a near-optimal (in 9998 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9999 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10000 CaseClusterIt LastLeft = W.FirstCluster; 10001 CaseClusterIt FirstRight = W.LastCluster; 10002 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10003 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10004 10005 // Move LastLeft and FirstRight towards each other from opposite directions to 10006 // find a partitioning of the clusters which balances the probability on both 10007 // sides. If LeftProb and RightProb are equal, alternate which side is 10008 // taken to ensure 0-probability nodes are distributed evenly. 10009 unsigned I = 0; 10010 while (LastLeft + 1 < FirstRight) { 10011 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10012 LeftProb += (++LastLeft)->Prob; 10013 else 10014 RightProb += (--FirstRight)->Prob; 10015 I++; 10016 } 10017 10018 while (true) { 10019 // Our binary search tree differs from a typical BST in that ours can have up 10020 // to three values in each leaf. The pivot selection above doesn't take that 10021 // into account, which means the tree might require more nodes and be less 10022 // efficient. We compensate for this here. 10023 10024 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10025 unsigned NumRight = W.LastCluster - FirstRight + 1; 10026 10027 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10028 // If one side has less than 3 clusters, and the other has more than 3, 10029 // consider taking a cluster from the other side. 10030 10031 if (NumLeft < NumRight) { 10032 // Consider moving the first cluster on the right to the left side. 10033 CaseCluster &CC = *FirstRight; 10034 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10035 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10036 if (LeftSideRank <= RightSideRank) { 10037 // Moving the cluster to the left does not demote it. 10038 ++LastLeft; 10039 ++FirstRight; 10040 continue; 10041 } 10042 } else { 10043 assert(NumRight < NumLeft); 10044 // Consider moving the last element on the left to the right side. 10045 CaseCluster &CC = *LastLeft; 10046 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10047 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10048 if (RightSideRank <= LeftSideRank) { 10049 // Moving the cluster to the right does not demot it. 10050 --LastLeft; 10051 --FirstRight; 10052 continue; 10053 } 10054 } 10055 } 10056 break; 10057 } 10058 10059 assert(LastLeft + 1 == FirstRight); 10060 assert(LastLeft >= W.FirstCluster); 10061 assert(FirstRight <= W.LastCluster); 10062 10063 // Use the first element on the right as pivot since we will make less-than 10064 // comparisons against it. 10065 CaseClusterIt PivotCluster = FirstRight; 10066 assert(PivotCluster > W.FirstCluster); 10067 assert(PivotCluster <= W.LastCluster); 10068 10069 CaseClusterIt FirstLeft = W.FirstCluster; 10070 CaseClusterIt LastRight = W.LastCluster; 10071 10072 const ConstantInt *Pivot = PivotCluster->Low; 10073 10074 // New blocks will be inserted immediately after the current one. 10075 MachineFunction::iterator BBI(W.MBB); 10076 ++BBI; 10077 10078 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10079 // we can branch to its destination directly if it's squeezed exactly in 10080 // between the known lower bound and Pivot - 1. 10081 MachineBasicBlock *LeftMBB; 10082 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10083 FirstLeft->Low == W.GE && 10084 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10085 LeftMBB = FirstLeft->MBB; 10086 } else { 10087 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10088 FuncInfo.MF->insert(BBI, LeftMBB); 10089 WorkList.push_back( 10090 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10091 // Put Cond in a virtual register to make it available from the new blocks. 10092 ExportFromCurrentBlock(Cond); 10093 } 10094 10095 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10096 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10097 // directly if RHS.High equals the current upper bound. 10098 MachineBasicBlock *RightMBB; 10099 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10100 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10101 RightMBB = FirstRight->MBB; 10102 } else { 10103 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10104 FuncInfo.MF->insert(BBI, RightMBB); 10105 WorkList.push_back( 10106 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10107 // Put Cond in a virtual register to make it available from the new blocks. 10108 ExportFromCurrentBlock(Cond); 10109 } 10110 10111 // Create the CaseBlock record that will be used to lower the branch. 10112 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10113 getCurSDLoc(), LeftProb, RightProb); 10114 10115 if (W.MBB == SwitchMBB) 10116 visitSwitchCase(CB, SwitchMBB); 10117 else 10118 SwitchCases.push_back(CB); 10119 } 10120 10121 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10122 // from the swith statement. 10123 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10124 BranchProbability PeeledCaseProb) { 10125 if (PeeledCaseProb == BranchProbability::getOne()) 10126 return BranchProbability::getZero(); 10127 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10128 10129 uint32_t Numerator = CaseProb.getNumerator(); 10130 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10131 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10132 } 10133 10134 // Try to peel the top probability case if it exceeds the threshold. 10135 // Return current MachineBasicBlock for the switch statement if the peeling 10136 // does not occur. 10137 // If the peeling is performed, return the newly created MachineBasicBlock 10138 // for the peeled switch statement. Also update Clusters to remove the peeled 10139 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10140 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10141 const SwitchInst &SI, CaseClusterVector &Clusters, 10142 BranchProbability &PeeledCaseProb) { 10143 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10144 // Don't perform if there is only one cluster or optimizing for size. 10145 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10146 TM.getOptLevel() == CodeGenOpt::None || 10147 SwitchMBB->getParent()->getFunction().optForMinSize()) 10148 return SwitchMBB; 10149 10150 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10151 unsigned PeeledCaseIndex = 0; 10152 bool SwitchPeeled = false; 10153 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10154 CaseCluster &CC = Clusters[Index]; 10155 if (CC.Prob < TopCaseProb) 10156 continue; 10157 TopCaseProb = CC.Prob; 10158 PeeledCaseIndex = Index; 10159 SwitchPeeled = true; 10160 } 10161 if (!SwitchPeeled) 10162 return SwitchMBB; 10163 10164 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10165 << TopCaseProb << "\n"); 10166 10167 // Record the MBB for the peeled switch statement. 10168 MachineFunction::iterator BBI(SwitchMBB); 10169 ++BBI; 10170 MachineBasicBlock *PeeledSwitchMBB = 10171 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10172 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10173 10174 ExportFromCurrentBlock(SI.getCondition()); 10175 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10176 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10177 nullptr, nullptr, TopCaseProb.getCompl()}; 10178 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10179 10180 Clusters.erase(PeeledCaseIt); 10181 for (CaseCluster &CC : Clusters) { 10182 LLVM_DEBUG( 10183 dbgs() << "Scale the probablity for one cluster, before scaling: " 10184 << CC.Prob << "\n"); 10185 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10186 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10187 } 10188 PeeledCaseProb = TopCaseProb; 10189 return PeeledSwitchMBB; 10190 } 10191 10192 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10193 // Extract cases from the switch. 10194 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10195 CaseClusterVector Clusters; 10196 Clusters.reserve(SI.getNumCases()); 10197 for (auto I : SI.cases()) { 10198 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10199 const ConstantInt *CaseVal = I.getCaseValue(); 10200 BranchProbability Prob = 10201 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10202 : BranchProbability(1, SI.getNumCases() + 1); 10203 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10204 } 10205 10206 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10207 10208 // Cluster adjacent cases with the same destination. We do this at all 10209 // optimization levels because it's cheap to do and will make codegen faster 10210 // if there are many clusters. 10211 sortAndRangeify(Clusters); 10212 10213 if (TM.getOptLevel() != CodeGenOpt::None) { 10214 // Replace an unreachable default with the most popular destination. 10215 // FIXME: Exploit unreachable default more aggressively. 10216 bool UnreachableDefault = 10217 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10218 if (UnreachableDefault && !Clusters.empty()) { 10219 DenseMap<const BasicBlock *, unsigned> Popularity; 10220 unsigned MaxPop = 0; 10221 const BasicBlock *MaxBB = nullptr; 10222 for (auto I : SI.cases()) { 10223 const BasicBlock *BB = I.getCaseSuccessor(); 10224 if (++Popularity[BB] > MaxPop) { 10225 MaxPop = Popularity[BB]; 10226 MaxBB = BB; 10227 } 10228 } 10229 // Set new default. 10230 assert(MaxPop > 0 && MaxBB); 10231 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10232 10233 // Remove cases that were pointing to the destination that is now the 10234 // default. 10235 CaseClusterVector New; 10236 New.reserve(Clusters.size()); 10237 for (CaseCluster &CC : Clusters) { 10238 if (CC.MBB != DefaultMBB) 10239 New.push_back(CC); 10240 } 10241 Clusters = std::move(New); 10242 } 10243 } 10244 10245 // The branch probablity of the peeled case. 10246 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10247 MachineBasicBlock *PeeledSwitchMBB = 10248 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10249 10250 // If there is only the default destination, jump there directly. 10251 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10252 if (Clusters.empty()) { 10253 assert(PeeledSwitchMBB == SwitchMBB); 10254 SwitchMBB->addSuccessor(DefaultMBB); 10255 if (DefaultMBB != NextBlock(SwitchMBB)) { 10256 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10257 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10258 } 10259 return; 10260 } 10261 10262 findJumpTables(Clusters, &SI, DefaultMBB); 10263 findBitTestClusters(Clusters, &SI); 10264 10265 LLVM_DEBUG({ 10266 dbgs() << "Case clusters: "; 10267 for (const CaseCluster &C : Clusters) { 10268 if (C.Kind == CC_JumpTable) 10269 dbgs() << "JT:"; 10270 if (C.Kind == CC_BitTests) 10271 dbgs() << "BT:"; 10272 10273 C.Low->getValue().print(dbgs(), true); 10274 if (C.Low != C.High) { 10275 dbgs() << '-'; 10276 C.High->getValue().print(dbgs(), true); 10277 } 10278 dbgs() << ' '; 10279 } 10280 dbgs() << '\n'; 10281 }); 10282 10283 assert(!Clusters.empty()); 10284 SwitchWorkList WorkList; 10285 CaseClusterIt First = Clusters.begin(); 10286 CaseClusterIt Last = Clusters.end() - 1; 10287 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10288 // Scale the branchprobability for DefaultMBB if the peel occurs and 10289 // DefaultMBB is not replaced. 10290 if (PeeledCaseProb != BranchProbability::getZero() && 10291 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10292 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10293 WorkList.push_back( 10294 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10295 10296 while (!WorkList.empty()) { 10297 SwitchWorkListItem W = WorkList.back(); 10298 WorkList.pop_back(); 10299 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10300 10301 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10302 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10303 // For optimized builds, lower large range as a balanced binary tree. 10304 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10305 continue; 10306 } 10307 10308 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10309 } 10310 } 10311