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