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 // True if the Value passed requires ABI mangling as it is a parameter to a 161 // function or a return value from a function which is not an intrinsic. 162 static bool isABIRegCopy(const Value *V) { 163 const bool IsRetInst = V && isa<ReturnInst>(V); 164 const bool IsCallInst = V && isa<CallInst>(V); 165 const bool IsInLineAsm = 166 IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm(); 167 const bool IsIndirectFunctionCall = 168 IsCallInst && !IsInLineAsm && 169 !static_cast<const CallInst *>(V)->getCalledFunction(); 170 // It is possible that the call instruction is an inline asm statement or an 171 // indirect function call in which case the return value of 172 // getCalledFunction() would be nullptr. 173 const bool IsInstrinsicCall = 174 IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall && 175 static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() != 176 Intrinsic::not_intrinsic; 177 178 return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall)); 179 } 180 181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 182 const SDValue *Parts, unsigned NumParts, 183 MVT PartVT, EVT ValueVT, const Value *V, 184 bool IsABIRegCopy); 185 186 /// getCopyFromParts - Create a value that contains the specified legal parts 187 /// combined into the value they represent. If the parts combine to a type 188 /// larger than ValueVT then AssertOp can be used to specify whether the extra 189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 190 /// (ISD::AssertSext). 191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 192 const SDValue *Parts, unsigned NumParts, 193 MVT PartVT, EVT ValueVT, const Value *V, 194 Optional<ISD::NodeType> AssertOp = None, 195 bool IsABIRegCopy = false) { 196 if (ValueVT.isVector()) 197 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 198 PartVT, ValueVT, V, IsABIRegCopy); 199 200 assert(NumParts > 0 && "No parts to assemble!"); 201 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 202 SDValue Val = Parts[0]; 203 204 if (NumParts > 1) { 205 // Assemble the value from multiple parts. 206 if (ValueVT.isInteger()) { 207 unsigned PartBits = PartVT.getSizeInBits(); 208 unsigned ValueBits = ValueVT.getSizeInBits(); 209 210 // Assemble the power of 2 part. 211 unsigned RoundParts = NumParts & (NumParts - 1) ? 212 1 << Log2_32(NumParts) : NumParts; 213 unsigned RoundBits = PartBits * RoundParts; 214 EVT RoundVT = RoundBits == ValueBits ? 215 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 216 SDValue Lo, Hi; 217 218 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 219 220 if (RoundParts > 2) { 221 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 222 PartVT, HalfVT, V); 223 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 224 RoundParts / 2, PartVT, HalfVT, V); 225 } else { 226 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 227 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 228 } 229 230 if (DAG.getDataLayout().isBigEndian()) 231 std::swap(Lo, Hi); 232 233 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 234 235 if (RoundParts < NumParts) { 236 // Assemble the trailing non-power-of-2 part. 237 unsigned OddParts = NumParts - RoundParts; 238 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 239 Hi = getCopyFromParts(DAG, DL, 240 Parts + RoundParts, OddParts, PartVT, OddVT, V); 241 242 // Combine the round and odd parts. 243 Lo = Val; 244 if (DAG.getDataLayout().isBigEndian()) 245 std::swap(Lo, Hi); 246 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 247 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 248 Hi = 249 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 250 DAG.getConstant(Lo.getValueSizeInBits(), DL, 251 TLI.getPointerTy(DAG.getDataLayout()))); 252 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 253 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 254 } 255 } else if (PartVT.isFloatingPoint()) { 256 // FP split into multiple FP parts (for ppcf128) 257 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 258 "Unexpected split"); 259 SDValue Lo, Hi; 260 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 261 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 262 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 263 std::swap(Lo, Hi); 264 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 265 } else { 266 // FP split into integer parts (soft fp) 267 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 268 !PartVT.isVector() && "Unexpected split"); 269 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 270 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 271 } 272 } 273 274 // There is now one part, held in Val. Correct it to match ValueVT. 275 // PartEVT is the type of the register class that holds the value. 276 // ValueVT is the type of the inline asm operation. 277 EVT PartEVT = Val.getValueType(); 278 279 if (PartEVT == ValueVT) 280 return Val; 281 282 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 283 ValueVT.bitsLT(PartEVT)) { 284 // For an FP value in an integer part, we need to truncate to the right 285 // width first. 286 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 287 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 288 } 289 290 // Handle types that have the same size. 291 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 292 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 293 294 // Handle types with different sizes. 295 if (PartEVT.isInteger() && ValueVT.isInteger()) { 296 if (ValueVT.bitsLT(PartEVT)) { 297 // For a truncate, see if we have any information to 298 // indicate whether the truncated bits will always be 299 // zero or sign-extension. 300 if (AssertOp.hasValue()) 301 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 302 DAG.getValueType(ValueVT)); 303 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 304 } 305 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 306 } 307 308 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 309 // FP_ROUND's are always exact here. 310 if (ValueVT.bitsLT(Val.getValueType())) 311 return DAG.getNode( 312 ISD::FP_ROUND, DL, ValueVT, Val, 313 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 314 315 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 316 } 317 318 llvm_unreachable("Unknown mismatch!"); 319 } 320 321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 322 const Twine &ErrMsg) { 323 const Instruction *I = dyn_cast_or_null<Instruction>(V); 324 if (!V) 325 return Ctx.emitError(ErrMsg); 326 327 const char *AsmError = ", possible invalid constraint for vector type"; 328 if (const CallInst *CI = dyn_cast<CallInst>(I)) 329 if (isa<InlineAsm>(CI->getCalledValue())) 330 return Ctx.emitError(I, ErrMsg + AsmError); 331 332 return Ctx.emitError(I, ErrMsg); 333 } 334 335 /// getCopyFromPartsVector - Create a value that contains the specified legal 336 /// parts combined into the value they represent. If the parts combine to a 337 /// type larger than ValueVT then AssertOp can be used to specify whether the 338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 339 /// ValueVT (ISD::AssertSext). 340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 341 const SDValue *Parts, unsigned NumParts, 342 MVT PartVT, EVT ValueVT, const Value *V, 343 bool IsABIRegCopy) { 344 assert(ValueVT.isVector() && "Not a vector value"); 345 assert(NumParts > 0 && "No parts to assemble!"); 346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 347 SDValue Val = Parts[0]; 348 349 // Handle a multi-element vector. 350 if (NumParts > 1) { 351 EVT IntermediateVT; 352 MVT RegisterVT; 353 unsigned NumIntermediates; 354 unsigned NumRegs; 355 356 if (IsABIRegCopy) { 357 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 358 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 359 RegisterVT); 360 } else { 361 NumRegs = 362 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } 365 366 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 367 NumParts = NumRegs; // Silence a compiler warning. 368 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 369 assert(RegisterVT.getSizeInBits() == 370 Parts[0].getSimpleValueType().getSizeInBits() && 371 "Part type sizes don't match!"); 372 373 // Assemble the parts into intermediate operands. 374 SmallVector<SDValue, 8> Ops(NumIntermediates); 375 if (NumIntermediates == NumParts) { 376 // If the register was not expanded, truncate or copy the value, 377 // as appropriate. 378 for (unsigned i = 0; i != NumParts; ++i) 379 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 380 PartVT, IntermediateVT, V); 381 } else if (NumParts > 0) { 382 // If the intermediate type was expanded, build the intermediate 383 // operands from the parts. 384 assert(NumParts % NumIntermediates == 0 && 385 "Must expand into a divisible number of parts!"); 386 unsigned Factor = NumParts / NumIntermediates; 387 for (unsigned i = 0; i != NumIntermediates; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 389 PartVT, IntermediateVT, V); 390 } 391 392 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 393 // intermediate operands. 394 EVT BuiltVectorTy = 395 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 396 (IntermediateVT.isVector() 397 ? IntermediateVT.getVectorNumElements() * NumParts 398 : NumIntermediates)); 399 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 400 : ISD::BUILD_VECTOR, 401 DL, BuiltVectorTy, Ops); 402 } 403 404 // There is now one part, held in Val. Correct it to match ValueVT. 405 EVT PartEVT = Val.getValueType(); 406 407 if (PartEVT == ValueVT) 408 return Val; 409 410 if (PartEVT.isVector()) { 411 // If the element type of the source/dest vectors are the same, but the 412 // parts vector has more elements than the value vector, then we have a 413 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 414 // elements we want. 415 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 416 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 417 "Cannot narrow, it would be a lossy transformation"); 418 return DAG.getNode( 419 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 420 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 421 } 422 423 // Vector/Vector bitcast. 424 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 425 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 426 427 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 428 "Cannot handle this kind of promotion"); 429 // Promoted vector extract 430 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 431 432 } 433 434 // Trivial bitcast if the types are the same size and the destination 435 // vector type is legal. 436 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 437 TLI.isTypeLegal(ValueVT)) 438 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 439 440 if (ValueVT.getVectorNumElements() != 1) { 441 // Certain ABIs require that vectors are passed as integers. For vectors 442 // are the same size, this is an obvious bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 446 // Bitcast Val back the original type and extract the corresponding 447 // vector we want. 448 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 449 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 450 ValueVT.getVectorElementType(), Elts); 451 Val = DAG.getBitcast(WiderVecType, Val); 452 return DAG.getNode( 453 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 454 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 455 } 456 457 diagnosePossiblyInvalidConstraint( 458 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 459 return DAG.getUNDEF(ValueVT); 460 } 461 462 // Handle cases such as i8 -> <1 x i1> 463 EVT ValueSVT = ValueVT.getVectorElementType(); 464 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 465 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 466 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 467 468 return DAG.getBuildVector(ValueVT, DL, Val); 469 } 470 471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 472 SDValue Val, SDValue *Parts, unsigned NumParts, 473 MVT PartVT, const Value *V, bool IsABIRegCopy); 474 475 /// getCopyToParts - Create a series of nodes that contain the specified value 476 /// split into legal parts. If the parts contain more bits than Val, then, for 477 /// integers, ExtendKind can be used to specify how to generate the extra bits. 478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 479 SDValue *Parts, unsigned NumParts, MVT PartVT, 480 const Value *V, 481 ISD::NodeType ExtendKind = ISD::ANY_EXTEND, 482 bool IsABIRegCopy = false) { 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 IsABIRegCopy); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getIntPtrConstant(RoundBits, DL)); 567 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 568 569 if (DAG.getDataLayout().isBigEndian()) 570 // The odd parts were reversed by getCopyToParts - unreverse them. 571 std::reverse(Parts + RoundParts, Parts + NumParts); 572 573 NumParts = RoundParts; 574 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 575 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 576 } 577 578 // The number of parts is a power of 2. Repeatedly bisect the value using 579 // EXTRACT_ELEMENT. 580 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 581 EVT::getIntegerVT(*DAG.getContext(), 582 ValueVT.getSizeInBits()), 583 Val); 584 585 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 586 for (unsigned i = 0; i < NumParts; i += StepSize) { 587 unsigned ThisBits = StepSize * PartBits / 2; 588 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 589 SDValue &Part0 = Parts[i]; 590 SDValue &Part1 = Parts[i+StepSize/2]; 591 592 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 593 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 594 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 596 597 if (ThisBits == PartBits && ThisVT != PartVT) { 598 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 599 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 600 } 601 } 602 } 603 604 if (DAG.getDataLayout().isBigEndian()) 605 std::reverse(Parts, Parts + OrigNumParts); 606 } 607 608 609 /// getCopyToPartsVector - Create a series of nodes that contain the specified 610 /// value split into legal parts. 611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 612 SDValue Val, SDValue *Parts, unsigned NumParts, 613 MVT PartVT, const Value *V, 614 bool IsABIRegCopy) { 615 EVT ValueVT = Val.getValueType(); 616 assert(ValueVT.isVector() && "Not a vector"); 617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 618 619 if (NumParts == 1) { 620 EVT PartEVT = PartVT; 621 if (PartEVT == ValueVT) { 622 // Nothing to do. 623 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 624 // Bitconvert vector->vector case. 625 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 626 } else if (PartVT.isVector() && 627 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 628 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 629 EVT ElementVT = PartVT.getVectorElementType(); 630 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 631 // undef elements. 632 SmallVector<SDValue, 16> Ops; 633 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 634 Ops.push_back(DAG.getNode( 635 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 636 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 637 638 for (unsigned i = ValueVT.getVectorNumElements(), 639 e = PartVT.getVectorNumElements(); i != e; ++i) 640 Ops.push_back(DAG.getUNDEF(ElementVT)); 641 642 Val = DAG.getBuildVector(PartVT, DL, Ops); 643 644 // FIXME: Use CONCAT for 2x -> 4x. 645 646 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 647 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 648 } else if (PartVT.isVector() && 649 PartEVT.getVectorElementType().bitsGE( 650 ValueVT.getVectorElementType()) && 651 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 652 653 // Promoted vector extract 654 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 655 } else { 656 if (ValueVT.getVectorNumElements() == 1) { 657 Val = DAG.getNode( 658 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 659 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 660 } else { 661 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 662 "lossy conversion of vector to scalar type"); 663 EVT IntermediateType = 664 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 665 Val = DAG.getBitcast(IntermediateType, Val); 666 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 667 } 668 } 669 670 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 671 Parts[0] = Val; 672 return; 673 } 674 675 // Handle a multi-element vector. 676 EVT IntermediateVT; 677 MVT RegisterVT; 678 unsigned NumIntermediates; 679 unsigned NumRegs; 680 if (IsABIRegCopy) { 681 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 682 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 683 RegisterVT); 684 } else { 685 NumRegs = 686 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 687 NumIntermediates, RegisterVT); 688 } 689 unsigned NumElements = ValueVT.getVectorNumElements(); 690 691 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 692 NumParts = NumRegs; // Silence a compiler warning. 693 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 694 695 // Convert the vector to the appropiate type if necessary. 696 unsigned DestVectorNoElts = 697 NumIntermediates * 698 (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1); 699 EVT BuiltVectorTy = EVT::getVectorVT( 700 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 701 if (Val.getValueType() != BuiltVectorTy) 702 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 703 704 // Split the vector into intermediate operands. 705 SmallVector<SDValue, 8> Ops(NumIntermediates); 706 for (unsigned i = 0; i != NumIntermediates; ++i) { 707 if (IntermediateVT.isVector()) 708 Ops[i] = 709 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 710 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 711 TLI.getVectorIdxTy(DAG.getDataLayout()))); 712 else 713 Ops[i] = DAG.getNode( 714 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 715 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 716 } 717 718 // Split the intermediate operands into legal parts. 719 if (NumParts == NumIntermediates) { 720 // If the register was not expanded, promote or copy the value, 721 // as appropriate. 722 for (unsigned i = 0; i != NumParts; ++i) 723 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 724 } else if (NumParts > 0) { 725 // If the intermediate type was expanded, split each the value into 726 // legal parts. 727 assert(NumIntermediates != 0 && "division by zero"); 728 assert(NumParts % NumIntermediates == 0 && 729 "Must expand into a divisible number of parts!"); 730 unsigned Factor = NumParts / NumIntermediates; 731 for (unsigned i = 0; i != NumIntermediates; ++i) 732 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 733 } 734 } 735 736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 737 EVT valuevt, bool IsABIMangledValue) 738 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 739 RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {} 740 741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 742 const DataLayout &DL, unsigned Reg, Type *Ty, 743 bool IsABIMangledValue) { 744 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 745 746 IsABIMangled = IsABIMangledValue; 747 748 for (EVT ValueVT : ValueVTs) { 749 unsigned NumRegs = IsABIMangledValue 750 ? TLI.getNumRegistersForCallingConv(Context, ValueVT) 751 : TLI.getNumRegisters(Context, ValueVT); 752 MVT RegisterVT = IsABIMangledValue 753 ? TLI.getRegisterTypeForCallingConv(Context, ValueVT) 754 : TLI.getRegisterType(Context, ValueVT); 755 for (unsigned i = 0; i != NumRegs; ++i) 756 Regs.push_back(Reg + i); 757 RegVTs.push_back(RegisterVT); 758 RegCount.push_back(NumRegs); 759 Reg += NumRegs; 760 } 761 } 762 763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 764 FunctionLoweringInfo &FuncInfo, 765 const SDLoc &dl, SDValue &Chain, 766 SDValue *Flag, const Value *V) const { 767 // A Value with type {} or [0 x %t] needs no registers. 768 if (ValueVTs.empty()) 769 return SDValue(); 770 771 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 772 773 // Assemble the legal parts into the final values. 774 SmallVector<SDValue, 4> Values(ValueVTs.size()); 775 SmallVector<SDValue, 8> Parts; 776 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 777 // Copy the legal parts from the registers. 778 EVT ValueVT = ValueVTs[Value]; 779 unsigned NumRegs = RegCount[Value]; 780 MVT RegisterVT = IsABIMangled 781 ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value]) 782 : RegVTs[Value]; 783 784 Parts.resize(NumRegs); 785 for (unsigned i = 0; i != NumRegs; ++i) { 786 SDValue P; 787 if (!Flag) { 788 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 789 } else { 790 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 791 *Flag = P.getValue(2); 792 } 793 794 Chain = P.getValue(1); 795 Parts[i] = P; 796 797 // If the source register was virtual and if we know something about it, 798 // add an assert node. 799 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 800 !RegisterVT.isInteger() || RegisterVT.isVector()) 801 continue; 802 803 const FunctionLoweringInfo::LiveOutInfo *LOI = 804 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 805 if (!LOI) 806 continue; 807 808 unsigned RegSize = RegisterVT.getSizeInBits(); 809 unsigned NumSignBits = LOI->NumSignBits; 810 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 811 812 if (NumZeroBits == RegSize) { 813 // The current value is a zero. 814 // Explicitly express that as it would be easier for 815 // optimizations to kick in. 816 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 817 continue; 818 } 819 820 // FIXME: We capture more information than the dag can represent. For 821 // now, just use the tightest assertzext/assertsext possible. 822 bool isSExt; 823 EVT FromVT(MVT::Other); 824 if (NumZeroBits) { 825 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 826 isSExt = false; 827 } else if (NumSignBits > 1) { 828 FromVT = 829 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 830 isSExt = true; 831 } else { 832 continue; 833 } 834 // Add an assertion node. 835 assert(FromVT != MVT::Other); 836 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 837 RegisterVT, P, DAG.getValueType(FromVT)); 838 } 839 840 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 841 NumRegs, RegisterVT, ValueVT, V); 842 Part += NumRegs; 843 Parts.clear(); 844 } 845 846 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 847 } 848 849 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 850 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 851 const Value *V, 852 ISD::NodeType PreferredExtendType) const { 853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 854 ISD::NodeType ExtendKind = PreferredExtendType; 855 856 // Get the list of the values's legal parts. 857 unsigned NumRegs = Regs.size(); 858 SmallVector<SDValue, 8> Parts(NumRegs); 859 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 860 unsigned NumParts = RegCount[Value]; 861 862 MVT RegisterVT = IsABIMangled 863 ? TLI.getRegisterTypeForCallingConv(*DAG.getContext(), RegVTs[Value]) 864 : RegVTs[Value]; 865 866 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 867 ExtendKind = ISD::ZERO_EXTEND; 868 869 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 870 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 871 Part += NumParts; 872 } 873 874 // Copy the parts into the registers. 875 SmallVector<SDValue, 8> Chains(NumRegs); 876 for (unsigned i = 0; i != NumRegs; ++i) { 877 SDValue Part; 878 if (!Flag) { 879 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 880 } else { 881 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 882 *Flag = Part.getValue(1); 883 } 884 885 Chains[i] = Part.getValue(0); 886 } 887 888 if (NumRegs == 1 || Flag) 889 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 890 // flagged to it. That is the CopyToReg nodes and the user are considered 891 // a single scheduling unit. If we create a TokenFactor and return it as 892 // chain, then the TokenFactor is both a predecessor (operand) of the 893 // user as well as a successor (the TF operands are flagged to the user). 894 // c1, f1 = CopyToReg 895 // c2, f2 = CopyToReg 896 // c3 = TokenFactor c1, c2 897 // ... 898 // = op c3, ..., f2 899 Chain = Chains[NumRegs-1]; 900 else 901 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 902 } 903 904 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 905 unsigned MatchingIdx, const SDLoc &dl, 906 SelectionDAG &DAG, 907 std::vector<SDValue> &Ops) const { 908 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 909 910 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 911 if (HasMatching) 912 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 913 else if (!Regs.empty() && 914 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 915 // Put the register class of the virtual registers in the flag word. That 916 // way, later passes can recompute register class constraints for inline 917 // assembly as well as normal instructions. 918 // Don't do this for tied operands that can use the regclass information 919 // from the def. 920 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 921 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 922 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 923 } 924 925 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 926 Ops.push_back(Res); 927 928 if (Code == InlineAsm::Kind_Clobber) { 929 // Clobbers should always have a 1:1 mapping with registers, and may 930 // reference registers that have illegal (e.g. vector) types. Hence, we 931 // shouldn't try to apply any sort of splitting logic to them. 932 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 933 "No 1:1 mapping from clobbers to regs?"); 934 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 935 (void)SP; 936 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 937 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 938 assert( 939 (Regs[I] != SP || 940 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 941 "If we clobbered the stack pointer, MFI should know about it."); 942 } 943 return; 944 } 945 946 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 947 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 948 MVT RegisterVT = RegVTs[Value]; 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 951 unsigned TheReg = Regs[Reg++]; 952 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 953 } 954 } 955 } 956 957 SmallVector<std::pair<unsigned, unsigned>, 4> 958 RegsForValue::getRegsAndSizes() const { 959 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 960 unsigned I = 0; 961 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 962 unsigned RegCount = std::get<0>(CountAndVT); 963 MVT RegisterVT = std::get<1>(CountAndVT); 964 unsigned RegisterSize = RegisterVT.getSizeInBits(); 965 for (unsigned E = I + RegCount; I != E; ++I) 966 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 967 } 968 return OutVec; 969 } 970 971 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 972 const TargetLibraryInfo *li) { 973 AA = aa; 974 GFI = gfi; 975 LibInfo = li; 976 DL = &DAG.getDataLayout(); 977 Context = DAG.getContext(); 978 LPadToCallSiteMap.clear(); 979 } 980 981 void SelectionDAGBuilder::clear() { 982 NodeMap.clear(); 983 UnusedArgNodeMap.clear(); 984 PendingLoads.clear(); 985 PendingExports.clear(); 986 CurInst = nullptr; 987 HasTailCall = false; 988 SDNodeOrder = LowestSDNodeOrder; 989 StatepointLowering.clear(); 990 } 991 992 void SelectionDAGBuilder::clearDanglingDebugInfo() { 993 DanglingDebugInfoMap.clear(); 994 } 995 996 SDValue SelectionDAGBuilder::getRoot() { 997 if (PendingLoads.empty()) 998 return DAG.getRoot(); 999 1000 if (PendingLoads.size() == 1) { 1001 SDValue Root = PendingLoads[0]; 1002 DAG.setRoot(Root); 1003 PendingLoads.clear(); 1004 return Root; 1005 } 1006 1007 // Otherwise, we have to make a token factor node. 1008 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1009 PendingLoads); 1010 PendingLoads.clear(); 1011 DAG.setRoot(Root); 1012 return Root; 1013 } 1014 1015 SDValue SelectionDAGBuilder::getControlRoot() { 1016 SDValue Root = DAG.getRoot(); 1017 1018 if (PendingExports.empty()) 1019 return Root; 1020 1021 // Turn all of the CopyToReg chains into one factored node. 1022 if (Root.getOpcode() != ISD::EntryToken) { 1023 unsigned i = 0, e = PendingExports.size(); 1024 for (; i != e; ++i) { 1025 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1026 if (PendingExports[i].getNode()->getOperand(0) == Root) 1027 break; // Don't add the root if we already indirectly depend on it. 1028 } 1029 1030 if (i == e) 1031 PendingExports.push_back(Root); 1032 } 1033 1034 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1035 PendingExports); 1036 PendingExports.clear(); 1037 DAG.setRoot(Root); 1038 return Root; 1039 } 1040 1041 void SelectionDAGBuilder::visit(const Instruction &I) { 1042 // Set up outgoing PHI node register values before emitting the terminator. 1043 if (isa<TerminatorInst>(&I)) { 1044 HandlePHINodesInSuccessorBlocks(I.getParent()); 1045 } 1046 1047 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1048 if (!isa<DbgInfoIntrinsic>(I)) 1049 ++SDNodeOrder; 1050 1051 CurInst = &I; 1052 1053 visit(I.getOpcode(), I); 1054 1055 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1056 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1057 // maps to this instruction. 1058 // TODO: We could handle all flags (nsw, etc) here. 1059 // TODO: If an IR instruction maps to >1 node, only the final node will have 1060 // flags set. 1061 if (SDNode *Node = getNodeForIRValue(&I)) { 1062 SDNodeFlags IncomingFlags; 1063 IncomingFlags.copyFMF(*FPMO); 1064 if (!Node->getFlags().isDefined()) 1065 Node->setFlags(IncomingFlags); 1066 else 1067 Node->intersectFlagsWith(IncomingFlags); 1068 } 1069 } 1070 1071 if (!isa<TerminatorInst>(&I) && !HasTailCall && 1072 !isStatepoint(&I)) // statepoints handle their exports internally 1073 CopyToExportRegsIfNeeded(&I); 1074 1075 CurInst = nullptr; 1076 } 1077 1078 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1079 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1080 } 1081 1082 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1083 // Note: this doesn't use InstVisitor, because it has to work with 1084 // ConstantExpr's in addition to instructions. 1085 switch (Opcode) { 1086 default: llvm_unreachable("Unknown instruction type encountered!"); 1087 // Build the switch statement using the Instruction.def file. 1088 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1089 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1090 #include "llvm/IR/Instruction.def" 1091 } 1092 } 1093 1094 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1095 const DIExpression *Expr) { 1096 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1097 const DbgValueInst *DI = DDI.getDI(); 1098 DIVariable *DanglingVariable = DI->getVariable(); 1099 DIExpression *DanglingExpr = DI->getExpression(); 1100 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1101 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1102 return true; 1103 } 1104 return false; 1105 }; 1106 1107 for (auto &DDIMI : DanglingDebugInfoMap) { 1108 DanglingDebugInfoVector &DDIV = DDIMI.second; 1109 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1110 } 1111 } 1112 1113 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1114 // generate the debug data structures now that we've seen its definition. 1115 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1116 SDValue Val) { 1117 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1118 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1119 return; 1120 1121 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1122 for (auto &DDI : DDIV) { 1123 const DbgValueInst *DI = DDI.getDI(); 1124 assert(DI && "Ill-formed DanglingDebugInfo"); 1125 DebugLoc dl = DDI.getdl(); 1126 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1127 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1128 DILocalVariable *Variable = DI->getVariable(); 1129 DIExpression *Expr = DI->getExpression(); 1130 assert(Variable->isValidLocationForIntrinsic(dl) && 1131 "Expected inlined-at fields to agree"); 1132 SDDbgValue *SDV; 1133 if (Val.getNode()) { 1134 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1135 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1136 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1137 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1138 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1139 // inserted after the definition of Val when emitting the instructions 1140 // after ISel. An alternative could be to teach 1141 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1142 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1143 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1144 << ValSDNodeOrder << "\n"); 1145 SDV = getDbgValue(Val, Variable, Expr, dl, 1146 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1147 DAG.AddDbgValue(SDV, Val.getNode(), false); 1148 } else 1149 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1150 << "in EmitFuncArgumentDbgValue\n"); 1151 } else 1152 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1153 } 1154 DDIV.clear(); 1155 } 1156 1157 /// getCopyFromRegs - If there was virtual register allocated for the value V 1158 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1159 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1160 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1161 SDValue Result; 1162 1163 if (It != FuncInfo.ValueMap.end()) { 1164 unsigned InReg = It->second; 1165 1166 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1167 DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V)); 1168 SDValue Chain = DAG.getEntryNode(); 1169 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1170 V); 1171 resolveDanglingDebugInfo(V, Result); 1172 } 1173 1174 return Result; 1175 } 1176 1177 /// getValue - Return an SDValue for the given Value. 1178 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1179 // If we already have an SDValue for this value, use it. It's important 1180 // to do this first, so that we don't create a CopyFromReg if we already 1181 // have a regular SDValue. 1182 SDValue &N = NodeMap[V]; 1183 if (N.getNode()) return N; 1184 1185 // If there's a virtual register allocated and initialized for this 1186 // value, use it. 1187 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1188 return copyFromReg; 1189 1190 // Otherwise create a new SDValue and remember it. 1191 SDValue Val = getValueImpl(V); 1192 NodeMap[V] = Val; 1193 resolveDanglingDebugInfo(V, Val); 1194 return Val; 1195 } 1196 1197 // Return true if SDValue exists for the given Value 1198 bool SelectionDAGBuilder::findValue(const Value *V) const { 1199 return (NodeMap.find(V) != NodeMap.end()) || 1200 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1201 } 1202 1203 /// getNonRegisterValue - Return an SDValue for the given Value, but 1204 /// don't look in FuncInfo.ValueMap for a virtual register. 1205 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1206 // If we already have an SDValue for this value, use it. 1207 SDValue &N = NodeMap[V]; 1208 if (N.getNode()) { 1209 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1210 // Remove the debug location from the node as the node is about to be used 1211 // in a location which may differ from the original debug location. This 1212 // is relevant to Constant and ConstantFP nodes because they can appear 1213 // as constant expressions inside PHI nodes. 1214 N->setDebugLoc(DebugLoc()); 1215 } 1216 return N; 1217 } 1218 1219 // Otherwise create a new SDValue and remember it. 1220 SDValue Val = getValueImpl(V); 1221 NodeMap[V] = Val; 1222 resolveDanglingDebugInfo(V, Val); 1223 return Val; 1224 } 1225 1226 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1227 /// Create an SDValue for the given value. 1228 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1229 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1230 1231 if (const Constant *C = dyn_cast<Constant>(V)) { 1232 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1233 1234 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1235 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1236 1237 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1238 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1239 1240 if (isa<ConstantPointerNull>(C)) { 1241 unsigned AS = V->getType()->getPointerAddressSpace(); 1242 return DAG.getConstant(0, getCurSDLoc(), 1243 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1244 } 1245 1246 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1247 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1248 1249 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1250 return DAG.getUNDEF(VT); 1251 1252 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1253 visit(CE->getOpcode(), *CE); 1254 SDValue N1 = NodeMap[V]; 1255 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1256 return N1; 1257 } 1258 1259 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1260 SmallVector<SDValue, 4> Constants; 1261 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1262 OI != OE; ++OI) { 1263 SDNode *Val = getValue(*OI).getNode(); 1264 // If the operand is an empty aggregate, there are no values. 1265 if (!Val) continue; 1266 // Add each leaf value from the operand to the Constants list 1267 // to form a flattened list of all the values. 1268 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1269 Constants.push_back(SDValue(Val, i)); 1270 } 1271 1272 return DAG.getMergeValues(Constants, getCurSDLoc()); 1273 } 1274 1275 if (const ConstantDataSequential *CDS = 1276 dyn_cast<ConstantDataSequential>(C)) { 1277 SmallVector<SDValue, 4> Ops; 1278 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1279 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1280 // Add each leaf value from the operand to the Constants list 1281 // to form a flattened list of all the values. 1282 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1283 Ops.push_back(SDValue(Val, i)); 1284 } 1285 1286 if (isa<ArrayType>(CDS->getType())) 1287 return DAG.getMergeValues(Ops, getCurSDLoc()); 1288 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1289 } 1290 1291 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1292 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1293 "Unknown struct or array constant!"); 1294 1295 SmallVector<EVT, 4> ValueVTs; 1296 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1297 unsigned NumElts = ValueVTs.size(); 1298 if (NumElts == 0) 1299 return SDValue(); // empty struct 1300 SmallVector<SDValue, 4> Constants(NumElts); 1301 for (unsigned i = 0; i != NumElts; ++i) { 1302 EVT EltVT = ValueVTs[i]; 1303 if (isa<UndefValue>(C)) 1304 Constants[i] = DAG.getUNDEF(EltVT); 1305 else if (EltVT.isFloatingPoint()) 1306 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1307 else 1308 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1309 } 1310 1311 return DAG.getMergeValues(Constants, getCurSDLoc()); 1312 } 1313 1314 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1315 return DAG.getBlockAddress(BA, VT); 1316 1317 VectorType *VecTy = cast<VectorType>(V->getType()); 1318 unsigned NumElements = VecTy->getNumElements(); 1319 1320 // Now that we know the number and type of the elements, get that number of 1321 // elements into the Ops array based on what kind of constant it is. 1322 SmallVector<SDValue, 16> Ops; 1323 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1324 for (unsigned i = 0; i != NumElements; ++i) 1325 Ops.push_back(getValue(CV->getOperand(i))); 1326 } else { 1327 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1328 EVT EltVT = 1329 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1330 1331 SDValue Op; 1332 if (EltVT.isFloatingPoint()) 1333 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1334 else 1335 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1336 Ops.assign(NumElements, Op); 1337 } 1338 1339 // Create a BUILD_VECTOR node. 1340 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1341 } 1342 1343 // If this is a static alloca, generate it as the frameindex instead of 1344 // computation. 1345 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1346 DenseMap<const AllocaInst*, int>::iterator SI = 1347 FuncInfo.StaticAllocaMap.find(AI); 1348 if (SI != FuncInfo.StaticAllocaMap.end()) 1349 return DAG.getFrameIndex(SI->second, 1350 TLI.getFrameIndexTy(DAG.getDataLayout())); 1351 } 1352 1353 // If this is an instruction which fast-isel has deferred, select it now. 1354 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1355 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1356 1357 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1358 Inst->getType(), isABIRegCopy(V)); 1359 SDValue Chain = DAG.getEntryNode(); 1360 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1361 } 1362 1363 llvm_unreachable("Can't get register for value!"); 1364 } 1365 1366 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1367 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1368 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1369 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1370 bool IsSEH = isAsynchronousEHPersonality(Pers); 1371 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1372 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1373 if (!IsSEH) 1374 CatchPadMBB->setIsEHScopeEntry(); 1375 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1376 if (IsMSVCCXX || IsCoreCLR) 1377 CatchPadMBB->setIsEHFuncletEntry(); 1378 // Wasm does not need catchpads anymore 1379 if (!IsWasmCXX) 1380 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1381 getControlRoot())); 1382 } 1383 1384 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1385 // Update machine-CFG edge. 1386 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1387 FuncInfo.MBB->addSuccessor(TargetMBB); 1388 1389 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1390 bool IsSEH = isAsynchronousEHPersonality(Pers); 1391 if (IsSEH) { 1392 // If this is not a fall-through branch or optimizations are switched off, 1393 // emit the branch. 1394 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1395 TM.getOptLevel() == CodeGenOpt::None) 1396 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1397 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1398 return; 1399 } 1400 1401 // Figure out the funclet membership for the catchret's successor. 1402 // This will be used by the FuncletLayout pass to determine how to order the 1403 // BB's. 1404 // A 'catchret' returns to the outer scope's color. 1405 Value *ParentPad = I.getCatchSwitchParentPad(); 1406 const BasicBlock *SuccessorColor; 1407 if (isa<ConstantTokenNone>(ParentPad)) 1408 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1409 else 1410 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1411 assert(SuccessorColor && "No parent funclet for catchret!"); 1412 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1413 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1414 1415 // Create the terminator node. 1416 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1417 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1418 DAG.getBasicBlock(SuccessorColorMBB)); 1419 DAG.setRoot(Ret); 1420 } 1421 1422 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1423 // Don't emit any special code for the cleanuppad instruction. It just marks 1424 // the start of an EH scope/funclet. 1425 FuncInfo.MBB->setIsEHScopeEntry(); 1426 FuncInfo.MBB->setIsEHFuncletEntry(); 1427 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1428 } 1429 1430 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1431 /// many places it could ultimately go. In the IR, we have a single unwind 1432 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1433 /// This function skips over imaginary basic blocks that hold catchswitch 1434 /// instructions, and finds all the "real" machine 1435 /// basic block destinations. As those destinations may not be successors of 1436 /// EHPadBB, here we also calculate the edge probability to those destinations. 1437 /// The passed-in Prob is the edge probability to EHPadBB. 1438 static void findUnwindDestinations( 1439 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1440 BranchProbability Prob, 1441 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1442 &UnwindDests) { 1443 EHPersonality Personality = 1444 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1445 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1446 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1447 bool IsSEH = isAsynchronousEHPersonality(Personality); 1448 1449 while (EHPadBB) { 1450 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1451 BasicBlock *NewEHPadBB = nullptr; 1452 if (isa<LandingPadInst>(Pad)) { 1453 // Stop on landingpads. They are not funclets. 1454 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1455 break; 1456 } else if (isa<CleanupPadInst>(Pad)) { 1457 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1458 // personalities. 1459 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1460 UnwindDests.back().first->setIsEHScopeEntry(); 1461 UnwindDests.back().first->setIsEHFuncletEntry(); 1462 break; 1463 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1464 // Add the catchpad handlers to the possible destinations. 1465 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1466 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1467 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1468 if (IsMSVCCXX || IsCoreCLR) 1469 UnwindDests.back().first->setIsEHFuncletEntry(); 1470 if (!IsSEH) 1471 UnwindDests.back().first->setIsEHScopeEntry(); 1472 } 1473 NewEHPadBB = CatchSwitch->getUnwindDest(); 1474 } else { 1475 continue; 1476 } 1477 1478 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1479 if (BPI && NewEHPadBB) 1480 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1481 EHPadBB = NewEHPadBB; 1482 } 1483 } 1484 1485 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1486 // Update successor info. 1487 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1488 auto UnwindDest = I.getUnwindDest(); 1489 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1490 BranchProbability UnwindDestProb = 1491 (BPI && UnwindDest) 1492 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1493 : BranchProbability::getZero(); 1494 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1495 for (auto &UnwindDest : UnwindDests) { 1496 UnwindDest.first->setIsEHPad(); 1497 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1498 } 1499 FuncInfo.MBB->normalizeSuccProbs(); 1500 1501 // Create the terminator node. 1502 SDValue Ret = 1503 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1504 DAG.setRoot(Ret); 1505 } 1506 1507 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1508 report_fatal_error("visitCatchSwitch not yet implemented!"); 1509 } 1510 1511 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1513 auto &DL = DAG.getDataLayout(); 1514 SDValue Chain = getControlRoot(); 1515 SmallVector<ISD::OutputArg, 8> Outs; 1516 SmallVector<SDValue, 8> OutVals; 1517 1518 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1519 // lower 1520 // 1521 // %val = call <ty> @llvm.experimental.deoptimize() 1522 // ret <ty> %val 1523 // 1524 // differently. 1525 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1526 LowerDeoptimizingReturn(); 1527 return; 1528 } 1529 1530 if (!FuncInfo.CanLowerReturn) { 1531 unsigned DemoteReg = FuncInfo.DemoteRegister; 1532 const Function *F = I.getParent()->getParent(); 1533 1534 // Emit a store of the return value through the virtual register. 1535 // Leave Outs empty so that LowerReturn won't try to load return 1536 // registers the usual way. 1537 SmallVector<EVT, 1> PtrValueVTs; 1538 ComputeValueVTs(TLI, DL, 1539 F->getReturnType()->getPointerTo( 1540 DAG.getDataLayout().getAllocaAddrSpace()), 1541 PtrValueVTs); 1542 1543 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1544 DemoteReg, PtrValueVTs[0]); 1545 SDValue RetOp = getValue(I.getOperand(0)); 1546 1547 SmallVector<EVT, 4> ValueVTs; 1548 SmallVector<uint64_t, 4> Offsets; 1549 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1550 unsigned NumValues = ValueVTs.size(); 1551 1552 SmallVector<SDValue, 4> Chains(NumValues); 1553 for (unsigned i = 0; i != NumValues; ++i) { 1554 // An aggregate return value cannot wrap around the address space, so 1555 // offsets to its parts don't wrap either. 1556 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1557 Chains[i] = DAG.getStore( 1558 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1559 // FIXME: better loc info would be nice. 1560 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1561 } 1562 1563 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1564 MVT::Other, Chains); 1565 } else if (I.getNumOperands() != 0) { 1566 SmallVector<EVT, 4> ValueVTs; 1567 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1568 unsigned NumValues = ValueVTs.size(); 1569 if (NumValues) { 1570 SDValue RetOp = getValue(I.getOperand(0)); 1571 1572 const Function *F = I.getParent()->getParent(); 1573 1574 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1575 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1576 Attribute::SExt)) 1577 ExtendKind = ISD::SIGN_EXTEND; 1578 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1579 Attribute::ZExt)) 1580 ExtendKind = ISD::ZERO_EXTEND; 1581 1582 LLVMContext &Context = F->getContext(); 1583 bool RetInReg = F->getAttributes().hasAttribute( 1584 AttributeList::ReturnIndex, Attribute::InReg); 1585 1586 for (unsigned j = 0; j != NumValues; ++j) { 1587 EVT VT = ValueVTs[j]; 1588 1589 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1590 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1591 1592 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT); 1593 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT); 1594 SmallVector<SDValue, 4> Parts(NumParts); 1595 getCopyToParts(DAG, getCurSDLoc(), 1596 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1597 &Parts[0], NumParts, PartVT, &I, ExtendKind, true); 1598 1599 // 'inreg' on function refers to return value 1600 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1601 if (RetInReg) 1602 Flags.setInReg(); 1603 1604 // Propagate extension type if any 1605 if (ExtendKind == ISD::SIGN_EXTEND) 1606 Flags.setSExt(); 1607 else if (ExtendKind == ISD::ZERO_EXTEND) 1608 Flags.setZExt(); 1609 1610 for (unsigned i = 0; i < NumParts; ++i) { 1611 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1612 VT, /*isfixed=*/true, 0, 0)); 1613 OutVals.push_back(Parts[i]); 1614 } 1615 } 1616 } 1617 } 1618 1619 // Push in swifterror virtual register as the last element of Outs. This makes 1620 // sure swifterror virtual register will be returned in the swifterror 1621 // physical register. 1622 const Function *F = I.getParent()->getParent(); 1623 if (TLI.supportSwiftError() && 1624 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1625 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1626 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1627 Flags.setSwiftError(); 1628 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1629 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1630 true /*isfixed*/, 1 /*origidx*/, 1631 0 /*partOffs*/)); 1632 // Create SDNode for the swifterror virtual register. 1633 OutVals.push_back( 1634 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1635 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1636 EVT(TLI.getPointerTy(DL)))); 1637 } 1638 1639 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1640 CallingConv::ID CallConv = 1641 DAG.getMachineFunction().getFunction().getCallingConv(); 1642 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1643 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1644 1645 // Verify that the target's LowerReturn behaved as expected. 1646 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1647 "LowerReturn didn't return a valid chain!"); 1648 1649 // Update the DAG with the new chain value resulting from return lowering. 1650 DAG.setRoot(Chain); 1651 } 1652 1653 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1654 /// created for it, emit nodes to copy the value into the virtual 1655 /// registers. 1656 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1657 // Skip empty types 1658 if (V->getType()->isEmptyTy()) 1659 return; 1660 1661 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1662 if (VMI != FuncInfo.ValueMap.end()) { 1663 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1664 CopyValueToVirtualRegister(V, VMI->second); 1665 } 1666 } 1667 1668 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1669 /// the current basic block, add it to ValueMap now so that we'll get a 1670 /// CopyTo/FromReg. 1671 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1672 // No need to export constants. 1673 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1674 1675 // Already exported? 1676 if (FuncInfo.isExportedInst(V)) return; 1677 1678 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1679 CopyValueToVirtualRegister(V, Reg); 1680 } 1681 1682 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1683 const BasicBlock *FromBB) { 1684 // The operands of the setcc have to be in this block. We don't know 1685 // how to export them from some other block. 1686 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1687 // Can export from current BB. 1688 if (VI->getParent() == FromBB) 1689 return true; 1690 1691 // Is already exported, noop. 1692 return FuncInfo.isExportedInst(V); 1693 } 1694 1695 // If this is an argument, we can export it if the BB is the entry block or 1696 // if it is already exported. 1697 if (isa<Argument>(V)) { 1698 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1699 return true; 1700 1701 // Otherwise, can only export this if it is already exported. 1702 return FuncInfo.isExportedInst(V); 1703 } 1704 1705 // Otherwise, constants can always be exported. 1706 return true; 1707 } 1708 1709 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1710 BranchProbability 1711 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1712 const MachineBasicBlock *Dst) const { 1713 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1714 const BasicBlock *SrcBB = Src->getBasicBlock(); 1715 const BasicBlock *DstBB = Dst->getBasicBlock(); 1716 if (!BPI) { 1717 // If BPI is not available, set the default probability as 1 / N, where N is 1718 // the number of successors. 1719 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1720 return BranchProbability(1, SuccSize); 1721 } 1722 return BPI->getEdgeProbability(SrcBB, DstBB); 1723 } 1724 1725 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1726 MachineBasicBlock *Dst, 1727 BranchProbability Prob) { 1728 if (!FuncInfo.BPI) 1729 Src->addSuccessorWithoutProb(Dst); 1730 else { 1731 if (Prob.isUnknown()) 1732 Prob = getEdgeProbability(Src, Dst); 1733 Src->addSuccessor(Dst, Prob); 1734 } 1735 } 1736 1737 static bool InBlock(const Value *V, const BasicBlock *BB) { 1738 if (const Instruction *I = dyn_cast<Instruction>(V)) 1739 return I->getParent() == BB; 1740 return true; 1741 } 1742 1743 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1744 /// This function emits a branch and is used at the leaves of an OR or an 1745 /// AND operator tree. 1746 void 1747 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1748 MachineBasicBlock *TBB, 1749 MachineBasicBlock *FBB, 1750 MachineBasicBlock *CurBB, 1751 MachineBasicBlock *SwitchBB, 1752 BranchProbability TProb, 1753 BranchProbability FProb, 1754 bool InvertCond) { 1755 const BasicBlock *BB = CurBB->getBasicBlock(); 1756 1757 // If the leaf of the tree is a comparison, merge the condition into 1758 // the caseblock. 1759 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1760 // The operands of the cmp have to be in this block. We don't know 1761 // how to export them from some other block. If this is the first block 1762 // of the sequence, no exporting is needed. 1763 if (CurBB == SwitchBB || 1764 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1765 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1766 ISD::CondCode Condition; 1767 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1768 ICmpInst::Predicate Pred = 1769 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1770 Condition = getICmpCondCode(Pred); 1771 } else { 1772 const FCmpInst *FC = cast<FCmpInst>(Cond); 1773 FCmpInst::Predicate Pred = 1774 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1775 Condition = getFCmpCondCode(Pred); 1776 if (TM.Options.NoNaNsFPMath) 1777 Condition = getFCmpCodeWithoutNaN(Condition); 1778 } 1779 1780 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1781 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1782 SwitchCases.push_back(CB); 1783 return; 1784 } 1785 } 1786 1787 // Create a CaseBlock record representing this branch. 1788 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1789 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1790 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1791 SwitchCases.push_back(CB); 1792 } 1793 1794 /// FindMergedConditions - If Cond is an expression like 1795 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1796 MachineBasicBlock *TBB, 1797 MachineBasicBlock *FBB, 1798 MachineBasicBlock *CurBB, 1799 MachineBasicBlock *SwitchBB, 1800 Instruction::BinaryOps Opc, 1801 BranchProbability TProb, 1802 BranchProbability FProb, 1803 bool InvertCond) { 1804 // Skip over not part of the tree and remember to invert op and operands at 1805 // next level. 1806 if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) { 1807 const Value *CondOp = BinaryOperator::getNotArgument(Cond); 1808 if (InBlock(CondOp, CurBB->getBasicBlock())) { 1809 FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1810 !InvertCond); 1811 return; 1812 } 1813 } 1814 1815 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1816 // Compute the effective opcode for Cond, taking into account whether it needs 1817 // to be inverted, e.g. 1818 // and (not (or A, B)), C 1819 // gets lowered as 1820 // and (and (not A, not B), C) 1821 unsigned BOpc = 0; 1822 if (BOp) { 1823 BOpc = BOp->getOpcode(); 1824 if (InvertCond) { 1825 if (BOpc == Instruction::And) 1826 BOpc = Instruction::Or; 1827 else if (BOpc == Instruction::Or) 1828 BOpc = Instruction::And; 1829 } 1830 } 1831 1832 // If this node is not part of the or/and tree, emit it as a branch. 1833 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1834 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1835 BOp->getParent() != CurBB->getBasicBlock() || 1836 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1837 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1838 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1839 TProb, FProb, InvertCond); 1840 return; 1841 } 1842 1843 // Create TmpBB after CurBB. 1844 MachineFunction::iterator BBI(CurBB); 1845 MachineFunction &MF = DAG.getMachineFunction(); 1846 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1847 CurBB->getParent()->insert(++BBI, TmpBB); 1848 1849 if (Opc == Instruction::Or) { 1850 // Codegen X | Y as: 1851 // BB1: 1852 // jmp_if_X TBB 1853 // jmp TmpBB 1854 // TmpBB: 1855 // jmp_if_Y TBB 1856 // jmp FBB 1857 // 1858 1859 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1860 // The requirement is that 1861 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1862 // = TrueProb for original BB. 1863 // Assuming the original probabilities are A and B, one choice is to set 1864 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1865 // A/(1+B) and 2B/(1+B). This choice assumes that 1866 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1867 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1868 // TmpBB, but the math is more complicated. 1869 1870 auto NewTrueProb = TProb / 2; 1871 auto NewFalseProb = TProb / 2 + FProb; 1872 // Emit the LHS condition. 1873 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1874 NewTrueProb, NewFalseProb, InvertCond); 1875 1876 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1877 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1878 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1879 // Emit the RHS condition into TmpBB. 1880 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1881 Probs[0], Probs[1], InvertCond); 1882 } else { 1883 assert(Opc == Instruction::And && "Unknown merge op!"); 1884 // Codegen X & Y as: 1885 // BB1: 1886 // jmp_if_X TmpBB 1887 // jmp FBB 1888 // TmpBB: 1889 // jmp_if_Y TBB 1890 // jmp FBB 1891 // 1892 // This requires creation of TmpBB after CurBB. 1893 1894 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1895 // The requirement is that 1896 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1897 // = FalseProb for original BB. 1898 // Assuming the original probabilities are A and B, one choice is to set 1899 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1900 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1901 // TrueProb for BB1 * FalseProb for TmpBB. 1902 1903 auto NewTrueProb = TProb + FProb / 2; 1904 auto NewFalseProb = FProb / 2; 1905 // Emit the LHS condition. 1906 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1907 NewTrueProb, NewFalseProb, InvertCond); 1908 1909 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1910 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 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 } 1916 } 1917 1918 /// If the set of cases should be emitted as a series of branches, return true. 1919 /// If we should emit this as a bunch of and/or'd together conditions, return 1920 /// false. 1921 bool 1922 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1923 if (Cases.size() != 2) return true; 1924 1925 // If this is two comparisons of the same values or'd or and'd together, they 1926 // will get folded into a single comparison, so don't emit two blocks. 1927 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1928 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1929 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1930 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1931 return false; 1932 } 1933 1934 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1935 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1936 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1937 Cases[0].CC == Cases[1].CC && 1938 isa<Constant>(Cases[0].CmpRHS) && 1939 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1940 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1941 return false; 1942 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1943 return false; 1944 } 1945 1946 return true; 1947 } 1948 1949 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1950 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1951 1952 // Update machine-CFG edges. 1953 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1954 1955 if (I.isUnconditional()) { 1956 // Update machine-CFG edges. 1957 BrMBB->addSuccessor(Succ0MBB); 1958 1959 // If this is not a fall-through branch or optimizations are switched off, 1960 // emit the branch. 1961 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1962 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1963 MVT::Other, getControlRoot(), 1964 DAG.getBasicBlock(Succ0MBB))); 1965 1966 return; 1967 } 1968 1969 // If this condition is one of the special cases we handle, do special stuff 1970 // now. 1971 const Value *CondVal = I.getCondition(); 1972 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1973 1974 // If this is a series of conditions that are or'd or and'd together, emit 1975 // this as a sequence of branches instead of setcc's with and/or operations. 1976 // As long as jumps are not expensive, this should improve performance. 1977 // For example, instead of something like: 1978 // cmp A, B 1979 // C = seteq 1980 // cmp D, E 1981 // F = setle 1982 // or C, F 1983 // jnz foo 1984 // Emit: 1985 // cmp A, B 1986 // je foo 1987 // cmp D, E 1988 // jle foo 1989 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1990 Instruction::BinaryOps Opcode = BOp->getOpcode(); 1991 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 1992 !I.getMetadata(LLVMContext::MD_unpredictable) && 1993 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 1994 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1995 Opcode, 1996 getEdgeProbability(BrMBB, Succ0MBB), 1997 getEdgeProbability(BrMBB, Succ1MBB), 1998 /*InvertCond=*/false); 1999 // If the compares in later blocks need to use values not currently 2000 // exported from this block, export them now. This block should always 2001 // be the first entry. 2002 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2003 2004 // Allow some cases to be rejected. 2005 if (ShouldEmitAsBranches(SwitchCases)) { 2006 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2007 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2008 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2009 } 2010 2011 // Emit the branch for this block. 2012 visitSwitchCase(SwitchCases[0], BrMBB); 2013 SwitchCases.erase(SwitchCases.begin()); 2014 return; 2015 } 2016 2017 // Okay, we decided not to do this, remove any inserted MBB's and clear 2018 // SwitchCases. 2019 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2020 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2021 2022 SwitchCases.clear(); 2023 } 2024 } 2025 2026 // Create a CaseBlock record representing this branch. 2027 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2028 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2029 2030 // Use visitSwitchCase to actually insert the fast branch sequence for this 2031 // cond branch. 2032 visitSwitchCase(CB, BrMBB); 2033 } 2034 2035 /// visitSwitchCase - Emits the necessary code to represent a single node in 2036 /// the binary search tree resulting from lowering a switch instruction. 2037 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2038 MachineBasicBlock *SwitchBB) { 2039 SDValue Cond; 2040 SDValue CondLHS = getValue(CB.CmpLHS); 2041 SDLoc dl = CB.DL; 2042 2043 // Build the setcc now. 2044 if (!CB.CmpMHS) { 2045 // Fold "(X == true)" to X and "(X == false)" to !X to 2046 // handle common cases produced by branch lowering. 2047 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2048 CB.CC == ISD::SETEQ) 2049 Cond = CondLHS; 2050 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2051 CB.CC == ISD::SETEQ) { 2052 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2053 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2054 } else 2055 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2056 } else { 2057 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2058 2059 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2060 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2061 2062 SDValue CmpOp = getValue(CB.CmpMHS); 2063 EVT VT = CmpOp.getValueType(); 2064 2065 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2066 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2067 ISD::SETLE); 2068 } else { 2069 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2070 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2071 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2072 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2073 } 2074 } 2075 2076 // Update successor info 2077 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2078 // TrueBB and FalseBB are always different unless the incoming IR is 2079 // degenerate. This only happens when running llc on weird IR. 2080 if (CB.TrueBB != CB.FalseBB) 2081 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2082 SwitchBB->normalizeSuccProbs(); 2083 2084 // If the lhs block is the next block, invert the condition so that we can 2085 // fall through to the lhs instead of the rhs block. 2086 if (CB.TrueBB == NextBlock(SwitchBB)) { 2087 std::swap(CB.TrueBB, CB.FalseBB); 2088 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2089 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2090 } 2091 2092 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2093 MVT::Other, getControlRoot(), Cond, 2094 DAG.getBasicBlock(CB.TrueBB)); 2095 2096 // Insert the false branch. Do this even if it's a fall through branch, 2097 // this makes it easier to do DAG optimizations which require inverting 2098 // the branch condition. 2099 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2100 DAG.getBasicBlock(CB.FalseBB)); 2101 2102 DAG.setRoot(BrCond); 2103 } 2104 2105 /// visitJumpTable - Emit JumpTable node in the current MBB 2106 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2107 // Emit the code for the jump table 2108 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2109 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2110 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2111 JT.Reg, PTy); 2112 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2113 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2114 MVT::Other, Index.getValue(1), 2115 Table, Index); 2116 DAG.setRoot(BrJumpTable); 2117 } 2118 2119 /// visitJumpTableHeader - This function emits necessary code to produce index 2120 /// in the JumpTable from switch case. 2121 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2122 JumpTableHeader &JTH, 2123 MachineBasicBlock *SwitchBB) { 2124 SDLoc dl = getCurSDLoc(); 2125 2126 // Subtract the lowest switch case value from the value being switched on and 2127 // conditional branch to default mbb if the result is greater than the 2128 // difference between smallest and largest cases. 2129 SDValue SwitchOp = getValue(JTH.SValue); 2130 EVT VT = SwitchOp.getValueType(); 2131 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2132 DAG.getConstant(JTH.First, dl, VT)); 2133 2134 // The SDNode we just created, which holds the value being switched on minus 2135 // the smallest case value, needs to be copied to a virtual register so it 2136 // can be used as an index into the jump table in a subsequent basic block. 2137 // This value may be smaller or larger than the target's pointer type, and 2138 // therefore require extension or truncating. 2139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2140 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2141 2142 unsigned JumpTableReg = 2143 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2144 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2145 JumpTableReg, SwitchOp); 2146 JT.Reg = JumpTableReg; 2147 2148 // Emit the range check for the jump table, and branch to the default block 2149 // for the switch statement if the value being switched on exceeds the largest 2150 // case in the switch. 2151 SDValue CMP = DAG.getSetCC( 2152 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2153 Sub.getValueType()), 2154 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2155 2156 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2157 MVT::Other, CopyTo, CMP, 2158 DAG.getBasicBlock(JT.Default)); 2159 2160 // Avoid emitting unnecessary branches to the next block. 2161 if (JT.MBB != NextBlock(SwitchBB)) 2162 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2163 DAG.getBasicBlock(JT.MBB)); 2164 2165 DAG.setRoot(BrCond); 2166 } 2167 2168 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2169 /// variable if there exists one. 2170 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2171 SDValue &Chain) { 2172 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2173 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2174 MachineFunction &MF = DAG.getMachineFunction(); 2175 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2176 MachineSDNode *Node = 2177 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2178 if (Global) { 2179 MachinePointerInfo MPInfo(Global); 2180 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 2181 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2182 MachineMemOperand::MODereferenceable; 2183 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8, 2184 DAG.getEVTAlignment(PtrTy)); 2185 Node->setMemRefs(MemRefs, MemRefs + 1); 2186 } 2187 return SDValue(Node, 0); 2188 } 2189 2190 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2191 /// tail spliced into a stack protector check success bb. 2192 /// 2193 /// For a high level explanation of how this fits into the stack protector 2194 /// generation see the comment on the declaration of class 2195 /// StackProtectorDescriptor. 2196 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2197 MachineBasicBlock *ParentBB) { 2198 2199 // First create the loads to the guard/stack slot for the comparison. 2200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2201 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2202 2203 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2204 int FI = MFI.getStackProtectorIndex(); 2205 2206 SDValue Guard; 2207 SDLoc dl = getCurSDLoc(); 2208 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2209 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2210 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2211 2212 // Generate code to load the content of the guard slot. 2213 SDValue GuardVal = DAG.getLoad( 2214 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2215 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2216 MachineMemOperand::MOVolatile); 2217 2218 if (TLI.useStackGuardXorFP()) 2219 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2220 2221 // Retrieve guard check function, nullptr if instrumentation is inlined. 2222 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2223 // The target provides a guard check function to validate the guard value. 2224 // Generate a call to that function with the content of the guard slot as 2225 // argument. 2226 auto *Fn = cast<Function>(GuardCheck); 2227 FunctionType *FnTy = Fn->getFunctionType(); 2228 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2229 2230 TargetLowering::ArgListTy Args; 2231 TargetLowering::ArgListEntry Entry; 2232 Entry.Node = GuardVal; 2233 Entry.Ty = FnTy->getParamType(0); 2234 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2235 Entry.IsInReg = true; 2236 Args.push_back(Entry); 2237 2238 TargetLowering::CallLoweringInfo CLI(DAG); 2239 CLI.setDebugLoc(getCurSDLoc()) 2240 .setChain(DAG.getEntryNode()) 2241 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2242 getValue(GuardCheck), std::move(Args)); 2243 2244 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2245 DAG.setRoot(Result.second); 2246 return; 2247 } 2248 2249 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2250 // Otherwise, emit a volatile load to retrieve the stack guard value. 2251 SDValue Chain = DAG.getEntryNode(); 2252 if (TLI.useLoadStackGuardNode()) { 2253 Guard = getLoadStackGuard(DAG, dl, Chain); 2254 } else { 2255 const Value *IRGuard = TLI.getSDagStackGuard(M); 2256 SDValue GuardPtr = getValue(IRGuard); 2257 2258 Guard = 2259 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2260 Align, MachineMemOperand::MOVolatile); 2261 } 2262 2263 // Perform the comparison via a subtract/getsetcc. 2264 EVT VT = Guard.getValueType(); 2265 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2266 2267 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2268 *DAG.getContext(), 2269 Sub.getValueType()), 2270 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2271 2272 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2273 // branch to failure MBB. 2274 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2275 MVT::Other, GuardVal.getOperand(0), 2276 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2277 // Otherwise branch to success MBB. 2278 SDValue Br = DAG.getNode(ISD::BR, dl, 2279 MVT::Other, BrCond, 2280 DAG.getBasicBlock(SPD.getSuccessMBB())); 2281 2282 DAG.setRoot(Br); 2283 } 2284 2285 /// Codegen the failure basic block for a stack protector check. 2286 /// 2287 /// A failure stack protector machine basic block consists simply of a call to 2288 /// __stack_chk_fail(). 2289 /// 2290 /// For a high level explanation of how this fits into the stack protector 2291 /// generation see the comment on the declaration of class 2292 /// StackProtectorDescriptor. 2293 void 2294 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2295 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2296 SDValue Chain = 2297 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2298 None, false, getCurSDLoc(), false, false).second; 2299 DAG.setRoot(Chain); 2300 } 2301 2302 /// visitBitTestHeader - This function emits necessary code to produce value 2303 /// suitable for "bit tests" 2304 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2305 MachineBasicBlock *SwitchBB) { 2306 SDLoc dl = getCurSDLoc(); 2307 2308 // Subtract the minimum value 2309 SDValue SwitchOp = getValue(B.SValue); 2310 EVT VT = SwitchOp.getValueType(); 2311 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2312 DAG.getConstant(B.First, dl, VT)); 2313 2314 // Check range 2315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2316 SDValue RangeCmp = DAG.getSetCC( 2317 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2318 Sub.getValueType()), 2319 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2320 2321 // Determine the type of the test operands. 2322 bool UsePtrType = false; 2323 if (!TLI.isTypeLegal(VT)) 2324 UsePtrType = true; 2325 else { 2326 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2327 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2328 // Switch table case range are encoded into series of masks. 2329 // Just use pointer type, it's guaranteed to fit. 2330 UsePtrType = true; 2331 break; 2332 } 2333 } 2334 if (UsePtrType) { 2335 VT = TLI.getPointerTy(DAG.getDataLayout()); 2336 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2337 } 2338 2339 B.RegVT = VT.getSimpleVT(); 2340 B.Reg = FuncInfo.CreateReg(B.RegVT); 2341 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2342 2343 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2344 2345 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2346 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2347 SwitchBB->normalizeSuccProbs(); 2348 2349 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2350 MVT::Other, CopyTo, RangeCmp, 2351 DAG.getBasicBlock(B.Default)); 2352 2353 // Avoid emitting unnecessary branches to the next block. 2354 if (MBB != NextBlock(SwitchBB)) 2355 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2356 DAG.getBasicBlock(MBB)); 2357 2358 DAG.setRoot(BrRange); 2359 } 2360 2361 /// visitBitTestCase - this function produces one "bit test" 2362 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2363 MachineBasicBlock* NextMBB, 2364 BranchProbability BranchProbToNext, 2365 unsigned Reg, 2366 BitTestCase &B, 2367 MachineBasicBlock *SwitchBB) { 2368 SDLoc dl = getCurSDLoc(); 2369 MVT VT = BB.RegVT; 2370 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2371 SDValue Cmp; 2372 unsigned PopCount = countPopulation(B.Mask); 2373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2374 if (PopCount == 1) { 2375 // Testing for a single bit; just compare the shift count with what it 2376 // would need to be to shift a 1 bit in that position. 2377 Cmp = DAG.getSetCC( 2378 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2379 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2380 ISD::SETEQ); 2381 } else if (PopCount == BB.Range) { 2382 // There is only one zero bit in the range, test for it directly. 2383 Cmp = DAG.getSetCC( 2384 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2385 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2386 ISD::SETNE); 2387 } else { 2388 // Make desired shift 2389 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2390 DAG.getConstant(1, dl, VT), ShiftOp); 2391 2392 // Emit bit tests and jumps 2393 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2394 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2395 Cmp = DAG.getSetCC( 2396 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2397 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2398 } 2399 2400 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2401 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2402 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2403 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2404 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2405 // one as they are relative probabilities (and thus work more like weights), 2406 // and hence we need to normalize them to let the sum of them become one. 2407 SwitchBB->normalizeSuccProbs(); 2408 2409 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2410 MVT::Other, getControlRoot(), 2411 Cmp, DAG.getBasicBlock(B.TargetBB)); 2412 2413 // Avoid emitting unnecessary branches to the next block. 2414 if (NextMBB != NextBlock(SwitchBB)) 2415 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2416 DAG.getBasicBlock(NextMBB)); 2417 2418 DAG.setRoot(BrAnd); 2419 } 2420 2421 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2422 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2423 2424 // Retrieve successors. Look through artificial IR level blocks like 2425 // catchswitch for successors. 2426 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2427 const BasicBlock *EHPadBB = I.getSuccessor(1); 2428 2429 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2430 // have to do anything here to lower funclet bundles. 2431 assert(!I.hasOperandBundlesOtherThan( 2432 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2433 "Cannot lower invokes with arbitrary operand bundles yet!"); 2434 2435 const Value *Callee(I.getCalledValue()); 2436 const Function *Fn = dyn_cast<Function>(Callee); 2437 if (isa<InlineAsm>(Callee)) 2438 visitInlineAsm(&I); 2439 else if (Fn && Fn->isIntrinsic()) { 2440 switch (Fn->getIntrinsicID()) { 2441 default: 2442 llvm_unreachable("Cannot invoke this intrinsic"); 2443 case Intrinsic::donothing: 2444 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2445 break; 2446 case Intrinsic::experimental_patchpoint_void: 2447 case Intrinsic::experimental_patchpoint_i64: 2448 visitPatchpoint(&I, EHPadBB); 2449 break; 2450 case Intrinsic::experimental_gc_statepoint: 2451 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2452 break; 2453 } 2454 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2455 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2456 // Eventually we will support lowering the @llvm.experimental.deoptimize 2457 // intrinsic, and right now there are no plans to support other intrinsics 2458 // with deopt state. 2459 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2460 } else { 2461 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2462 } 2463 2464 // If the value of the invoke is used outside of its defining block, make it 2465 // available as a virtual register. 2466 // We already took care of the exported value for the statepoint instruction 2467 // during call to the LowerStatepoint. 2468 if (!isStatepoint(I)) { 2469 CopyToExportRegsIfNeeded(&I); 2470 } 2471 2472 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2473 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2474 BranchProbability EHPadBBProb = 2475 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2476 : BranchProbability::getZero(); 2477 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2478 2479 // Update successor info. 2480 addSuccessorWithProb(InvokeMBB, Return); 2481 for (auto &UnwindDest : UnwindDests) { 2482 UnwindDest.first->setIsEHPad(); 2483 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2484 } 2485 InvokeMBB->normalizeSuccProbs(); 2486 2487 // Drop into normal successor. 2488 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2489 MVT::Other, getControlRoot(), 2490 DAG.getBasicBlock(Return))); 2491 } 2492 2493 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2494 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2495 } 2496 2497 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2498 assert(FuncInfo.MBB->isEHPad() && 2499 "Call to landingpad not in landing pad!"); 2500 2501 MachineBasicBlock *MBB = FuncInfo.MBB; 2502 addLandingPadInfo(LP, *MBB); 2503 2504 // If there aren't registers to copy the values into (e.g., during SjLj 2505 // exceptions), then don't bother to create these DAG nodes. 2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2507 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2508 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2509 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2510 return; 2511 2512 // If landingpad's return type is token type, we don't create DAG nodes 2513 // for its exception pointer and selector value. The extraction of exception 2514 // pointer or selector value from token type landingpads is not currently 2515 // supported. 2516 if (LP.getType()->isTokenTy()) 2517 return; 2518 2519 SmallVector<EVT, 2> ValueVTs; 2520 SDLoc dl = getCurSDLoc(); 2521 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2522 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2523 2524 // Get the two live-in registers as SDValues. The physregs have already been 2525 // copied into virtual registers. 2526 SDValue Ops[2]; 2527 if (FuncInfo.ExceptionPointerVirtReg) { 2528 Ops[0] = DAG.getZExtOrTrunc( 2529 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2530 FuncInfo.ExceptionPointerVirtReg, 2531 TLI.getPointerTy(DAG.getDataLayout())), 2532 dl, ValueVTs[0]); 2533 } else { 2534 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2535 } 2536 Ops[1] = DAG.getZExtOrTrunc( 2537 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2538 FuncInfo.ExceptionSelectorVirtReg, 2539 TLI.getPointerTy(DAG.getDataLayout())), 2540 dl, ValueVTs[1]); 2541 2542 // Merge into one. 2543 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2544 DAG.getVTList(ValueVTs), Ops); 2545 setValue(&LP, Res); 2546 } 2547 2548 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2549 #ifndef NDEBUG 2550 for (const CaseCluster &CC : Clusters) 2551 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2552 #endif 2553 2554 llvm::sort(Clusters.begin(), Clusters.end(), 2555 [](const CaseCluster &a, const CaseCluster &b) { 2556 return a.Low->getValue().slt(b.Low->getValue()); 2557 }); 2558 2559 // Merge adjacent clusters with the same destination. 2560 const unsigned N = Clusters.size(); 2561 unsigned DstIndex = 0; 2562 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2563 CaseCluster &CC = Clusters[SrcIndex]; 2564 const ConstantInt *CaseVal = CC.Low; 2565 MachineBasicBlock *Succ = CC.MBB; 2566 2567 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2568 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2569 // If this case has the same successor and is a neighbour, merge it into 2570 // the previous cluster. 2571 Clusters[DstIndex - 1].High = CaseVal; 2572 Clusters[DstIndex - 1].Prob += CC.Prob; 2573 } else { 2574 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2575 sizeof(Clusters[SrcIndex])); 2576 } 2577 } 2578 Clusters.resize(DstIndex); 2579 } 2580 2581 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2582 MachineBasicBlock *Last) { 2583 // Update JTCases. 2584 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2585 if (JTCases[i].first.HeaderBB == First) 2586 JTCases[i].first.HeaderBB = Last; 2587 2588 // Update BitTestCases. 2589 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2590 if (BitTestCases[i].Parent == First) 2591 BitTestCases[i].Parent = Last; 2592 } 2593 2594 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2595 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2596 2597 // Update machine-CFG edges with unique successors. 2598 SmallSet<BasicBlock*, 32> Done; 2599 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2600 BasicBlock *BB = I.getSuccessor(i); 2601 bool Inserted = Done.insert(BB).second; 2602 if (!Inserted) 2603 continue; 2604 2605 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2606 addSuccessorWithProb(IndirectBrMBB, Succ); 2607 } 2608 IndirectBrMBB->normalizeSuccProbs(); 2609 2610 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2611 MVT::Other, getControlRoot(), 2612 getValue(I.getAddress()))); 2613 } 2614 2615 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2616 if (!DAG.getTarget().Options.TrapUnreachable) 2617 return; 2618 2619 // We may be able to ignore unreachable behind a noreturn call. 2620 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2621 const BasicBlock &BB = *I.getParent(); 2622 if (&I != &BB.front()) { 2623 BasicBlock::const_iterator PredI = 2624 std::prev(BasicBlock::const_iterator(&I)); 2625 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2626 if (Call->doesNotReturn()) 2627 return; 2628 } 2629 } 2630 } 2631 2632 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2633 } 2634 2635 void SelectionDAGBuilder::visitFSub(const User &I) { 2636 // -0.0 - X --> fneg 2637 Type *Ty = I.getType(); 2638 if (isa<Constant>(I.getOperand(0)) && 2639 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2640 SDValue Op2 = getValue(I.getOperand(1)); 2641 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2642 Op2.getValueType(), Op2)); 2643 return; 2644 } 2645 2646 visitBinary(I, ISD::FSUB); 2647 } 2648 2649 /// Checks if the given instruction performs a vector reduction, in which case 2650 /// we have the freedom to alter the elements in the result as long as the 2651 /// reduction of them stays unchanged. 2652 static bool isVectorReductionOp(const User *I) { 2653 const Instruction *Inst = dyn_cast<Instruction>(I); 2654 if (!Inst || !Inst->getType()->isVectorTy()) 2655 return false; 2656 2657 auto OpCode = Inst->getOpcode(); 2658 switch (OpCode) { 2659 case Instruction::Add: 2660 case Instruction::Mul: 2661 case Instruction::And: 2662 case Instruction::Or: 2663 case Instruction::Xor: 2664 break; 2665 case Instruction::FAdd: 2666 case Instruction::FMul: 2667 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2668 if (FPOp->getFastMathFlags().isFast()) 2669 break; 2670 LLVM_FALLTHROUGH; 2671 default: 2672 return false; 2673 } 2674 2675 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2676 // Ensure the reduction size is a power of 2. 2677 if (!isPowerOf2_32(ElemNum)) 2678 return false; 2679 2680 unsigned ElemNumToReduce = ElemNum; 2681 2682 // Do DFS search on the def-use chain from the given instruction. We only 2683 // allow four kinds of operations during the search until we reach the 2684 // instruction that extracts the first element from the vector: 2685 // 2686 // 1. The reduction operation of the same opcode as the given instruction. 2687 // 2688 // 2. PHI node. 2689 // 2690 // 3. ShuffleVector instruction together with a reduction operation that 2691 // does a partial reduction. 2692 // 2693 // 4. ExtractElement that extracts the first element from the vector, and we 2694 // stop searching the def-use chain here. 2695 // 2696 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2697 // from 1-3 to the stack to continue the DFS. The given instruction is not 2698 // a reduction operation if we meet any other instructions other than those 2699 // listed above. 2700 2701 SmallVector<const User *, 16> UsersToVisit{Inst}; 2702 SmallPtrSet<const User *, 16> Visited; 2703 bool ReduxExtracted = false; 2704 2705 while (!UsersToVisit.empty()) { 2706 auto User = UsersToVisit.back(); 2707 UsersToVisit.pop_back(); 2708 if (!Visited.insert(User).second) 2709 continue; 2710 2711 for (const auto &U : User->users()) { 2712 auto Inst = dyn_cast<Instruction>(U); 2713 if (!Inst) 2714 return false; 2715 2716 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2717 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2718 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2719 return false; 2720 UsersToVisit.push_back(U); 2721 } else if (const ShuffleVectorInst *ShufInst = 2722 dyn_cast<ShuffleVectorInst>(U)) { 2723 // Detect the following pattern: A ShuffleVector instruction together 2724 // with a reduction that do partial reduction on the first and second 2725 // ElemNumToReduce / 2 elements, and store the result in 2726 // ElemNumToReduce / 2 elements in another vector. 2727 2728 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2729 if (ResultElements < ElemNum) 2730 return false; 2731 2732 if (ElemNumToReduce == 1) 2733 return false; 2734 if (!isa<UndefValue>(U->getOperand(1))) 2735 return false; 2736 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2737 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2738 return false; 2739 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2740 if (ShufInst->getMaskValue(i) != -1) 2741 return false; 2742 2743 // There is only one user of this ShuffleVector instruction, which 2744 // must be a reduction operation. 2745 if (!U->hasOneUse()) 2746 return false; 2747 2748 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2749 if (!U2 || U2->getOpcode() != OpCode) 2750 return false; 2751 2752 // Check operands of the reduction operation. 2753 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2754 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2755 UsersToVisit.push_back(U2); 2756 ElemNumToReduce /= 2; 2757 } else 2758 return false; 2759 } else if (isa<ExtractElementInst>(U)) { 2760 // At this moment we should have reduced all elements in the vector. 2761 if (ElemNumToReduce != 1) 2762 return false; 2763 2764 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2765 if (!Val || !Val->isZero()) 2766 return false; 2767 2768 ReduxExtracted = true; 2769 } else 2770 return false; 2771 } 2772 } 2773 return ReduxExtracted; 2774 } 2775 2776 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2777 SDNodeFlags Flags; 2778 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2779 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2780 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2781 } 2782 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2783 Flags.setExact(ExactOp->isExact()); 2784 } 2785 if (isVectorReductionOp(&I)) { 2786 Flags.setVectorReduction(true); 2787 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2788 } 2789 2790 SDValue Op1 = getValue(I.getOperand(0)); 2791 SDValue Op2 = getValue(I.getOperand(1)); 2792 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2793 Op1, Op2, Flags); 2794 setValue(&I, BinNodeValue); 2795 } 2796 2797 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2798 SDValue Op1 = getValue(I.getOperand(0)); 2799 SDValue Op2 = getValue(I.getOperand(1)); 2800 2801 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2802 Op2.getValueType(), DAG.getDataLayout()); 2803 2804 // Coerce the shift amount to the right type if we can. 2805 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2806 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2807 unsigned Op2Size = Op2.getValueSizeInBits(); 2808 SDLoc DL = getCurSDLoc(); 2809 2810 // If the operand is smaller than the shift count type, promote it. 2811 if (ShiftSize > Op2Size) 2812 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2813 2814 // If the operand is larger than the shift count type but the shift 2815 // count type has enough bits to represent any shift value, truncate 2816 // it now. This is a common case and it exposes the truncate to 2817 // optimization early. 2818 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2819 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2820 // Otherwise we'll need to temporarily settle for some other convenient 2821 // type. Type legalization will make adjustments once the shiftee is split. 2822 else 2823 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2824 } 2825 2826 bool nuw = false; 2827 bool nsw = false; 2828 bool exact = false; 2829 2830 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2831 2832 if (const OverflowingBinaryOperator *OFBinOp = 2833 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2834 nuw = OFBinOp->hasNoUnsignedWrap(); 2835 nsw = OFBinOp->hasNoSignedWrap(); 2836 } 2837 if (const PossiblyExactOperator *ExactOp = 2838 dyn_cast<const PossiblyExactOperator>(&I)) 2839 exact = ExactOp->isExact(); 2840 } 2841 SDNodeFlags Flags; 2842 Flags.setExact(exact); 2843 Flags.setNoSignedWrap(nsw); 2844 Flags.setNoUnsignedWrap(nuw); 2845 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2846 Flags); 2847 setValue(&I, Res); 2848 } 2849 2850 void SelectionDAGBuilder::visitSDiv(const User &I) { 2851 SDValue Op1 = getValue(I.getOperand(0)); 2852 SDValue Op2 = getValue(I.getOperand(1)); 2853 2854 SDNodeFlags Flags; 2855 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2856 cast<PossiblyExactOperator>(&I)->isExact()); 2857 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2858 Op2, Flags)); 2859 } 2860 2861 void SelectionDAGBuilder::visitICmp(const User &I) { 2862 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2863 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2864 predicate = IC->getPredicate(); 2865 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2866 predicate = ICmpInst::Predicate(IC->getPredicate()); 2867 SDValue Op1 = getValue(I.getOperand(0)); 2868 SDValue Op2 = getValue(I.getOperand(1)); 2869 ISD::CondCode Opcode = getICmpCondCode(predicate); 2870 2871 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2872 I.getType()); 2873 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2874 } 2875 2876 void SelectionDAGBuilder::visitFCmp(const User &I) { 2877 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2878 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2879 predicate = FC->getPredicate(); 2880 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2881 predicate = FCmpInst::Predicate(FC->getPredicate()); 2882 SDValue Op1 = getValue(I.getOperand(0)); 2883 SDValue Op2 = getValue(I.getOperand(1)); 2884 2885 ISD::CondCode Condition = getFCmpCondCode(predicate); 2886 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2887 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2888 Condition = getFCmpCodeWithoutNaN(Condition); 2889 2890 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2891 I.getType()); 2892 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2893 } 2894 2895 // Check if the condition of the select has one use or two users that are both 2896 // selects with the same condition. 2897 static bool hasOnlySelectUsers(const Value *Cond) { 2898 return llvm::all_of(Cond->users(), [](const Value *V) { 2899 return isa<SelectInst>(V); 2900 }); 2901 } 2902 2903 void SelectionDAGBuilder::visitSelect(const User &I) { 2904 SmallVector<EVT, 4> ValueVTs; 2905 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2906 ValueVTs); 2907 unsigned NumValues = ValueVTs.size(); 2908 if (NumValues == 0) return; 2909 2910 SmallVector<SDValue, 4> Values(NumValues); 2911 SDValue Cond = getValue(I.getOperand(0)); 2912 SDValue LHSVal = getValue(I.getOperand(1)); 2913 SDValue RHSVal = getValue(I.getOperand(2)); 2914 auto BaseOps = {Cond}; 2915 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2916 ISD::VSELECT : ISD::SELECT; 2917 2918 // Min/max matching is only viable if all output VTs are the same. 2919 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2920 EVT VT = ValueVTs[0]; 2921 LLVMContext &Ctx = *DAG.getContext(); 2922 auto &TLI = DAG.getTargetLoweringInfo(); 2923 2924 // We care about the legality of the operation after it has been type 2925 // legalized. 2926 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2927 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2928 VT = TLI.getTypeToTransformTo(Ctx, VT); 2929 2930 // If the vselect is legal, assume we want to leave this as a vector setcc + 2931 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2932 // min/max is legal on the scalar type. 2933 bool UseScalarMinMax = VT.isVector() && 2934 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2935 2936 Value *LHS, *RHS; 2937 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2938 ISD::NodeType Opc = ISD::DELETED_NODE; 2939 switch (SPR.Flavor) { 2940 case SPF_UMAX: Opc = ISD::UMAX; break; 2941 case SPF_UMIN: Opc = ISD::UMIN; break; 2942 case SPF_SMAX: Opc = ISD::SMAX; break; 2943 case SPF_SMIN: Opc = ISD::SMIN; break; 2944 case SPF_FMINNUM: 2945 switch (SPR.NaNBehavior) { 2946 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2947 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2948 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2949 case SPNB_RETURNS_ANY: { 2950 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2951 Opc = ISD::FMINNUM; 2952 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2953 Opc = ISD::FMINNAN; 2954 else if (UseScalarMinMax) 2955 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2956 ISD::FMINNUM : ISD::FMINNAN; 2957 break; 2958 } 2959 } 2960 break; 2961 case SPF_FMAXNUM: 2962 switch (SPR.NaNBehavior) { 2963 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2964 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2965 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2966 case SPNB_RETURNS_ANY: 2967 2968 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2969 Opc = ISD::FMAXNUM; 2970 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2971 Opc = ISD::FMAXNAN; 2972 else if (UseScalarMinMax) 2973 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2974 ISD::FMAXNUM : ISD::FMAXNAN; 2975 break; 2976 } 2977 break; 2978 default: break; 2979 } 2980 2981 if (Opc != ISD::DELETED_NODE && 2982 (TLI.isOperationLegalOrCustom(Opc, VT) || 2983 (UseScalarMinMax && 2984 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 2985 // If the underlying comparison instruction is used by any other 2986 // instruction, the consumed instructions won't be destroyed, so it is 2987 // not profitable to convert to a min/max. 2988 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 2989 OpCode = Opc; 2990 LHSVal = getValue(LHS); 2991 RHSVal = getValue(RHS); 2992 BaseOps = {}; 2993 } 2994 } 2995 2996 for (unsigned i = 0; i != NumValues; ++i) { 2997 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2998 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2999 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3000 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3001 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3002 Ops); 3003 } 3004 3005 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3006 DAG.getVTList(ValueVTs), Values)); 3007 } 3008 3009 void SelectionDAGBuilder::visitTrunc(const User &I) { 3010 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3011 SDValue N = getValue(I.getOperand(0)); 3012 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3013 I.getType()); 3014 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3015 } 3016 3017 void SelectionDAGBuilder::visitZExt(const User &I) { 3018 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3019 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3020 SDValue N = getValue(I.getOperand(0)); 3021 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3022 I.getType()); 3023 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3024 } 3025 3026 void SelectionDAGBuilder::visitSExt(const User &I) { 3027 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3028 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3029 SDValue N = getValue(I.getOperand(0)); 3030 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3031 I.getType()); 3032 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3033 } 3034 3035 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3036 // FPTrunc is never a no-op cast, no need to check 3037 SDValue N = getValue(I.getOperand(0)); 3038 SDLoc dl = getCurSDLoc(); 3039 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3040 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3041 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3042 DAG.getTargetConstant( 3043 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3044 } 3045 3046 void SelectionDAGBuilder::visitFPExt(const User &I) { 3047 // FPExt is never a no-op cast, no need to check 3048 SDValue N = getValue(I.getOperand(0)); 3049 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3050 I.getType()); 3051 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3052 } 3053 3054 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3055 // FPToUI is never a no-op cast, no need to check 3056 SDValue N = getValue(I.getOperand(0)); 3057 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3058 I.getType()); 3059 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3060 } 3061 3062 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3063 // FPToSI is never a no-op cast, no need to check 3064 SDValue N = getValue(I.getOperand(0)); 3065 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3066 I.getType()); 3067 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3068 } 3069 3070 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3071 // UIToFP is never a no-op cast, no need to check 3072 SDValue N = getValue(I.getOperand(0)); 3073 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3074 I.getType()); 3075 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3076 } 3077 3078 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3079 // SIToFP is never a no-op cast, no need to check 3080 SDValue N = getValue(I.getOperand(0)); 3081 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3082 I.getType()); 3083 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3084 } 3085 3086 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3087 // What to do depends on the size of the integer and the size of the pointer. 3088 // We can either truncate, zero extend, or no-op, accordingly. 3089 SDValue N = getValue(I.getOperand(0)); 3090 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3091 I.getType()); 3092 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3093 } 3094 3095 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3096 // What to do depends on the size of the integer and the size of the pointer. 3097 // We can either truncate, zero extend, or no-op, accordingly. 3098 SDValue N = getValue(I.getOperand(0)); 3099 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3100 I.getType()); 3101 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3102 } 3103 3104 void SelectionDAGBuilder::visitBitCast(const User &I) { 3105 SDValue N = getValue(I.getOperand(0)); 3106 SDLoc dl = getCurSDLoc(); 3107 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3108 I.getType()); 3109 3110 // BitCast assures us that source and destination are the same size so this is 3111 // either a BITCAST or a no-op. 3112 if (DestVT != N.getValueType()) 3113 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3114 DestVT, N)); // convert types. 3115 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3116 // might fold any kind of constant expression to an integer constant and that 3117 // is not what we are looking for. Only recognize a bitcast of a genuine 3118 // constant integer as an opaque constant. 3119 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3120 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3121 /*isOpaque*/true)); 3122 else 3123 setValue(&I, N); // noop cast. 3124 } 3125 3126 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3128 const Value *SV = I.getOperand(0); 3129 SDValue N = getValue(SV); 3130 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3131 3132 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3133 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3134 3135 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3136 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3137 3138 setValue(&I, N); 3139 } 3140 3141 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3143 SDValue InVec = getValue(I.getOperand(0)); 3144 SDValue InVal = getValue(I.getOperand(1)); 3145 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3146 TLI.getVectorIdxTy(DAG.getDataLayout())); 3147 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3148 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3149 InVec, InVal, InIdx)); 3150 } 3151 3152 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3154 SDValue InVec = getValue(I.getOperand(0)); 3155 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3156 TLI.getVectorIdxTy(DAG.getDataLayout())); 3157 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3158 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3159 InVec, InIdx)); 3160 } 3161 3162 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3163 SDValue Src1 = getValue(I.getOperand(0)); 3164 SDValue Src2 = getValue(I.getOperand(1)); 3165 SDLoc DL = getCurSDLoc(); 3166 3167 SmallVector<int, 8> Mask; 3168 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3169 unsigned MaskNumElts = Mask.size(); 3170 3171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3172 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3173 EVT SrcVT = Src1.getValueType(); 3174 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3175 3176 if (SrcNumElts == MaskNumElts) { 3177 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3178 return; 3179 } 3180 3181 // Normalize the shuffle vector since mask and vector length don't match. 3182 if (SrcNumElts < MaskNumElts) { 3183 // Mask is longer than the source vectors. We can use concatenate vector to 3184 // make the mask and vectors lengths match. 3185 3186 if (MaskNumElts % SrcNumElts == 0) { 3187 // Mask length is a multiple of the source vector length. 3188 // Check if the shuffle is some kind of concatenation of the input 3189 // vectors. 3190 unsigned NumConcat = MaskNumElts / SrcNumElts; 3191 bool IsConcat = true; 3192 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3193 for (unsigned i = 0; i != MaskNumElts; ++i) { 3194 int Idx = Mask[i]; 3195 if (Idx < 0) 3196 continue; 3197 // Ensure the indices in each SrcVT sized piece are sequential and that 3198 // the same source is used for the whole piece. 3199 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3200 (ConcatSrcs[i / SrcNumElts] >= 0 && 3201 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3202 IsConcat = false; 3203 break; 3204 } 3205 // Remember which source this index came from. 3206 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3207 } 3208 3209 // The shuffle is concatenating multiple vectors together. Just emit 3210 // a CONCAT_VECTORS operation. 3211 if (IsConcat) { 3212 SmallVector<SDValue, 8> ConcatOps; 3213 for (auto Src : ConcatSrcs) { 3214 if (Src < 0) 3215 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3216 else if (Src == 0) 3217 ConcatOps.push_back(Src1); 3218 else 3219 ConcatOps.push_back(Src2); 3220 } 3221 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3222 return; 3223 } 3224 } 3225 3226 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3227 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3228 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3229 PaddedMaskNumElts); 3230 3231 // Pad both vectors with undefs to make them the same length as the mask. 3232 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3233 3234 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3235 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3236 MOps1[0] = Src1; 3237 MOps2[0] = Src2; 3238 3239 Src1 = Src1.isUndef() 3240 ? DAG.getUNDEF(PaddedVT) 3241 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3242 Src2 = Src2.isUndef() 3243 ? DAG.getUNDEF(PaddedVT) 3244 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3245 3246 // Readjust mask for new input vector length. 3247 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3248 for (unsigned i = 0; i != MaskNumElts; ++i) { 3249 int Idx = Mask[i]; 3250 if (Idx >= (int)SrcNumElts) 3251 Idx -= SrcNumElts - PaddedMaskNumElts; 3252 MappedOps[i] = Idx; 3253 } 3254 3255 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3256 3257 // If the concatenated vector was padded, extract a subvector with the 3258 // correct number of elements. 3259 if (MaskNumElts != PaddedMaskNumElts) 3260 Result = DAG.getNode( 3261 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3262 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3263 3264 setValue(&I, Result); 3265 return; 3266 } 3267 3268 if (SrcNumElts > MaskNumElts) { 3269 // Analyze the access pattern of the vector to see if we can extract 3270 // two subvectors and do the shuffle. 3271 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3272 bool CanExtract = true; 3273 for (int Idx : Mask) { 3274 unsigned Input = 0; 3275 if (Idx < 0) 3276 continue; 3277 3278 if (Idx >= (int)SrcNumElts) { 3279 Input = 1; 3280 Idx -= SrcNumElts; 3281 } 3282 3283 // If all the indices come from the same MaskNumElts sized portion of 3284 // the sources we can use extract. Also make sure the extract wouldn't 3285 // extract past the end of the source. 3286 int NewStartIdx = alignDown(Idx, MaskNumElts); 3287 if (NewStartIdx + MaskNumElts > SrcNumElts || 3288 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3289 CanExtract = false; 3290 // Make sure we always update StartIdx as we use it to track if all 3291 // elements are undef. 3292 StartIdx[Input] = NewStartIdx; 3293 } 3294 3295 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3296 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3297 return; 3298 } 3299 if (CanExtract) { 3300 // Extract appropriate subvector and generate a vector shuffle 3301 for (unsigned Input = 0; Input < 2; ++Input) { 3302 SDValue &Src = Input == 0 ? Src1 : Src2; 3303 if (StartIdx[Input] < 0) 3304 Src = DAG.getUNDEF(VT); 3305 else { 3306 Src = DAG.getNode( 3307 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3308 DAG.getConstant(StartIdx[Input], DL, 3309 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3310 } 3311 } 3312 3313 // Calculate new mask. 3314 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3315 for (int &Idx : MappedOps) { 3316 if (Idx >= (int)SrcNumElts) 3317 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3318 else if (Idx >= 0) 3319 Idx -= StartIdx[0]; 3320 } 3321 3322 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3323 return; 3324 } 3325 } 3326 3327 // We can't use either concat vectors or extract subvectors so fall back to 3328 // replacing the shuffle with extract and build vector. 3329 // to insert and build vector. 3330 EVT EltVT = VT.getVectorElementType(); 3331 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3332 SmallVector<SDValue,8> Ops; 3333 for (int Idx : Mask) { 3334 SDValue Res; 3335 3336 if (Idx < 0) { 3337 Res = DAG.getUNDEF(EltVT); 3338 } else { 3339 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3340 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3341 3342 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3343 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3344 } 3345 3346 Ops.push_back(Res); 3347 } 3348 3349 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3350 } 3351 3352 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3353 ArrayRef<unsigned> Indices; 3354 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3355 Indices = IV->getIndices(); 3356 else 3357 Indices = cast<ConstantExpr>(&I)->getIndices(); 3358 3359 const Value *Op0 = I.getOperand(0); 3360 const Value *Op1 = I.getOperand(1); 3361 Type *AggTy = I.getType(); 3362 Type *ValTy = Op1->getType(); 3363 bool IntoUndef = isa<UndefValue>(Op0); 3364 bool FromUndef = isa<UndefValue>(Op1); 3365 3366 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3367 3368 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3369 SmallVector<EVT, 4> AggValueVTs; 3370 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3371 SmallVector<EVT, 4> ValValueVTs; 3372 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3373 3374 unsigned NumAggValues = AggValueVTs.size(); 3375 unsigned NumValValues = ValValueVTs.size(); 3376 SmallVector<SDValue, 4> Values(NumAggValues); 3377 3378 // Ignore an insertvalue that produces an empty object 3379 if (!NumAggValues) { 3380 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3381 return; 3382 } 3383 3384 SDValue Agg = getValue(Op0); 3385 unsigned i = 0; 3386 // Copy the beginning value(s) from the original aggregate. 3387 for (; i != LinearIndex; ++i) 3388 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3389 SDValue(Agg.getNode(), Agg.getResNo() + i); 3390 // Copy values from the inserted value(s). 3391 if (NumValValues) { 3392 SDValue Val = getValue(Op1); 3393 for (; i != LinearIndex + NumValValues; ++i) 3394 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3395 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3396 } 3397 // Copy remaining value(s) from the original aggregate. 3398 for (; i != NumAggValues; ++i) 3399 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3400 SDValue(Agg.getNode(), Agg.getResNo() + i); 3401 3402 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3403 DAG.getVTList(AggValueVTs), Values)); 3404 } 3405 3406 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3407 ArrayRef<unsigned> Indices; 3408 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3409 Indices = EV->getIndices(); 3410 else 3411 Indices = cast<ConstantExpr>(&I)->getIndices(); 3412 3413 const Value *Op0 = I.getOperand(0); 3414 Type *AggTy = Op0->getType(); 3415 Type *ValTy = I.getType(); 3416 bool OutOfUndef = isa<UndefValue>(Op0); 3417 3418 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3419 3420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3421 SmallVector<EVT, 4> ValValueVTs; 3422 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3423 3424 unsigned NumValValues = ValValueVTs.size(); 3425 3426 // Ignore a extractvalue that produces an empty object 3427 if (!NumValValues) { 3428 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3429 return; 3430 } 3431 3432 SmallVector<SDValue, 4> Values(NumValValues); 3433 3434 SDValue Agg = getValue(Op0); 3435 // Copy out the selected value(s). 3436 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3437 Values[i - LinearIndex] = 3438 OutOfUndef ? 3439 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3440 SDValue(Agg.getNode(), Agg.getResNo() + i); 3441 3442 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3443 DAG.getVTList(ValValueVTs), Values)); 3444 } 3445 3446 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3447 Value *Op0 = I.getOperand(0); 3448 // Note that the pointer operand may be a vector of pointers. Take the scalar 3449 // element which holds a pointer. 3450 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3451 SDValue N = getValue(Op0); 3452 SDLoc dl = getCurSDLoc(); 3453 3454 // Normalize Vector GEP - all scalar operands should be converted to the 3455 // splat vector. 3456 unsigned VectorWidth = I.getType()->isVectorTy() ? 3457 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3458 3459 if (VectorWidth && !N.getValueType().isVector()) { 3460 LLVMContext &Context = *DAG.getContext(); 3461 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3462 N = DAG.getSplatBuildVector(VT, dl, N); 3463 } 3464 3465 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3466 GTI != E; ++GTI) { 3467 const Value *Idx = GTI.getOperand(); 3468 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3469 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3470 if (Field) { 3471 // N = N + Offset 3472 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3473 3474 // In an inbounds GEP with an offset that is nonnegative even when 3475 // interpreted as signed, assume there is no unsigned overflow. 3476 SDNodeFlags Flags; 3477 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3478 Flags.setNoUnsignedWrap(true); 3479 3480 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3481 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3482 } 3483 } else { 3484 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3485 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3486 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3487 3488 // If this is a scalar constant or a splat vector of constants, 3489 // handle it quickly. 3490 const auto *CI = dyn_cast<ConstantInt>(Idx); 3491 if (!CI && isa<ConstantDataVector>(Idx) && 3492 cast<ConstantDataVector>(Idx)->getSplatValue()) 3493 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3494 3495 if (CI) { 3496 if (CI->isZero()) 3497 continue; 3498 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3499 LLVMContext &Context = *DAG.getContext(); 3500 SDValue OffsVal = VectorWidth ? 3501 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3502 DAG.getConstant(Offs, dl, IdxTy); 3503 3504 // In an inbouds GEP with an offset that is nonnegative even when 3505 // interpreted as signed, assume there is no unsigned overflow. 3506 SDNodeFlags Flags; 3507 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3508 Flags.setNoUnsignedWrap(true); 3509 3510 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3511 continue; 3512 } 3513 3514 // N = N + Idx * ElementSize; 3515 SDValue IdxN = getValue(Idx); 3516 3517 if (!IdxN.getValueType().isVector() && VectorWidth) { 3518 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3519 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3520 } 3521 3522 // If the index is smaller or larger than intptr_t, truncate or extend 3523 // it. 3524 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3525 3526 // If this is a multiply by a power of two, turn it into a shl 3527 // immediately. This is a very common case. 3528 if (ElementSize != 1) { 3529 if (ElementSize.isPowerOf2()) { 3530 unsigned Amt = ElementSize.logBase2(); 3531 IdxN = DAG.getNode(ISD::SHL, dl, 3532 N.getValueType(), IdxN, 3533 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3534 } else { 3535 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3536 IdxN = DAG.getNode(ISD::MUL, dl, 3537 N.getValueType(), IdxN, Scale); 3538 } 3539 } 3540 3541 N = DAG.getNode(ISD::ADD, dl, 3542 N.getValueType(), N, IdxN); 3543 } 3544 } 3545 3546 setValue(&I, N); 3547 } 3548 3549 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3550 // If this is a fixed sized alloca in the entry block of the function, 3551 // allocate it statically on the stack. 3552 if (FuncInfo.StaticAllocaMap.count(&I)) 3553 return; // getValue will auto-populate this. 3554 3555 SDLoc dl = getCurSDLoc(); 3556 Type *Ty = I.getAllocatedType(); 3557 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3558 auto &DL = DAG.getDataLayout(); 3559 uint64_t TySize = DL.getTypeAllocSize(Ty); 3560 unsigned Align = 3561 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3562 3563 SDValue AllocSize = getValue(I.getArraySize()); 3564 3565 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3566 if (AllocSize.getValueType() != IntPtr) 3567 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3568 3569 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3570 AllocSize, 3571 DAG.getConstant(TySize, dl, IntPtr)); 3572 3573 // Handle alignment. If the requested alignment is less than or equal to 3574 // the stack alignment, ignore it. If the size is greater than or equal to 3575 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3576 unsigned StackAlign = 3577 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3578 if (Align <= StackAlign) 3579 Align = 0; 3580 3581 // Round the size of the allocation up to the stack alignment size 3582 // by add SA-1 to the size. This doesn't overflow because we're computing 3583 // an address inside an alloca. 3584 SDNodeFlags Flags; 3585 Flags.setNoUnsignedWrap(true); 3586 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3587 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3588 3589 // Mask out the low bits for alignment purposes. 3590 AllocSize = 3591 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3592 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3593 3594 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3595 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3596 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3597 setValue(&I, DSA); 3598 DAG.setRoot(DSA.getValue(1)); 3599 3600 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3601 } 3602 3603 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3604 if (I.isAtomic()) 3605 return visitAtomicLoad(I); 3606 3607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3608 const Value *SV = I.getOperand(0); 3609 if (TLI.supportSwiftError()) { 3610 // Swifterror values can come from either a function parameter with 3611 // swifterror attribute or an alloca with swifterror attribute. 3612 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3613 if (Arg->hasSwiftErrorAttr()) 3614 return visitLoadFromSwiftError(I); 3615 } 3616 3617 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3618 if (Alloca->isSwiftError()) 3619 return visitLoadFromSwiftError(I); 3620 } 3621 } 3622 3623 SDValue Ptr = getValue(SV); 3624 3625 Type *Ty = I.getType(); 3626 3627 bool isVolatile = I.isVolatile(); 3628 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3629 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3630 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3631 unsigned Alignment = I.getAlignment(); 3632 3633 AAMDNodes AAInfo; 3634 I.getAAMetadata(AAInfo); 3635 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3636 3637 SmallVector<EVT, 4> ValueVTs; 3638 SmallVector<uint64_t, 4> Offsets; 3639 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3640 unsigned NumValues = ValueVTs.size(); 3641 if (NumValues == 0) 3642 return; 3643 3644 SDValue Root; 3645 bool ConstantMemory = false; 3646 if (isVolatile || NumValues > MaxParallelChains) 3647 // Serialize volatile loads with other side effects. 3648 Root = getRoot(); 3649 else if (AA && AA->pointsToConstantMemory(MemoryLocation( 3650 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3651 // Do not serialize (non-volatile) loads of constant memory with anything. 3652 Root = DAG.getEntryNode(); 3653 ConstantMemory = true; 3654 } else { 3655 // Do not serialize non-volatile loads against each other. 3656 Root = DAG.getRoot(); 3657 } 3658 3659 SDLoc dl = getCurSDLoc(); 3660 3661 if (isVolatile) 3662 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3663 3664 // An aggregate load cannot wrap around the address space, so offsets to its 3665 // parts don't wrap either. 3666 SDNodeFlags Flags; 3667 Flags.setNoUnsignedWrap(true); 3668 3669 SmallVector<SDValue, 4> Values(NumValues); 3670 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3671 EVT PtrVT = Ptr.getValueType(); 3672 unsigned ChainI = 0; 3673 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3674 // Serializing loads here may result in excessive register pressure, and 3675 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3676 // could recover a bit by hoisting nodes upward in the chain by recognizing 3677 // they are side-effect free or do not alias. The optimizer should really 3678 // avoid this case by converting large object/array copies to llvm.memcpy 3679 // (MaxParallelChains should always remain as failsafe). 3680 if (ChainI == MaxParallelChains) { 3681 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3682 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3683 makeArrayRef(Chains.data(), ChainI)); 3684 Root = Chain; 3685 ChainI = 0; 3686 } 3687 SDValue A = DAG.getNode(ISD::ADD, dl, 3688 PtrVT, Ptr, 3689 DAG.getConstant(Offsets[i], dl, PtrVT), 3690 Flags); 3691 auto MMOFlags = MachineMemOperand::MONone; 3692 if (isVolatile) 3693 MMOFlags |= MachineMemOperand::MOVolatile; 3694 if (isNonTemporal) 3695 MMOFlags |= MachineMemOperand::MONonTemporal; 3696 if (isInvariant) 3697 MMOFlags |= MachineMemOperand::MOInvariant; 3698 if (isDereferenceable) 3699 MMOFlags |= MachineMemOperand::MODereferenceable; 3700 MMOFlags |= TLI.getMMOFlags(I); 3701 3702 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3703 MachinePointerInfo(SV, Offsets[i]), Alignment, 3704 MMOFlags, AAInfo, Ranges); 3705 3706 Values[i] = L; 3707 Chains[ChainI] = L.getValue(1); 3708 } 3709 3710 if (!ConstantMemory) { 3711 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3712 makeArrayRef(Chains.data(), ChainI)); 3713 if (isVolatile) 3714 DAG.setRoot(Chain); 3715 else 3716 PendingLoads.push_back(Chain); 3717 } 3718 3719 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3720 DAG.getVTList(ValueVTs), Values)); 3721 } 3722 3723 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3724 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3725 "call visitStoreToSwiftError when backend supports swifterror"); 3726 3727 SmallVector<EVT, 4> ValueVTs; 3728 SmallVector<uint64_t, 4> Offsets; 3729 const Value *SrcV = I.getOperand(0); 3730 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3731 SrcV->getType(), ValueVTs, &Offsets); 3732 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3733 "expect a single EVT for swifterror"); 3734 3735 SDValue Src = getValue(SrcV); 3736 // Create a virtual register, then update the virtual register. 3737 unsigned VReg; bool CreatedVReg; 3738 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3739 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3740 // Chain can be getRoot or getControlRoot. 3741 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3742 SDValue(Src.getNode(), Src.getResNo())); 3743 DAG.setRoot(CopyNode); 3744 if (CreatedVReg) 3745 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3746 } 3747 3748 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3749 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3750 "call visitLoadFromSwiftError when backend supports swifterror"); 3751 3752 assert(!I.isVolatile() && 3753 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3754 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3755 "Support volatile, non temporal, invariant for load_from_swift_error"); 3756 3757 const Value *SV = I.getOperand(0); 3758 Type *Ty = I.getType(); 3759 AAMDNodes AAInfo; 3760 I.getAAMetadata(AAInfo); 3761 assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( 3762 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && 3763 "load_from_swift_error should not be constant memory"); 3764 3765 SmallVector<EVT, 4> ValueVTs; 3766 SmallVector<uint64_t, 4> Offsets; 3767 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3768 ValueVTs, &Offsets); 3769 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3770 "expect a single EVT for swifterror"); 3771 3772 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3773 SDValue L = DAG.getCopyFromReg( 3774 getRoot(), getCurSDLoc(), 3775 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3776 ValueVTs[0]); 3777 3778 setValue(&I, L); 3779 } 3780 3781 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3782 if (I.isAtomic()) 3783 return visitAtomicStore(I); 3784 3785 const Value *SrcV = I.getOperand(0); 3786 const Value *PtrV = I.getOperand(1); 3787 3788 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3789 if (TLI.supportSwiftError()) { 3790 // Swifterror values can come from either a function parameter with 3791 // swifterror attribute or an alloca with swifterror attribute. 3792 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3793 if (Arg->hasSwiftErrorAttr()) 3794 return visitStoreToSwiftError(I); 3795 } 3796 3797 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3798 if (Alloca->isSwiftError()) 3799 return visitStoreToSwiftError(I); 3800 } 3801 } 3802 3803 SmallVector<EVT, 4> ValueVTs; 3804 SmallVector<uint64_t, 4> Offsets; 3805 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3806 SrcV->getType(), ValueVTs, &Offsets); 3807 unsigned NumValues = ValueVTs.size(); 3808 if (NumValues == 0) 3809 return; 3810 3811 // Get the lowered operands. Note that we do this after 3812 // checking if NumResults is zero, because with zero results 3813 // the operands won't have values in the map. 3814 SDValue Src = getValue(SrcV); 3815 SDValue Ptr = getValue(PtrV); 3816 3817 SDValue Root = getRoot(); 3818 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3819 SDLoc dl = getCurSDLoc(); 3820 EVT PtrVT = Ptr.getValueType(); 3821 unsigned Alignment = I.getAlignment(); 3822 AAMDNodes AAInfo; 3823 I.getAAMetadata(AAInfo); 3824 3825 auto MMOFlags = MachineMemOperand::MONone; 3826 if (I.isVolatile()) 3827 MMOFlags |= MachineMemOperand::MOVolatile; 3828 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3829 MMOFlags |= MachineMemOperand::MONonTemporal; 3830 MMOFlags |= TLI.getMMOFlags(I); 3831 3832 // An aggregate load cannot wrap around the address space, so offsets to its 3833 // parts don't wrap either. 3834 SDNodeFlags Flags; 3835 Flags.setNoUnsignedWrap(true); 3836 3837 unsigned ChainI = 0; 3838 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3839 // See visitLoad comments. 3840 if (ChainI == MaxParallelChains) { 3841 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3842 makeArrayRef(Chains.data(), ChainI)); 3843 Root = Chain; 3844 ChainI = 0; 3845 } 3846 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3847 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3848 SDValue St = DAG.getStore( 3849 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3850 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3851 Chains[ChainI] = St; 3852 } 3853 3854 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3855 makeArrayRef(Chains.data(), ChainI)); 3856 DAG.setRoot(StoreNode); 3857 } 3858 3859 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3860 bool IsCompressing) { 3861 SDLoc sdl = getCurSDLoc(); 3862 3863 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3864 unsigned& Alignment) { 3865 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3866 Src0 = I.getArgOperand(0); 3867 Ptr = I.getArgOperand(1); 3868 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3869 Mask = I.getArgOperand(3); 3870 }; 3871 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3872 unsigned& Alignment) { 3873 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3874 Src0 = I.getArgOperand(0); 3875 Ptr = I.getArgOperand(1); 3876 Mask = I.getArgOperand(2); 3877 Alignment = 0; 3878 }; 3879 3880 Value *PtrOperand, *MaskOperand, *Src0Operand; 3881 unsigned Alignment; 3882 if (IsCompressing) 3883 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3884 else 3885 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3886 3887 SDValue Ptr = getValue(PtrOperand); 3888 SDValue Src0 = getValue(Src0Operand); 3889 SDValue Mask = getValue(MaskOperand); 3890 3891 EVT VT = Src0.getValueType(); 3892 if (!Alignment) 3893 Alignment = DAG.getEVTAlignment(VT); 3894 3895 AAMDNodes AAInfo; 3896 I.getAAMetadata(AAInfo); 3897 3898 MachineMemOperand *MMO = 3899 DAG.getMachineFunction(). 3900 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3901 MachineMemOperand::MOStore, VT.getStoreSize(), 3902 Alignment, AAInfo); 3903 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3904 MMO, false /* Truncating */, 3905 IsCompressing); 3906 DAG.setRoot(StoreNode); 3907 setValue(&I, StoreNode); 3908 } 3909 3910 // Get a uniform base for the Gather/Scatter intrinsic. 3911 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3912 // We try to represent it as a base pointer + vector of indices. 3913 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3914 // The first operand of the GEP may be a single pointer or a vector of pointers 3915 // Example: 3916 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3917 // or 3918 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3919 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3920 // 3921 // When the first GEP operand is a single pointer - it is the uniform base we 3922 // are looking for. If first operand of the GEP is a splat vector - we 3923 // extract the splat value and use it as a uniform base. 3924 // In all other cases the function returns 'false'. 3925 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3926 SDValue &Scale, SelectionDAGBuilder* SDB) { 3927 SelectionDAG& DAG = SDB->DAG; 3928 LLVMContext &Context = *DAG.getContext(); 3929 3930 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3931 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3932 if (!GEP) 3933 return false; 3934 3935 const Value *GEPPtr = GEP->getPointerOperand(); 3936 if (!GEPPtr->getType()->isVectorTy()) 3937 Ptr = GEPPtr; 3938 else if (!(Ptr = getSplatValue(GEPPtr))) 3939 return false; 3940 3941 unsigned FinalIndex = GEP->getNumOperands() - 1; 3942 Value *IndexVal = GEP->getOperand(FinalIndex); 3943 3944 // Ensure all the other indices are 0. 3945 for (unsigned i = 1; i < FinalIndex; ++i) { 3946 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3947 if (!C || !C->isZero()) 3948 return false; 3949 } 3950 3951 // The operands of the GEP may be defined in another basic block. 3952 // In this case we'll not find nodes for the operands. 3953 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3954 return false; 3955 3956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3957 const DataLayout &DL = DAG.getDataLayout(); 3958 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 3959 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 3960 Base = SDB->getValue(Ptr); 3961 Index = SDB->getValue(IndexVal); 3962 3963 if (!Index.getValueType().isVector()) { 3964 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3965 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3966 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 3967 } 3968 return true; 3969 } 3970 3971 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3972 SDLoc sdl = getCurSDLoc(); 3973 3974 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3975 const Value *Ptr = I.getArgOperand(1); 3976 SDValue Src0 = getValue(I.getArgOperand(0)); 3977 SDValue Mask = getValue(I.getArgOperand(3)); 3978 EVT VT = Src0.getValueType(); 3979 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3980 if (!Alignment) 3981 Alignment = DAG.getEVTAlignment(VT); 3982 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3983 3984 AAMDNodes AAInfo; 3985 I.getAAMetadata(AAInfo); 3986 3987 SDValue Base; 3988 SDValue Index; 3989 SDValue Scale; 3990 const Value *BasePtr = Ptr; 3991 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 3992 3993 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3994 MachineMemOperand *MMO = DAG.getMachineFunction(). 3995 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3996 MachineMemOperand::MOStore, VT.getStoreSize(), 3997 Alignment, AAInfo); 3998 if (!UniformBase) { 3999 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4000 Index = getValue(Ptr); 4001 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4002 } 4003 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4004 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4005 Ops, MMO); 4006 DAG.setRoot(Scatter); 4007 setValue(&I, Scatter); 4008 } 4009 4010 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4011 SDLoc sdl = getCurSDLoc(); 4012 4013 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4014 unsigned& Alignment) { 4015 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4016 Ptr = I.getArgOperand(0); 4017 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4018 Mask = I.getArgOperand(2); 4019 Src0 = I.getArgOperand(3); 4020 }; 4021 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4022 unsigned& Alignment) { 4023 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4024 Ptr = I.getArgOperand(0); 4025 Alignment = 0; 4026 Mask = I.getArgOperand(1); 4027 Src0 = I.getArgOperand(2); 4028 }; 4029 4030 Value *PtrOperand, *MaskOperand, *Src0Operand; 4031 unsigned Alignment; 4032 if (IsExpanding) 4033 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4034 else 4035 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4036 4037 SDValue Ptr = getValue(PtrOperand); 4038 SDValue Src0 = getValue(Src0Operand); 4039 SDValue Mask = getValue(MaskOperand); 4040 4041 EVT VT = Src0.getValueType(); 4042 if (!Alignment) 4043 Alignment = DAG.getEVTAlignment(VT); 4044 4045 AAMDNodes AAInfo; 4046 I.getAAMetadata(AAInfo); 4047 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4048 4049 // Do not serialize masked loads of constant memory with anything. 4050 bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( 4051 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 4052 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4053 4054 MachineMemOperand *MMO = 4055 DAG.getMachineFunction(). 4056 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4057 MachineMemOperand::MOLoad, VT.getStoreSize(), 4058 Alignment, AAInfo, Ranges); 4059 4060 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4061 ISD::NON_EXTLOAD, IsExpanding); 4062 if (AddToChain) { 4063 SDValue OutChain = Load.getValue(1); 4064 DAG.setRoot(OutChain); 4065 } 4066 setValue(&I, Load); 4067 } 4068 4069 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4070 SDLoc sdl = getCurSDLoc(); 4071 4072 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4073 const Value *Ptr = I.getArgOperand(0); 4074 SDValue Src0 = getValue(I.getArgOperand(3)); 4075 SDValue Mask = getValue(I.getArgOperand(2)); 4076 4077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4078 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4079 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4080 if (!Alignment) 4081 Alignment = DAG.getEVTAlignment(VT); 4082 4083 AAMDNodes AAInfo; 4084 I.getAAMetadata(AAInfo); 4085 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4086 4087 SDValue Root = DAG.getRoot(); 4088 SDValue Base; 4089 SDValue Index; 4090 SDValue Scale; 4091 const Value *BasePtr = Ptr; 4092 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4093 bool ConstantMemory = false; 4094 if (UniformBase && 4095 AA && AA->pointsToConstantMemory(MemoryLocation( 4096 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 4097 AAInfo))) { 4098 // Do not serialize (non-volatile) loads of constant memory with anything. 4099 Root = DAG.getEntryNode(); 4100 ConstantMemory = true; 4101 } 4102 4103 MachineMemOperand *MMO = 4104 DAG.getMachineFunction(). 4105 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4106 MachineMemOperand::MOLoad, VT.getStoreSize(), 4107 Alignment, AAInfo, Ranges); 4108 4109 if (!UniformBase) { 4110 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4111 Index = getValue(Ptr); 4112 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4113 } 4114 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4115 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4116 Ops, MMO); 4117 4118 SDValue OutChain = Gather.getValue(1); 4119 if (!ConstantMemory) 4120 PendingLoads.push_back(OutChain); 4121 setValue(&I, Gather); 4122 } 4123 4124 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4125 SDLoc dl = getCurSDLoc(); 4126 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4127 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4128 SyncScope::ID SSID = I.getSyncScopeID(); 4129 4130 SDValue InChain = getRoot(); 4131 4132 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4133 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4134 SDValue L = DAG.getAtomicCmpSwap( 4135 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4136 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4137 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4138 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4139 4140 SDValue OutChain = L.getValue(2); 4141 4142 setValue(&I, L); 4143 DAG.setRoot(OutChain); 4144 } 4145 4146 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4147 SDLoc dl = getCurSDLoc(); 4148 ISD::NodeType NT; 4149 switch (I.getOperation()) { 4150 default: llvm_unreachable("Unknown atomicrmw operation"); 4151 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4152 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4153 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4154 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4155 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4156 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4157 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4158 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4159 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4160 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4161 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4162 } 4163 AtomicOrdering Order = I.getOrdering(); 4164 SyncScope::ID SSID = I.getSyncScopeID(); 4165 4166 SDValue InChain = getRoot(); 4167 4168 SDValue L = 4169 DAG.getAtomic(NT, dl, 4170 getValue(I.getValOperand()).getSimpleValueType(), 4171 InChain, 4172 getValue(I.getPointerOperand()), 4173 getValue(I.getValOperand()), 4174 I.getPointerOperand(), 4175 /* Alignment=*/ 0, Order, SSID); 4176 4177 SDValue OutChain = L.getValue(1); 4178 4179 setValue(&I, L); 4180 DAG.setRoot(OutChain); 4181 } 4182 4183 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4184 SDLoc dl = getCurSDLoc(); 4185 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4186 SDValue Ops[3]; 4187 Ops[0] = getRoot(); 4188 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4189 TLI.getFenceOperandTy(DAG.getDataLayout())); 4190 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4191 TLI.getFenceOperandTy(DAG.getDataLayout())); 4192 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4193 } 4194 4195 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4196 SDLoc dl = getCurSDLoc(); 4197 AtomicOrdering Order = I.getOrdering(); 4198 SyncScope::ID SSID = I.getSyncScopeID(); 4199 4200 SDValue InChain = getRoot(); 4201 4202 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4203 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4204 4205 if (!TLI.supportsUnalignedAtomics() && 4206 I.getAlignment() < VT.getStoreSize()) 4207 report_fatal_error("Cannot generate unaligned atomic load"); 4208 4209 MachineMemOperand *MMO = 4210 DAG.getMachineFunction(). 4211 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4212 MachineMemOperand::MOVolatile | 4213 MachineMemOperand::MOLoad, 4214 VT.getStoreSize(), 4215 I.getAlignment() ? I.getAlignment() : 4216 DAG.getEVTAlignment(VT), 4217 AAMDNodes(), nullptr, SSID, Order); 4218 4219 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4220 SDValue L = 4221 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4222 getValue(I.getPointerOperand()), MMO); 4223 4224 SDValue OutChain = L.getValue(1); 4225 4226 setValue(&I, L); 4227 DAG.setRoot(OutChain); 4228 } 4229 4230 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4231 SDLoc dl = getCurSDLoc(); 4232 4233 AtomicOrdering Order = I.getOrdering(); 4234 SyncScope::ID SSID = I.getSyncScopeID(); 4235 4236 SDValue InChain = getRoot(); 4237 4238 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4239 EVT VT = 4240 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4241 4242 if (I.getAlignment() < VT.getStoreSize()) 4243 report_fatal_error("Cannot generate unaligned atomic store"); 4244 4245 SDValue OutChain = 4246 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4247 InChain, 4248 getValue(I.getPointerOperand()), 4249 getValue(I.getValueOperand()), 4250 I.getPointerOperand(), I.getAlignment(), 4251 Order, SSID); 4252 4253 DAG.setRoot(OutChain); 4254 } 4255 4256 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4257 /// node. 4258 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4259 unsigned Intrinsic) { 4260 // Ignore the callsite's attributes. A specific call site may be marked with 4261 // readnone, but the lowering code will expect the chain based on the 4262 // definition. 4263 const Function *F = I.getCalledFunction(); 4264 bool HasChain = !F->doesNotAccessMemory(); 4265 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4266 4267 // Build the operand list. 4268 SmallVector<SDValue, 8> Ops; 4269 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4270 if (OnlyLoad) { 4271 // We don't need to serialize loads against other loads. 4272 Ops.push_back(DAG.getRoot()); 4273 } else { 4274 Ops.push_back(getRoot()); 4275 } 4276 } 4277 4278 // Info is set by getTgtMemInstrinsic 4279 TargetLowering::IntrinsicInfo Info; 4280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4281 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4282 DAG.getMachineFunction(), 4283 Intrinsic); 4284 4285 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4286 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4287 Info.opc == ISD::INTRINSIC_W_CHAIN) 4288 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4289 TLI.getPointerTy(DAG.getDataLayout()))); 4290 4291 // Add all operands of the call to the operand list. 4292 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4293 SDValue Op = getValue(I.getArgOperand(i)); 4294 Ops.push_back(Op); 4295 } 4296 4297 SmallVector<EVT, 4> ValueVTs; 4298 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4299 4300 if (HasChain) 4301 ValueVTs.push_back(MVT::Other); 4302 4303 SDVTList VTs = DAG.getVTList(ValueVTs); 4304 4305 // Create the node. 4306 SDValue Result; 4307 if (IsTgtIntrinsic) { 4308 // This is target intrinsic that touches memory 4309 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4310 Ops, Info.memVT, 4311 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4312 Info.flags, Info.size); 4313 } else if (!HasChain) { 4314 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4315 } else if (!I.getType()->isVoidTy()) { 4316 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4317 } else { 4318 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4319 } 4320 4321 if (HasChain) { 4322 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4323 if (OnlyLoad) 4324 PendingLoads.push_back(Chain); 4325 else 4326 DAG.setRoot(Chain); 4327 } 4328 4329 if (!I.getType()->isVoidTy()) { 4330 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4331 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4332 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4333 } else 4334 Result = lowerRangeToAssertZExt(DAG, I, Result); 4335 4336 setValue(&I, Result); 4337 } 4338 } 4339 4340 /// GetSignificand - Get the significand and build it into a floating-point 4341 /// number with exponent of 1: 4342 /// 4343 /// Op = (Op & 0x007fffff) | 0x3f800000; 4344 /// 4345 /// where Op is the hexadecimal representation of floating point value. 4346 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4347 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4348 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4349 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4350 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4351 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4352 } 4353 4354 /// GetExponent - Get the exponent: 4355 /// 4356 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4357 /// 4358 /// where Op is the hexadecimal representation of floating point value. 4359 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4360 const TargetLowering &TLI, const SDLoc &dl) { 4361 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4362 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4363 SDValue t1 = DAG.getNode( 4364 ISD::SRL, dl, MVT::i32, t0, 4365 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4366 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4367 DAG.getConstant(127, dl, MVT::i32)); 4368 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4369 } 4370 4371 /// getF32Constant - Get 32-bit floating point constant. 4372 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4373 const SDLoc &dl) { 4374 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4375 MVT::f32); 4376 } 4377 4378 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4379 SelectionDAG &DAG) { 4380 // TODO: What fast-math-flags should be set on the floating-point nodes? 4381 4382 // IntegerPartOfX = ((int32_t)(t0); 4383 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4384 4385 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4386 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4387 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4388 4389 // IntegerPartOfX <<= 23; 4390 IntegerPartOfX = DAG.getNode( 4391 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4392 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4393 DAG.getDataLayout()))); 4394 4395 SDValue TwoToFractionalPartOfX; 4396 if (LimitFloatPrecision <= 6) { 4397 // For floating-point precision of 6: 4398 // 4399 // TwoToFractionalPartOfX = 4400 // 0.997535578f + 4401 // (0.735607626f + 0.252464424f * x) * x; 4402 // 4403 // error 0.0144103317, which is 6 bits 4404 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4405 getF32Constant(DAG, 0x3e814304, dl)); 4406 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4407 getF32Constant(DAG, 0x3f3c50c8, dl)); 4408 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4409 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4410 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4411 } else if (LimitFloatPrecision <= 12) { 4412 // For floating-point precision of 12: 4413 // 4414 // TwoToFractionalPartOfX = 4415 // 0.999892986f + 4416 // (0.696457318f + 4417 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4418 // 4419 // error 0.000107046256, which is 13 to 14 bits 4420 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4421 getF32Constant(DAG, 0x3da235e3, dl)); 4422 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4423 getF32Constant(DAG, 0x3e65b8f3, dl)); 4424 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4425 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4426 getF32Constant(DAG, 0x3f324b07, dl)); 4427 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4428 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4429 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4430 } else { // LimitFloatPrecision <= 18 4431 // For floating-point precision of 18: 4432 // 4433 // TwoToFractionalPartOfX = 4434 // 0.999999982f + 4435 // (0.693148872f + 4436 // (0.240227044f + 4437 // (0.554906021e-1f + 4438 // (0.961591928e-2f + 4439 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4440 // error 2.47208000*10^(-7), which is better than 18 bits 4441 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4442 getF32Constant(DAG, 0x3924b03e, dl)); 4443 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4444 getF32Constant(DAG, 0x3ab24b87, dl)); 4445 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4446 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4447 getF32Constant(DAG, 0x3c1d8c17, dl)); 4448 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4449 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4450 getF32Constant(DAG, 0x3d634a1d, dl)); 4451 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4452 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4453 getF32Constant(DAG, 0x3e75fe14, dl)); 4454 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4455 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4456 getF32Constant(DAG, 0x3f317234, dl)); 4457 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4458 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4459 getF32Constant(DAG, 0x3f800000, dl)); 4460 } 4461 4462 // Add the exponent into the result in integer domain. 4463 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4464 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4465 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4466 } 4467 4468 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4469 /// limited-precision mode. 4470 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4471 const TargetLowering &TLI) { 4472 if (Op.getValueType() == MVT::f32 && 4473 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4474 4475 // Put the exponent in the right bit position for later addition to the 4476 // final result: 4477 // 4478 // #define LOG2OFe 1.4426950f 4479 // t0 = Op * LOG2OFe 4480 4481 // TODO: What fast-math-flags should be set here? 4482 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4483 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4484 return getLimitedPrecisionExp2(t0, dl, DAG); 4485 } 4486 4487 // No special expansion. 4488 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4489 } 4490 4491 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4492 /// limited-precision mode. 4493 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4494 const TargetLowering &TLI) { 4495 // TODO: What fast-math-flags should be set on the floating-point nodes? 4496 4497 if (Op.getValueType() == MVT::f32 && 4498 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4499 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4500 4501 // Scale the exponent by log(2) [0.69314718f]. 4502 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4503 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4504 getF32Constant(DAG, 0x3f317218, dl)); 4505 4506 // Get the significand and build it into a floating-point number with 4507 // exponent of 1. 4508 SDValue X = GetSignificand(DAG, Op1, dl); 4509 4510 SDValue LogOfMantissa; 4511 if (LimitFloatPrecision <= 6) { 4512 // For floating-point precision of 6: 4513 // 4514 // LogofMantissa = 4515 // -1.1609546f + 4516 // (1.4034025f - 0.23903021f * x) * x; 4517 // 4518 // error 0.0034276066, which is better than 8 bits 4519 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4520 getF32Constant(DAG, 0xbe74c456, dl)); 4521 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4522 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4523 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4524 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4525 getF32Constant(DAG, 0x3f949a29, dl)); 4526 } else if (LimitFloatPrecision <= 12) { 4527 // For floating-point precision of 12: 4528 // 4529 // LogOfMantissa = 4530 // -1.7417939f + 4531 // (2.8212026f + 4532 // (-1.4699568f + 4533 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4534 // 4535 // error 0.000061011436, which is 14 bits 4536 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4537 getF32Constant(DAG, 0xbd67b6d6, dl)); 4538 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4539 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4540 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4541 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4542 getF32Constant(DAG, 0x3fbc278b, dl)); 4543 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4544 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4545 getF32Constant(DAG, 0x40348e95, dl)); 4546 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4547 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4548 getF32Constant(DAG, 0x3fdef31a, dl)); 4549 } else { // LimitFloatPrecision <= 18 4550 // For floating-point precision of 18: 4551 // 4552 // LogOfMantissa = 4553 // -2.1072184f + 4554 // (4.2372794f + 4555 // (-3.7029485f + 4556 // (2.2781945f + 4557 // (-0.87823314f + 4558 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4559 // 4560 // error 0.0000023660568, which is better than 18 bits 4561 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4562 getF32Constant(DAG, 0xbc91e5ac, dl)); 4563 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4564 getF32Constant(DAG, 0x3e4350aa, dl)); 4565 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4566 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4567 getF32Constant(DAG, 0x3f60d3e3, dl)); 4568 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4569 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4570 getF32Constant(DAG, 0x4011cdf0, dl)); 4571 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4572 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4573 getF32Constant(DAG, 0x406cfd1c, dl)); 4574 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4575 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4576 getF32Constant(DAG, 0x408797cb, dl)); 4577 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4578 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4579 getF32Constant(DAG, 0x4006dcab, dl)); 4580 } 4581 4582 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4583 } 4584 4585 // No special expansion. 4586 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4587 } 4588 4589 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4590 /// limited-precision mode. 4591 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4592 const TargetLowering &TLI) { 4593 // TODO: What fast-math-flags should be set on the floating-point nodes? 4594 4595 if (Op.getValueType() == MVT::f32 && 4596 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4597 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4598 4599 // Get the exponent. 4600 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4601 4602 // Get the significand and build it into a floating-point number with 4603 // exponent of 1. 4604 SDValue X = GetSignificand(DAG, Op1, dl); 4605 4606 // Different possible minimax approximations of significand in 4607 // floating-point for various degrees of accuracy over [1,2]. 4608 SDValue Log2ofMantissa; 4609 if (LimitFloatPrecision <= 6) { 4610 // For floating-point precision of 6: 4611 // 4612 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4613 // 4614 // error 0.0049451742, which is more than 7 bits 4615 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4616 getF32Constant(DAG, 0xbeb08fe0, dl)); 4617 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4618 getF32Constant(DAG, 0x40019463, dl)); 4619 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4620 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4621 getF32Constant(DAG, 0x3fd6633d, dl)); 4622 } else if (LimitFloatPrecision <= 12) { 4623 // For floating-point precision of 12: 4624 // 4625 // Log2ofMantissa = 4626 // -2.51285454f + 4627 // (4.07009056f + 4628 // (-2.12067489f + 4629 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4630 // 4631 // error 0.0000876136000, which is better than 13 bits 4632 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4633 getF32Constant(DAG, 0xbda7262e, dl)); 4634 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4635 getF32Constant(DAG, 0x3f25280b, dl)); 4636 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4637 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4638 getF32Constant(DAG, 0x4007b923, dl)); 4639 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4640 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4641 getF32Constant(DAG, 0x40823e2f, dl)); 4642 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4643 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4644 getF32Constant(DAG, 0x4020d29c, dl)); 4645 } else { // LimitFloatPrecision <= 18 4646 // For floating-point precision of 18: 4647 // 4648 // Log2ofMantissa = 4649 // -3.0400495f + 4650 // (6.1129976f + 4651 // (-5.3420409f + 4652 // (3.2865683f + 4653 // (-1.2669343f + 4654 // (0.27515199f - 4655 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4656 // 4657 // error 0.0000018516, which is better than 18 bits 4658 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4659 getF32Constant(DAG, 0xbcd2769e, dl)); 4660 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4661 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4662 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4663 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4664 getF32Constant(DAG, 0x3fa22ae7, dl)); 4665 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4666 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4667 getF32Constant(DAG, 0x40525723, dl)); 4668 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4669 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4670 getF32Constant(DAG, 0x40aaf200, dl)); 4671 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4672 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4673 getF32Constant(DAG, 0x40c39dad, dl)); 4674 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4675 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4676 getF32Constant(DAG, 0x4042902c, dl)); 4677 } 4678 4679 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4680 } 4681 4682 // No special expansion. 4683 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4684 } 4685 4686 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4687 /// limited-precision mode. 4688 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4689 const TargetLowering &TLI) { 4690 // TODO: What fast-math-flags should be set on the floating-point nodes? 4691 4692 if (Op.getValueType() == MVT::f32 && 4693 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4694 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4695 4696 // Scale the exponent by log10(2) [0.30102999f]. 4697 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4698 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4699 getF32Constant(DAG, 0x3e9a209a, dl)); 4700 4701 // Get the significand and build it into a floating-point number with 4702 // exponent of 1. 4703 SDValue X = GetSignificand(DAG, Op1, dl); 4704 4705 SDValue Log10ofMantissa; 4706 if (LimitFloatPrecision <= 6) { 4707 // For floating-point precision of 6: 4708 // 4709 // Log10ofMantissa = 4710 // -0.50419619f + 4711 // (0.60948995f - 0.10380950f * x) * x; 4712 // 4713 // error 0.0014886165, which is 6 bits 4714 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4715 getF32Constant(DAG, 0xbdd49a13, dl)); 4716 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4717 getF32Constant(DAG, 0x3f1c0789, dl)); 4718 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4719 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4720 getF32Constant(DAG, 0x3f011300, dl)); 4721 } else if (LimitFloatPrecision <= 12) { 4722 // For floating-point precision of 12: 4723 // 4724 // Log10ofMantissa = 4725 // -0.64831180f + 4726 // (0.91751397f + 4727 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4728 // 4729 // error 0.00019228036, which is better than 12 bits 4730 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4731 getF32Constant(DAG, 0x3d431f31, dl)); 4732 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4733 getF32Constant(DAG, 0x3ea21fb2, dl)); 4734 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4735 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4736 getF32Constant(DAG, 0x3f6ae232, dl)); 4737 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4738 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4739 getF32Constant(DAG, 0x3f25f7c3, dl)); 4740 } else { // LimitFloatPrecision <= 18 4741 // For floating-point precision of 18: 4742 // 4743 // Log10ofMantissa = 4744 // -0.84299375f + 4745 // (1.5327582f + 4746 // (-1.0688956f + 4747 // (0.49102474f + 4748 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4749 // 4750 // error 0.0000037995730, which is better than 18 bits 4751 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4752 getF32Constant(DAG, 0x3c5d51ce, dl)); 4753 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4754 getF32Constant(DAG, 0x3e00685a, dl)); 4755 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4756 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4757 getF32Constant(DAG, 0x3efb6798, dl)); 4758 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4759 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4760 getF32Constant(DAG, 0x3f88d192, dl)); 4761 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4762 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4763 getF32Constant(DAG, 0x3fc4316c, dl)); 4764 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4765 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4766 getF32Constant(DAG, 0x3f57ce70, dl)); 4767 } 4768 4769 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4770 } 4771 4772 // No special expansion. 4773 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4774 } 4775 4776 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4777 /// limited-precision mode. 4778 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4779 const TargetLowering &TLI) { 4780 if (Op.getValueType() == MVT::f32 && 4781 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4782 return getLimitedPrecisionExp2(Op, dl, DAG); 4783 4784 // No special expansion. 4785 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4786 } 4787 4788 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4789 /// limited-precision mode with x == 10.0f. 4790 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4791 SelectionDAG &DAG, const TargetLowering &TLI) { 4792 bool IsExp10 = false; 4793 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4794 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4795 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4796 APFloat Ten(10.0f); 4797 IsExp10 = LHSC->isExactlyValue(Ten); 4798 } 4799 } 4800 4801 // TODO: What fast-math-flags should be set on the FMUL node? 4802 if (IsExp10) { 4803 // Put the exponent in the right bit position for later addition to the 4804 // final result: 4805 // 4806 // #define LOG2OF10 3.3219281f 4807 // t0 = Op * LOG2OF10; 4808 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4809 getF32Constant(DAG, 0x40549a78, dl)); 4810 return getLimitedPrecisionExp2(t0, dl, DAG); 4811 } 4812 4813 // No special expansion. 4814 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4815 } 4816 4817 /// ExpandPowI - Expand a llvm.powi intrinsic. 4818 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4819 SelectionDAG &DAG) { 4820 // If RHS is a constant, we can expand this out to a multiplication tree, 4821 // otherwise we end up lowering to a call to __powidf2 (for example). When 4822 // optimizing for size, we only want to do this if the expansion would produce 4823 // a small number of multiplies, otherwise we do the full expansion. 4824 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4825 // Get the exponent as a positive value. 4826 unsigned Val = RHSC->getSExtValue(); 4827 if ((int)Val < 0) Val = -Val; 4828 4829 // powi(x, 0) -> 1.0 4830 if (Val == 0) 4831 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4832 4833 const Function &F = DAG.getMachineFunction().getFunction(); 4834 if (!F.optForSize() || 4835 // If optimizing for size, don't insert too many multiplies. 4836 // This inserts up to 5 multiplies. 4837 countPopulation(Val) + Log2_32(Val) < 7) { 4838 // We use the simple binary decomposition method to generate the multiply 4839 // sequence. There are more optimal ways to do this (for example, 4840 // powi(x,15) generates one more multiply than it should), but this has 4841 // the benefit of being both really simple and much better than a libcall. 4842 SDValue Res; // Logically starts equal to 1.0 4843 SDValue CurSquare = LHS; 4844 // TODO: Intrinsics should have fast-math-flags that propagate to these 4845 // nodes. 4846 while (Val) { 4847 if (Val & 1) { 4848 if (Res.getNode()) 4849 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4850 else 4851 Res = CurSquare; // 1.0*CurSquare. 4852 } 4853 4854 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4855 CurSquare, CurSquare); 4856 Val >>= 1; 4857 } 4858 4859 // If the original was negative, invert the result, producing 1/(x*x*x). 4860 if (RHSC->getSExtValue() < 0) 4861 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4862 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4863 return Res; 4864 } 4865 } 4866 4867 // Otherwise, expand to a libcall. 4868 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4869 } 4870 4871 // getUnderlyingArgReg - Find underlying register used for a truncated or 4872 // bitcasted argument. 4873 static unsigned getUnderlyingArgReg(const SDValue &N) { 4874 switch (N.getOpcode()) { 4875 case ISD::CopyFromReg: 4876 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4877 case ISD::BITCAST: 4878 case ISD::AssertZext: 4879 case ISD::AssertSext: 4880 case ISD::TRUNCATE: 4881 return getUnderlyingArgReg(N.getOperand(0)); 4882 default: 4883 return 0; 4884 } 4885 } 4886 4887 /// If the DbgValueInst is a dbg_value of a function argument, create the 4888 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4889 /// instruction selection, they will be inserted to the entry BB. 4890 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4891 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4892 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4893 const Argument *Arg = dyn_cast<Argument>(V); 4894 if (!Arg) 4895 return false; 4896 4897 MachineFunction &MF = DAG.getMachineFunction(); 4898 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4899 4900 bool IsIndirect = false; 4901 Optional<MachineOperand> Op; 4902 // Some arguments' frame index is recorded during argument lowering. 4903 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4904 if (FI != std::numeric_limits<int>::max()) 4905 Op = MachineOperand::CreateFI(FI); 4906 4907 if (!Op && N.getNode()) { 4908 unsigned Reg = getUnderlyingArgReg(N); 4909 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4910 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4911 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4912 if (PR) 4913 Reg = PR; 4914 } 4915 if (Reg) { 4916 Op = MachineOperand::CreateReg(Reg, false); 4917 IsIndirect = IsDbgDeclare; 4918 } 4919 } 4920 4921 if (!Op && N.getNode()) 4922 // Check if frame index is available. 4923 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4924 if (FrameIndexSDNode *FINode = 4925 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4926 Op = MachineOperand::CreateFI(FINode->getIndex()); 4927 4928 if (!Op) { 4929 // Check if ValueMap has reg number. 4930 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4931 if (VMI != FuncInfo.ValueMap.end()) { 4932 const auto &TLI = DAG.getTargetLoweringInfo(); 4933 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4934 V->getType(), isABIRegCopy(V)); 4935 if (RFV.occupiesMultipleRegs()) { 4936 unsigned Offset = 0; 4937 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4938 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4939 auto FragmentExpr = DIExpression::createFragmentExpression( 4940 Expr, Offset, RegAndSize.second); 4941 if (!FragmentExpr) 4942 continue; 4943 FuncInfo.ArgDbgValues.push_back( 4944 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4945 Op->getReg(), Variable, *FragmentExpr)); 4946 Offset += RegAndSize.second; 4947 } 4948 return true; 4949 } 4950 Op = MachineOperand::CreateReg(VMI->second, false); 4951 IsIndirect = IsDbgDeclare; 4952 } 4953 } 4954 4955 if (!Op) 4956 return false; 4957 4958 assert(Variable->isValidLocationForIntrinsic(DL) && 4959 "Expected inlined-at fields to agree"); 4960 IsIndirect = (Op->isReg()) ? IsIndirect : true; 4961 FuncInfo.ArgDbgValues.push_back( 4962 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4963 *Op, Variable, Expr)); 4964 4965 return true; 4966 } 4967 4968 /// Return the appropriate SDDbgValue based on N. 4969 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4970 DILocalVariable *Variable, 4971 DIExpression *Expr, 4972 const DebugLoc &dl, 4973 unsigned DbgSDNodeOrder) { 4974 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 4975 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4976 // stack slot locations. 4977 // 4978 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 4979 // debug values here after optimization: 4980 // 4981 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 4982 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 4983 // 4984 // Both describe the direct values of their associated variables. 4985 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 4986 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 4987 } 4988 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 4989 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 4990 } 4991 4992 // VisualStudio defines setjmp as _setjmp 4993 #if defined(_MSC_VER) && defined(setjmp) && \ 4994 !defined(setjmp_undefined_for_msvc) 4995 # pragma push_macro("setjmp") 4996 # undef setjmp 4997 # define setjmp_undefined_for_msvc 4998 #endif 4999 5000 /// Lower the call to the specified intrinsic function. If we want to emit this 5001 /// as a call to a named external function, return the name. Otherwise, lower it 5002 /// and return null. 5003 const char * 5004 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5006 SDLoc sdl = getCurSDLoc(); 5007 DebugLoc dl = getCurDebugLoc(); 5008 SDValue Res; 5009 5010 switch (Intrinsic) { 5011 default: 5012 // By default, turn this into a target intrinsic node. 5013 visitTargetIntrinsic(I, Intrinsic); 5014 return nullptr; 5015 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5016 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5017 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5018 case Intrinsic::returnaddress: 5019 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5020 TLI.getPointerTy(DAG.getDataLayout()), 5021 getValue(I.getArgOperand(0)))); 5022 return nullptr; 5023 case Intrinsic::addressofreturnaddress: 5024 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5025 TLI.getPointerTy(DAG.getDataLayout()))); 5026 return nullptr; 5027 case Intrinsic::frameaddress: 5028 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5029 TLI.getPointerTy(DAG.getDataLayout()), 5030 getValue(I.getArgOperand(0)))); 5031 return nullptr; 5032 case Intrinsic::read_register: { 5033 Value *Reg = I.getArgOperand(0); 5034 SDValue Chain = getRoot(); 5035 SDValue RegName = 5036 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5037 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5038 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5039 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5040 setValue(&I, Res); 5041 DAG.setRoot(Res.getValue(1)); 5042 return nullptr; 5043 } 5044 case Intrinsic::write_register: { 5045 Value *Reg = I.getArgOperand(0); 5046 Value *RegValue = I.getArgOperand(1); 5047 SDValue Chain = getRoot(); 5048 SDValue RegName = 5049 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5050 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5051 RegName, getValue(RegValue))); 5052 return nullptr; 5053 } 5054 case Intrinsic::setjmp: 5055 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5056 case Intrinsic::longjmp: 5057 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5058 case Intrinsic::memcpy: { 5059 const auto &MCI = cast<MemCpyInst>(I); 5060 SDValue Op1 = getValue(I.getArgOperand(0)); 5061 SDValue Op2 = getValue(I.getArgOperand(1)); 5062 SDValue Op3 = getValue(I.getArgOperand(2)); 5063 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5064 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5065 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5066 unsigned Align = MinAlign(DstAlign, SrcAlign); 5067 bool isVol = MCI.isVolatile(); 5068 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5069 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5070 // node. 5071 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5072 false, isTC, 5073 MachinePointerInfo(I.getArgOperand(0)), 5074 MachinePointerInfo(I.getArgOperand(1))); 5075 updateDAGForMaybeTailCall(MC); 5076 return nullptr; 5077 } 5078 case Intrinsic::memset: { 5079 const auto &MSI = cast<MemSetInst>(I); 5080 SDValue Op1 = getValue(I.getArgOperand(0)); 5081 SDValue Op2 = getValue(I.getArgOperand(1)); 5082 SDValue Op3 = getValue(I.getArgOperand(2)); 5083 // @llvm.memset defines 0 and 1 to both mean no alignment. 5084 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5085 bool isVol = MSI.isVolatile(); 5086 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5087 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5088 isTC, MachinePointerInfo(I.getArgOperand(0))); 5089 updateDAGForMaybeTailCall(MS); 5090 return nullptr; 5091 } 5092 case Intrinsic::memmove: { 5093 const auto &MMI = cast<MemMoveInst>(I); 5094 SDValue Op1 = getValue(I.getArgOperand(0)); 5095 SDValue Op2 = getValue(I.getArgOperand(1)); 5096 SDValue Op3 = getValue(I.getArgOperand(2)); 5097 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5098 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5099 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5100 unsigned Align = MinAlign(DstAlign, SrcAlign); 5101 bool isVol = MMI.isVolatile(); 5102 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5103 // FIXME: Support passing different dest/src alignments to the memmove DAG 5104 // node. 5105 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5106 isTC, MachinePointerInfo(I.getArgOperand(0)), 5107 MachinePointerInfo(I.getArgOperand(1))); 5108 updateDAGForMaybeTailCall(MM); 5109 return nullptr; 5110 } 5111 case Intrinsic::memcpy_element_unordered_atomic: { 5112 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5113 SDValue Dst = getValue(MI.getRawDest()); 5114 SDValue Src = getValue(MI.getRawSource()); 5115 SDValue Length = getValue(MI.getLength()); 5116 5117 unsigned DstAlign = MI.getDestAlignment(); 5118 unsigned SrcAlign = MI.getSourceAlignment(); 5119 Type *LengthTy = MI.getLength()->getType(); 5120 unsigned ElemSz = MI.getElementSizeInBytes(); 5121 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5122 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5123 SrcAlign, Length, LengthTy, ElemSz, isTC, 5124 MachinePointerInfo(MI.getRawDest()), 5125 MachinePointerInfo(MI.getRawSource())); 5126 updateDAGForMaybeTailCall(MC); 5127 return nullptr; 5128 } 5129 case Intrinsic::memmove_element_unordered_atomic: { 5130 auto &MI = cast<AtomicMemMoveInst>(I); 5131 SDValue Dst = getValue(MI.getRawDest()); 5132 SDValue Src = getValue(MI.getRawSource()); 5133 SDValue Length = getValue(MI.getLength()); 5134 5135 unsigned DstAlign = MI.getDestAlignment(); 5136 unsigned SrcAlign = MI.getSourceAlignment(); 5137 Type *LengthTy = MI.getLength()->getType(); 5138 unsigned ElemSz = MI.getElementSizeInBytes(); 5139 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5140 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5141 SrcAlign, Length, LengthTy, ElemSz, isTC, 5142 MachinePointerInfo(MI.getRawDest()), 5143 MachinePointerInfo(MI.getRawSource())); 5144 updateDAGForMaybeTailCall(MC); 5145 return nullptr; 5146 } 5147 case Intrinsic::memset_element_unordered_atomic: { 5148 auto &MI = cast<AtomicMemSetInst>(I); 5149 SDValue Dst = getValue(MI.getRawDest()); 5150 SDValue Val = getValue(MI.getValue()); 5151 SDValue Length = getValue(MI.getLength()); 5152 5153 unsigned DstAlign = MI.getDestAlignment(); 5154 Type *LengthTy = MI.getLength()->getType(); 5155 unsigned ElemSz = MI.getElementSizeInBytes(); 5156 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5157 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5158 LengthTy, ElemSz, isTC, 5159 MachinePointerInfo(MI.getRawDest())); 5160 updateDAGForMaybeTailCall(MC); 5161 return nullptr; 5162 } 5163 case Intrinsic::dbg_addr: 5164 case Intrinsic::dbg_declare: { 5165 const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I); 5166 DILocalVariable *Variable = DI.getVariable(); 5167 DIExpression *Expression = DI.getExpression(); 5168 dropDanglingDebugInfo(Variable, Expression); 5169 assert(Variable && "Missing variable"); 5170 5171 // Check if address has undef value. 5172 const Value *Address = DI.getVariableLocation(); 5173 if (!Address || isa<UndefValue>(Address) || 5174 (Address->use_empty() && !isa<Argument>(Address))) { 5175 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5176 return nullptr; 5177 } 5178 5179 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5180 5181 // Check if this variable can be described by a frame index, typically 5182 // either as a static alloca or a byval parameter. 5183 int FI = std::numeric_limits<int>::max(); 5184 if (const auto *AI = 5185 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5186 if (AI->isStaticAlloca()) { 5187 auto I = FuncInfo.StaticAllocaMap.find(AI); 5188 if (I != FuncInfo.StaticAllocaMap.end()) 5189 FI = I->second; 5190 } 5191 } else if (const auto *Arg = dyn_cast<Argument>( 5192 Address->stripInBoundsConstantOffsets())) { 5193 FI = FuncInfo.getArgumentFrameIndex(Arg); 5194 } 5195 5196 // llvm.dbg.addr is control dependent and always generates indirect 5197 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5198 // the MachineFunction variable table. 5199 if (FI != std::numeric_limits<int>::max()) { 5200 if (Intrinsic == Intrinsic::dbg_addr) { 5201 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5202 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5203 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5204 } 5205 return nullptr; 5206 } 5207 5208 SDValue &N = NodeMap[Address]; 5209 if (!N.getNode() && isa<Argument>(Address)) 5210 // Check unused arguments map. 5211 N = UnusedArgNodeMap[Address]; 5212 SDDbgValue *SDV; 5213 if (N.getNode()) { 5214 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5215 Address = BCI->getOperand(0); 5216 // Parameters are handled specially. 5217 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5218 if (isParameter && FINode) { 5219 // Byval parameter. We have a frame index at this point. 5220 SDV = 5221 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5222 /*IsIndirect*/ true, dl, SDNodeOrder); 5223 } else if (isa<Argument>(Address)) { 5224 // Address is an argument, so try to emit its dbg value using 5225 // virtual register info from the FuncInfo.ValueMap. 5226 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5227 return nullptr; 5228 } else { 5229 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5230 true, dl, SDNodeOrder); 5231 } 5232 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5233 } else { 5234 // If Address is an argument then try to emit its dbg value using 5235 // virtual register info from the FuncInfo.ValueMap. 5236 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5237 N)) { 5238 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5239 } 5240 } 5241 return nullptr; 5242 } 5243 case Intrinsic::dbg_label: { 5244 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5245 DILabel *Label = DI.getLabel(); 5246 assert(Label && "Missing label"); 5247 5248 SDDbgLabel *SDV; 5249 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5250 DAG.AddDbgLabel(SDV); 5251 return nullptr; 5252 } 5253 case Intrinsic::dbg_value: { 5254 const DbgValueInst &DI = cast<DbgValueInst>(I); 5255 assert(DI.getVariable() && "Missing variable"); 5256 5257 DILocalVariable *Variable = DI.getVariable(); 5258 DIExpression *Expression = DI.getExpression(); 5259 dropDanglingDebugInfo(Variable, Expression); 5260 const Value *V = DI.getValue(); 5261 if (!V) 5262 return nullptr; 5263 5264 SDDbgValue *SDV; 5265 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5266 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5267 DAG.AddDbgValue(SDV, nullptr, false); 5268 return nullptr; 5269 } 5270 5271 // Do not use getValue() in here; we don't want to generate code at 5272 // this point if it hasn't been done yet. 5273 SDValue N = NodeMap[V]; 5274 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5275 N = UnusedArgNodeMap[V]; 5276 if (N.getNode()) { 5277 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5278 return nullptr; 5279 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5280 DAG.AddDbgValue(SDV, N.getNode(), false); 5281 return nullptr; 5282 } 5283 5284 // PHI nodes have already been selected, so we should know which VReg that 5285 // is assigns to already. 5286 if (isa<PHINode>(V)) { 5287 auto VMI = FuncInfo.ValueMap.find(V); 5288 if (VMI != FuncInfo.ValueMap.end()) { 5289 unsigned Reg = VMI->second; 5290 // The PHI node may be split up into several MI PHI nodes (in 5291 // FunctionLoweringInfo::set). 5292 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5293 V->getType(), false); 5294 if (RFV.occupiesMultipleRegs()) { 5295 unsigned Offset = 0; 5296 unsigned BitsToDescribe = 0; 5297 if (auto VarSize = Variable->getSizeInBits()) 5298 BitsToDescribe = *VarSize; 5299 if (auto Fragment = Expression->getFragmentInfo()) 5300 BitsToDescribe = Fragment->SizeInBits; 5301 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5302 unsigned RegisterSize = RegAndSize.second; 5303 // Bail out if all bits are described already. 5304 if (Offset >= BitsToDescribe) 5305 break; 5306 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5307 ? BitsToDescribe - Offset 5308 : RegisterSize; 5309 auto FragmentExpr = DIExpression::createFragmentExpression( 5310 Expression, Offset, FragmentSize); 5311 if (!FragmentExpr) 5312 continue; 5313 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5314 false, dl, SDNodeOrder); 5315 DAG.AddDbgValue(SDV, nullptr, false); 5316 Offset += RegisterSize; 5317 } 5318 } else { 5319 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5320 SDNodeOrder); 5321 DAG.AddDbgValue(SDV, nullptr, false); 5322 } 5323 return nullptr; 5324 } 5325 } 5326 5327 // TODO: When we get here we will either drop the dbg.value completely, or 5328 // we try to move it forward by letting it dangle for awhile. So we should 5329 // probably add an extra DbgValue to the DAG here, with a reference to 5330 // "noreg", to indicate that we have lost the debug location for the 5331 // variable. 5332 5333 if (!V->use_empty() ) { 5334 // Do not call getValue(V) yet, as we don't want to generate code. 5335 // Remember it for later. 5336 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5337 return nullptr; 5338 } 5339 5340 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5341 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5342 return nullptr; 5343 } 5344 5345 case Intrinsic::eh_typeid_for: { 5346 // Find the type id for the given typeinfo. 5347 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5348 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5349 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5350 setValue(&I, Res); 5351 return nullptr; 5352 } 5353 5354 case Intrinsic::eh_return_i32: 5355 case Intrinsic::eh_return_i64: 5356 DAG.getMachineFunction().setCallsEHReturn(true); 5357 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5358 MVT::Other, 5359 getControlRoot(), 5360 getValue(I.getArgOperand(0)), 5361 getValue(I.getArgOperand(1)))); 5362 return nullptr; 5363 case Intrinsic::eh_unwind_init: 5364 DAG.getMachineFunction().setCallsUnwindInit(true); 5365 return nullptr; 5366 case Intrinsic::eh_dwarf_cfa: 5367 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5368 TLI.getPointerTy(DAG.getDataLayout()), 5369 getValue(I.getArgOperand(0)))); 5370 return nullptr; 5371 case Intrinsic::eh_sjlj_callsite: { 5372 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5373 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5374 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5375 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5376 5377 MMI.setCurrentCallSite(CI->getZExtValue()); 5378 return nullptr; 5379 } 5380 case Intrinsic::eh_sjlj_functioncontext: { 5381 // Get and store the index of the function context. 5382 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5383 AllocaInst *FnCtx = 5384 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5385 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5386 MFI.setFunctionContextIndex(FI); 5387 return nullptr; 5388 } 5389 case Intrinsic::eh_sjlj_setjmp: { 5390 SDValue Ops[2]; 5391 Ops[0] = getRoot(); 5392 Ops[1] = getValue(I.getArgOperand(0)); 5393 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5394 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5395 setValue(&I, Op.getValue(0)); 5396 DAG.setRoot(Op.getValue(1)); 5397 return nullptr; 5398 } 5399 case Intrinsic::eh_sjlj_longjmp: 5400 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5401 getRoot(), getValue(I.getArgOperand(0)))); 5402 return nullptr; 5403 case Intrinsic::eh_sjlj_setup_dispatch: 5404 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5405 getRoot())); 5406 return nullptr; 5407 case Intrinsic::masked_gather: 5408 visitMaskedGather(I); 5409 return nullptr; 5410 case Intrinsic::masked_load: 5411 visitMaskedLoad(I); 5412 return nullptr; 5413 case Intrinsic::masked_scatter: 5414 visitMaskedScatter(I); 5415 return nullptr; 5416 case Intrinsic::masked_store: 5417 visitMaskedStore(I); 5418 return nullptr; 5419 case Intrinsic::masked_expandload: 5420 visitMaskedLoad(I, true /* IsExpanding */); 5421 return nullptr; 5422 case Intrinsic::masked_compressstore: 5423 visitMaskedStore(I, true /* IsCompressing */); 5424 return nullptr; 5425 case Intrinsic::x86_mmx_pslli_w: 5426 case Intrinsic::x86_mmx_pslli_d: 5427 case Intrinsic::x86_mmx_pslli_q: 5428 case Intrinsic::x86_mmx_psrli_w: 5429 case Intrinsic::x86_mmx_psrli_d: 5430 case Intrinsic::x86_mmx_psrli_q: 5431 case Intrinsic::x86_mmx_psrai_w: 5432 case Intrinsic::x86_mmx_psrai_d: { 5433 SDValue ShAmt = getValue(I.getArgOperand(1)); 5434 if (isa<ConstantSDNode>(ShAmt)) { 5435 visitTargetIntrinsic(I, Intrinsic); 5436 return nullptr; 5437 } 5438 unsigned NewIntrinsic = 0; 5439 EVT ShAmtVT = MVT::v2i32; 5440 switch (Intrinsic) { 5441 case Intrinsic::x86_mmx_pslli_w: 5442 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5443 break; 5444 case Intrinsic::x86_mmx_pslli_d: 5445 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5446 break; 5447 case Intrinsic::x86_mmx_pslli_q: 5448 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5449 break; 5450 case Intrinsic::x86_mmx_psrli_w: 5451 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5452 break; 5453 case Intrinsic::x86_mmx_psrli_d: 5454 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5455 break; 5456 case Intrinsic::x86_mmx_psrli_q: 5457 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5458 break; 5459 case Intrinsic::x86_mmx_psrai_w: 5460 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5461 break; 5462 case Intrinsic::x86_mmx_psrai_d: 5463 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5464 break; 5465 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5466 } 5467 5468 // The vector shift intrinsics with scalars uses 32b shift amounts but 5469 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5470 // to be zero. 5471 // We must do this early because v2i32 is not a legal type. 5472 SDValue ShOps[2]; 5473 ShOps[0] = ShAmt; 5474 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5475 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5476 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5477 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5478 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5479 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5480 getValue(I.getArgOperand(0)), ShAmt); 5481 setValue(&I, Res); 5482 return nullptr; 5483 } 5484 case Intrinsic::powi: 5485 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5486 getValue(I.getArgOperand(1)), DAG)); 5487 return nullptr; 5488 case Intrinsic::log: 5489 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5490 return nullptr; 5491 case Intrinsic::log2: 5492 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5493 return nullptr; 5494 case Intrinsic::log10: 5495 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5496 return nullptr; 5497 case Intrinsic::exp: 5498 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5499 return nullptr; 5500 case Intrinsic::exp2: 5501 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5502 return nullptr; 5503 case Intrinsic::pow: 5504 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5505 getValue(I.getArgOperand(1)), DAG, TLI)); 5506 return nullptr; 5507 case Intrinsic::sqrt: 5508 case Intrinsic::fabs: 5509 case Intrinsic::sin: 5510 case Intrinsic::cos: 5511 case Intrinsic::floor: 5512 case Intrinsic::ceil: 5513 case Intrinsic::trunc: 5514 case Intrinsic::rint: 5515 case Intrinsic::nearbyint: 5516 case Intrinsic::round: 5517 case Intrinsic::canonicalize: { 5518 unsigned Opcode; 5519 switch (Intrinsic) { 5520 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5521 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5522 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5523 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5524 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5525 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5526 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5527 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5528 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5529 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5530 case Intrinsic::round: Opcode = ISD::FROUND; break; 5531 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5532 } 5533 5534 setValue(&I, DAG.getNode(Opcode, sdl, 5535 getValue(I.getArgOperand(0)).getValueType(), 5536 getValue(I.getArgOperand(0)))); 5537 return nullptr; 5538 } 5539 case Intrinsic::minnum: { 5540 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5541 unsigned Opc = 5542 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5543 ? ISD::FMINNAN 5544 : ISD::FMINNUM; 5545 setValue(&I, DAG.getNode(Opc, sdl, VT, 5546 getValue(I.getArgOperand(0)), 5547 getValue(I.getArgOperand(1)))); 5548 return nullptr; 5549 } 5550 case Intrinsic::maxnum: { 5551 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5552 unsigned Opc = 5553 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5554 ? ISD::FMAXNAN 5555 : ISD::FMAXNUM; 5556 setValue(&I, DAG.getNode(Opc, sdl, VT, 5557 getValue(I.getArgOperand(0)), 5558 getValue(I.getArgOperand(1)))); 5559 return nullptr; 5560 } 5561 case Intrinsic::copysign: 5562 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5563 getValue(I.getArgOperand(0)).getValueType(), 5564 getValue(I.getArgOperand(0)), 5565 getValue(I.getArgOperand(1)))); 5566 return nullptr; 5567 case Intrinsic::fma: 5568 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5569 getValue(I.getArgOperand(0)).getValueType(), 5570 getValue(I.getArgOperand(0)), 5571 getValue(I.getArgOperand(1)), 5572 getValue(I.getArgOperand(2)))); 5573 return nullptr; 5574 case Intrinsic::experimental_constrained_fadd: 5575 case Intrinsic::experimental_constrained_fsub: 5576 case Intrinsic::experimental_constrained_fmul: 5577 case Intrinsic::experimental_constrained_fdiv: 5578 case Intrinsic::experimental_constrained_frem: 5579 case Intrinsic::experimental_constrained_fma: 5580 case Intrinsic::experimental_constrained_sqrt: 5581 case Intrinsic::experimental_constrained_pow: 5582 case Intrinsic::experimental_constrained_powi: 5583 case Intrinsic::experimental_constrained_sin: 5584 case Intrinsic::experimental_constrained_cos: 5585 case Intrinsic::experimental_constrained_exp: 5586 case Intrinsic::experimental_constrained_exp2: 5587 case Intrinsic::experimental_constrained_log: 5588 case Intrinsic::experimental_constrained_log10: 5589 case Intrinsic::experimental_constrained_log2: 5590 case Intrinsic::experimental_constrained_rint: 5591 case Intrinsic::experimental_constrained_nearbyint: 5592 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5593 return nullptr; 5594 case Intrinsic::fmuladd: { 5595 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5596 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5597 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5598 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5599 getValue(I.getArgOperand(0)).getValueType(), 5600 getValue(I.getArgOperand(0)), 5601 getValue(I.getArgOperand(1)), 5602 getValue(I.getArgOperand(2)))); 5603 } else { 5604 // TODO: Intrinsic calls should have fast-math-flags. 5605 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5606 getValue(I.getArgOperand(0)).getValueType(), 5607 getValue(I.getArgOperand(0)), 5608 getValue(I.getArgOperand(1))); 5609 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5610 getValue(I.getArgOperand(0)).getValueType(), 5611 Mul, 5612 getValue(I.getArgOperand(2))); 5613 setValue(&I, Add); 5614 } 5615 return nullptr; 5616 } 5617 case Intrinsic::convert_to_fp16: 5618 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5619 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5620 getValue(I.getArgOperand(0)), 5621 DAG.getTargetConstant(0, sdl, 5622 MVT::i32)))); 5623 return nullptr; 5624 case Intrinsic::convert_from_fp16: 5625 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5626 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5627 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5628 getValue(I.getArgOperand(0))))); 5629 return nullptr; 5630 case Intrinsic::pcmarker: { 5631 SDValue Tmp = getValue(I.getArgOperand(0)); 5632 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5633 return nullptr; 5634 } 5635 case Intrinsic::readcyclecounter: { 5636 SDValue Op = getRoot(); 5637 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5638 DAG.getVTList(MVT::i64, MVT::Other), Op); 5639 setValue(&I, Res); 5640 DAG.setRoot(Res.getValue(1)); 5641 return nullptr; 5642 } 5643 case Intrinsic::bitreverse: 5644 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5645 getValue(I.getArgOperand(0)).getValueType(), 5646 getValue(I.getArgOperand(0)))); 5647 return nullptr; 5648 case Intrinsic::bswap: 5649 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5650 getValue(I.getArgOperand(0)).getValueType(), 5651 getValue(I.getArgOperand(0)))); 5652 return nullptr; 5653 case Intrinsic::cttz: { 5654 SDValue Arg = getValue(I.getArgOperand(0)); 5655 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5656 EVT Ty = Arg.getValueType(); 5657 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5658 sdl, Ty, Arg)); 5659 return nullptr; 5660 } 5661 case Intrinsic::ctlz: { 5662 SDValue Arg = getValue(I.getArgOperand(0)); 5663 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5664 EVT Ty = Arg.getValueType(); 5665 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5666 sdl, Ty, Arg)); 5667 return nullptr; 5668 } 5669 case Intrinsic::ctpop: { 5670 SDValue Arg = getValue(I.getArgOperand(0)); 5671 EVT Ty = Arg.getValueType(); 5672 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5673 return nullptr; 5674 } 5675 case Intrinsic::fshl: 5676 case Intrinsic::fshr: { 5677 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5678 SDValue X = getValue(I.getArgOperand(0)); 5679 SDValue Y = getValue(I.getArgOperand(1)); 5680 SDValue Z = getValue(I.getArgOperand(2)); 5681 EVT VT = X.getValueType(); 5682 5683 // When X == Y, this is rotate. Create the node directly if legal. 5684 // TODO: This should also be done if the operation is custom, but we have 5685 // to make sure targets are handling the modulo shift amount as expected. 5686 // TODO: If the rotate direction (left or right) corresponding to the shift 5687 // is not available, adjust the shift value and invert the direction. 5688 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5689 if (X == Y && TLI.isOperationLegal(RotateOpcode, VT)) { 5690 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5691 return nullptr; 5692 } 5693 5694 // Get the shift amount and inverse shift amount, modulo the bit-width. 5695 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5696 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5697 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, Z); 5698 SDValue InvShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5699 5700 // fshl: (X << (Z % BW)) | (Y >> ((BW - Z) % BW)) 5701 // fshr: (X << ((BW - Z) % BW)) | (Y >> (Z % BW)) 5702 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5703 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5704 SDValue Res = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5705 5706 // If (Z % BW == 0), then (BW - Z) % BW is also zero, so the result would 5707 // be X | Y. If X == Y (rotate), that's fine. If not, we have to select. 5708 if (X != Y) { 5709 SDValue Zero = DAG.getConstant(0, sdl, VT); 5710 EVT CCVT = MVT::i1; 5711 if (VT.isVector()) 5712 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5713 // For fshl, 0 shift returns the 1st arg (X). 5714 // For fshr, 0 shift returns the 2nd arg (Y). 5715 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5716 Res = DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Res); 5717 } 5718 setValue(&I, Res); 5719 return nullptr; 5720 } 5721 case Intrinsic::stacksave: { 5722 SDValue Op = getRoot(); 5723 Res = DAG.getNode( 5724 ISD::STACKSAVE, sdl, 5725 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5726 setValue(&I, Res); 5727 DAG.setRoot(Res.getValue(1)); 5728 return nullptr; 5729 } 5730 case Intrinsic::stackrestore: 5731 Res = getValue(I.getArgOperand(0)); 5732 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5733 return nullptr; 5734 case Intrinsic::get_dynamic_area_offset: { 5735 SDValue Op = getRoot(); 5736 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5737 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5738 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5739 // target. 5740 if (PtrTy != ResTy) 5741 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5742 " intrinsic!"); 5743 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5744 Op); 5745 DAG.setRoot(Op); 5746 setValue(&I, Res); 5747 return nullptr; 5748 } 5749 case Intrinsic::stackguard: { 5750 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5751 MachineFunction &MF = DAG.getMachineFunction(); 5752 const Module &M = *MF.getFunction().getParent(); 5753 SDValue Chain = getRoot(); 5754 if (TLI.useLoadStackGuardNode()) { 5755 Res = getLoadStackGuard(DAG, sdl, Chain); 5756 } else { 5757 const Value *Global = TLI.getSDagStackGuard(M); 5758 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5759 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5760 MachinePointerInfo(Global, 0), Align, 5761 MachineMemOperand::MOVolatile); 5762 } 5763 if (TLI.useStackGuardXorFP()) 5764 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5765 DAG.setRoot(Chain); 5766 setValue(&I, Res); 5767 return nullptr; 5768 } 5769 case Intrinsic::stackprotector: { 5770 // Emit code into the DAG to store the stack guard onto the stack. 5771 MachineFunction &MF = DAG.getMachineFunction(); 5772 MachineFrameInfo &MFI = MF.getFrameInfo(); 5773 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5774 SDValue Src, Chain = getRoot(); 5775 5776 if (TLI.useLoadStackGuardNode()) 5777 Src = getLoadStackGuard(DAG, sdl, Chain); 5778 else 5779 Src = getValue(I.getArgOperand(0)); // The guard's value. 5780 5781 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5782 5783 int FI = FuncInfo.StaticAllocaMap[Slot]; 5784 MFI.setStackProtectorIndex(FI); 5785 5786 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5787 5788 // Store the stack protector onto the stack. 5789 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5790 DAG.getMachineFunction(), FI), 5791 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5792 setValue(&I, Res); 5793 DAG.setRoot(Res); 5794 return nullptr; 5795 } 5796 case Intrinsic::objectsize: { 5797 // If we don't know by now, we're never going to know. 5798 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5799 5800 assert(CI && "Non-constant type in __builtin_object_size?"); 5801 5802 SDValue Arg = getValue(I.getCalledValue()); 5803 EVT Ty = Arg.getValueType(); 5804 5805 if (CI->isZero()) 5806 Res = DAG.getConstant(-1ULL, sdl, Ty); 5807 else 5808 Res = DAG.getConstant(0, sdl, Ty); 5809 5810 setValue(&I, Res); 5811 return nullptr; 5812 } 5813 case Intrinsic::annotation: 5814 case Intrinsic::ptr_annotation: 5815 case Intrinsic::launder_invariant_group: 5816 case Intrinsic::strip_invariant_group: 5817 // Drop the intrinsic, but forward the value 5818 setValue(&I, getValue(I.getOperand(0))); 5819 return nullptr; 5820 case Intrinsic::assume: 5821 case Intrinsic::var_annotation: 5822 case Intrinsic::sideeffect: 5823 // Discard annotate attributes, assumptions, and artificial side-effects. 5824 return nullptr; 5825 5826 case Intrinsic::codeview_annotation: { 5827 // Emit a label associated with this metadata. 5828 MachineFunction &MF = DAG.getMachineFunction(); 5829 MCSymbol *Label = 5830 MF.getMMI().getContext().createTempSymbol("annotation", true); 5831 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5832 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5833 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5834 DAG.setRoot(Res); 5835 return nullptr; 5836 } 5837 5838 case Intrinsic::init_trampoline: { 5839 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5840 5841 SDValue Ops[6]; 5842 Ops[0] = getRoot(); 5843 Ops[1] = getValue(I.getArgOperand(0)); 5844 Ops[2] = getValue(I.getArgOperand(1)); 5845 Ops[3] = getValue(I.getArgOperand(2)); 5846 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5847 Ops[5] = DAG.getSrcValue(F); 5848 5849 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5850 5851 DAG.setRoot(Res); 5852 return nullptr; 5853 } 5854 case Intrinsic::adjust_trampoline: 5855 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5856 TLI.getPointerTy(DAG.getDataLayout()), 5857 getValue(I.getArgOperand(0)))); 5858 return nullptr; 5859 case Intrinsic::gcroot: { 5860 assert(DAG.getMachineFunction().getFunction().hasGC() && 5861 "only valid in functions with gc specified, enforced by Verifier"); 5862 assert(GFI && "implied by previous"); 5863 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5864 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5865 5866 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5867 GFI->addStackRoot(FI->getIndex(), TypeMap); 5868 return nullptr; 5869 } 5870 case Intrinsic::gcread: 5871 case Intrinsic::gcwrite: 5872 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5873 case Intrinsic::flt_rounds: 5874 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5875 return nullptr; 5876 5877 case Intrinsic::expect: 5878 // Just replace __builtin_expect(exp, c) with EXP. 5879 setValue(&I, getValue(I.getArgOperand(0))); 5880 return nullptr; 5881 5882 case Intrinsic::debugtrap: 5883 case Intrinsic::trap: { 5884 StringRef TrapFuncName = 5885 I.getAttributes() 5886 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5887 .getValueAsString(); 5888 if (TrapFuncName.empty()) { 5889 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5890 ISD::TRAP : ISD::DEBUGTRAP; 5891 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5892 return nullptr; 5893 } 5894 TargetLowering::ArgListTy Args; 5895 5896 TargetLowering::CallLoweringInfo CLI(DAG); 5897 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5898 CallingConv::C, I.getType(), 5899 DAG.getExternalSymbol(TrapFuncName.data(), 5900 TLI.getPointerTy(DAG.getDataLayout())), 5901 std::move(Args)); 5902 5903 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5904 DAG.setRoot(Result.second); 5905 return nullptr; 5906 } 5907 5908 case Intrinsic::uadd_with_overflow: 5909 case Intrinsic::sadd_with_overflow: 5910 case Intrinsic::usub_with_overflow: 5911 case Intrinsic::ssub_with_overflow: 5912 case Intrinsic::umul_with_overflow: 5913 case Intrinsic::smul_with_overflow: { 5914 ISD::NodeType Op; 5915 switch (Intrinsic) { 5916 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5917 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5918 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5919 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5920 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5921 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5922 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5923 } 5924 SDValue Op1 = getValue(I.getArgOperand(0)); 5925 SDValue Op2 = getValue(I.getArgOperand(1)); 5926 5927 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5928 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5929 return nullptr; 5930 } 5931 case Intrinsic::prefetch: { 5932 SDValue Ops[5]; 5933 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5934 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 5935 Ops[0] = DAG.getRoot(); 5936 Ops[1] = getValue(I.getArgOperand(0)); 5937 Ops[2] = getValue(I.getArgOperand(1)); 5938 Ops[3] = getValue(I.getArgOperand(2)); 5939 Ops[4] = getValue(I.getArgOperand(3)); 5940 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5941 DAG.getVTList(MVT::Other), Ops, 5942 EVT::getIntegerVT(*Context, 8), 5943 MachinePointerInfo(I.getArgOperand(0)), 5944 0, /* align */ 5945 Flags); 5946 5947 // Chain the prefetch in parallell with any pending loads, to stay out of 5948 // the way of later optimizations. 5949 PendingLoads.push_back(Result); 5950 Result = getRoot(); 5951 DAG.setRoot(Result); 5952 return nullptr; 5953 } 5954 case Intrinsic::lifetime_start: 5955 case Intrinsic::lifetime_end: { 5956 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5957 // Stack coloring is not enabled in O0, discard region information. 5958 if (TM.getOptLevel() == CodeGenOpt::None) 5959 return nullptr; 5960 5961 SmallVector<Value *, 4> Allocas; 5962 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5963 5964 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5965 E = Allocas.end(); Object != E; ++Object) { 5966 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5967 5968 // Could not find an Alloca. 5969 if (!LifetimeObject) 5970 continue; 5971 5972 // First check that the Alloca is static, otherwise it won't have a 5973 // valid frame index. 5974 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5975 if (SI == FuncInfo.StaticAllocaMap.end()) 5976 return nullptr; 5977 5978 int FI = SI->second; 5979 5980 SDValue Ops[2]; 5981 Ops[0] = getRoot(); 5982 Ops[1] = 5983 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 5984 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5985 5986 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5987 DAG.setRoot(Res); 5988 } 5989 return nullptr; 5990 } 5991 case Intrinsic::invariant_start: 5992 // Discard region information. 5993 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5994 return nullptr; 5995 case Intrinsic::invariant_end: 5996 // Discard region information. 5997 return nullptr; 5998 case Intrinsic::clear_cache: 5999 return TLI.getClearCacheBuiltinName(); 6000 case Intrinsic::donothing: 6001 // ignore 6002 return nullptr; 6003 case Intrinsic::experimental_stackmap: 6004 visitStackmap(I); 6005 return nullptr; 6006 case Intrinsic::experimental_patchpoint_void: 6007 case Intrinsic::experimental_patchpoint_i64: 6008 visitPatchpoint(&I); 6009 return nullptr; 6010 case Intrinsic::experimental_gc_statepoint: 6011 LowerStatepoint(ImmutableStatepoint(&I)); 6012 return nullptr; 6013 case Intrinsic::experimental_gc_result: 6014 visitGCResult(cast<GCResultInst>(I)); 6015 return nullptr; 6016 case Intrinsic::experimental_gc_relocate: 6017 visitGCRelocate(cast<GCRelocateInst>(I)); 6018 return nullptr; 6019 case Intrinsic::instrprof_increment: 6020 llvm_unreachable("instrprof failed to lower an increment"); 6021 case Intrinsic::instrprof_value_profile: 6022 llvm_unreachable("instrprof failed to lower a value profiling call"); 6023 case Intrinsic::localescape: { 6024 MachineFunction &MF = DAG.getMachineFunction(); 6025 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6026 6027 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6028 // is the same on all targets. 6029 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6030 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6031 if (isa<ConstantPointerNull>(Arg)) 6032 continue; // Skip null pointers. They represent a hole in index space. 6033 AllocaInst *Slot = cast<AllocaInst>(Arg); 6034 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6035 "can only escape static allocas"); 6036 int FI = FuncInfo.StaticAllocaMap[Slot]; 6037 MCSymbol *FrameAllocSym = 6038 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6039 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6040 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6041 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6042 .addSym(FrameAllocSym) 6043 .addFrameIndex(FI); 6044 } 6045 6046 return nullptr; 6047 } 6048 6049 case Intrinsic::localrecover: { 6050 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6051 MachineFunction &MF = DAG.getMachineFunction(); 6052 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6053 6054 // Get the symbol that defines the frame offset. 6055 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6056 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6057 unsigned IdxVal = 6058 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6059 MCSymbol *FrameAllocSym = 6060 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6061 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6062 6063 // Create a MCSymbol for the label to avoid any target lowering 6064 // that would make this PC relative. 6065 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6066 SDValue OffsetVal = 6067 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6068 6069 // Add the offset to the FP. 6070 Value *FP = I.getArgOperand(1); 6071 SDValue FPVal = getValue(FP); 6072 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6073 setValue(&I, Add); 6074 6075 return nullptr; 6076 } 6077 6078 case Intrinsic::eh_exceptionpointer: 6079 case Intrinsic::eh_exceptioncode: { 6080 // Get the exception pointer vreg, copy from it, and resize it to fit. 6081 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6082 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6083 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6084 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6085 SDValue N = 6086 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6087 if (Intrinsic == Intrinsic::eh_exceptioncode) 6088 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6089 setValue(&I, N); 6090 return nullptr; 6091 } 6092 case Intrinsic::xray_customevent: { 6093 // Here we want to make sure that the intrinsic behaves as if it has a 6094 // specific calling convention, and only for x86_64. 6095 // FIXME: Support other platforms later. 6096 const auto &Triple = DAG.getTarget().getTargetTriple(); 6097 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6098 return nullptr; 6099 6100 SDLoc DL = getCurSDLoc(); 6101 SmallVector<SDValue, 8> Ops; 6102 6103 // We want to say that we always want the arguments in registers. 6104 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6105 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6106 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6107 SDValue Chain = getRoot(); 6108 Ops.push_back(LogEntryVal); 6109 Ops.push_back(StrSizeVal); 6110 Ops.push_back(Chain); 6111 6112 // We need to enforce the calling convention for the callsite, so that 6113 // argument ordering is enforced correctly, and that register allocation can 6114 // see that some registers may be assumed clobbered and have to preserve 6115 // them across calls to the intrinsic. 6116 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6117 DL, NodeTys, Ops); 6118 SDValue patchableNode = SDValue(MN, 0); 6119 DAG.setRoot(patchableNode); 6120 setValue(&I, patchableNode); 6121 return nullptr; 6122 } 6123 case Intrinsic::xray_typedevent: { 6124 // Here we want to make sure that the intrinsic behaves as if it has a 6125 // specific calling convention, and only for x86_64. 6126 // FIXME: Support other platforms later. 6127 const auto &Triple = DAG.getTarget().getTargetTriple(); 6128 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6129 return nullptr; 6130 6131 SDLoc DL = getCurSDLoc(); 6132 SmallVector<SDValue, 8> Ops; 6133 6134 // We want to say that we always want the arguments in registers. 6135 // It's unclear to me how manipulating the selection DAG here forces callers 6136 // to provide arguments in registers instead of on the stack. 6137 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6138 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6139 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6141 SDValue Chain = getRoot(); 6142 Ops.push_back(LogTypeId); 6143 Ops.push_back(LogEntryVal); 6144 Ops.push_back(StrSizeVal); 6145 Ops.push_back(Chain); 6146 6147 // We need to enforce the calling convention for the callsite, so that 6148 // argument ordering is enforced correctly, and that register allocation can 6149 // see that some registers may be assumed clobbered and have to preserve 6150 // them across calls to the intrinsic. 6151 MachineSDNode *MN = DAG.getMachineNode( 6152 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6153 SDValue patchableNode = SDValue(MN, 0); 6154 DAG.setRoot(patchableNode); 6155 setValue(&I, patchableNode); 6156 return nullptr; 6157 } 6158 case Intrinsic::experimental_deoptimize: 6159 LowerDeoptimizeCall(&I); 6160 return nullptr; 6161 6162 case Intrinsic::experimental_vector_reduce_fadd: 6163 case Intrinsic::experimental_vector_reduce_fmul: 6164 case Intrinsic::experimental_vector_reduce_add: 6165 case Intrinsic::experimental_vector_reduce_mul: 6166 case Intrinsic::experimental_vector_reduce_and: 6167 case Intrinsic::experimental_vector_reduce_or: 6168 case Intrinsic::experimental_vector_reduce_xor: 6169 case Intrinsic::experimental_vector_reduce_smax: 6170 case Intrinsic::experimental_vector_reduce_smin: 6171 case Intrinsic::experimental_vector_reduce_umax: 6172 case Intrinsic::experimental_vector_reduce_umin: 6173 case Intrinsic::experimental_vector_reduce_fmax: 6174 case Intrinsic::experimental_vector_reduce_fmin: 6175 visitVectorReduce(I, Intrinsic); 6176 return nullptr; 6177 6178 case Intrinsic::icall_branch_funnel: { 6179 SmallVector<SDValue, 16> Ops; 6180 Ops.push_back(DAG.getRoot()); 6181 Ops.push_back(getValue(I.getArgOperand(0))); 6182 6183 int64_t Offset; 6184 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6185 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6186 if (!Base) 6187 report_fatal_error( 6188 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6189 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6190 6191 struct BranchFunnelTarget { 6192 int64_t Offset; 6193 SDValue Target; 6194 }; 6195 SmallVector<BranchFunnelTarget, 8> Targets; 6196 6197 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6198 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6199 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6200 if (ElemBase != Base) 6201 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6202 "to the same GlobalValue"); 6203 6204 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6205 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6206 if (!GA) 6207 report_fatal_error( 6208 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6209 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6210 GA->getGlobal(), getCurSDLoc(), 6211 Val.getValueType(), GA->getOffset())}); 6212 } 6213 llvm::sort(Targets.begin(), Targets.end(), 6214 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6215 return T1.Offset < T2.Offset; 6216 }); 6217 6218 for (auto &T : Targets) { 6219 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6220 Ops.push_back(T.Target); 6221 } 6222 6223 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6224 getCurSDLoc(), MVT::Other, Ops), 6225 0); 6226 DAG.setRoot(N); 6227 setValue(&I, N); 6228 HasTailCall = true; 6229 return nullptr; 6230 } 6231 6232 case Intrinsic::wasm_landingpad_index: { 6233 // TODO store landing pad index in a map, which will be used when generating 6234 // LSDA information 6235 return nullptr; 6236 } 6237 } 6238 } 6239 6240 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6241 const ConstrainedFPIntrinsic &FPI) { 6242 SDLoc sdl = getCurSDLoc(); 6243 unsigned Opcode; 6244 switch (FPI.getIntrinsicID()) { 6245 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6246 case Intrinsic::experimental_constrained_fadd: 6247 Opcode = ISD::STRICT_FADD; 6248 break; 6249 case Intrinsic::experimental_constrained_fsub: 6250 Opcode = ISD::STRICT_FSUB; 6251 break; 6252 case Intrinsic::experimental_constrained_fmul: 6253 Opcode = ISD::STRICT_FMUL; 6254 break; 6255 case Intrinsic::experimental_constrained_fdiv: 6256 Opcode = ISD::STRICT_FDIV; 6257 break; 6258 case Intrinsic::experimental_constrained_frem: 6259 Opcode = ISD::STRICT_FREM; 6260 break; 6261 case Intrinsic::experimental_constrained_fma: 6262 Opcode = ISD::STRICT_FMA; 6263 break; 6264 case Intrinsic::experimental_constrained_sqrt: 6265 Opcode = ISD::STRICT_FSQRT; 6266 break; 6267 case Intrinsic::experimental_constrained_pow: 6268 Opcode = ISD::STRICT_FPOW; 6269 break; 6270 case Intrinsic::experimental_constrained_powi: 6271 Opcode = ISD::STRICT_FPOWI; 6272 break; 6273 case Intrinsic::experimental_constrained_sin: 6274 Opcode = ISD::STRICT_FSIN; 6275 break; 6276 case Intrinsic::experimental_constrained_cos: 6277 Opcode = ISD::STRICT_FCOS; 6278 break; 6279 case Intrinsic::experimental_constrained_exp: 6280 Opcode = ISD::STRICT_FEXP; 6281 break; 6282 case Intrinsic::experimental_constrained_exp2: 6283 Opcode = ISD::STRICT_FEXP2; 6284 break; 6285 case Intrinsic::experimental_constrained_log: 6286 Opcode = ISD::STRICT_FLOG; 6287 break; 6288 case Intrinsic::experimental_constrained_log10: 6289 Opcode = ISD::STRICT_FLOG10; 6290 break; 6291 case Intrinsic::experimental_constrained_log2: 6292 Opcode = ISD::STRICT_FLOG2; 6293 break; 6294 case Intrinsic::experimental_constrained_rint: 6295 Opcode = ISD::STRICT_FRINT; 6296 break; 6297 case Intrinsic::experimental_constrained_nearbyint: 6298 Opcode = ISD::STRICT_FNEARBYINT; 6299 break; 6300 } 6301 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6302 SDValue Chain = getRoot(); 6303 SmallVector<EVT, 4> ValueVTs; 6304 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6305 ValueVTs.push_back(MVT::Other); // Out chain 6306 6307 SDVTList VTs = DAG.getVTList(ValueVTs); 6308 SDValue Result; 6309 if (FPI.isUnaryOp()) 6310 Result = DAG.getNode(Opcode, sdl, VTs, 6311 { Chain, getValue(FPI.getArgOperand(0)) }); 6312 else if (FPI.isTernaryOp()) 6313 Result = DAG.getNode(Opcode, sdl, VTs, 6314 { Chain, getValue(FPI.getArgOperand(0)), 6315 getValue(FPI.getArgOperand(1)), 6316 getValue(FPI.getArgOperand(2)) }); 6317 else 6318 Result = DAG.getNode(Opcode, sdl, VTs, 6319 { Chain, getValue(FPI.getArgOperand(0)), 6320 getValue(FPI.getArgOperand(1)) }); 6321 6322 assert(Result.getNode()->getNumValues() == 2); 6323 SDValue OutChain = Result.getValue(1); 6324 DAG.setRoot(OutChain); 6325 SDValue FPResult = Result.getValue(0); 6326 setValue(&FPI, FPResult); 6327 } 6328 6329 std::pair<SDValue, SDValue> 6330 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6331 const BasicBlock *EHPadBB) { 6332 MachineFunction &MF = DAG.getMachineFunction(); 6333 MachineModuleInfo &MMI = MF.getMMI(); 6334 MCSymbol *BeginLabel = nullptr; 6335 6336 if (EHPadBB) { 6337 // Insert a label before the invoke call to mark the try range. This can be 6338 // used to detect deletion of the invoke via the MachineModuleInfo. 6339 BeginLabel = MMI.getContext().createTempSymbol(); 6340 6341 // For SjLj, keep track of which landing pads go with which invokes 6342 // so as to maintain the ordering of pads in the LSDA. 6343 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6344 if (CallSiteIndex) { 6345 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6346 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6347 6348 // Now that the call site is handled, stop tracking it. 6349 MMI.setCurrentCallSite(0); 6350 } 6351 6352 // Both PendingLoads and PendingExports must be flushed here; 6353 // this call might not return. 6354 (void)getRoot(); 6355 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6356 6357 CLI.setChain(getRoot()); 6358 } 6359 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6360 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6361 6362 assert((CLI.IsTailCall || Result.second.getNode()) && 6363 "Non-null chain expected with non-tail call!"); 6364 assert((Result.second.getNode() || !Result.first.getNode()) && 6365 "Null value expected with tail call!"); 6366 6367 if (!Result.second.getNode()) { 6368 // As a special case, a null chain means that a tail call has been emitted 6369 // and the DAG root is already updated. 6370 HasTailCall = true; 6371 6372 // Since there's no actual continuation from this block, nothing can be 6373 // relying on us setting vregs for them. 6374 PendingExports.clear(); 6375 } else { 6376 DAG.setRoot(Result.second); 6377 } 6378 6379 if (EHPadBB) { 6380 // Insert a label at the end of the invoke call to mark the try range. This 6381 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6382 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6383 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6384 6385 // Inform MachineModuleInfo of range. 6386 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6387 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6388 // actually use outlined funclets and their LSDA info style. 6389 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6390 assert(CLI.CS); 6391 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6392 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6393 BeginLabel, EndLabel); 6394 } else { 6395 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6396 } 6397 } 6398 6399 return Result; 6400 } 6401 6402 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6403 bool isTailCall, 6404 const BasicBlock *EHPadBB) { 6405 auto &DL = DAG.getDataLayout(); 6406 FunctionType *FTy = CS.getFunctionType(); 6407 Type *RetTy = CS.getType(); 6408 6409 TargetLowering::ArgListTy Args; 6410 Args.reserve(CS.arg_size()); 6411 6412 const Value *SwiftErrorVal = nullptr; 6413 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6414 6415 // We can't tail call inside a function with a swifterror argument. Lowering 6416 // does not support this yet. It would have to move into the swifterror 6417 // register before the call. 6418 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6419 if (TLI.supportSwiftError() && 6420 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6421 isTailCall = false; 6422 6423 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6424 i != e; ++i) { 6425 TargetLowering::ArgListEntry Entry; 6426 const Value *V = *i; 6427 6428 // Skip empty types 6429 if (V->getType()->isEmptyTy()) 6430 continue; 6431 6432 SDValue ArgNode = getValue(V); 6433 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6434 6435 Entry.setAttributes(&CS, i - CS.arg_begin()); 6436 6437 // Use swifterror virtual register as input to the call. 6438 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6439 SwiftErrorVal = V; 6440 // We find the virtual register for the actual swifterror argument. 6441 // Instead of using the Value, we use the virtual register instead. 6442 Entry.Node = DAG.getRegister(FuncInfo 6443 .getOrCreateSwiftErrorVRegUseAt( 6444 CS.getInstruction(), FuncInfo.MBB, V) 6445 .first, 6446 EVT(TLI.getPointerTy(DL))); 6447 } 6448 6449 Args.push_back(Entry); 6450 6451 // If we have an explicit sret argument that is an Instruction, (i.e., it 6452 // might point to function-local memory), we can't meaningfully tail-call. 6453 if (Entry.IsSRet && isa<Instruction>(V)) 6454 isTailCall = false; 6455 } 6456 6457 // Check if target-independent constraints permit a tail call here. 6458 // Target-dependent constraints are checked within TLI->LowerCallTo. 6459 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6460 isTailCall = false; 6461 6462 // Disable tail calls if there is an swifterror argument. Targets have not 6463 // been updated to support tail calls. 6464 if (TLI.supportSwiftError() && SwiftErrorVal) 6465 isTailCall = false; 6466 6467 TargetLowering::CallLoweringInfo CLI(DAG); 6468 CLI.setDebugLoc(getCurSDLoc()) 6469 .setChain(getRoot()) 6470 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6471 .setTailCall(isTailCall) 6472 .setConvergent(CS.isConvergent()); 6473 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6474 6475 if (Result.first.getNode()) { 6476 const Instruction *Inst = CS.getInstruction(); 6477 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6478 setValue(Inst, Result.first); 6479 } 6480 6481 // The last element of CLI.InVals has the SDValue for swifterror return. 6482 // Here we copy it to a virtual register and update SwiftErrorMap for 6483 // book-keeping. 6484 if (SwiftErrorVal && TLI.supportSwiftError()) { 6485 // Get the last element of InVals. 6486 SDValue Src = CLI.InVals.back(); 6487 unsigned VReg; bool CreatedVReg; 6488 std::tie(VReg, CreatedVReg) = 6489 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6490 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6491 // We update the virtual register for the actual swifterror argument. 6492 if (CreatedVReg) 6493 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6494 DAG.setRoot(CopyNode); 6495 } 6496 } 6497 6498 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6499 SelectionDAGBuilder &Builder) { 6500 // Check to see if this load can be trivially constant folded, e.g. if the 6501 // input is from a string literal. 6502 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6503 // Cast pointer to the type we really want to load. 6504 Type *LoadTy = 6505 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6506 if (LoadVT.isVector()) 6507 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6508 6509 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6510 PointerType::getUnqual(LoadTy)); 6511 6512 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6513 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6514 return Builder.getValue(LoadCst); 6515 } 6516 6517 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6518 // still constant memory, the input chain can be the entry node. 6519 SDValue Root; 6520 bool ConstantMemory = false; 6521 6522 // Do not serialize (non-volatile) loads of constant memory with anything. 6523 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6524 Root = Builder.DAG.getEntryNode(); 6525 ConstantMemory = true; 6526 } else { 6527 // Do not serialize non-volatile loads against each other. 6528 Root = Builder.DAG.getRoot(); 6529 } 6530 6531 SDValue Ptr = Builder.getValue(PtrVal); 6532 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6533 Ptr, MachinePointerInfo(PtrVal), 6534 /* Alignment = */ 1); 6535 6536 if (!ConstantMemory) 6537 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6538 return LoadVal; 6539 } 6540 6541 /// Record the value for an instruction that produces an integer result, 6542 /// converting the type where necessary. 6543 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6544 SDValue Value, 6545 bool IsSigned) { 6546 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6547 I.getType(), true); 6548 if (IsSigned) 6549 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6550 else 6551 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6552 setValue(&I, Value); 6553 } 6554 6555 /// See if we can lower a memcmp call into an optimized form. If so, return 6556 /// true and lower it. Otherwise return false, and it will be lowered like a 6557 /// normal call. 6558 /// The caller already checked that \p I calls the appropriate LibFunc with a 6559 /// correct prototype. 6560 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6561 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6562 const Value *Size = I.getArgOperand(2); 6563 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6564 if (CSize && CSize->getZExtValue() == 0) { 6565 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6566 I.getType(), true); 6567 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6568 return true; 6569 } 6570 6571 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6572 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6573 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6574 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6575 if (Res.first.getNode()) { 6576 processIntegerCallValue(I, Res.first, true); 6577 PendingLoads.push_back(Res.second); 6578 return true; 6579 } 6580 6581 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6582 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6583 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6584 return false; 6585 6586 // If the target has a fast compare for the given size, it will return a 6587 // preferred load type for that size. Require that the load VT is legal and 6588 // that the target supports unaligned loads of that type. Otherwise, return 6589 // INVALID. 6590 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6592 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6593 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6594 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6595 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6596 // TODO: Check alignment of src and dest ptrs. 6597 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6598 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6599 if (!TLI.isTypeLegal(LVT) || 6600 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6601 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6602 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6603 } 6604 6605 return LVT; 6606 }; 6607 6608 // This turns into unaligned loads. We only do this if the target natively 6609 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6610 // we'll only produce a small number of byte loads. 6611 MVT LoadVT; 6612 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6613 switch (NumBitsToCompare) { 6614 default: 6615 return false; 6616 case 16: 6617 LoadVT = MVT::i16; 6618 break; 6619 case 32: 6620 LoadVT = MVT::i32; 6621 break; 6622 case 64: 6623 case 128: 6624 case 256: 6625 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6626 break; 6627 } 6628 6629 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6630 return false; 6631 6632 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6633 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6634 6635 // Bitcast to a wide integer type if the loads are vectors. 6636 if (LoadVT.isVector()) { 6637 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6638 LoadL = DAG.getBitcast(CmpVT, LoadL); 6639 LoadR = DAG.getBitcast(CmpVT, LoadR); 6640 } 6641 6642 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6643 processIntegerCallValue(I, Cmp, false); 6644 return true; 6645 } 6646 6647 /// See if we can lower a memchr call into an optimized form. If so, return 6648 /// true and lower it. Otherwise return false, and it will be lowered like a 6649 /// normal call. 6650 /// The caller already checked that \p I calls the appropriate LibFunc with a 6651 /// correct prototype. 6652 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6653 const Value *Src = I.getArgOperand(0); 6654 const Value *Char = I.getArgOperand(1); 6655 const Value *Length = I.getArgOperand(2); 6656 6657 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6658 std::pair<SDValue, SDValue> Res = 6659 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6660 getValue(Src), getValue(Char), getValue(Length), 6661 MachinePointerInfo(Src)); 6662 if (Res.first.getNode()) { 6663 setValue(&I, Res.first); 6664 PendingLoads.push_back(Res.second); 6665 return true; 6666 } 6667 6668 return false; 6669 } 6670 6671 /// See if we can lower a mempcpy call into an optimized form. If so, return 6672 /// true and lower it. Otherwise return false, and it will be lowered like a 6673 /// normal call. 6674 /// The caller already checked that \p I calls the appropriate LibFunc with a 6675 /// correct prototype. 6676 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6677 SDValue Dst = getValue(I.getArgOperand(0)); 6678 SDValue Src = getValue(I.getArgOperand(1)); 6679 SDValue Size = getValue(I.getArgOperand(2)); 6680 6681 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6682 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6683 unsigned Align = std::min(DstAlign, SrcAlign); 6684 if (Align == 0) // Alignment of one or both could not be inferred. 6685 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6686 6687 bool isVol = false; 6688 SDLoc sdl = getCurSDLoc(); 6689 6690 // In the mempcpy context we need to pass in a false value for isTailCall 6691 // because the return pointer needs to be adjusted by the size of 6692 // the copied memory. 6693 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6694 false, /*isTailCall=*/false, 6695 MachinePointerInfo(I.getArgOperand(0)), 6696 MachinePointerInfo(I.getArgOperand(1))); 6697 assert(MC.getNode() != nullptr && 6698 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6699 DAG.setRoot(MC); 6700 6701 // Check if Size needs to be truncated or extended. 6702 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6703 6704 // Adjust return pointer to point just past the last dst byte. 6705 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6706 Dst, Size); 6707 setValue(&I, DstPlusSize); 6708 return true; 6709 } 6710 6711 /// See if we can lower a strcpy call into an optimized form. If so, return 6712 /// true and lower it, otherwise return false and it will be lowered like a 6713 /// normal call. 6714 /// The caller already checked that \p I calls the appropriate LibFunc with a 6715 /// correct prototype. 6716 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6717 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6718 6719 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6720 std::pair<SDValue, SDValue> Res = 6721 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6722 getValue(Arg0), getValue(Arg1), 6723 MachinePointerInfo(Arg0), 6724 MachinePointerInfo(Arg1), isStpcpy); 6725 if (Res.first.getNode()) { 6726 setValue(&I, Res.first); 6727 DAG.setRoot(Res.second); 6728 return true; 6729 } 6730 6731 return false; 6732 } 6733 6734 /// See if we can lower a strcmp call into an optimized form. If so, return 6735 /// true and lower it, otherwise return false and it will be lowered like a 6736 /// normal call. 6737 /// The caller already checked that \p I calls the appropriate LibFunc with a 6738 /// correct prototype. 6739 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6740 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6741 6742 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6743 std::pair<SDValue, SDValue> Res = 6744 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6745 getValue(Arg0), getValue(Arg1), 6746 MachinePointerInfo(Arg0), 6747 MachinePointerInfo(Arg1)); 6748 if (Res.first.getNode()) { 6749 processIntegerCallValue(I, Res.first, true); 6750 PendingLoads.push_back(Res.second); 6751 return true; 6752 } 6753 6754 return false; 6755 } 6756 6757 /// See if we can lower a strlen call into an optimized form. If so, return 6758 /// true and lower it, otherwise return false and it will be lowered like a 6759 /// normal call. 6760 /// The caller already checked that \p I calls the appropriate LibFunc with a 6761 /// correct prototype. 6762 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6763 const Value *Arg0 = I.getArgOperand(0); 6764 6765 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6766 std::pair<SDValue, SDValue> Res = 6767 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6768 getValue(Arg0), MachinePointerInfo(Arg0)); 6769 if (Res.first.getNode()) { 6770 processIntegerCallValue(I, Res.first, false); 6771 PendingLoads.push_back(Res.second); 6772 return true; 6773 } 6774 6775 return false; 6776 } 6777 6778 /// See if we can lower a strnlen call into an optimized form. If so, return 6779 /// true and lower it, otherwise return false and it will be lowered like a 6780 /// normal call. 6781 /// The caller already checked that \p I calls the appropriate LibFunc with a 6782 /// correct prototype. 6783 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6784 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6785 6786 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6787 std::pair<SDValue, SDValue> Res = 6788 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6789 getValue(Arg0), getValue(Arg1), 6790 MachinePointerInfo(Arg0)); 6791 if (Res.first.getNode()) { 6792 processIntegerCallValue(I, Res.first, false); 6793 PendingLoads.push_back(Res.second); 6794 return true; 6795 } 6796 6797 return false; 6798 } 6799 6800 /// See if we can lower a unary floating-point operation into an SDNode with 6801 /// the specified Opcode. If so, return true and lower it, otherwise return 6802 /// false and it will be lowered like a normal call. 6803 /// The caller already checked that \p I calls the appropriate LibFunc with a 6804 /// correct prototype. 6805 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6806 unsigned Opcode) { 6807 // We already checked this call's prototype; verify it doesn't modify errno. 6808 if (!I.onlyReadsMemory()) 6809 return false; 6810 6811 SDValue Tmp = getValue(I.getArgOperand(0)); 6812 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6813 return true; 6814 } 6815 6816 /// See if we can lower a binary floating-point operation into an SDNode with 6817 /// the specified Opcode. If so, return true and lower it. Otherwise return 6818 /// false, and it will be lowered like a normal call. 6819 /// The caller already checked that \p I calls the appropriate LibFunc with a 6820 /// correct prototype. 6821 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6822 unsigned Opcode) { 6823 // We already checked this call's prototype; verify it doesn't modify errno. 6824 if (!I.onlyReadsMemory()) 6825 return false; 6826 6827 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6828 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6829 EVT VT = Tmp0.getValueType(); 6830 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6831 return true; 6832 } 6833 6834 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6835 // Handle inline assembly differently. 6836 if (isa<InlineAsm>(I.getCalledValue())) { 6837 visitInlineAsm(&I); 6838 return; 6839 } 6840 6841 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6842 computeUsesVAFloatArgument(I, MMI); 6843 6844 const char *RenameFn = nullptr; 6845 if (Function *F = I.getCalledFunction()) { 6846 if (F->isDeclaration()) { 6847 // Is this an LLVM intrinsic or a target-specific intrinsic? 6848 unsigned IID = F->getIntrinsicID(); 6849 if (!IID) 6850 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6851 IID = II->getIntrinsicID(F); 6852 6853 if (IID) { 6854 RenameFn = visitIntrinsicCall(I, IID); 6855 if (!RenameFn) 6856 return; 6857 } 6858 } 6859 6860 // Check for well-known libc/libm calls. If the function is internal, it 6861 // can't be a library call. Don't do the check if marked as nobuiltin for 6862 // some reason or the call site requires strict floating point semantics. 6863 LibFunc Func; 6864 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6865 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6866 LibInfo->hasOptimizedCodeGen(Func)) { 6867 switch (Func) { 6868 default: break; 6869 case LibFunc_copysign: 6870 case LibFunc_copysignf: 6871 case LibFunc_copysignl: 6872 // We already checked this call's prototype; verify it doesn't modify 6873 // errno. 6874 if (I.onlyReadsMemory()) { 6875 SDValue LHS = getValue(I.getArgOperand(0)); 6876 SDValue RHS = getValue(I.getArgOperand(1)); 6877 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6878 LHS.getValueType(), LHS, RHS)); 6879 return; 6880 } 6881 break; 6882 case LibFunc_fabs: 6883 case LibFunc_fabsf: 6884 case LibFunc_fabsl: 6885 if (visitUnaryFloatCall(I, ISD::FABS)) 6886 return; 6887 break; 6888 case LibFunc_fmin: 6889 case LibFunc_fminf: 6890 case LibFunc_fminl: 6891 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6892 return; 6893 break; 6894 case LibFunc_fmax: 6895 case LibFunc_fmaxf: 6896 case LibFunc_fmaxl: 6897 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6898 return; 6899 break; 6900 case LibFunc_sin: 6901 case LibFunc_sinf: 6902 case LibFunc_sinl: 6903 if (visitUnaryFloatCall(I, ISD::FSIN)) 6904 return; 6905 break; 6906 case LibFunc_cos: 6907 case LibFunc_cosf: 6908 case LibFunc_cosl: 6909 if (visitUnaryFloatCall(I, ISD::FCOS)) 6910 return; 6911 break; 6912 case LibFunc_sqrt: 6913 case LibFunc_sqrtf: 6914 case LibFunc_sqrtl: 6915 case LibFunc_sqrt_finite: 6916 case LibFunc_sqrtf_finite: 6917 case LibFunc_sqrtl_finite: 6918 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6919 return; 6920 break; 6921 case LibFunc_floor: 6922 case LibFunc_floorf: 6923 case LibFunc_floorl: 6924 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6925 return; 6926 break; 6927 case LibFunc_nearbyint: 6928 case LibFunc_nearbyintf: 6929 case LibFunc_nearbyintl: 6930 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6931 return; 6932 break; 6933 case LibFunc_ceil: 6934 case LibFunc_ceilf: 6935 case LibFunc_ceill: 6936 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6937 return; 6938 break; 6939 case LibFunc_rint: 6940 case LibFunc_rintf: 6941 case LibFunc_rintl: 6942 if (visitUnaryFloatCall(I, ISD::FRINT)) 6943 return; 6944 break; 6945 case LibFunc_round: 6946 case LibFunc_roundf: 6947 case LibFunc_roundl: 6948 if (visitUnaryFloatCall(I, ISD::FROUND)) 6949 return; 6950 break; 6951 case LibFunc_trunc: 6952 case LibFunc_truncf: 6953 case LibFunc_truncl: 6954 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6955 return; 6956 break; 6957 case LibFunc_log2: 6958 case LibFunc_log2f: 6959 case LibFunc_log2l: 6960 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6961 return; 6962 break; 6963 case LibFunc_exp2: 6964 case LibFunc_exp2f: 6965 case LibFunc_exp2l: 6966 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6967 return; 6968 break; 6969 case LibFunc_memcmp: 6970 if (visitMemCmpCall(I)) 6971 return; 6972 break; 6973 case LibFunc_mempcpy: 6974 if (visitMemPCpyCall(I)) 6975 return; 6976 break; 6977 case LibFunc_memchr: 6978 if (visitMemChrCall(I)) 6979 return; 6980 break; 6981 case LibFunc_strcpy: 6982 if (visitStrCpyCall(I, false)) 6983 return; 6984 break; 6985 case LibFunc_stpcpy: 6986 if (visitStrCpyCall(I, true)) 6987 return; 6988 break; 6989 case LibFunc_strcmp: 6990 if (visitStrCmpCall(I)) 6991 return; 6992 break; 6993 case LibFunc_strlen: 6994 if (visitStrLenCall(I)) 6995 return; 6996 break; 6997 case LibFunc_strnlen: 6998 if (visitStrNLenCall(I)) 6999 return; 7000 break; 7001 } 7002 } 7003 } 7004 7005 SDValue Callee; 7006 if (!RenameFn) 7007 Callee = getValue(I.getCalledValue()); 7008 else 7009 Callee = DAG.getExternalSymbol( 7010 RenameFn, 7011 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7012 7013 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7014 // have to do anything here to lower funclet bundles. 7015 assert(!I.hasOperandBundlesOtherThan( 7016 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7017 "Cannot lower calls with arbitrary operand bundles!"); 7018 7019 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7020 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7021 else 7022 // Check if we can potentially perform a tail call. More detailed checking 7023 // is be done within LowerCallTo, after more information about the call is 7024 // known. 7025 LowerCallTo(&I, Callee, I.isTailCall()); 7026 } 7027 7028 namespace { 7029 7030 /// AsmOperandInfo - This contains information for each constraint that we are 7031 /// lowering. 7032 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7033 public: 7034 /// CallOperand - If this is the result output operand or a clobber 7035 /// this is null, otherwise it is the incoming operand to the CallInst. 7036 /// This gets modified as the asm is processed. 7037 SDValue CallOperand; 7038 7039 /// AssignedRegs - If this is a register or register class operand, this 7040 /// contains the set of register corresponding to the operand. 7041 RegsForValue AssignedRegs; 7042 7043 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7044 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7045 } 7046 7047 /// Whether or not this operand accesses memory 7048 bool hasMemory(const TargetLowering &TLI) const { 7049 // Indirect operand accesses access memory. 7050 if (isIndirect) 7051 return true; 7052 7053 for (const auto &Code : Codes) 7054 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7055 return true; 7056 7057 return false; 7058 } 7059 7060 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7061 /// corresponds to. If there is no Value* for this operand, it returns 7062 /// MVT::Other. 7063 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7064 const DataLayout &DL) const { 7065 if (!CallOperandVal) return MVT::Other; 7066 7067 if (isa<BasicBlock>(CallOperandVal)) 7068 return TLI.getPointerTy(DL); 7069 7070 llvm::Type *OpTy = CallOperandVal->getType(); 7071 7072 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7073 // If this is an indirect operand, the operand is a pointer to the 7074 // accessed type. 7075 if (isIndirect) { 7076 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7077 if (!PtrTy) 7078 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7079 OpTy = PtrTy->getElementType(); 7080 } 7081 7082 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7083 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7084 if (STy->getNumElements() == 1) 7085 OpTy = STy->getElementType(0); 7086 7087 // If OpTy is not a single value, it may be a struct/union that we 7088 // can tile with integers. 7089 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7090 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7091 switch (BitSize) { 7092 default: break; 7093 case 1: 7094 case 8: 7095 case 16: 7096 case 32: 7097 case 64: 7098 case 128: 7099 OpTy = IntegerType::get(Context, BitSize); 7100 break; 7101 } 7102 } 7103 7104 return TLI.getValueType(DL, OpTy, true); 7105 } 7106 }; 7107 7108 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7109 7110 } // end anonymous namespace 7111 7112 /// Make sure that the output operand \p OpInfo and its corresponding input 7113 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7114 /// out). 7115 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7116 SDISelAsmOperandInfo &MatchingOpInfo, 7117 SelectionDAG &DAG) { 7118 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7119 return; 7120 7121 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7122 const auto &TLI = DAG.getTargetLoweringInfo(); 7123 7124 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7125 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7126 OpInfo.ConstraintVT); 7127 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7128 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7129 MatchingOpInfo.ConstraintVT); 7130 if ((OpInfo.ConstraintVT.isInteger() != 7131 MatchingOpInfo.ConstraintVT.isInteger()) || 7132 (MatchRC.second != InputRC.second)) { 7133 // FIXME: error out in a more elegant fashion 7134 report_fatal_error("Unsupported asm: input constraint" 7135 " with a matching output constraint of" 7136 " incompatible type!"); 7137 } 7138 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7139 } 7140 7141 /// Get a direct memory input to behave well as an indirect operand. 7142 /// This may introduce stores, hence the need for a \p Chain. 7143 /// \return The (possibly updated) chain. 7144 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7145 SDISelAsmOperandInfo &OpInfo, 7146 SelectionDAG &DAG) { 7147 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7148 7149 // If we don't have an indirect input, put it in the constpool if we can, 7150 // otherwise spill it to a stack slot. 7151 // TODO: This isn't quite right. We need to handle these according to 7152 // the addressing mode that the constraint wants. Also, this may take 7153 // an additional register for the computation and we don't want that 7154 // either. 7155 7156 // If the operand is a float, integer, or vector constant, spill to a 7157 // constant pool entry to get its address. 7158 const Value *OpVal = OpInfo.CallOperandVal; 7159 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7160 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7161 OpInfo.CallOperand = DAG.getConstantPool( 7162 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7163 return Chain; 7164 } 7165 7166 // Otherwise, create a stack slot and emit a store to it before the asm. 7167 Type *Ty = OpVal->getType(); 7168 auto &DL = DAG.getDataLayout(); 7169 uint64_t TySize = DL.getTypeAllocSize(Ty); 7170 unsigned Align = DL.getPrefTypeAlignment(Ty); 7171 MachineFunction &MF = DAG.getMachineFunction(); 7172 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7173 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7174 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7175 MachinePointerInfo::getFixedStack(MF, SSFI)); 7176 OpInfo.CallOperand = StackSlot; 7177 7178 return Chain; 7179 } 7180 7181 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7182 /// specified operand. We prefer to assign virtual registers, to allow the 7183 /// register allocator to handle the assignment process. However, if the asm 7184 /// uses features that we can't model on machineinstrs, we have SDISel do the 7185 /// allocation. This produces generally horrible, but correct, code. 7186 /// 7187 /// OpInfo describes the operand. 7188 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7189 const SDLoc &DL, 7190 SDISelAsmOperandInfo &OpInfo) { 7191 LLVMContext &Context = *DAG.getContext(); 7192 7193 MachineFunction &MF = DAG.getMachineFunction(); 7194 SmallVector<unsigned, 4> Regs; 7195 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7196 7197 // If this is a constraint for a single physreg, or a constraint for a 7198 // register class, find it. 7199 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7200 TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode, 7201 OpInfo.ConstraintVT); 7202 7203 unsigned NumRegs = 1; 7204 if (OpInfo.ConstraintVT != MVT::Other) { 7205 // If this is a FP operand in an integer register (or visa versa), or more 7206 // generally if the operand value disagrees with the register class we plan 7207 // to stick it in, fix the operand type. 7208 // 7209 // If this is an input value, the bitcast to the new type is done now. 7210 // Bitcast for output value is done at the end of visitInlineAsm(). 7211 if ((OpInfo.Type == InlineAsm::isOutput || 7212 OpInfo.Type == InlineAsm::isInput) && 7213 PhysReg.second && 7214 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7215 // Try to convert to the first EVT that the reg class contains. If the 7216 // types are identical size, use a bitcast to convert (e.g. two differing 7217 // vector types). Note: output bitcast is done at the end of 7218 // visitInlineAsm(). 7219 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7220 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7221 // Exclude indirect inputs while they are unsupported because the code 7222 // to perform the load is missing and thus OpInfo.CallOperand still 7223 // refer to the input address rather than the pointed-to value. 7224 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7225 OpInfo.CallOperand = 7226 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7227 OpInfo.ConstraintVT = RegVT; 7228 // If the operand is a FP value and we want it in integer registers, 7229 // use the corresponding integer type. This turns an f64 value into 7230 // i64, which can be passed with two i32 values on a 32-bit machine. 7231 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7232 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7233 if (OpInfo.Type == InlineAsm::isInput) 7234 OpInfo.CallOperand = 7235 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7236 OpInfo.ConstraintVT = RegVT; 7237 } 7238 } 7239 7240 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7241 } 7242 7243 MVT RegVT; 7244 EVT ValueVT = OpInfo.ConstraintVT; 7245 7246 // If this is a constraint for a specific physical register, like {r17}, 7247 // assign it now. 7248 if (unsigned AssignedReg = PhysReg.first) { 7249 const TargetRegisterClass *RC = PhysReg.second; 7250 if (OpInfo.ConstraintVT == MVT::Other) 7251 ValueVT = *TRI.legalclasstypes_begin(*RC); 7252 7253 // Get the actual register value type. This is important, because the user 7254 // may have asked for (e.g.) the AX register in i32 type. We need to 7255 // remember that AX is actually i16 to get the right extension. 7256 RegVT = *TRI.legalclasstypes_begin(*RC); 7257 7258 // This is a explicit reference to a physical register. 7259 Regs.push_back(AssignedReg); 7260 7261 // If this is an expanded reference, add the rest of the regs to Regs. 7262 if (NumRegs != 1) { 7263 TargetRegisterClass::iterator I = RC->begin(); 7264 for (; *I != AssignedReg; ++I) 7265 assert(I != RC->end() && "Didn't find reg!"); 7266 7267 // Already added the first reg. 7268 --NumRegs; ++I; 7269 for (; NumRegs; --NumRegs, ++I) { 7270 assert(I != RC->end() && "Ran out of registers to allocate!"); 7271 Regs.push_back(*I); 7272 } 7273 } 7274 7275 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7276 return; 7277 } 7278 7279 // Otherwise, if this was a reference to an LLVM register class, create vregs 7280 // for this reference. 7281 if (const TargetRegisterClass *RC = PhysReg.second) { 7282 RegVT = *TRI.legalclasstypes_begin(*RC); 7283 if (OpInfo.ConstraintVT == MVT::Other) 7284 ValueVT = RegVT; 7285 7286 // Create the appropriate number of virtual registers. 7287 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7288 for (; NumRegs; --NumRegs) 7289 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7290 7291 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7292 return; 7293 } 7294 7295 // Otherwise, we couldn't allocate enough registers for this. 7296 } 7297 7298 static unsigned 7299 findMatchingInlineAsmOperand(unsigned OperandNo, 7300 const std::vector<SDValue> &AsmNodeOperands) { 7301 // Scan until we find the definition we already emitted of this operand. 7302 unsigned CurOp = InlineAsm::Op_FirstOperand; 7303 for (; OperandNo; --OperandNo) { 7304 // Advance to the next operand. 7305 unsigned OpFlag = 7306 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7307 assert((InlineAsm::isRegDefKind(OpFlag) || 7308 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7309 InlineAsm::isMemKind(OpFlag)) && 7310 "Skipped past definitions?"); 7311 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7312 } 7313 return CurOp; 7314 } 7315 7316 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7317 /// \return true if it has succeeded, false otherwise 7318 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7319 MVT RegVT, SelectionDAG &DAG) { 7320 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7321 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7322 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7323 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7324 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7325 else 7326 return false; 7327 } 7328 return true; 7329 } 7330 7331 namespace { 7332 7333 class ExtraFlags { 7334 unsigned Flags = 0; 7335 7336 public: 7337 explicit ExtraFlags(ImmutableCallSite CS) { 7338 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7339 if (IA->hasSideEffects()) 7340 Flags |= InlineAsm::Extra_HasSideEffects; 7341 if (IA->isAlignStack()) 7342 Flags |= InlineAsm::Extra_IsAlignStack; 7343 if (CS.isConvergent()) 7344 Flags |= InlineAsm::Extra_IsConvergent; 7345 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7346 } 7347 7348 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7349 // Ideally, we would only check against memory constraints. However, the 7350 // meaning of an Other constraint can be target-specific and we can't easily 7351 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7352 // for Other constraints as well. 7353 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7354 OpInfo.ConstraintType == TargetLowering::C_Other) { 7355 if (OpInfo.Type == InlineAsm::isInput) 7356 Flags |= InlineAsm::Extra_MayLoad; 7357 else if (OpInfo.Type == InlineAsm::isOutput) 7358 Flags |= InlineAsm::Extra_MayStore; 7359 else if (OpInfo.Type == InlineAsm::isClobber) 7360 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7361 } 7362 } 7363 7364 unsigned get() const { return Flags; } 7365 }; 7366 7367 } // end anonymous namespace 7368 7369 /// visitInlineAsm - Handle a call to an InlineAsm object. 7370 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7371 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7372 7373 /// ConstraintOperands - Information about all of the constraints. 7374 SDISelAsmOperandInfoVector ConstraintOperands; 7375 7376 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7377 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7378 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7379 7380 bool hasMemory = false; 7381 7382 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7383 ExtraFlags ExtraInfo(CS); 7384 7385 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7386 unsigned ResNo = 0; // ResNo - The result number of the next output. 7387 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7388 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7389 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7390 7391 MVT OpVT = MVT::Other; 7392 7393 // Compute the value type for each operand. 7394 if (OpInfo.Type == InlineAsm::isInput || 7395 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7396 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7397 7398 // Process the call argument. BasicBlocks are labels, currently appearing 7399 // only in asm's. 7400 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7401 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7402 } else { 7403 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7404 } 7405 7406 OpVT = 7407 OpInfo 7408 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7409 .getSimpleVT(); 7410 } 7411 7412 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7413 // The return value of the call is this value. As such, there is no 7414 // corresponding argument. 7415 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7416 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7417 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7418 STy->getElementType(ResNo)); 7419 } else { 7420 assert(ResNo == 0 && "Asm only has one result!"); 7421 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7422 } 7423 ++ResNo; 7424 } 7425 7426 OpInfo.ConstraintVT = OpVT; 7427 7428 if (!hasMemory) 7429 hasMemory = OpInfo.hasMemory(TLI); 7430 7431 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7432 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7433 auto TargetConstraint = TargetConstraints[i]; 7434 7435 // Compute the constraint code and ConstraintType to use. 7436 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7437 7438 ExtraInfo.update(TargetConstraint); 7439 } 7440 7441 SDValue Chain, Flag; 7442 7443 // We won't need to flush pending loads if this asm doesn't touch 7444 // memory and is nonvolatile. 7445 if (hasMemory || IA->hasSideEffects()) 7446 Chain = getRoot(); 7447 else 7448 Chain = DAG.getRoot(); 7449 7450 // Second pass over the constraints: compute which constraint option to use 7451 // and assign registers to constraints that want a specific physreg. 7452 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7453 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7454 7455 // If this is an output operand with a matching input operand, look up the 7456 // matching input. If their types mismatch, e.g. one is an integer, the 7457 // other is floating point, or their sizes are different, flag it as an 7458 // error. 7459 if (OpInfo.hasMatchingInput()) { 7460 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7461 patchMatchingInput(OpInfo, Input, DAG); 7462 } 7463 7464 // Compute the constraint code and ConstraintType to use. 7465 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7466 7467 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7468 OpInfo.Type == InlineAsm::isClobber) 7469 continue; 7470 7471 // If this is a memory input, and if the operand is not indirect, do what we 7472 // need to provide an address for the memory input. 7473 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7474 !OpInfo.isIndirect) { 7475 assert((OpInfo.isMultipleAlternative || 7476 (OpInfo.Type == InlineAsm::isInput)) && 7477 "Can only indirectify direct input operands!"); 7478 7479 // Memory operands really want the address of the value. 7480 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7481 7482 // There is no longer a Value* corresponding to this operand. 7483 OpInfo.CallOperandVal = nullptr; 7484 7485 // It is now an indirect operand. 7486 OpInfo.isIndirect = true; 7487 } 7488 7489 // If this constraint is for a specific register, allocate it before 7490 // anything else. 7491 if (OpInfo.ConstraintType == TargetLowering::C_Register) 7492 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7493 } 7494 7495 // Third pass - Loop over all of the operands, assigning virtual or physregs 7496 // to register class operands. 7497 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7498 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7499 7500 // C_Register operands have already been allocated, Other/Memory don't need 7501 // to be. 7502 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7503 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7504 } 7505 7506 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7507 std::vector<SDValue> AsmNodeOperands; 7508 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7509 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7510 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7511 7512 // If we have a !srcloc metadata node associated with it, we want to attach 7513 // this to the ultimately generated inline asm machineinstr. To do this, we 7514 // pass in the third operand as this (potentially null) inline asm MDNode. 7515 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7516 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7517 7518 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7519 // bits as operand 3. 7520 AsmNodeOperands.push_back(DAG.getTargetConstant( 7521 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7522 7523 // Loop over all of the inputs, copying the operand values into the 7524 // appropriate registers and processing the output regs. 7525 RegsForValue RetValRegs; 7526 7527 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7528 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7529 7530 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7531 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7532 7533 switch (OpInfo.Type) { 7534 case InlineAsm::isOutput: 7535 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7536 OpInfo.ConstraintType != TargetLowering::C_Register) { 7537 // Memory output, or 'other' output (e.g. 'X' constraint). 7538 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7539 7540 unsigned ConstraintID = 7541 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7542 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7543 "Failed to convert memory constraint code to constraint id."); 7544 7545 // Add information to the INLINEASM node to know about this output. 7546 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7547 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7548 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7549 MVT::i32)); 7550 AsmNodeOperands.push_back(OpInfo.CallOperand); 7551 break; 7552 } 7553 7554 // Otherwise, this is a register or register class output. 7555 7556 // Copy the output from the appropriate register. Find a register that 7557 // we can use. 7558 if (OpInfo.AssignedRegs.Regs.empty()) { 7559 emitInlineAsmError( 7560 CS, "couldn't allocate output register for constraint '" + 7561 Twine(OpInfo.ConstraintCode) + "'"); 7562 return; 7563 } 7564 7565 // If this is an indirect operand, store through the pointer after the 7566 // asm. 7567 if (OpInfo.isIndirect) { 7568 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7569 OpInfo.CallOperandVal)); 7570 } else { 7571 // This is the result value of the call. 7572 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7573 // Concatenate this output onto the outputs list. 7574 RetValRegs.append(OpInfo.AssignedRegs); 7575 } 7576 7577 // Add information to the INLINEASM node to know that this register is 7578 // set. 7579 OpInfo.AssignedRegs 7580 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7581 ? InlineAsm::Kind_RegDefEarlyClobber 7582 : InlineAsm::Kind_RegDef, 7583 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7584 break; 7585 7586 case InlineAsm::isInput: { 7587 SDValue InOperandVal = OpInfo.CallOperand; 7588 7589 if (OpInfo.isMatchingInputConstraint()) { 7590 // If this is required to match an output register we have already set, 7591 // just use its register. 7592 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7593 AsmNodeOperands); 7594 unsigned OpFlag = 7595 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7596 if (InlineAsm::isRegDefKind(OpFlag) || 7597 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7598 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7599 if (OpInfo.isIndirect) { 7600 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7601 emitInlineAsmError(CS, "inline asm not supported yet:" 7602 " don't know how to handle tied " 7603 "indirect register inputs"); 7604 return; 7605 } 7606 7607 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7608 SmallVector<unsigned, 4> Regs; 7609 7610 if (!createVirtualRegs(Regs, 7611 InlineAsm::getNumOperandRegisters(OpFlag), 7612 RegVT, DAG)) { 7613 emitInlineAsmError(CS, "inline asm error: This value type register " 7614 "class is not natively supported!"); 7615 return; 7616 } 7617 7618 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7619 7620 SDLoc dl = getCurSDLoc(); 7621 // Use the produced MatchedRegs object to 7622 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7623 CS.getInstruction()); 7624 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7625 true, OpInfo.getMatchedOperand(), dl, 7626 DAG, AsmNodeOperands); 7627 break; 7628 } 7629 7630 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7631 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7632 "Unexpected number of operands"); 7633 // Add information to the INLINEASM node to know about this input. 7634 // See InlineAsm.h isUseOperandTiedToDef. 7635 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7636 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7637 OpInfo.getMatchedOperand()); 7638 AsmNodeOperands.push_back(DAG.getTargetConstant( 7639 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7640 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7641 break; 7642 } 7643 7644 // Treat indirect 'X' constraint as memory. 7645 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7646 OpInfo.isIndirect) 7647 OpInfo.ConstraintType = TargetLowering::C_Memory; 7648 7649 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7650 std::vector<SDValue> Ops; 7651 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7652 Ops, DAG); 7653 if (Ops.empty()) { 7654 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7655 Twine(OpInfo.ConstraintCode) + "'"); 7656 return; 7657 } 7658 7659 // Add information to the INLINEASM node to know about this input. 7660 unsigned ResOpType = 7661 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7662 AsmNodeOperands.push_back(DAG.getTargetConstant( 7663 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7664 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7665 break; 7666 } 7667 7668 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7669 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7670 assert(InOperandVal.getValueType() == 7671 TLI.getPointerTy(DAG.getDataLayout()) && 7672 "Memory operands expect pointer values"); 7673 7674 unsigned ConstraintID = 7675 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7676 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7677 "Failed to convert memory constraint code to constraint id."); 7678 7679 // Add information to the INLINEASM node to know about this input. 7680 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7681 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7682 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7683 getCurSDLoc(), 7684 MVT::i32)); 7685 AsmNodeOperands.push_back(InOperandVal); 7686 break; 7687 } 7688 7689 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7690 OpInfo.ConstraintType == TargetLowering::C_Register) && 7691 "Unknown constraint type!"); 7692 7693 // TODO: Support this. 7694 if (OpInfo.isIndirect) { 7695 emitInlineAsmError( 7696 CS, "Don't know how to handle indirect register inputs yet " 7697 "for constraint '" + 7698 Twine(OpInfo.ConstraintCode) + "'"); 7699 return; 7700 } 7701 7702 // Copy the input into the appropriate registers. 7703 if (OpInfo.AssignedRegs.Regs.empty()) { 7704 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7705 Twine(OpInfo.ConstraintCode) + "'"); 7706 return; 7707 } 7708 7709 SDLoc dl = getCurSDLoc(); 7710 7711 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7712 Chain, &Flag, CS.getInstruction()); 7713 7714 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7715 dl, DAG, AsmNodeOperands); 7716 break; 7717 } 7718 case InlineAsm::isClobber: 7719 // Add the clobbered value to the operand list, so that the register 7720 // allocator is aware that the physreg got clobbered. 7721 if (!OpInfo.AssignedRegs.Regs.empty()) 7722 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7723 false, 0, getCurSDLoc(), DAG, 7724 AsmNodeOperands); 7725 break; 7726 } 7727 } 7728 7729 // Finish up input operands. Set the input chain and add the flag last. 7730 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7731 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7732 7733 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7734 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7735 Flag = Chain.getValue(1); 7736 7737 // If this asm returns a register value, copy the result from that register 7738 // and set it as the value of the call. 7739 if (!RetValRegs.Regs.empty()) { 7740 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7741 Chain, &Flag, CS.getInstruction()); 7742 7743 // FIXME: Why don't we do this for inline asms with MRVs? 7744 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7745 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7746 7747 // If the type of the inline asm call site return value is different but 7748 // has same size as the type of the asm output bitcast it. One example 7749 // of this is for vectors with different width / number of elements. 7750 // This can happen for register classes that can contain multiple 7751 // different value types. The preg or vreg allocated may not have the 7752 // same VT as was expected. 7753 // 7754 // This can also happen for a return value that disagrees with the 7755 // register class it is put in, eg. a double in a general-purpose 7756 // register on a 32-bit machine. 7757 if (ResultType != Val.getValueType() && 7758 ResultType.getSizeInBits() == Val.getValueSizeInBits()) { 7759 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7760 ResultType, Val); 7761 7762 } else if (ResultType != Val.getValueType() && 7763 ResultType.isInteger() && Val.getValueType().isInteger()) { 7764 // If a result value was tied to an input value, the computed result may 7765 // have a wider width than the expected result. Extract the relevant 7766 // portion. 7767 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7768 } 7769 7770 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7771 } 7772 7773 setValue(CS.getInstruction(), Val); 7774 // Don't need to use this as a chain in this case. 7775 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7776 return; 7777 } 7778 7779 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7780 7781 // Process indirect outputs, first output all of the flagged copies out of 7782 // physregs. 7783 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7784 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7785 const Value *Ptr = IndirectStoresToEmit[i].second; 7786 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7787 Chain, &Flag, IA); 7788 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7789 } 7790 7791 // Emit the non-flagged stores from the physregs. 7792 SmallVector<SDValue, 8> OutChains; 7793 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7794 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7795 getValue(StoresToEmit[i].second), 7796 MachinePointerInfo(StoresToEmit[i].second)); 7797 OutChains.push_back(Val); 7798 } 7799 7800 if (!OutChains.empty()) 7801 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7802 7803 DAG.setRoot(Chain); 7804 } 7805 7806 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7807 const Twine &Message) { 7808 LLVMContext &Ctx = *DAG.getContext(); 7809 Ctx.emitError(CS.getInstruction(), Message); 7810 7811 // Make sure we leave the DAG in a valid state 7812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7813 SmallVector<EVT, 1> ValueVTs; 7814 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7815 7816 if (ValueVTs.empty()) 7817 return; 7818 7819 SmallVector<SDValue, 1> Ops; 7820 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7821 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7822 7823 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7824 } 7825 7826 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7827 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7828 MVT::Other, getRoot(), 7829 getValue(I.getArgOperand(0)), 7830 DAG.getSrcValue(I.getArgOperand(0)))); 7831 } 7832 7833 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7835 const DataLayout &DL = DAG.getDataLayout(); 7836 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7837 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7838 DAG.getSrcValue(I.getOperand(0)), 7839 DL.getABITypeAlignment(I.getType())); 7840 setValue(&I, V); 7841 DAG.setRoot(V.getValue(1)); 7842 } 7843 7844 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7845 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7846 MVT::Other, getRoot(), 7847 getValue(I.getArgOperand(0)), 7848 DAG.getSrcValue(I.getArgOperand(0)))); 7849 } 7850 7851 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7852 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7853 MVT::Other, getRoot(), 7854 getValue(I.getArgOperand(0)), 7855 getValue(I.getArgOperand(1)), 7856 DAG.getSrcValue(I.getArgOperand(0)), 7857 DAG.getSrcValue(I.getArgOperand(1)))); 7858 } 7859 7860 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7861 const Instruction &I, 7862 SDValue Op) { 7863 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7864 if (!Range) 7865 return Op; 7866 7867 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7868 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7869 return Op; 7870 7871 APInt Lo = CR.getUnsignedMin(); 7872 if (!Lo.isMinValue()) 7873 return Op; 7874 7875 APInt Hi = CR.getUnsignedMax(); 7876 unsigned Bits = Hi.getActiveBits(); 7877 7878 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7879 7880 SDLoc SL = getCurSDLoc(); 7881 7882 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7883 DAG.getValueType(SmallVT)); 7884 unsigned NumVals = Op.getNode()->getNumValues(); 7885 if (NumVals == 1) 7886 return ZExt; 7887 7888 SmallVector<SDValue, 4> Ops; 7889 7890 Ops.push_back(ZExt); 7891 for (unsigned I = 1; I != NumVals; ++I) 7892 Ops.push_back(Op.getValue(I)); 7893 7894 return DAG.getMergeValues(Ops, SL); 7895 } 7896 7897 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 7898 /// the call being lowered. 7899 /// 7900 /// This is a helper for lowering intrinsics that follow a target calling 7901 /// convention or require stack pointer adjustment. Only a subset of the 7902 /// intrinsic's operands need to participate in the calling convention. 7903 void SelectionDAGBuilder::populateCallLoweringInfo( 7904 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7905 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7906 bool IsPatchPoint) { 7907 TargetLowering::ArgListTy Args; 7908 Args.reserve(NumArgs); 7909 7910 // Populate the argument list. 7911 // Attributes for args start at offset 1, after the return attribute. 7912 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7913 ArgI != ArgE; ++ArgI) { 7914 const Value *V = CS->getOperand(ArgI); 7915 7916 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7917 7918 TargetLowering::ArgListEntry Entry; 7919 Entry.Node = getValue(V); 7920 Entry.Ty = V->getType(); 7921 Entry.setAttributes(&CS, ArgI); 7922 Args.push_back(Entry); 7923 } 7924 7925 CLI.setDebugLoc(getCurSDLoc()) 7926 .setChain(getRoot()) 7927 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7928 .setDiscardResult(CS->use_empty()) 7929 .setIsPatchPoint(IsPatchPoint); 7930 } 7931 7932 /// Add a stack map intrinsic call's live variable operands to a stackmap 7933 /// or patchpoint target node's operand list. 7934 /// 7935 /// Constants are converted to TargetConstants purely as an optimization to 7936 /// avoid constant materialization and register allocation. 7937 /// 7938 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7939 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7940 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7941 /// address materialization and register allocation, but may also be required 7942 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7943 /// alloca in the entry block, then the runtime may assume that the alloca's 7944 /// StackMap location can be read immediately after compilation and that the 7945 /// location is valid at any point during execution (this is similar to the 7946 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7947 /// only available in a register, then the runtime would need to trap when 7948 /// execution reaches the StackMap in order to read the alloca's location. 7949 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7950 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7951 SelectionDAGBuilder &Builder) { 7952 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7953 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7954 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7955 Ops.push_back( 7956 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7957 Ops.push_back( 7958 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7959 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7960 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7961 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7962 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 7963 } else 7964 Ops.push_back(OpVal); 7965 } 7966 } 7967 7968 /// Lower llvm.experimental.stackmap directly to its target opcode. 7969 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7970 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7971 // [live variables...]) 7972 7973 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7974 7975 SDValue Chain, InFlag, Callee, NullPtr; 7976 SmallVector<SDValue, 32> Ops; 7977 7978 SDLoc DL = getCurSDLoc(); 7979 Callee = getValue(CI.getCalledValue()); 7980 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7981 7982 // The stackmap intrinsic only records the live variables (the arguemnts 7983 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7984 // intrinsic, this won't be lowered to a function call. This means we don't 7985 // have to worry about calling conventions and target specific lowering code. 7986 // Instead we perform the call lowering right here. 7987 // 7988 // chain, flag = CALLSEQ_START(chain, 0, 0) 7989 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7990 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7991 // 7992 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 7993 InFlag = Chain.getValue(1); 7994 7995 // Add the <id> and <numBytes> constants. 7996 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7997 Ops.push_back(DAG.getTargetConstant( 7998 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7999 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8000 Ops.push_back(DAG.getTargetConstant( 8001 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8002 MVT::i32)); 8003 8004 // Push live variables for the stack map. 8005 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8006 8007 // We are not pushing any register mask info here on the operands list, 8008 // because the stackmap doesn't clobber anything. 8009 8010 // Push the chain and the glue flag. 8011 Ops.push_back(Chain); 8012 Ops.push_back(InFlag); 8013 8014 // Create the STACKMAP node. 8015 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8016 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8017 Chain = SDValue(SM, 0); 8018 InFlag = Chain.getValue(1); 8019 8020 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8021 8022 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8023 8024 // Set the root to the target-lowered call chain. 8025 DAG.setRoot(Chain); 8026 8027 // Inform the Frame Information that we have a stackmap in this function. 8028 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8029 } 8030 8031 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8032 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8033 const BasicBlock *EHPadBB) { 8034 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8035 // i32 <numBytes>, 8036 // i8* <target>, 8037 // i32 <numArgs>, 8038 // [Args...], 8039 // [live variables...]) 8040 8041 CallingConv::ID CC = CS.getCallingConv(); 8042 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8043 bool HasDef = !CS->getType()->isVoidTy(); 8044 SDLoc dl = getCurSDLoc(); 8045 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8046 8047 // Handle immediate and symbolic callees. 8048 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8049 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8050 /*isTarget=*/true); 8051 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8052 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8053 SDLoc(SymbolicCallee), 8054 SymbolicCallee->getValueType(0)); 8055 8056 // Get the real number of arguments participating in the call <numArgs> 8057 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8058 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8059 8060 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8061 // Intrinsics include all meta-operands up to but not including CC. 8062 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8063 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8064 "Not enough arguments provided to the patchpoint intrinsic"); 8065 8066 // For AnyRegCC the arguments are lowered later on manually. 8067 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8068 Type *ReturnTy = 8069 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8070 8071 TargetLowering::CallLoweringInfo CLI(DAG); 8072 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8073 true); 8074 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8075 8076 SDNode *CallEnd = Result.second.getNode(); 8077 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8078 CallEnd = CallEnd->getOperand(0).getNode(); 8079 8080 /// Get a call instruction from the call sequence chain. 8081 /// Tail calls are not allowed. 8082 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8083 "Expected a callseq node."); 8084 SDNode *Call = CallEnd->getOperand(0).getNode(); 8085 bool HasGlue = Call->getGluedNode(); 8086 8087 // Replace the target specific call node with the patchable intrinsic. 8088 SmallVector<SDValue, 8> Ops; 8089 8090 // Add the <id> and <numBytes> constants. 8091 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8092 Ops.push_back(DAG.getTargetConstant( 8093 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8094 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8095 Ops.push_back(DAG.getTargetConstant( 8096 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8097 MVT::i32)); 8098 8099 // Add the callee. 8100 Ops.push_back(Callee); 8101 8102 // Adjust <numArgs> to account for any arguments that have been passed on the 8103 // stack instead. 8104 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8105 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8106 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8107 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8108 8109 // Add the calling convention 8110 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8111 8112 // Add the arguments we omitted previously. The register allocator should 8113 // place these in any free register. 8114 if (IsAnyRegCC) 8115 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8116 Ops.push_back(getValue(CS.getArgument(i))); 8117 8118 // Push the arguments from the call instruction up to the register mask. 8119 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8120 Ops.append(Call->op_begin() + 2, e); 8121 8122 // Push live variables for the stack map. 8123 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8124 8125 // Push the register mask info. 8126 if (HasGlue) 8127 Ops.push_back(*(Call->op_end()-2)); 8128 else 8129 Ops.push_back(*(Call->op_end()-1)); 8130 8131 // Push the chain (this is originally the first operand of the call, but 8132 // becomes now the last or second to last operand). 8133 Ops.push_back(*(Call->op_begin())); 8134 8135 // Push the glue flag (last operand). 8136 if (HasGlue) 8137 Ops.push_back(*(Call->op_end()-1)); 8138 8139 SDVTList NodeTys; 8140 if (IsAnyRegCC && HasDef) { 8141 // Create the return types based on the intrinsic definition 8142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8143 SmallVector<EVT, 3> ValueVTs; 8144 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8145 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8146 8147 // There is always a chain and a glue type at the end 8148 ValueVTs.push_back(MVT::Other); 8149 ValueVTs.push_back(MVT::Glue); 8150 NodeTys = DAG.getVTList(ValueVTs); 8151 } else 8152 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8153 8154 // Replace the target specific call node with a PATCHPOINT node. 8155 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8156 dl, NodeTys, Ops); 8157 8158 // Update the NodeMap. 8159 if (HasDef) { 8160 if (IsAnyRegCC) 8161 setValue(CS.getInstruction(), SDValue(MN, 0)); 8162 else 8163 setValue(CS.getInstruction(), Result.first); 8164 } 8165 8166 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8167 // call sequence. Furthermore the location of the chain and glue can change 8168 // when the AnyReg calling convention is used and the intrinsic returns a 8169 // value. 8170 if (IsAnyRegCC && HasDef) { 8171 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8172 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8173 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8174 } else 8175 DAG.ReplaceAllUsesWith(Call, MN); 8176 DAG.DeleteNode(Call); 8177 8178 // Inform the Frame Information that we have a patchpoint in this function. 8179 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8180 } 8181 8182 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8183 unsigned Intrinsic) { 8184 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8185 SDValue Op1 = getValue(I.getArgOperand(0)); 8186 SDValue Op2; 8187 if (I.getNumArgOperands() > 1) 8188 Op2 = getValue(I.getArgOperand(1)); 8189 SDLoc dl = getCurSDLoc(); 8190 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8191 SDValue Res; 8192 FastMathFlags FMF; 8193 if (isa<FPMathOperator>(I)) 8194 FMF = I.getFastMathFlags(); 8195 8196 switch (Intrinsic) { 8197 case Intrinsic::experimental_vector_reduce_fadd: 8198 if (FMF.isFast()) 8199 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8200 else 8201 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8202 break; 8203 case Intrinsic::experimental_vector_reduce_fmul: 8204 if (FMF.isFast()) 8205 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8206 else 8207 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8208 break; 8209 case Intrinsic::experimental_vector_reduce_add: 8210 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8211 break; 8212 case Intrinsic::experimental_vector_reduce_mul: 8213 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8214 break; 8215 case Intrinsic::experimental_vector_reduce_and: 8216 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8217 break; 8218 case Intrinsic::experimental_vector_reduce_or: 8219 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8220 break; 8221 case Intrinsic::experimental_vector_reduce_xor: 8222 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8223 break; 8224 case Intrinsic::experimental_vector_reduce_smax: 8225 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8226 break; 8227 case Intrinsic::experimental_vector_reduce_smin: 8228 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8229 break; 8230 case Intrinsic::experimental_vector_reduce_umax: 8231 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8232 break; 8233 case Intrinsic::experimental_vector_reduce_umin: 8234 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8235 break; 8236 case Intrinsic::experimental_vector_reduce_fmax: 8237 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8238 break; 8239 case Intrinsic::experimental_vector_reduce_fmin: 8240 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8241 break; 8242 default: 8243 llvm_unreachable("Unhandled vector reduce intrinsic"); 8244 } 8245 setValue(&I, Res); 8246 } 8247 8248 /// Returns an AttributeList representing the attributes applied to the return 8249 /// value of the given call. 8250 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8251 SmallVector<Attribute::AttrKind, 2> Attrs; 8252 if (CLI.RetSExt) 8253 Attrs.push_back(Attribute::SExt); 8254 if (CLI.RetZExt) 8255 Attrs.push_back(Attribute::ZExt); 8256 if (CLI.IsInReg) 8257 Attrs.push_back(Attribute::InReg); 8258 8259 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8260 Attrs); 8261 } 8262 8263 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8264 /// implementation, which just calls LowerCall. 8265 /// FIXME: When all targets are 8266 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8267 std::pair<SDValue, SDValue> 8268 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8269 // Handle the incoming return values from the call. 8270 CLI.Ins.clear(); 8271 Type *OrigRetTy = CLI.RetTy; 8272 SmallVector<EVT, 4> RetTys; 8273 SmallVector<uint64_t, 4> Offsets; 8274 auto &DL = CLI.DAG.getDataLayout(); 8275 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8276 8277 if (CLI.IsPostTypeLegalization) { 8278 // If we are lowering a libcall after legalization, split the return type. 8279 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8280 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8281 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8282 EVT RetVT = OldRetTys[i]; 8283 uint64_t Offset = OldOffsets[i]; 8284 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8285 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8286 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8287 RetTys.append(NumRegs, RegisterVT); 8288 for (unsigned j = 0; j != NumRegs; ++j) 8289 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8290 } 8291 } 8292 8293 SmallVector<ISD::OutputArg, 4> Outs; 8294 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8295 8296 bool CanLowerReturn = 8297 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8298 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8299 8300 SDValue DemoteStackSlot; 8301 int DemoteStackIdx = -100; 8302 if (!CanLowerReturn) { 8303 // FIXME: equivalent assert? 8304 // assert(!CS.hasInAllocaArgument() && 8305 // "sret demotion is incompatible with inalloca"); 8306 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8307 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8308 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8309 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8310 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 8311 8312 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8313 ArgListEntry Entry; 8314 Entry.Node = DemoteStackSlot; 8315 Entry.Ty = StackSlotPtrType; 8316 Entry.IsSExt = false; 8317 Entry.IsZExt = false; 8318 Entry.IsInReg = false; 8319 Entry.IsSRet = true; 8320 Entry.IsNest = false; 8321 Entry.IsByVal = false; 8322 Entry.IsReturned = false; 8323 Entry.IsSwiftSelf = false; 8324 Entry.IsSwiftError = false; 8325 Entry.Alignment = Align; 8326 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8327 CLI.NumFixedArgs += 1; 8328 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8329 8330 // sret demotion isn't compatible with tail-calls, since the sret argument 8331 // points into the callers stack frame. 8332 CLI.IsTailCall = false; 8333 } else { 8334 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8335 EVT VT = RetTys[I]; 8336 MVT RegisterVT = 8337 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8338 unsigned NumRegs = 8339 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8340 for (unsigned i = 0; i != NumRegs; ++i) { 8341 ISD::InputArg MyFlags; 8342 MyFlags.VT = RegisterVT; 8343 MyFlags.ArgVT = VT; 8344 MyFlags.Used = CLI.IsReturnValueUsed; 8345 if (CLI.RetSExt) 8346 MyFlags.Flags.setSExt(); 8347 if (CLI.RetZExt) 8348 MyFlags.Flags.setZExt(); 8349 if (CLI.IsInReg) 8350 MyFlags.Flags.setInReg(); 8351 CLI.Ins.push_back(MyFlags); 8352 } 8353 } 8354 } 8355 8356 // We push in swifterror return as the last element of CLI.Ins. 8357 ArgListTy &Args = CLI.getArgs(); 8358 if (supportSwiftError()) { 8359 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8360 if (Args[i].IsSwiftError) { 8361 ISD::InputArg MyFlags; 8362 MyFlags.VT = getPointerTy(DL); 8363 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8364 MyFlags.Flags.setSwiftError(); 8365 CLI.Ins.push_back(MyFlags); 8366 } 8367 } 8368 } 8369 8370 // Handle all of the outgoing arguments. 8371 CLI.Outs.clear(); 8372 CLI.OutVals.clear(); 8373 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8374 SmallVector<EVT, 4> ValueVTs; 8375 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8376 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8377 Type *FinalType = Args[i].Ty; 8378 if (Args[i].IsByVal) 8379 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8380 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8381 FinalType, CLI.CallConv, CLI.IsVarArg); 8382 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8383 ++Value) { 8384 EVT VT = ValueVTs[Value]; 8385 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8386 SDValue Op = SDValue(Args[i].Node.getNode(), 8387 Args[i].Node.getResNo() + Value); 8388 ISD::ArgFlagsTy Flags; 8389 8390 // Certain targets (such as MIPS), may have a different ABI alignment 8391 // for a type depending on the context. Give the target a chance to 8392 // specify the alignment it wants. 8393 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8394 8395 if (Args[i].IsZExt) 8396 Flags.setZExt(); 8397 if (Args[i].IsSExt) 8398 Flags.setSExt(); 8399 if (Args[i].IsInReg) { 8400 // If we are using vectorcall calling convention, a structure that is 8401 // passed InReg - is surely an HVA 8402 if (CLI.CallConv == CallingConv::X86_VectorCall && 8403 isa<StructType>(FinalType)) { 8404 // The first value of a structure is marked 8405 if (0 == Value) 8406 Flags.setHvaStart(); 8407 Flags.setHva(); 8408 } 8409 // Set InReg Flag 8410 Flags.setInReg(); 8411 } 8412 if (Args[i].IsSRet) 8413 Flags.setSRet(); 8414 if (Args[i].IsSwiftSelf) 8415 Flags.setSwiftSelf(); 8416 if (Args[i].IsSwiftError) 8417 Flags.setSwiftError(); 8418 if (Args[i].IsByVal) 8419 Flags.setByVal(); 8420 if (Args[i].IsInAlloca) { 8421 Flags.setInAlloca(); 8422 // Set the byval flag for CCAssignFn callbacks that don't know about 8423 // inalloca. This way we can know how many bytes we should've allocated 8424 // and how many bytes a callee cleanup function will pop. If we port 8425 // inalloca to more targets, we'll have to add custom inalloca handling 8426 // in the various CC lowering callbacks. 8427 Flags.setByVal(); 8428 } 8429 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8430 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8431 Type *ElementTy = Ty->getElementType(); 8432 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8433 // For ByVal, alignment should come from FE. BE will guess if this 8434 // info is not there but there are cases it cannot get right. 8435 unsigned FrameAlign; 8436 if (Args[i].Alignment) 8437 FrameAlign = Args[i].Alignment; 8438 else 8439 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8440 Flags.setByValAlign(FrameAlign); 8441 } 8442 if (Args[i].IsNest) 8443 Flags.setNest(); 8444 if (NeedsRegBlock) 8445 Flags.setInConsecutiveRegs(); 8446 Flags.setOrigAlign(OriginalAlignment); 8447 8448 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8449 unsigned NumParts = 8450 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8451 SmallVector<SDValue, 4> Parts(NumParts); 8452 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8453 8454 if (Args[i].IsSExt) 8455 ExtendKind = ISD::SIGN_EXTEND; 8456 else if (Args[i].IsZExt) 8457 ExtendKind = ISD::ZERO_EXTEND; 8458 8459 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8460 // for now. 8461 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8462 CanLowerReturn) { 8463 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8464 "unexpected use of 'returned'"); 8465 // Before passing 'returned' to the target lowering code, ensure that 8466 // either the register MVT and the actual EVT are the same size or that 8467 // the return value and argument are extended in the same way; in these 8468 // cases it's safe to pass the argument register value unchanged as the 8469 // return register value (although it's at the target's option whether 8470 // to do so) 8471 // TODO: allow code generation to take advantage of partially preserved 8472 // registers rather than clobbering the entire register when the 8473 // parameter extension method is not compatible with the return 8474 // extension method 8475 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8476 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8477 CLI.RetZExt == Args[i].IsZExt)) 8478 Flags.setReturned(); 8479 } 8480 8481 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8482 CLI.CS.getInstruction(), ExtendKind, true); 8483 8484 for (unsigned j = 0; j != NumParts; ++j) { 8485 // if it isn't first piece, alignment must be 1 8486 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8487 i < CLI.NumFixedArgs, 8488 i, j*Parts[j].getValueType().getStoreSize()); 8489 if (NumParts > 1 && j == 0) 8490 MyFlags.Flags.setSplit(); 8491 else if (j != 0) { 8492 MyFlags.Flags.setOrigAlign(1); 8493 if (j == NumParts - 1) 8494 MyFlags.Flags.setSplitEnd(); 8495 } 8496 8497 CLI.Outs.push_back(MyFlags); 8498 CLI.OutVals.push_back(Parts[j]); 8499 } 8500 8501 if (NeedsRegBlock && Value == NumValues - 1) 8502 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8503 } 8504 } 8505 8506 SmallVector<SDValue, 4> InVals; 8507 CLI.Chain = LowerCall(CLI, InVals); 8508 8509 // Update CLI.InVals to use outside of this function. 8510 CLI.InVals = InVals; 8511 8512 // Verify that the target's LowerCall behaved as expected. 8513 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8514 "LowerCall didn't return a valid chain!"); 8515 assert((!CLI.IsTailCall || InVals.empty()) && 8516 "LowerCall emitted a return value for a tail call!"); 8517 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8518 "LowerCall didn't emit the correct number of values!"); 8519 8520 // For a tail call, the return value is merely live-out and there aren't 8521 // any nodes in the DAG representing it. Return a special value to 8522 // indicate that a tail call has been emitted and no more Instructions 8523 // should be processed in the current block. 8524 if (CLI.IsTailCall) { 8525 CLI.DAG.setRoot(CLI.Chain); 8526 return std::make_pair(SDValue(), SDValue()); 8527 } 8528 8529 #ifndef NDEBUG 8530 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8531 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8532 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8533 "LowerCall emitted a value with the wrong type!"); 8534 } 8535 #endif 8536 8537 SmallVector<SDValue, 4> ReturnValues; 8538 if (!CanLowerReturn) { 8539 // The instruction result is the result of loading from the 8540 // hidden sret parameter. 8541 SmallVector<EVT, 1> PVTs; 8542 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8543 8544 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8545 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8546 EVT PtrVT = PVTs[0]; 8547 8548 unsigned NumValues = RetTys.size(); 8549 ReturnValues.resize(NumValues); 8550 SmallVector<SDValue, 4> Chains(NumValues); 8551 8552 // An aggregate return value cannot wrap around the address space, so 8553 // offsets to its parts don't wrap either. 8554 SDNodeFlags Flags; 8555 Flags.setNoUnsignedWrap(true); 8556 8557 for (unsigned i = 0; i < NumValues; ++i) { 8558 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8559 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8560 PtrVT), Flags); 8561 SDValue L = CLI.DAG.getLoad( 8562 RetTys[i], CLI.DL, CLI.Chain, Add, 8563 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8564 DemoteStackIdx, Offsets[i]), 8565 /* Alignment = */ 1); 8566 ReturnValues[i] = L; 8567 Chains[i] = L.getValue(1); 8568 } 8569 8570 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8571 } else { 8572 // Collect the legal value parts into potentially illegal values 8573 // that correspond to the original function's return values. 8574 Optional<ISD::NodeType> AssertOp; 8575 if (CLI.RetSExt) 8576 AssertOp = ISD::AssertSext; 8577 else if (CLI.RetZExt) 8578 AssertOp = ISD::AssertZext; 8579 unsigned CurReg = 0; 8580 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8581 EVT VT = RetTys[I]; 8582 MVT RegisterVT = 8583 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8584 unsigned NumRegs = 8585 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8586 8587 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8588 NumRegs, RegisterVT, VT, nullptr, 8589 AssertOp, true)); 8590 CurReg += NumRegs; 8591 } 8592 8593 // For a function returning void, there is no return value. We can't create 8594 // such a node, so we just return a null return value in that case. In 8595 // that case, nothing will actually look at the value. 8596 if (ReturnValues.empty()) 8597 return std::make_pair(SDValue(), CLI.Chain); 8598 } 8599 8600 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8601 CLI.DAG.getVTList(RetTys), ReturnValues); 8602 return std::make_pair(Res, CLI.Chain); 8603 } 8604 8605 void TargetLowering::LowerOperationWrapper(SDNode *N, 8606 SmallVectorImpl<SDValue> &Results, 8607 SelectionDAG &DAG) const { 8608 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8609 Results.push_back(Res); 8610 } 8611 8612 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8613 llvm_unreachable("LowerOperation not implemented for this target!"); 8614 } 8615 8616 void 8617 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8618 SDValue Op = getNonRegisterValue(V); 8619 assert((Op.getOpcode() != ISD::CopyFromReg || 8620 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8621 "Copy from a reg to the same reg!"); 8622 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8623 8624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8625 // If this is an InlineAsm we have to match the registers required, not the 8626 // notional registers required by the type. 8627 8628 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 8629 V->getType(), isABIRegCopy(V)); 8630 SDValue Chain = DAG.getEntryNode(); 8631 8632 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8633 FuncInfo.PreferredExtendType.end()) 8634 ? ISD::ANY_EXTEND 8635 : FuncInfo.PreferredExtendType[V]; 8636 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8637 PendingExports.push_back(Chain); 8638 } 8639 8640 #include "llvm/CodeGen/SelectionDAGISel.h" 8641 8642 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8643 /// entry block, return true. This includes arguments used by switches, since 8644 /// the switch may expand into multiple basic blocks. 8645 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8646 // With FastISel active, we may be splitting blocks, so force creation 8647 // of virtual registers for all non-dead arguments. 8648 if (FastISel) 8649 return A->use_empty(); 8650 8651 const BasicBlock &Entry = A->getParent()->front(); 8652 for (const User *U : A->users()) 8653 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8654 return false; // Use not in entry block. 8655 8656 return true; 8657 } 8658 8659 using ArgCopyElisionMapTy = 8660 DenseMap<const Argument *, 8661 std::pair<const AllocaInst *, const StoreInst *>>; 8662 8663 /// Scan the entry block of the function in FuncInfo for arguments that look 8664 /// like copies into a local alloca. Record any copied arguments in 8665 /// ArgCopyElisionCandidates. 8666 static void 8667 findArgumentCopyElisionCandidates(const DataLayout &DL, 8668 FunctionLoweringInfo *FuncInfo, 8669 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8670 // Record the state of every static alloca used in the entry block. Argument 8671 // allocas are all used in the entry block, so we need approximately as many 8672 // entries as we have arguments. 8673 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8674 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8675 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8676 StaticAllocas.reserve(NumArgs * 2); 8677 8678 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8679 if (!V) 8680 return nullptr; 8681 V = V->stripPointerCasts(); 8682 const auto *AI = dyn_cast<AllocaInst>(V); 8683 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8684 return nullptr; 8685 auto Iter = StaticAllocas.insert({AI, Unknown}); 8686 return &Iter.first->second; 8687 }; 8688 8689 // Look for stores of arguments to static allocas. Look through bitcasts and 8690 // GEPs to handle type coercions, as long as the alloca is fully initialized 8691 // by the store. Any non-store use of an alloca escapes it and any subsequent 8692 // unanalyzed store might write it. 8693 // FIXME: Handle structs initialized with multiple stores. 8694 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8695 // Look for stores, and handle non-store uses conservatively. 8696 const auto *SI = dyn_cast<StoreInst>(&I); 8697 if (!SI) { 8698 // We will look through cast uses, so ignore them completely. 8699 if (I.isCast()) 8700 continue; 8701 // Ignore debug info intrinsics, they don't escape or store to allocas. 8702 if (isa<DbgInfoIntrinsic>(I)) 8703 continue; 8704 // This is an unknown instruction. Assume it escapes or writes to all 8705 // static alloca operands. 8706 for (const Use &U : I.operands()) { 8707 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8708 *Info = StaticAllocaInfo::Clobbered; 8709 } 8710 continue; 8711 } 8712 8713 // If the stored value is a static alloca, mark it as escaped. 8714 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8715 *Info = StaticAllocaInfo::Clobbered; 8716 8717 // Check if the destination is a static alloca. 8718 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8719 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8720 if (!Info) 8721 continue; 8722 const AllocaInst *AI = cast<AllocaInst>(Dst); 8723 8724 // Skip allocas that have been initialized or clobbered. 8725 if (*Info != StaticAllocaInfo::Unknown) 8726 continue; 8727 8728 // Check if the stored value is an argument, and that this store fully 8729 // initializes the alloca. Don't elide copies from the same argument twice. 8730 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8731 const auto *Arg = dyn_cast<Argument>(Val); 8732 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8733 Arg->getType()->isEmptyTy() || 8734 DL.getTypeStoreSize(Arg->getType()) != 8735 DL.getTypeAllocSize(AI->getAllocatedType()) || 8736 ArgCopyElisionCandidates.count(Arg)) { 8737 *Info = StaticAllocaInfo::Clobbered; 8738 continue; 8739 } 8740 8741 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8742 << '\n'); 8743 8744 // Mark this alloca and store for argument copy elision. 8745 *Info = StaticAllocaInfo::Elidable; 8746 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8747 8748 // Stop scanning if we've seen all arguments. This will happen early in -O0 8749 // builds, which is useful, because -O0 builds have large entry blocks and 8750 // many allocas. 8751 if (ArgCopyElisionCandidates.size() == NumArgs) 8752 break; 8753 } 8754 } 8755 8756 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8757 /// ArgVal is a load from a suitable fixed stack object. 8758 static void tryToElideArgumentCopy( 8759 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8760 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8761 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8762 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8763 SDValue ArgVal, bool &ArgHasUses) { 8764 // Check if this is a load from a fixed stack object. 8765 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8766 if (!LNode) 8767 return; 8768 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8769 if (!FINode) 8770 return; 8771 8772 // Check that the fixed stack object is the right size and alignment. 8773 // Look at the alignment that the user wrote on the alloca instead of looking 8774 // at the stack object. 8775 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8776 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8777 const AllocaInst *AI = ArgCopyIter->second.first; 8778 int FixedIndex = FINode->getIndex(); 8779 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8780 int OldIndex = AllocaIndex; 8781 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8782 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8783 LLVM_DEBUG( 8784 dbgs() << " argument copy elision failed due to bad fixed stack " 8785 "object size\n"); 8786 return; 8787 } 8788 unsigned RequiredAlignment = AI->getAlignment(); 8789 if (!RequiredAlignment) { 8790 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8791 AI->getAllocatedType()); 8792 } 8793 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8794 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8795 "greater than stack argument alignment (" 8796 << RequiredAlignment << " vs " 8797 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8798 return; 8799 } 8800 8801 // Perform the elision. Delete the old stack object and replace its only use 8802 // in the variable info map. Mark the stack object as mutable. 8803 LLVM_DEBUG({ 8804 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8805 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8806 << '\n'; 8807 }); 8808 MFI.RemoveStackObject(OldIndex); 8809 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8810 AllocaIndex = FixedIndex; 8811 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8812 Chains.push_back(ArgVal.getValue(1)); 8813 8814 // Avoid emitting code for the store implementing the copy. 8815 const StoreInst *SI = ArgCopyIter->second.second; 8816 ElidedArgCopyInstrs.insert(SI); 8817 8818 // Check for uses of the argument again so that we can avoid exporting ArgVal 8819 // if it is't used by anything other than the store. 8820 for (const Value *U : Arg.users()) { 8821 if (U != SI) { 8822 ArgHasUses = true; 8823 break; 8824 } 8825 } 8826 } 8827 8828 void SelectionDAGISel::LowerArguments(const Function &F) { 8829 SelectionDAG &DAG = SDB->DAG; 8830 SDLoc dl = SDB->getCurSDLoc(); 8831 const DataLayout &DL = DAG.getDataLayout(); 8832 SmallVector<ISD::InputArg, 16> Ins; 8833 8834 if (!FuncInfo->CanLowerReturn) { 8835 // Put in an sret pointer parameter before all the other parameters. 8836 SmallVector<EVT, 1> ValueVTs; 8837 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8838 F.getReturnType()->getPointerTo( 8839 DAG.getDataLayout().getAllocaAddrSpace()), 8840 ValueVTs); 8841 8842 // NOTE: Assuming that a pointer will never break down to more than one VT 8843 // or one register. 8844 ISD::ArgFlagsTy Flags; 8845 Flags.setSRet(); 8846 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8847 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8848 ISD::InputArg::NoArgIndex, 0); 8849 Ins.push_back(RetArg); 8850 } 8851 8852 // Look for stores of arguments to static allocas. Mark such arguments with a 8853 // flag to ask the target to give us the memory location of that argument if 8854 // available. 8855 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8856 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8857 8858 // Set up the incoming argument description vector. 8859 for (const Argument &Arg : F.args()) { 8860 unsigned ArgNo = Arg.getArgNo(); 8861 SmallVector<EVT, 4> ValueVTs; 8862 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8863 bool isArgValueUsed = !Arg.use_empty(); 8864 unsigned PartBase = 0; 8865 Type *FinalType = Arg.getType(); 8866 if (Arg.hasAttribute(Attribute::ByVal)) 8867 FinalType = cast<PointerType>(FinalType)->getElementType(); 8868 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8869 FinalType, F.getCallingConv(), F.isVarArg()); 8870 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8871 Value != NumValues; ++Value) { 8872 EVT VT = ValueVTs[Value]; 8873 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8874 ISD::ArgFlagsTy Flags; 8875 8876 // Certain targets (such as MIPS), may have a different ABI alignment 8877 // for a type depending on the context. Give the target a chance to 8878 // specify the alignment it wants. 8879 unsigned OriginalAlignment = 8880 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8881 8882 if (Arg.hasAttribute(Attribute::ZExt)) 8883 Flags.setZExt(); 8884 if (Arg.hasAttribute(Attribute::SExt)) 8885 Flags.setSExt(); 8886 if (Arg.hasAttribute(Attribute::InReg)) { 8887 // If we are using vectorcall calling convention, a structure that is 8888 // passed InReg - is surely an HVA 8889 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8890 isa<StructType>(Arg.getType())) { 8891 // The first value of a structure is marked 8892 if (0 == Value) 8893 Flags.setHvaStart(); 8894 Flags.setHva(); 8895 } 8896 // Set InReg Flag 8897 Flags.setInReg(); 8898 } 8899 if (Arg.hasAttribute(Attribute::StructRet)) 8900 Flags.setSRet(); 8901 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8902 Flags.setSwiftSelf(); 8903 if (Arg.hasAttribute(Attribute::SwiftError)) 8904 Flags.setSwiftError(); 8905 if (Arg.hasAttribute(Attribute::ByVal)) 8906 Flags.setByVal(); 8907 if (Arg.hasAttribute(Attribute::InAlloca)) { 8908 Flags.setInAlloca(); 8909 // Set the byval flag for CCAssignFn callbacks that don't know about 8910 // inalloca. This way we can know how many bytes we should've allocated 8911 // and how many bytes a callee cleanup function will pop. If we port 8912 // inalloca to more targets, we'll have to add custom inalloca handling 8913 // in the various CC lowering callbacks. 8914 Flags.setByVal(); 8915 } 8916 if (F.getCallingConv() == CallingConv::X86_INTR) { 8917 // IA Interrupt passes frame (1st parameter) by value in the stack. 8918 if (ArgNo == 0) 8919 Flags.setByVal(); 8920 } 8921 if (Flags.isByVal() || Flags.isInAlloca()) { 8922 PointerType *Ty = cast<PointerType>(Arg.getType()); 8923 Type *ElementTy = Ty->getElementType(); 8924 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8925 // For ByVal, alignment should be passed from FE. BE will guess if 8926 // this info is not there but there are cases it cannot get right. 8927 unsigned FrameAlign; 8928 if (Arg.getParamAlignment()) 8929 FrameAlign = Arg.getParamAlignment(); 8930 else 8931 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8932 Flags.setByValAlign(FrameAlign); 8933 } 8934 if (Arg.hasAttribute(Attribute::Nest)) 8935 Flags.setNest(); 8936 if (NeedsRegBlock) 8937 Flags.setInConsecutiveRegs(); 8938 Flags.setOrigAlign(OriginalAlignment); 8939 if (ArgCopyElisionCandidates.count(&Arg)) 8940 Flags.setCopyElisionCandidate(); 8941 8942 MVT RegisterVT = 8943 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8944 unsigned NumRegs = 8945 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8946 for (unsigned i = 0; i != NumRegs; ++i) { 8947 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8948 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 8949 if (NumRegs > 1 && i == 0) 8950 MyFlags.Flags.setSplit(); 8951 // if it isn't first piece, alignment must be 1 8952 else if (i > 0) { 8953 MyFlags.Flags.setOrigAlign(1); 8954 if (i == NumRegs - 1) 8955 MyFlags.Flags.setSplitEnd(); 8956 } 8957 Ins.push_back(MyFlags); 8958 } 8959 if (NeedsRegBlock && Value == NumValues - 1) 8960 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8961 PartBase += VT.getStoreSize(); 8962 } 8963 } 8964 8965 // Call the target to set up the argument values. 8966 SmallVector<SDValue, 8> InVals; 8967 SDValue NewRoot = TLI->LowerFormalArguments( 8968 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 8969 8970 // Verify that the target's LowerFormalArguments behaved as expected. 8971 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 8972 "LowerFormalArguments didn't return a valid chain!"); 8973 assert(InVals.size() == Ins.size() && 8974 "LowerFormalArguments didn't emit the correct number of values!"); 8975 LLVM_DEBUG({ 8976 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 8977 assert(InVals[i].getNode() && 8978 "LowerFormalArguments emitted a null value!"); 8979 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 8980 "LowerFormalArguments emitted a value with the wrong type!"); 8981 } 8982 }); 8983 8984 // Update the DAG with the new chain value resulting from argument lowering. 8985 DAG.setRoot(NewRoot); 8986 8987 // Set up the argument values. 8988 unsigned i = 0; 8989 if (!FuncInfo->CanLowerReturn) { 8990 // Create a virtual register for the sret pointer, and put in a copy 8991 // from the sret argument into it. 8992 SmallVector<EVT, 1> ValueVTs; 8993 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8994 F.getReturnType()->getPointerTo( 8995 DAG.getDataLayout().getAllocaAddrSpace()), 8996 ValueVTs); 8997 MVT VT = ValueVTs[0].getSimpleVT(); 8998 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8999 Optional<ISD::NodeType> AssertOp = None; 9000 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 9001 RegVT, VT, nullptr, AssertOp); 9002 9003 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9004 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9005 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9006 FuncInfo->DemoteRegister = SRetReg; 9007 NewRoot = 9008 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9009 DAG.setRoot(NewRoot); 9010 9011 // i indexes lowered arguments. Bump it past the hidden sret argument. 9012 ++i; 9013 } 9014 9015 SmallVector<SDValue, 4> Chains; 9016 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9017 for (const Argument &Arg : F.args()) { 9018 SmallVector<SDValue, 4> ArgValues; 9019 SmallVector<EVT, 4> ValueVTs; 9020 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9021 unsigned NumValues = ValueVTs.size(); 9022 if (NumValues == 0) 9023 continue; 9024 9025 bool ArgHasUses = !Arg.use_empty(); 9026 9027 // Elide the copying store if the target loaded this argument from a 9028 // suitable fixed stack object. 9029 if (Ins[i].Flags.isCopyElisionCandidate()) { 9030 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9031 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9032 InVals[i], ArgHasUses); 9033 } 9034 9035 // If this argument is unused then remember its value. It is used to generate 9036 // debugging information. 9037 bool isSwiftErrorArg = 9038 TLI->supportSwiftError() && 9039 Arg.hasAttribute(Attribute::SwiftError); 9040 if (!ArgHasUses && !isSwiftErrorArg) { 9041 SDB->setUnusedArgValue(&Arg, InVals[i]); 9042 9043 // Also remember any frame index for use in FastISel. 9044 if (FrameIndexSDNode *FI = 9045 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9046 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9047 } 9048 9049 for (unsigned Val = 0; Val != NumValues; ++Val) { 9050 EVT VT = ValueVTs[Val]; 9051 MVT PartVT = 9052 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 9053 unsigned NumParts = 9054 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 9055 9056 // Even an apparant 'unused' swifterror argument needs to be returned. So 9057 // we do generate a copy for it that can be used on return from the 9058 // function. 9059 if (ArgHasUses || isSwiftErrorArg) { 9060 Optional<ISD::NodeType> AssertOp; 9061 if (Arg.hasAttribute(Attribute::SExt)) 9062 AssertOp = ISD::AssertSext; 9063 else if (Arg.hasAttribute(Attribute::ZExt)) 9064 AssertOp = ISD::AssertZext; 9065 9066 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9067 PartVT, VT, nullptr, AssertOp, 9068 true)); 9069 } 9070 9071 i += NumParts; 9072 } 9073 9074 // We don't need to do anything else for unused arguments. 9075 if (ArgValues.empty()) 9076 continue; 9077 9078 // Note down frame index. 9079 if (FrameIndexSDNode *FI = 9080 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9081 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9082 9083 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9084 SDB->getCurSDLoc()); 9085 9086 SDB->setValue(&Arg, Res); 9087 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9088 // We want to associate the argument with the frame index, among 9089 // involved operands, that correspond to the lowest address. The 9090 // getCopyFromParts function, called earlier, is swapping the order of 9091 // the operands to BUILD_PAIR depending on endianness. The result of 9092 // that swapping is that the least significant bits of the argument will 9093 // be in the first operand of the BUILD_PAIR node, and the most 9094 // significant bits will be in the second operand. 9095 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9096 if (LoadSDNode *LNode = 9097 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9098 if (FrameIndexSDNode *FI = 9099 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9100 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9101 } 9102 9103 // Update the SwiftErrorVRegDefMap. 9104 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9105 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9106 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9107 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9108 FuncInfo->SwiftErrorArg, Reg); 9109 } 9110 9111 // If this argument is live outside of the entry block, insert a copy from 9112 // wherever we got it to the vreg that other BB's will reference it as. 9113 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9114 // If we can, though, try to skip creating an unnecessary vreg. 9115 // FIXME: This isn't very clean... it would be nice to make this more 9116 // general. It's also subtly incompatible with the hacks FastISel 9117 // uses with vregs. 9118 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9119 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9120 FuncInfo->ValueMap[&Arg] = Reg; 9121 continue; 9122 } 9123 } 9124 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9125 FuncInfo->InitializeRegForValue(&Arg); 9126 SDB->CopyToExportRegsIfNeeded(&Arg); 9127 } 9128 } 9129 9130 if (!Chains.empty()) { 9131 Chains.push_back(NewRoot); 9132 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9133 } 9134 9135 DAG.setRoot(NewRoot); 9136 9137 assert(i == InVals.size() && "Argument register count mismatch!"); 9138 9139 // If any argument copy elisions occurred and we have debug info, update the 9140 // stale frame indices used in the dbg.declare variable info table. 9141 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9142 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9143 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9144 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9145 if (I != ArgCopyElisionFrameIndexMap.end()) 9146 VI.Slot = I->second; 9147 } 9148 } 9149 9150 // Finally, if the target has anything special to do, allow it to do so. 9151 EmitFunctionEntryCode(); 9152 } 9153 9154 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9155 /// ensure constants are generated when needed. Remember the virtual registers 9156 /// that need to be added to the Machine PHI nodes as input. We cannot just 9157 /// directly add them, because expansion might result in multiple MBB's for one 9158 /// BB. As such, the start of the BB might correspond to a different MBB than 9159 /// the end. 9160 void 9161 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9162 const TerminatorInst *TI = LLVMBB->getTerminator(); 9163 9164 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9165 9166 // Check PHI nodes in successors that expect a value to be available from this 9167 // block. 9168 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9169 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9170 if (!isa<PHINode>(SuccBB->begin())) continue; 9171 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9172 9173 // If this terminator has multiple identical successors (common for 9174 // switches), only handle each succ once. 9175 if (!SuccsHandled.insert(SuccMBB).second) 9176 continue; 9177 9178 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9179 9180 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9181 // nodes and Machine PHI nodes, but the incoming operands have not been 9182 // emitted yet. 9183 for (const PHINode &PN : SuccBB->phis()) { 9184 // Ignore dead phi's. 9185 if (PN.use_empty()) 9186 continue; 9187 9188 // Skip empty types 9189 if (PN.getType()->isEmptyTy()) 9190 continue; 9191 9192 unsigned Reg; 9193 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9194 9195 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9196 unsigned &RegOut = ConstantsOut[C]; 9197 if (RegOut == 0) { 9198 RegOut = FuncInfo.CreateRegs(C->getType()); 9199 CopyValueToVirtualRegister(C, RegOut); 9200 } 9201 Reg = RegOut; 9202 } else { 9203 DenseMap<const Value *, unsigned>::iterator I = 9204 FuncInfo.ValueMap.find(PHIOp); 9205 if (I != FuncInfo.ValueMap.end()) 9206 Reg = I->second; 9207 else { 9208 assert(isa<AllocaInst>(PHIOp) && 9209 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9210 "Didn't codegen value into a register!??"); 9211 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9212 CopyValueToVirtualRegister(PHIOp, Reg); 9213 } 9214 } 9215 9216 // Remember that this register needs to added to the machine PHI node as 9217 // the input for this MBB. 9218 SmallVector<EVT, 4> ValueVTs; 9219 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9220 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9221 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9222 EVT VT = ValueVTs[vti]; 9223 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9224 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9225 FuncInfo.PHINodesToUpdate.push_back( 9226 std::make_pair(&*MBBI++, Reg + i)); 9227 Reg += NumRegisters; 9228 } 9229 } 9230 } 9231 9232 ConstantsOut.clear(); 9233 } 9234 9235 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9236 /// is 0. 9237 MachineBasicBlock * 9238 SelectionDAGBuilder::StackProtectorDescriptor:: 9239 AddSuccessorMBB(const BasicBlock *BB, 9240 MachineBasicBlock *ParentMBB, 9241 bool IsLikely, 9242 MachineBasicBlock *SuccMBB) { 9243 // If SuccBB has not been created yet, create it. 9244 if (!SuccMBB) { 9245 MachineFunction *MF = ParentMBB->getParent(); 9246 MachineFunction::iterator BBI(ParentMBB); 9247 SuccMBB = MF->CreateMachineBasicBlock(BB); 9248 MF->insert(++BBI, SuccMBB); 9249 } 9250 // Add it as a successor of ParentMBB. 9251 ParentMBB->addSuccessor( 9252 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9253 return SuccMBB; 9254 } 9255 9256 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9257 MachineFunction::iterator I(MBB); 9258 if (++I == FuncInfo.MF->end()) 9259 return nullptr; 9260 return &*I; 9261 } 9262 9263 /// During lowering new call nodes can be created (such as memset, etc.). 9264 /// Those will become new roots of the current DAG, but complications arise 9265 /// when they are tail calls. In such cases, the call lowering will update 9266 /// the root, but the builder still needs to know that a tail call has been 9267 /// lowered in order to avoid generating an additional return. 9268 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9269 // If the node is null, we do have a tail call. 9270 if (MaybeTC.getNode() != nullptr) 9271 DAG.setRoot(MaybeTC); 9272 else 9273 HasTailCall = true; 9274 } 9275 9276 uint64_t 9277 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9278 unsigned First, unsigned Last) const { 9279 assert(Last >= First); 9280 const APInt &LowCase = Clusters[First].Low->getValue(); 9281 const APInt &HighCase = Clusters[Last].High->getValue(); 9282 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9283 9284 // FIXME: A range of consecutive cases has 100% density, but only requires one 9285 // comparison to lower. We should discriminate against such consecutive ranges 9286 // in jump tables. 9287 9288 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9289 } 9290 9291 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9292 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9293 unsigned Last) const { 9294 assert(Last >= First); 9295 assert(TotalCases[Last] >= TotalCases[First]); 9296 uint64_t NumCases = 9297 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9298 return NumCases; 9299 } 9300 9301 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9302 unsigned First, unsigned Last, 9303 const SwitchInst *SI, 9304 MachineBasicBlock *DefaultMBB, 9305 CaseCluster &JTCluster) { 9306 assert(First <= Last); 9307 9308 auto Prob = BranchProbability::getZero(); 9309 unsigned NumCmps = 0; 9310 std::vector<MachineBasicBlock*> Table; 9311 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9312 9313 // Initialize probabilities in JTProbs. 9314 for (unsigned I = First; I <= Last; ++I) 9315 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9316 9317 for (unsigned I = First; I <= Last; ++I) { 9318 assert(Clusters[I].Kind == CC_Range); 9319 Prob += Clusters[I].Prob; 9320 const APInt &Low = Clusters[I].Low->getValue(); 9321 const APInt &High = Clusters[I].High->getValue(); 9322 NumCmps += (Low == High) ? 1 : 2; 9323 if (I != First) { 9324 // Fill the gap between this and the previous cluster. 9325 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9326 assert(PreviousHigh.slt(Low)); 9327 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9328 for (uint64_t J = 0; J < Gap; J++) 9329 Table.push_back(DefaultMBB); 9330 } 9331 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9332 for (uint64_t J = 0; J < ClusterSize; ++J) 9333 Table.push_back(Clusters[I].MBB); 9334 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9335 } 9336 9337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9338 unsigned NumDests = JTProbs.size(); 9339 if (TLI.isSuitableForBitTests( 9340 NumDests, NumCmps, Clusters[First].Low->getValue(), 9341 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9342 // Clusters[First..Last] should be lowered as bit tests instead. 9343 return false; 9344 } 9345 9346 // Create the MBB that will load from and jump through the table. 9347 // Note: We create it here, but it's not inserted into the function yet. 9348 MachineFunction *CurMF = FuncInfo.MF; 9349 MachineBasicBlock *JumpTableMBB = 9350 CurMF->CreateMachineBasicBlock(SI->getParent()); 9351 9352 // Add successors. Note: use table order for determinism. 9353 SmallPtrSet<MachineBasicBlock *, 8> Done; 9354 for (MachineBasicBlock *Succ : Table) { 9355 if (Done.count(Succ)) 9356 continue; 9357 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9358 Done.insert(Succ); 9359 } 9360 JumpTableMBB->normalizeSuccProbs(); 9361 9362 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9363 ->createJumpTableIndex(Table); 9364 9365 // Set up the jump table info. 9366 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9367 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9368 Clusters[Last].High->getValue(), SI->getCondition(), 9369 nullptr, false); 9370 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9371 9372 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9373 JTCases.size() - 1, Prob); 9374 return true; 9375 } 9376 9377 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9378 const SwitchInst *SI, 9379 MachineBasicBlock *DefaultMBB) { 9380 #ifndef NDEBUG 9381 // Clusters must be non-empty, sorted, and only contain Range clusters. 9382 assert(!Clusters.empty()); 9383 for (CaseCluster &C : Clusters) 9384 assert(C.Kind == CC_Range); 9385 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9386 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9387 #endif 9388 9389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9390 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9391 return; 9392 9393 const int64_t N = Clusters.size(); 9394 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9395 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9396 9397 if (N < 2 || N < MinJumpTableEntries) 9398 return; 9399 9400 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9401 SmallVector<unsigned, 8> TotalCases(N); 9402 for (unsigned i = 0; i < N; ++i) { 9403 const APInt &Hi = Clusters[i].High->getValue(); 9404 const APInt &Lo = Clusters[i].Low->getValue(); 9405 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9406 if (i != 0) 9407 TotalCases[i] += TotalCases[i - 1]; 9408 } 9409 9410 // Cheap case: the whole range may be suitable for jump table. 9411 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9412 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9413 assert(NumCases < UINT64_MAX / 100); 9414 assert(Range >= NumCases); 9415 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9416 CaseCluster JTCluster; 9417 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9418 Clusters[0] = JTCluster; 9419 Clusters.resize(1); 9420 return; 9421 } 9422 } 9423 9424 // The algorithm below is not suitable for -O0. 9425 if (TM.getOptLevel() == CodeGenOpt::None) 9426 return; 9427 9428 // Split Clusters into minimum number of dense partitions. The algorithm uses 9429 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9430 // for the Case Statement'" (1994), but builds the MinPartitions array in 9431 // reverse order to make it easier to reconstruct the partitions in ascending 9432 // order. In the choice between two optimal partitionings, it picks the one 9433 // which yields more jump tables. 9434 9435 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9436 SmallVector<unsigned, 8> MinPartitions(N); 9437 // LastElement[i] is the last element of the partition starting at i. 9438 SmallVector<unsigned, 8> LastElement(N); 9439 // PartitionsScore[i] is used to break ties when choosing between two 9440 // partitionings resulting in the same number of partitions. 9441 SmallVector<unsigned, 8> PartitionsScore(N); 9442 // For PartitionsScore, a small number of comparisons is considered as good as 9443 // a jump table and a single comparison is considered better than a jump 9444 // table. 9445 enum PartitionScores : unsigned { 9446 NoTable = 0, 9447 Table = 1, 9448 FewCases = 1, 9449 SingleCase = 2 9450 }; 9451 9452 // Base case: There is only one way to partition Clusters[N-1]. 9453 MinPartitions[N - 1] = 1; 9454 LastElement[N - 1] = N - 1; 9455 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9456 9457 // Note: loop indexes are signed to avoid underflow. 9458 for (int64_t i = N - 2; i >= 0; i--) { 9459 // Find optimal partitioning of Clusters[i..N-1]. 9460 // Baseline: Put Clusters[i] into a partition on its own. 9461 MinPartitions[i] = MinPartitions[i + 1] + 1; 9462 LastElement[i] = i; 9463 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9464 9465 // Search for a solution that results in fewer partitions. 9466 for (int64_t j = N - 1; j > i; j--) { 9467 // Try building a partition from Clusters[i..j]. 9468 uint64_t Range = getJumpTableRange(Clusters, i, j); 9469 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9470 assert(NumCases < UINT64_MAX / 100); 9471 assert(Range >= NumCases); 9472 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9473 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9474 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9475 int64_t NumEntries = j - i + 1; 9476 9477 if (NumEntries == 1) 9478 Score += PartitionScores::SingleCase; 9479 else if (NumEntries <= SmallNumberOfEntries) 9480 Score += PartitionScores::FewCases; 9481 else if (NumEntries >= MinJumpTableEntries) 9482 Score += PartitionScores::Table; 9483 9484 // If this leads to fewer partitions, or to the same number of 9485 // partitions with better score, it is a better partitioning. 9486 if (NumPartitions < MinPartitions[i] || 9487 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9488 MinPartitions[i] = NumPartitions; 9489 LastElement[i] = j; 9490 PartitionsScore[i] = Score; 9491 } 9492 } 9493 } 9494 } 9495 9496 // Iterate over the partitions, replacing some with jump tables in-place. 9497 unsigned DstIndex = 0; 9498 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9499 Last = LastElement[First]; 9500 assert(Last >= First); 9501 assert(DstIndex <= First); 9502 unsigned NumClusters = Last - First + 1; 9503 9504 CaseCluster JTCluster; 9505 if (NumClusters >= MinJumpTableEntries && 9506 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9507 Clusters[DstIndex++] = JTCluster; 9508 } else { 9509 for (unsigned I = First; I <= Last; ++I) 9510 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9511 } 9512 } 9513 Clusters.resize(DstIndex); 9514 } 9515 9516 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9517 unsigned First, unsigned Last, 9518 const SwitchInst *SI, 9519 CaseCluster &BTCluster) { 9520 assert(First <= Last); 9521 if (First == Last) 9522 return false; 9523 9524 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9525 unsigned NumCmps = 0; 9526 for (int64_t I = First; I <= Last; ++I) { 9527 assert(Clusters[I].Kind == CC_Range); 9528 Dests.set(Clusters[I].MBB->getNumber()); 9529 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9530 } 9531 unsigned NumDests = Dests.count(); 9532 9533 APInt Low = Clusters[First].Low->getValue(); 9534 APInt High = Clusters[Last].High->getValue(); 9535 assert(Low.slt(High)); 9536 9537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9538 const DataLayout &DL = DAG.getDataLayout(); 9539 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9540 return false; 9541 9542 APInt LowBound; 9543 APInt CmpRange; 9544 9545 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9546 assert(TLI.rangeFitsInWord(Low, High, DL) && 9547 "Case range must fit in bit mask!"); 9548 9549 // Check if the clusters cover a contiguous range such that no value in the 9550 // range will jump to the default statement. 9551 bool ContiguousRange = true; 9552 for (int64_t I = First + 1; I <= Last; ++I) { 9553 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9554 ContiguousRange = false; 9555 break; 9556 } 9557 } 9558 9559 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9560 // Optimize the case where all the case values fit in a word without having 9561 // to subtract minValue. In this case, we can optimize away the subtraction. 9562 LowBound = APInt::getNullValue(Low.getBitWidth()); 9563 CmpRange = High; 9564 ContiguousRange = false; 9565 } else { 9566 LowBound = Low; 9567 CmpRange = High - Low; 9568 } 9569 9570 CaseBitsVector CBV; 9571 auto TotalProb = BranchProbability::getZero(); 9572 for (unsigned i = First; i <= Last; ++i) { 9573 // Find the CaseBits for this destination. 9574 unsigned j; 9575 for (j = 0; j < CBV.size(); ++j) 9576 if (CBV[j].BB == Clusters[i].MBB) 9577 break; 9578 if (j == CBV.size()) 9579 CBV.push_back( 9580 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9581 CaseBits *CB = &CBV[j]; 9582 9583 // Update Mask, Bits and ExtraProb. 9584 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9585 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9586 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9587 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9588 CB->Bits += Hi - Lo + 1; 9589 CB->ExtraProb += Clusters[i].Prob; 9590 TotalProb += Clusters[i].Prob; 9591 } 9592 9593 BitTestInfo BTI; 9594 llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9595 // Sort by probability first, number of bits second, bit mask third. 9596 if (a.ExtraProb != b.ExtraProb) 9597 return a.ExtraProb > b.ExtraProb; 9598 if (a.Bits != b.Bits) 9599 return a.Bits > b.Bits; 9600 return a.Mask < b.Mask; 9601 }); 9602 9603 for (auto &CB : CBV) { 9604 MachineBasicBlock *BitTestBB = 9605 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9606 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9607 } 9608 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9609 SI->getCondition(), -1U, MVT::Other, false, 9610 ContiguousRange, nullptr, nullptr, std::move(BTI), 9611 TotalProb); 9612 9613 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9614 BitTestCases.size() - 1, TotalProb); 9615 return true; 9616 } 9617 9618 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9619 const SwitchInst *SI) { 9620 // Partition Clusters into as few subsets as possible, where each subset has a 9621 // range that fits in a machine word and has <= 3 unique destinations. 9622 9623 #ifndef NDEBUG 9624 // Clusters must be sorted and contain Range or JumpTable clusters. 9625 assert(!Clusters.empty()); 9626 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9627 for (const CaseCluster &C : Clusters) 9628 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9629 for (unsigned i = 1; i < Clusters.size(); ++i) 9630 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9631 #endif 9632 9633 // The algorithm below is not suitable for -O0. 9634 if (TM.getOptLevel() == CodeGenOpt::None) 9635 return; 9636 9637 // If target does not have legal shift left, do not emit bit tests at all. 9638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9639 const DataLayout &DL = DAG.getDataLayout(); 9640 9641 EVT PTy = TLI.getPointerTy(DL); 9642 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9643 return; 9644 9645 int BitWidth = PTy.getSizeInBits(); 9646 const int64_t N = Clusters.size(); 9647 9648 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9649 SmallVector<unsigned, 8> MinPartitions(N); 9650 // LastElement[i] is the last element of the partition starting at i. 9651 SmallVector<unsigned, 8> LastElement(N); 9652 9653 // FIXME: This might not be the best algorithm for finding bit test clusters. 9654 9655 // Base case: There is only one way to partition Clusters[N-1]. 9656 MinPartitions[N - 1] = 1; 9657 LastElement[N - 1] = N - 1; 9658 9659 // Note: loop indexes are signed to avoid underflow. 9660 for (int64_t i = N - 2; i >= 0; --i) { 9661 // Find optimal partitioning of Clusters[i..N-1]. 9662 // Baseline: Put Clusters[i] into a partition on its own. 9663 MinPartitions[i] = MinPartitions[i + 1] + 1; 9664 LastElement[i] = i; 9665 9666 // Search for a solution that results in fewer partitions. 9667 // Note: the search is limited by BitWidth, reducing time complexity. 9668 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9669 // Try building a partition from Clusters[i..j]. 9670 9671 // Check the range. 9672 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9673 Clusters[j].High->getValue(), DL)) 9674 continue; 9675 9676 // Check nbr of destinations and cluster types. 9677 // FIXME: This works, but doesn't seem very efficient. 9678 bool RangesOnly = true; 9679 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9680 for (int64_t k = i; k <= j; k++) { 9681 if (Clusters[k].Kind != CC_Range) { 9682 RangesOnly = false; 9683 break; 9684 } 9685 Dests.set(Clusters[k].MBB->getNumber()); 9686 } 9687 if (!RangesOnly || Dests.count() > 3) 9688 break; 9689 9690 // Check if it's a better partition. 9691 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9692 if (NumPartitions < MinPartitions[i]) { 9693 // Found a better partition. 9694 MinPartitions[i] = NumPartitions; 9695 LastElement[i] = j; 9696 } 9697 } 9698 } 9699 9700 // Iterate over the partitions, replacing with bit-test clusters in-place. 9701 unsigned DstIndex = 0; 9702 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9703 Last = LastElement[First]; 9704 assert(First <= Last); 9705 assert(DstIndex <= First); 9706 9707 CaseCluster BitTestCluster; 9708 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9709 Clusters[DstIndex++] = BitTestCluster; 9710 } else { 9711 size_t NumClusters = Last - First + 1; 9712 std::memmove(&Clusters[DstIndex], &Clusters[First], 9713 sizeof(Clusters[0]) * NumClusters); 9714 DstIndex += NumClusters; 9715 } 9716 } 9717 Clusters.resize(DstIndex); 9718 } 9719 9720 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9721 MachineBasicBlock *SwitchMBB, 9722 MachineBasicBlock *DefaultMBB) { 9723 MachineFunction *CurMF = FuncInfo.MF; 9724 MachineBasicBlock *NextMBB = nullptr; 9725 MachineFunction::iterator BBI(W.MBB); 9726 if (++BBI != FuncInfo.MF->end()) 9727 NextMBB = &*BBI; 9728 9729 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9730 9731 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9732 9733 if (Size == 2 && W.MBB == SwitchMBB) { 9734 // If any two of the cases has the same destination, and if one value 9735 // is the same as the other, but has one bit unset that the other has set, 9736 // use bit manipulation to do two compares at once. For example: 9737 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9738 // TODO: This could be extended to merge any 2 cases in switches with 3 9739 // cases. 9740 // TODO: Handle cases where W.CaseBB != SwitchBB. 9741 CaseCluster &Small = *W.FirstCluster; 9742 CaseCluster &Big = *W.LastCluster; 9743 9744 if (Small.Low == Small.High && Big.Low == Big.High && 9745 Small.MBB == Big.MBB) { 9746 const APInt &SmallValue = Small.Low->getValue(); 9747 const APInt &BigValue = Big.Low->getValue(); 9748 9749 // Check that there is only one bit different. 9750 APInt CommonBit = BigValue ^ SmallValue; 9751 if (CommonBit.isPowerOf2()) { 9752 SDValue CondLHS = getValue(Cond); 9753 EVT VT = CondLHS.getValueType(); 9754 SDLoc DL = getCurSDLoc(); 9755 9756 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9757 DAG.getConstant(CommonBit, DL, VT)); 9758 SDValue Cond = DAG.getSetCC( 9759 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9760 ISD::SETEQ); 9761 9762 // Update successor info. 9763 // Both Small and Big will jump to Small.BB, so we sum up the 9764 // probabilities. 9765 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9766 if (BPI) 9767 addSuccessorWithProb( 9768 SwitchMBB, DefaultMBB, 9769 // The default destination is the first successor in IR. 9770 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9771 else 9772 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9773 9774 // Insert the true branch. 9775 SDValue BrCond = 9776 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9777 DAG.getBasicBlock(Small.MBB)); 9778 // Insert the false branch. 9779 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9780 DAG.getBasicBlock(DefaultMBB)); 9781 9782 DAG.setRoot(BrCond); 9783 return; 9784 } 9785 } 9786 } 9787 9788 if (TM.getOptLevel() != CodeGenOpt::None) { 9789 // Here, we order cases by probability so the most likely case will be 9790 // checked first. However, two clusters can have the same probability in 9791 // which case their relative ordering is non-deterministic. So we use Low 9792 // as a tie-breaker as clusters are guaranteed to never overlap. 9793 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9794 [](const CaseCluster &a, const CaseCluster &b) { 9795 return a.Prob != b.Prob ? 9796 a.Prob > b.Prob : 9797 a.Low->getValue().slt(b.Low->getValue()); 9798 }); 9799 9800 // Rearrange the case blocks so that the last one falls through if possible 9801 // without changing the order of probabilities. 9802 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9803 --I; 9804 if (I->Prob > W.LastCluster->Prob) 9805 break; 9806 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9807 std::swap(*I, *W.LastCluster); 9808 break; 9809 } 9810 } 9811 } 9812 9813 // Compute total probability. 9814 BranchProbability DefaultProb = W.DefaultProb; 9815 BranchProbability UnhandledProbs = DefaultProb; 9816 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9817 UnhandledProbs += I->Prob; 9818 9819 MachineBasicBlock *CurMBB = W.MBB; 9820 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9821 MachineBasicBlock *Fallthrough; 9822 if (I == W.LastCluster) { 9823 // For the last cluster, fall through to the default destination. 9824 Fallthrough = DefaultMBB; 9825 } else { 9826 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9827 CurMF->insert(BBI, Fallthrough); 9828 // Put Cond in a virtual register to make it available from the new blocks. 9829 ExportFromCurrentBlock(Cond); 9830 } 9831 UnhandledProbs -= I->Prob; 9832 9833 switch (I->Kind) { 9834 case CC_JumpTable: { 9835 // FIXME: Optimize away range check based on pivot comparisons. 9836 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9837 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9838 9839 // The jump block hasn't been inserted yet; insert it here. 9840 MachineBasicBlock *JumpMBB = JT->MBB; 9841 CurMF->insert(BBI, JumpMBB); 9842 9843 auto JumpProb = I->Prob; 9844 auto FallthroughProb = UnhandledProbs; 9845 9846 // If the default statement is a target of the jump table, we evenly 9847 // distribute the default probability to successors of CurMBB. Also 9848 // update the probability on the edge from JumpMBB to Fallthrough. 9849 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9850 SE = JumpMBB->succ_end(); 9851 SI != SE; ++SI) { 9852 if (*SI == DefaultMBB) { 9853 JumpProb += DefaultProb / 2; 9854 FallthroughProb -= DefaultProb / 2; 9855 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9856 JumpMBB->normalizeSuccProbs(); 9857 break; 9858 } 9859 } 9860 9861 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9862 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9863 CurMBB->normalizeSuccProbs(); 9864 9865 // The jump table header will be inserted in our current block, do the 9866 // range check, and fall through to our fallthrough block. 9867 JTH->HeaderBB = CurMBB; 9868 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9869 9870 // If we're in the right place, emit the jump table header right now. 9871 if (CurMBB == SwitchMBB) { 9872 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9873 JTH->Emitted = true; 9874 } 9875 break; 9876 } 9877 case CC_BitTests: { 9878 // FIXME: Optimize away range check based on pivot comparisons. 9879 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9880 9881 // The bit test blocks haven't been inserted yet; insert them here. 9882 for (BitTestCase &BTC : BTB->Cases) 9883 CurMF->insert(BBI, BTC.ThisBB); 9884 9885 // Fill in fields of the BitTestBlock. 9886 BTB->Parent = CurMBB; 9887 BTB->Default = Fallthrough; 9888 9889 BTB->DefaultProb = UnhandledProbs; 9890 // If the cases in bit test don't form a contiguous range, we evenly 9891 // distribute the probability on the edge to Fallthrough to two 9892 // successors of CurMBB. 9893 if (!BTB->ContiguousRange) { 9894 BTB->Prob += DefaultProb / 2; 9895 BTB->DefaultProb -= DefaultProb / 2; 9896 } 9897 9898 // If we're in the right place, emit the bit test header right now. 9899 if (CurMBB == SwitchMBB) { 9900 visitBitTestHeader(*BTB, SwitchMBB); 9901 BTB->Emitted = true; 9902 } 9903 break; 9904 } 9905 case CC_Range: { 9906 const Value *RHS, *LHS, *MHS; 9907 ISD::CondCode CC; 9908 if (I->Low == I->High) { 9909 // Check Cond == I->Low. 9910 CC = ISD::SETEQ; 9911 LHS = Cond; 9912 RHS=I->Low; 9913 MHS = nullptr; 9914 } else { 9915 // Check I->Low <= Cond <= I->High. 9916 CC = ISD::SETLE; 9917 LHS = I->Low; 9918 MHS = Cond; 9919 RHS = I->High; 9920 } 9921 9922 // The false probability is the sum of all unhandled cases. 9923 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9924 getCurSDLoc(), I->Prob, UnhandledProbs); 9925 9926 if (CurMBB == SwitchMBB) 9927 visitSwitchCase(CB, SwitchMBB); 9928 else 9929 SwitchCases.push_back(CB); 9930 9931 break; 9932 } 9933 } 9934 CurMBB = Fallthrough; 9935 } 9936 } 9937 9938 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 9939 CaseClusterIt First, 9940 CaseClusterIt Last) { 9941 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 9942 if (X.Prob != CC.Prob) 9943 return X.Prob > CC.Prob; 9944 9945 // Ties are broken by comparing the case value. 9946 return X.Low->getValue().slt(CC.Low->getValue()); 9947 }); 9948 } 9949 9950 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9951 const SwitchWorkListItem &W, 9952 Value *Cond, 9953 MachineBasicBlock *SwitchMBB) { 9954 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9955 "Clusters not sorted?"); 9956 9957 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9958 9959 // Balance the tree based on branch probabilities to create a near-optimal (in 9960 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9961 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 9962 CaseClusterIt LastLeft = W.FirstCluster; 9963 CaseClusterIt FirstRight = W.LastCluster; 9964 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 9965 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 9966 9967 // Move LastLeft and FirstRight towards each other from opposite directions to 9968 // find a partitioning of the clusters which balances the probability on both 9969 // sides. If LeftProb and RightProb are equal, alternate which side is 9970 // taken to ensure 0-probability nodes are distributed evenly. 9971 unsigned I = 0; 9972 while (LastLeft + 1 < FirstRight) { 9973 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 9974 LeftProb += (++LastLeft)->Prob; 9975 else 9976 RightProb += (--FirstRight)->Prob; 9977 I++; 9978 } 9979 9980 while (true) { 9981 // Our binary search tree differs from a typical BST in that ours can have up 9982 // to three values in each leaf. The pivot selection above doesn't take that 9983 // into account, which means the tree might require more nodes and be less 9984 // efficient. We compensate for this here. 9985 9986 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 9987 unsigned NumRight = W.LastCluster - FirstRight + 1; 9988 9989 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 9990 // If one side has less than 3 clusters, and the other has more than 3, 9991 // consider taking a cluster from the other side. 9992 9993 if (NumLeft < NumRight) { 9994 // Consider moving the first cluster on the right to the left side. 9995 CaseCluster &CC = *FirstRight; 9996 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9997 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9998 if (LeftSideRank <= RightSideRank) { 9999 // Moving the cluster to the left does not demote it. 10000 ++LastLeft; 10001 ++FirstRight; 10002 continue; 10003 } 10004 } else { 10005 assert(NumRight < NumLeft); 10006 // Consider moving the last element on the left to the right side. 10007 CaseCluster &CC = *LastLeft; 10008 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10009 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10010 if (RightSideRank <= LeftSideRank) { 10011 // Moving the cluster to the right does not demot it. 10012 --LastLeft; 10013 --FirstRight; 10014 continue; 10015 } 10016 } 10017 } 10018 break; 10019 } 10020 10021 assert(LastLeft + 1 == FirstRight); 10022 assert(LastLeft >= W.FirstCluster); 10023 assert(FirstRight <= W.LastCluster); 10024 10025 // Use the first element on the right as pivot since we will make less-than 10026 // comparisons against it. 10027 CaseClusterIt PivotCluster = FirstRight; 10028 assert(PivotCluster > W.FirstCluster); 10029 assert(PivotCluster <= W.LastCluster); 10030 10031 CaseClusterIt FirstLeft = W.FirstCluster; 10032 CaseClusterIt LastRight = W.LastCluster; 10033 10034 const ConstantInt *Pivot = PivotCluster->Low; 10035 10036 // New blocks will be inserted immediately after the current one. 10037 MachineFunction::iterator BBI(W.MBB); 10038 ++BBI; 10039 10040 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10041 // we can branch to its destination directly if it's squeezed exactly in 10042 // between the known lower bound and Pivot - 1. 10043 MachineBasicBlock *LeftMBB; 10044 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10045 FirstLeft->Low == W.GE && 10046 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10047 LeftMBB = FirstLeft->MBB; 10048 } else { 10049 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10050 FuncInfo.MF->insert(BBI, LeftMBB); 10051 WorkList.push_back( 10052 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10053 // Put Cond in a virtual register to make it available from the new blocks. 10054 ExportFromCurrentBlock(Cond); 10055 } 10056 10057 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10058 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10059 // directly if RHS.High equals the current upper bound. 10060 MachineBasicBlock *RightMBB; 10061 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10062 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10063 RightMBB = FirstRight->MBB; 10064 } else { 10065 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10066 FuncInfo.MF->insert(BBI, RightMBB); 10067 WorkList.push_back( 10068 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10069 // Put Cond in a virtual register to make it available from the new blocks. 10070 ExportFromCurrentBlock(Cond); 10071 } 10072 10073 // Create the CaseBlock record that will be used to lower the branch. 10074 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10075 getCurSDLoc(), LeftProb, RightProb); 10076 10077 if (W.MBB == SwitchMBB) 10078 visitSwitchCase(CB, SwitchMBB); 10079 else 10080 SwitchCases.push_back(CB); 10081 } 10082 10083 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10084 // from the swith statement. 10085 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10086 BranchProbability PeeledCaseProb) { 10087 if (PeeledCaseProb == BranchProbability::getOne()) 10088 return BranchProbability::getZero(); 10089 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10090 10091 uint32_t Numerator = CaseProb.getNumerator(); 10092 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10093 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10094 } 10095 10096 // Try to peel the top probability case if it exceeds the threshold. 10097 // Return current MachineBasicBlock for the switch statement if the peeling 10098 // does not occur. 10099 // If the peeling is performed, return the newly created MachineBasicBlock 10100 // for the peeled switch statement. Also update Clusters to remove the peeled 10101 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10102 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10103 const SwitchInst &SI, CaseClusterVector &Clusters, 10104 BranchProbability &PeeledCaseProb) { 10105 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10106 // Don't perform if there is only one cluster or optimizing for size. 10107 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10108 TM.getOptLevel() == CodeGenOpt::None || 10109 SwitchMBB->getParent()->getFunction().optForMinSize()) 10110 return SwitchMBB; 10111 10112 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10113 unsigned PeeledCaseIndex = 0; 10114 bool SwitchPeeled = false; 10115 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10116 CaseCluster &CC = Clusters[Index]; 10117 if (CC.Prob < TopCaseProb) 10118 continue; 10119 TopCaseProb = CC.Prob; 10120 PeeledCaseIndex = Index; 10121 SwitchPeeled = true; 10122 } 10123 if (!SwitchPeeled) 10124 return SwitchMBB; 10125 10126 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10127 << TopCaseProb << "\n"); 10128 10129 // Record the MBB for the peeled switch statement. 10130 MachineFunction::iterator BBI(SwitchMBB); 10131 ++BBI; 10132 MachineBasicBlock *PeeledSwitchMBB = 10133 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10134 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10135 10136 ExportFromCurrentBlock(SI.getCondition()); 10137 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10138 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10139 nullptr, nullptr, TopCaseProb.getCompl()}; 10140 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10141 10142 Clusters.erase(PeeledCaseIt); 10143 for (CaseCluster &CC : Clusters) { 10144 LLVM_DEBUG( 10145 dbgs() << "Scale the probablity for one cluster, before scaling: " 10146 << CC.Prob << "\n"); 10147 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10148 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10149 } 10150 PeeledCaseProb = TopCaseProb; 10151 return PeeledSwitchMBB; 10152 } 10153 10154 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10155 // Extract cases from the switch. 10156 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10157 CaseClusterVector Clusters; 10158 Clusters.reserve(SI.getNumCases()); 10159 for (auto I : SI.cases()) { 10160 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10161 const ConstantInt *CaseVal = I.getCaseValue(); 10162 BranchProbability Prob = 10163 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10164 : BranchProbability(1, SI.getNumCases() + 1); 10165 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10166 } 10167 10168 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10169 10170 // Cluster adjacent cases with the same destination. We do this at all 10171 // optimization levels because it's cheap to do and will make codegen faster 10172 // if there are many clusters. 10173 sortAndRangeify(Clusters); 10174 10175 if (TM.getOptLevel() != CodeGenOpt::None) { 10176 // Replace an unreachable default with the most popular destination. 10177 // FIXME: Exploit unreachable default more aggressively. 10178 bool UnreachableDefault = 10179 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10180 if (UnreachableDefault && !Clusters.empty()) { 10181 DenseMap<const BasicBlock *, unsigned> Popularity; 10182 unsigned MaxPop = 0; 10183 const BasicBlock *MaxBB = nullptr; 10184 for (auto I : SI.cases()) { 10185 const BasicBlock *BB = I.getCaseSuccessor(); 10186 if (++Popularity[BB] > MaxPop) { 10187 MaxPop = Popularity[BB]; 10188 MaxBB = BB; 10189 } 10190 } 10191 // Set new default. 10192 assert(MaxPop > 0 && MaxBB); 10193 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10194 10195 // Remove cases that were pointing to the destination that is now the 10196 // default. 10197 CaseClusterVector New; 10198 New.reserve(Clusters.size()); 10199 for (CaseCluster &CC : Clusters) { 10200 if (CC.MBB != DefaultMBB) 10201 New.push_back(CC); 10202 } 10203 Clusters = std::move(New); 10204 } 10205 } 10206 10207 // The branch probablity of the peeled case. 10208 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10209 MachineBasicBlock *PeeledSwitchMBB = 10210 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10211 10212 // If there is only the default destination, jump there directly. 10213 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10214 if (Clusters.empty()) { 10215 assert(PeeledSwitchMBB == SwitchMBB); 10216 SwitchMBB->addSuccessor(DefaultMBB); 10217 if (DefaultMBB != NextBlock(SwitchMBB)) { 10218 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10219 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10220 } 10221 return; 10222 } 10223 10224 findJumpTables(Clusters, &SI, DefaultMBB); 10225 findBitTestClusters(Clusters, &SI); 10226 10227 LLVM_DEBUG({ 10228 dbgs() << "Case clusters: "; 10229 for (const CaseCluster &C : Clusters) { 10230 if (C.Kind == CC_JumpTable) 10231 dbgs() << "JT:"; 10232 if (C.Kind == CC_BitTests) 10233 dbgs() << "BT:"; 10234 10235 C.Low->getValue().print(dbgs(), true); 10236 if (C.Low != C.High) { 10237 dbgs() << '-'; 10238 C.High->getValue().print(dbgs(), true); 10239 } 10240 dbgs() << ' '; 10241 } 10242 dbgs() << '\n'; 10243 }); 10244 10245 assert(!Clusters.empty()); 10246 SwitchWorkList WorkList; 10247 CaseClusterIt First = Clusters.begin(); 10248 CaseClusterIt Last = Clusters.end() - 1; 10249 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10250 // Scale the branchprobability for DefaultMBB if the peel occurs and 10251 // DefaultMBB is not replaced. 10252 if (PeeledCaseProb != BranchProbability::getZero() && 10253 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10254 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10255 WorkList.push_back( 10256 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10257 10258 while (!WorkList.empty()) { 10259 SwitchWorkListItem W = WorkList.back(); 10260 WorkList.pop_back(); 10261 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10262 10263 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10264 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10265 // For optimized builds, lower large range as a balanced binary tree. 10266 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10267 continue; 10268 } 10269 10270 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10271 } 10272 } 10273