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 as such instead of as indirectly addressed 4977 // locations. 4978 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl, 4979 DbgSDNodeOrder); 4980 } 4981 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl, 4982 DbgSDNodeOrder); 4983 } 4984 4985 // VisualStudio defines setjmp as _setjmp 4986 #if defined(_MSC_VER) && defined(setjmp) && \ 4987 !defined(setjmp_undefined_for_msvc) 4988 # pragma push_macro("setjmp") 4989 # undef setjmp 4990 # define setjmp_undefined_for_msvc 4991 #endif 4992 4993 /// Lower the call to the specified intrinsic function. If we want to emit this 4994 /// as a call to a named external function, return the name. Otherwise, lower it 4995 /// and return null. 4996 const char * 4997 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4999 SDLoc sdl = getCurSDLoc(); 5000 DebugLoc dl = getCurDebugLoc(); 5001 SDValue Res; 5002 5003 switch (Intrinsic) { 5004 default: 5005 // By default, turn this into a target intrinsic node. 5006 visitTargetIntrinsic(I, Intrinsic); 5007 return nullptr; 5008 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5009 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5010 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5011 case Intrinsic::returnaddress: 5012 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5013 TLI.getPointerTy(DAG.getDataLayout()), 5014 getValue(I.getArgOperand(0)))); 5015 return nullptr; 5016 case Intrinsic::addressofreturnaddress: 5017 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5018 TLI.getPointerTy(DAG.getDataLayout()))); 5019 return nullptr; 5020 case Intrinsic::frameaddress: 5021 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5022 TLI.getPointerTy(DAG.getDataLayout()), 5023 getValue(I.getArgOperand(0)))); 5024 return nullptr; 5025 case Intrinsic::read_register: { 5026 Value *Reg = I.getArgOperand(0); 5027 SDValue Chain = getRoot(); 5028 SDValue RegName = 5029 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5030 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5031 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5032 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5033 setValue(&I, Res); 5034 DAG.setRoot(Res.getValue(1)); 5035 return nullptr; 5036 } 5037 case Intrinsic::write_register: { 5038 Value *Reg = I.getArgOperand(0); 5039 Value *RegValue = I.getArgOperand(1); 5040 SDValue Chain = getRoot(); 5041 SDValue RegName = 5042 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5043 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5044 RegName, getValue(RegValue))); 5045 return nullptr; 5046 } 5047 case Intrinsic::setjmp: 5048 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5049 case Intrinsic::longjmp: 5050 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5051 case Intrinsic::memcpy: { 5052 const auto &MCI = cast<MemCpyInst>(I); 5053 SDValue Op1 = getValue(I.getArgOperand(0)); 5054 SDValue Op2 = getValue(I.getArgOperand(1)); 5055 SDValue Op3 = getValue(I.getArgOperand(2)); 5056 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5057 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5058 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5059 unsigned Align = MinAlign(DstAlign, SrcAlign); 5060 bool isVol = MCI.isVolatile(); 5061 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5062 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5063 // node. 5064 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5065 false, isTC, 5066 MachinePointerInfo(I.getArgOperand(0)), 5067 MachinePointerInfo(I.getArgOperand(1))); 5068 updateDAGForMaybeTailCall(MC); 5069 return nullptr; 5070 } 5071 case Intrinsic::memset: { 5072 const auto &MSI = cast<MemSetInst>(I); 5073 SDValue Op1 = getValue(I.getArgOperand(0)); 5074 SDValue Op2 = getValue(I.getArgOperand(1)); 5075 SDValue Op3 = getValue(I.getArgOperand(2)); 5076 // @llvm.memset defines 0 and 1 to both mean no alignment. 5077 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5078 bool isVol = MSI.isVolatile(); 5079 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5080 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5081 isTC, MachinePointerInfo(I.getArgOperand(0))); 5082 updateDAGForMaybeTailCall(MS); 5083 return nullptr; 5084 } 5085 case Intrinsic::memmove: { 5086 const auto &MMI = cast<MemMoveInst>(I); 5087 SDValue Op1 = getValue(I.getArgOperand(0)); 5088 SDValue Op2 = getValue(I.getArgOperand(1)); 5089 SDValue Op3 = getValue(I.getArgOperand(2)); 5090 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5091 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5092 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5093 unsigned Align = MinAlign(DstAlign, SrcAlign); 5094 bool isVol = MMI.isVolatile(); 5095 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5096 // FIXME: Support passing different dest/src alignments to the memmove DAG 5097 // node. 5098 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5099 isTC, MachinePointerInfo(I.getArgOperand(0)), 5100 MachinePointerInfo(I.getArgOperand(1))); 5101 updateDAGForMaybeTailCall(MM); 5102 return nullptr; 5103 } 5104 case Intrinsic::memcpy_element_unordered_atomic: { 5105 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5106 SDValue Dst = getValue(MI.getRawDest()); 5107 SDValue Src = getValue(MI.getRawSource()); 5108 SDValue Length = getValue(MI.getLength()); 5109 5110 unsigned DstAlign = MI.getDestAlignment(); 5111 unsigned SrcAlign = MI.getSourceAlignment(); 5112 Type *LengthTy = MI.getLength()->getType(); 5113 unsigned ElemSz = MI.getElementSizeInBytes(); 5114 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5115 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5116 SrcAlign, Length, LengthTy, ElemSz, isTC, 5117 MachinePointerInfo(MI.getRawDest()), 5118 MachinePointerInfo(MI.getRawSource())); 5119 updateDAGForMaybeTailCall(MC); 5120 return nullptr; 5121 } 5122 case Intrinsic::memmove_element_unordered_atomic: { 5123 auto &MI = cast<AtomicMemMoveInst>(I); 5124 SDValue Dst = getValue(MI.getRawDest()); 5125 SDValue Src = getValue(MI.getRawSource()); 5126 SDValue Length = getValue(MI.getLength()); 5127 5128 unsigned DstAlign = MI.getDestAlignment(); 5129 unsigned SrcAlign = MI.getSourceAlignment(); 5130 Type *LengthTy = MI.getLength()->getType(); 5131 unsigned ElemSz = MI.getElementSizeInBytes(); 5132 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5133 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5134 SrcAlign, Length, LengthTy, ElemSz, isTC, 5135 MachinePointerInfo(MI.getRawDest()), 5136 MachinePointerInfo(MI.getRawSource())); 5137 updateDAGForMaybeTailCall(MC); 5138 return nullptr; 5139 } 5140 case Intrinsic::memset_element_unordered_atomic: { 5141 auto &MI = cast<AtomicMemSetInst>(I); 5142 SDValue Dst = getValue(MI.getRawDest()); 5143 SDValue Val = getValue(MI.getValue()); 5144 SDValue Length = getValue(MI.getLength()); 5145 5146 unsigned DstAlign = MI.getDestAlignment(); 5147 Type *LengthTy = MI.getLength()->getType(); 5148 unsigned ElemSz = MI.getElementSizeInBytes(); 5149 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5150 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5151 LengthTy, ElemSz, isTC, 5152 MachinePointerInfo(MI.getRawDest())); 5153 updateDAGForMaybeTailCall(MC); 5154 return nullptr; 5155 } 5156 case Intrinsic::dbg_addr: 5157 case Intrinsic::dbg_declare: { 5158 const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I); 5159 DILocalVariable *Variable = DI.getVariable(); 5160 DIExpression *Expression = DI.getExpression(); 5161 dropDanglingDebugInfo(Variable, Expression); 5162 assert(Variable && "Missing variable"); 5163 5164 // Check if address has undef value. 5165 const Value *Address = DI.getVariableLocation(); 5166 if (!Address || isa<UndefValue>(Address) || 5167 (Address->use_empty() && !isa<Argument>(Address))) { 5168 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5169 return nullptr; 5170 } 5171 5172 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5173 5174 // Check if this variable can be described by a frame index, typically 5175 // either as a static alloca or a byval parameter. 5176 int FI = std::numeric_limits<int>::max(); 5177 if (const auto *AI = 5178 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5179 if (AI->isStaticAlloca()) { 5180 auto I = FuncInfo.StaticAllocaMap.find(AI); 5181 if (I != FuncInfo.StaticAllocaMap.end()) 5182 FI = I->second; 5183 } 5184 } else if (const auto *Arg = dyn_cast<Argument>( 5185 Address->stripInBoundsConstantOffsets())) { 5186 FI = FuncInfo.getArgumentFrameIndex(Arg); 5187 } 5188 5189 // llvm.dbg.addr is control dependent and always generates indirect 5190 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5191 // the MachineFunction variable table. 5192 if (FI != std::numeric_limits<int>::max()) { 5193 if (Intrinsic == Intrinsic::dbg_addr) { 5194 SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 5195 FI, dl, SDNodeOrder); 5196 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5197 } 5198 return nullptr; 5199 } 5200 5201 SDValue &N = NodeMap[Address]; 5202 if (!N.getNode() && isa<Argument>(Address)) 5203 // Check unused arguments map. 5204 N = UnusedArgNodeMap[Address]; 5205 SDDbgValue *SDV; 5206 if (N.getNode()) { 5207 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5208 Address = BCI->getOperand(0); 5209 // Parameters are handled specially. 5210 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5211 if (isParameter && FINode) { 5212 // Byval parameter. We have a frame index at this point. 5213 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 5214 FINode->getIndex(), dl, SDNodeOrder); 5215 } else if (isa<Argument>(Address)) { 5216 // Address is an argument, so try to emit its dbg value using 5217 // virtual register info from the FuncInfo.ValueMap. 5218 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5219 return nullptr; 5220 } else { 5221 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5222 true, dl, SDNodeOrder); 5223 } 5224 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5225 } else { 5226 // If Address is an argument then try to emit its dbg value using 5227 // virtual register info from the FuncInfo.ValueMap. 5228 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5229 N)) { 5230 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5231 } 5232 } 5233 return nullptr; 5234 } 5235 case Intrinsic::dbg_label: { 5236 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5237 DILabel *Label = DI.getLabel(); 5238 assert(Label && "Missing label"); 5239 5240 SDDbgLabel *SDV; 5241 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5242 DAG.AddDbgLabel(SDV); 5243 return nullptr; 5244 } 5245 case Intrinsic::dbg_value: { 5246 const DbgValueInst &DI = cast<DbgValueInst>(I); 5247 assert(DI.getVariable() && "Missing variable"); 5248 5249 DILocalVariable *Variable = DI.getVariable(); 5250 DIExpression *Expression = DI.getExpression(); 5251 dropDanglingDebugInfo(Variable, Expression); 5252 const Value *V = DI.getValue(); 5253 if (!V) 5254 return nullptr; 5255 5256 SDDbgValue *SDV; 5257 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5258 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5259 DAG.AddDbgValue(SDV, nullptr, false); 5260 return nullptr; 5261 } 5262 5263 // Do not use getValue() in here; we don't want to generate code at 5264 // this point if it hasn't been done yet. 5265 SDValue N = NodeMap[V]; 5266 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5267 N = UnusedArgNodeMap[V]; 5268 if (N.getNode()) { 5269 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5270 return nullptr; 5271 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5272 DAG.AddDbgValue(SDV, N.getNode(), false); 5273 return nullptr; 5274 } 5275 5276 // PHI nodes have already been selected, so we should know which VReg that 5277 // is assigns to already. 5278 if (isa<PHINode>(V)) { 5279 auto VMI = FuncInfo.ValueMap.find(V); 5280 if (VMI != FuncInfo.ValueMap.end()) { 5281 unsigned Reg = VMI->second; 5282 // The PHI node may be split up into several MI PHI nodes (in 5283 // FunctionLoweringInfo::set). 5284 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5285 V->getType(), false); 5286 if (RFV.occupiesMultipleRegs()) { 5287 unsigned Offset = 0; 5288 unsigned BitsToDescribe = 0; 5289 if (auto VarSize = Variable->getSizeInBits()) 5290 BitsToDescribe = *VarSize; 5291 if (auto Fragment = Expression->getFragmentInfo()) 5292 BitsToDescribe = Fragment->SizeInBits; 5293 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5294 unsigned RegisterSize = RegAndSize.second; 5295 // Bail out if all bits are described already. 5296 if (Offset >= BitsToDescribe) 5297 break; 5298 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5299 ? BitsToDescribe - Offset 5300 : RegisterSize; 5301 auto FragmentExpr = DIExpression::createFragmentExpression( 5302 Expression, Offset, FragmentSize); 5303 if (!FragmentExpr) 5304 continue; 5305 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5306 false, dl, SDNodeOrder); 5307 DAG.AddDbgValue(SDV, nullptr, false); 5308 Offset += RegisterSize; 5309 } 5310 } else { 5311 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5312 SDNodeOrder); 5313 DAG.AddDbgValue(SDV, nullptr, false); 5314 } 5315 return nullptr; 5316 } 5317 } 5318 5319 // TODO: When we get here we will either drop the dbg.value completely, or 5320 // we try to move it forward by letting it dangle for awhile. So we should 5321 // probably add an extra DbgValue to the DAG here, with a reference to 5322 // "noreg", to indicate that we have lost the debug location for the 5323 // variable. 5324 5325 if (!V->use_empty() ) { 5326 // Do not call getValue(V) yet, as we don't want to generate code. 5327 // Remember it for later. 5328 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5329 return nullptr; 5330 } 5331 5332 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5333 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5334 return nullptr; 5335 } 5336 5337 case Intrinsic::eh_typeid_for: { 5338 // Find the type id for the given typeinfo. 5339 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5340 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5341 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5342 setValue(&I, Res); 5343 return nullptr; 5344 } 5345 5346 case Intrinsic::eh_return_i32: 5347 case Intrinsic::eh_return_i64: 5348 DAG.getMachineFunction().setCallsEHReturn(true); 5349 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5350 MVT::Other, 5351 getControlRoot(), 5352 getValue(I.getArgOperand(0)), 5353 getValue(I.getArgOperand(1)))); 5354 return nullptr; 5355 case Intrinsic::eh_unwind_init: 5356 DAG.getMachineFunction().setCallsUnwindInit(true); 5357 return nullptr; 5358 case Intrinsic::eh_dwarf_cfa: 5359 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5360 TLI.getPointerTy(DAG.getDataLayout()), 5361 getValue(I.getArgOperand(0)))); 5362 return nullptr; 5363 case Intrinsic::eh_sjlj_callsite: { 5364 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5365 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5366 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5367 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5368 5369 MMI.setCurrentCallSite(CI->getZExtValue()); 5370 return nullptr; 5371 } 5372 case Intrinsic::eh_sjlj_functioncontext: { 5373 // Get and store the index of the function context. 5374 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5375 AllocaInst *FnCtx = 5376 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5377 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5378 MFI.setFunctionContextIndex(FI); 5379 return nullptr; 5380 } 5381 case Intrinsic::eh_sjlj_setjmp: { 5382 SDValue Ops[2]; 5383 Ops[0] = getRoot(); 5384 Ops[1] = getValue(I.getArgOperand(0)); 5385 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5386 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5387 setValue(&I, Op.getValue(0)); 5388 DAG.setRoot(Op.getValue(1)); 5389 return nullptr; 5390 } 5391 case Intrinsic::eh_sjlj_longjmp: 5392 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5393 getRoot(), getValue(I.getArgOperand(0)))); 5394 return nullptr; 5395 case Intrinsic::eh_sjlj_setup_dispatch: 5396 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5397 getRoot())); 5398 return nullptr; 5399 case Intrinsic::masked_gather: 5400 visitMaskedGather(I); 5401 return nullptr; 5402 case Intrinsic::masked_load: 5403 visitMaskedLoad(I); 5404 return nullptr; 5405 case Intrinsic::masked_scatter: 5406 visitMaskedScatter(I); 5407 return nullptr; 5408 case Intrinsic::masked_store: 5409 visitMaskedStore(I); 5410 return nullptr; 5411 case Intrinsic::masked_expandload: 5412 visitMaskedLoad(I, true /* IsExpanding */); 5413 return nullptr; 5414 case Intrinsic::masked_compressstore: 5415 visitMaskedStore(I, true /* IsCompressing */); 5416 return nullptr; 5417 case Intrinsic::x86_mmx_pslli_w: 5418 case Intrinsic::x86_mmx_pslli_d: 5419 case Intrinsic::x86_mmx_pslli_q: 5420 case Intrinsic::x86_mmx_psrli_w: 5421 case Intrinsic::x86_mmx_psrli_d: 5422 case Intrinsic::x86_mmx_psrli_q: 5423 case Intrinsic::x86_mmx_psrai_w: 5424 case Intrinsic::x86_mmx_psrai_d: { 5425 SDValue ShAmt = getValue(I.getArgOperand(1)); 5426 if (isa<ConstantSDNode>(ShAmt)) { 5427 visitTargetIntrinsic(I, Intrinsic); 5428 return nullptr; 5429 } 5430 unsigned NewIntrinsic = 0; 5431 EVT ShAmtVT = MVT::v2i32; 5432 switch (Intrinsic) { 5433 case Intrinsic::x86_mmx_pslli_w: 5434 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5435 break; 5436 case Intrinsic::x86_mmx_pslli_d: 5437 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5438 break; 5439 case Intrinsic::x86_mmx_pslli_q: 5440 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5441 break; 5442 case Intrinsic::x86_mmx_psrli_w: 5443 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5444 break; 5445 case Intrinsic::x86_mmx_psrli_d: 5446 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5447 break; 5448 case Intrinsic::x86_mmx_psrli_q: 5449 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5450 break; 5451 case Intrinsic::x86_mmx_psrai_w: 5452 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5453 break; 5454 case Intrinsic::x86_mmx_psrai_d: 5455 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5456 break; 5457 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5458 } 5459 5460 // The vector shift intrinsics with scalars uses 32b shift amounts but 5461 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5462 // to be zero. 5463 // We must do this early because v2i32 is not a legal type. 5464 SDValue ShOps[2]; 5465 ShOps[0] = ShAmt; 5466 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5467 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5468 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5469 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5470 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5471 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5472 getValue(I.getArgOperand(0)), ShAmt); 5473 setValue(&I, Res); 5474 return nullptr; 5475 } 5476 case Intrinsic::powi: 5477 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5478 getValue(I.getArgOperand(1)), DAG)); 5479 return nullptr; 5480 case Intrinsic::log: 5481 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5482 return nullptr; 5483 case Intrinsic::log2: 5484 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5485 return nullptr; 5486 case Intrinsic::log10: 5487 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5488 return nullptr; 5489 case Intrinsic::exp: 5490 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5491 return nullptr; 5492 case Intrinsic::exp2: 5493 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5494 return nullptr; 5495 case Intrinsic::pow: 5496 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5497 getValue(I.getArgOperand(1)), DAG, TLI)); 5498 return nullptr; 5499 case Intrinsic::sqrt: 5500 case Intrinsic::fabs: 5501 case Intrinsic::sin: 5502 case Intrinsic::cos: 5503 case Intrinsic::floor: 5504 case Intrinsic::ceil: 5505 case Intrinsic::trunc: 5506 case Intrinsic::rint: 5507 case Intrinsic::nearbyint: 5508 case Intrinsic::round: 5509 case Intrinsic::canonicalize: { 5510 unsigned Opcode; 5511 switch (Intrinsic) { 5512 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5513 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5514 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5515 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5516 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5517 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5518 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5519 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5520 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5521 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5522 case Intrinsic::round: Opcode = ISD::FROUND; break; 5523 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5524 } 5525 5526 setValue(&I, DAG.getNode(Opcode, sdl, 5527 getValue(I.getArgOperand(0)).getValueType(), 5528 getValue(I.getArgOperand(0)))); 5529 return nullptr; 5530 } 5531 case Intrinsic::minnum: { 5532 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5533 unsigned Opc = 5534 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5535 ? ISD::FMINNAN 5536 : ISD::FMINNUM; 5537 setValue(&I, DAG.getNode(Opc, sdl, VT, 5538 getValue(I.getArgOperand(0)), 5539 getValue(I.getArgOperand(1)))); 5540 return nullptr; 5541 } 5542 case Intrinsic::maxnum: { 5543 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5544 unsigned Opc = 5545 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5546 ? ISD::FMAXNAN 5547 : ISD::FMAXNUM; 5548 setValue(&I, DAG.getNode(Opc, sdl, VT, 5549 getValue(I.getArgOperand(0)), 5550 getValue(I.getArgOperand(1)))); 5551 return nullptr; 5552 } 5553 case Intrinsic::copysign: 5554 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5555 getValue(I.getArgOperand(0)).getValueType(), 5556 getValue(I.getArgOperand(0)), 5557 getValue(I.getArgOperand(1)))); 5558 return nullptr; 5559 case Intrinsic::fma: 5560 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5561 getValue(I.getArgOperand(0)).getValueType(), 5562 getValue(I.getArgOperand(0)), 5563 getValue(I.getArgOperand(1)), 5564 getValue(I.getArgOperand(2)))); 5565 return nullptr; 5566 case Intrinsic::experimental_constrained_fadd: 5567 case Intrinsic::experimental_constrained_fsub: 5568 case Intrinsic::experimental_constrained_fmul: 5569 case Intrinsic::experimental_constrained_fdiv: 5570 case Intrinsic::experimental_constrained_frem: 5571 case Intrinsic::experimental_constrained_fma: 5572 case Intrinsic::experimental_constrained_sqrt: 5573 case Intrinsic::experimental_constrained_pow: 5574 case Intrinsic::experimental_constrained_powi: 5575 case Intrinsic::experimental_constrained_sin: 5576 case Intrinsic::experimental_constrained_cos: 5577 case Intrinsic::experimental_constrained_exp: 5578 case Intrinsic::experimental_constrained_exp2: 5579 case Intrinsic::experimental_constrained_log: 5580 case Intrinsic::experimental_constrained_log10: 5581 case Intrinsic::experimental_constrained_log2: 5582 case Intrinsic::experimental_constrained_rint: 5583 case Intrinsic::experimental_constrained_nearbyint: 5584 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5585 return nullptr; 5586 case Intrinsic::fmuladd: { 5587 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5588 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5589 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5590 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5591 getValue(I.getArgOperand(0)).getValueType(), 5592 getValue(I.getArgOperand(0)), 5593 getValue(I.getArgOperand(1)), 5594 getValue(I.getArgOperand(2)))); 5595 } else { 5596 // TODO: Intrinsic calls should have fast-math-flags. 5597 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5598 getValue(I.getArgOperand(0)).getValueType(), 5599 getValue(I.getArgOperand(0)), 5600 getValue(I.getArgOperand(1))); 5601 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5602 getValue(I.getArgOperand(0)).getValueType(), 5603 Mul, 5604 getValue(I.getArgOperand(2))); 5605 setValue(&I, Add); 5606 } 5607 return nullptr; 5608 } 5609 case Intrinsic::convert_to_fp16: 5610 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5611 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5612 getValue(I.getArgOperand(0)), 5613 DAG.getTargetConstant(0, sdl, 5614 MVT::i32)))); 5615 return nullptr; 5616 case Intrinsic::convert_from_fp16: 5617 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5618 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5619 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5620 getValue(I.getArgOperand(0))))); 5621 return nullptr; 5622 case Intrinsic::pcmarker: { 5623 SDValue Tmp = getValue(I.getArgOperand(0)); 5624 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5625 return nullptr; 5626 } 5627 case Intrinsic::readcyclecounter: { 5628 SDValue Op = getRoot(); 5629 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5630 DAG.getVTList(MVT::i64, MVT::Other), Op); 5631 setValue(&I, Res); 5632 DAG.setRoot(Res.getValue(1)); 5633 return nullptr; 5634 } 5635 case Intrinsic::bitreverse: 5636 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5637 getValue(I.getArgOperand(0)).getValueType(), 5638 getValue(I.getArgOperand(0)))); 5639 return nullptr; 5640 case Intrinsic::bswap: 5641 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5642 getValue(I.getArgOperand(0)).getValueType(), 5643 getValue(I.getArgOperand(0)))); 5644 return nullptr; 5645 case Intrinsic::cttz: { 5646 SDValue Arg = getValue(I.getArgOperand(0)); 5647 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5648 EVT Ty = Arg.getValueType(); 5649 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5650 sdl, Ty, Arg)); 5651 return nullptr; 5652 } 5653 case Intrinsic::ctlz: { 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::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5658 sdl, Ty, Arg)); 5659 return nullptr; 5660 } 5661 case Intrinsic::ctpop: { 5662 SDValue Arg = getValue(I.getArgOperand(0)); 5663 EVT Ty = Arg.getValueType(); 5664 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5665 return nullptr; 5666 } 5667 case Intrinsic::fshl: 5668 case Intrinsic::fshr: { 5669 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5670 SDValue X = getValue(I.getArgOperand(0)); 5671 SDValue Y = getValue(I.getArgOperand(1)); 5672 SDValue Z = getValue(I.getArgOperand(2)); 5673 EVT VT = X.getValueType(); 5674 5675 // TODO: When X == Y, this is rotate. Create the node directly if legal. 5676 5677 // Get the shift amount and inverse shift amount, modulo the bit-width. 5678 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5679 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5680 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, Z); 5681 SDValue InvShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5682 5683 // fshl: (X << (Z % BW)) | (Y >> ((BW - Z) % BW)) 5684 // fshr: (X << ((BW - Z) % BW)) | (Y >> (Z % BW)) 5685 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5686 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5687 SDValue Res = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5688 5689 // If (Z % BW == 0), then (BW - Z) % BW is also zero, so the result would 5690 // be X | Y. If X == Y (rotate), that's fine. If not, we have to select. 5691 if (X != Y) { 5692 SDValue Zero = DAG.getConstant(0, sdl, VT); 5693 EVT CCVT = MVT::i1; 5694 if (VT.isVector()) 5695 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5696 // For fshl, 0 shift returns the 1st arg (X). 5697 // For fshr, 0 shift returns the 2nd arg (Y). 5698 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5699 Res = DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Res); 5700 } 5701 setValue(&I, Res); 5702 return nullptr; 5703 } 5704 case Intrinsic::stacksave: { 5705 SDValue Op = getRoot(); 5706 Res = DAG.getNode( 5707 ISD::STACKSAVE, sdl, 5708 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5709 setValue(&I, Res); 5710 DAG.setRoot(Res.getValue(1)); 5711 return nullptr; 5712 } 5713 case Intrinsic::stackrestore: 5714 Res = getValue(I.getArgOperand(0)); 5715 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5716 return nullptr; 5717 case Intrinsic::get_dynamic_area_offset: { 5718 SDValue Op = getRoot(); 5719 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5720 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5721 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5722 // target. 5723 if (PtrTy != ResTy) 5724 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5725 " intrinsic!"); 5726 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5727 Op); 5728 DAG.setRoot(Op); 5729 setValue(&I, Res); 5730 return nullptr; 5731 } 5732 case Intrinsic::stackguard: { 5733 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5734 MachineFunction &MF = DAG.getMachineFunction(); 5735 const Module &M = *MF.getFunction().getParent(); 5736 SDValue Chain = getRoot(); 5737 if (TLI.useLoadStackGuardNode()) { 5738 Res = getLoadStackGuard(DAG, sdl, Chain); 5739 } else { 5740 const Value *Global = TLI.getSDagStackGuard(M); 5741 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5742 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5743 MachinePointerInfo(Global, 0), Align, 5744 MachineMemOperand::MOVolatile); 5745 } 5746 if (TLI.useStackGuardXorFP()) 5747 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5748 DAG.setRoot(Chain); 5749 setValue(&I, Res); 5750 return nullptr; 5751 } 5752 case Intrinsic::stackprotector: { 5753 // Emit code into the DAG to store the stack guard onto the stack. 5754 MachineFunction &MF = DAG.getMachineFunction(); 5755 MachineFrameInfo &MFI = MF.getFrameInfo(); 5756 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5757 SDValue Src, Chain = getRoot(); 5758 5759 if (TLI.useLoadStackGuardNode()) 5760 Src = getLoadStackGuard(DAG, sdl, Chain); 5761 else 5762 Src = getValue(I.getArgOperand(0)); // The guard's value. 5763 5764 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5765 5766 int FI = FuncInfo.StaticAllocaMap[Slot]; 5767 MFI.setStackProtectorIndex(FI); 5768 5769 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5770 5771 // Store the stack protector onto the stack. 5772 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5773 DAG.getMachineFunction(), FI), 5774 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5775 setValue(&I, Res); 5776 DAG.setRoot(Res); 5777 return nullptr; 5778 } 5779 case Intrinsic::objectsize: { 5780 // If we don't know by now, we're never going to know. 5781 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5782 5783 assert(CI && "Non-constant type in __builtin_object_size?"); 5784 5785 SDValue Arg = getValue(I.getCalledValue()); 5786 EVT Ty = Arg.getValueType(); 5787 5788 if (CI->isZero()) 5789 Res = DAG.getConstant(-1ULL, sdl, Ty); 5790 else 5791 Res = DAG.getConstant(0, sdl, Ty); 5792 5793 setValue(&I, Res); 5794 return nullptr; 5795 } 5796 case Intrinsic::annotation: 5797 case Intrinsic::ptr_annotation: 5798 case Intrinsic::launder_invariant_group: 5799 case Intrinsic::strip_invariant_group: 5800 // Drop the intrinsic, but forward the value 5801 setValue(&I, getValue(I.getOperand(0))); 5802 return nullptr; 5803 case Intrinsic::assume: 5804 case Intrinsic::var_annotation: 5805 case Intrinsic::sideeffect: 5806 // Discard annotate attributes, assumptions, and artificial side-effects. 5807 return nullptr; 5808 5809 case Intrinsic::codeview_annotation: { 5810 // Emit a label associated with this metadata. 5811 MachineFunction &MF = DAG.getMachineFunction(); 5812 MCSymbol *Label = 5813 MF.getMMI().getContext().createTempSymbol("annotation", true); 5814 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5815 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5816 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5817 DAG.setRoot(Res); 5818 return nullptr; 5819 } 5820 5821 case Intrinsic::init_trampoline: { 5822 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5823 5824 SDValue Ops[6]; 5825 Ops[0] = getRoot(); 5826 Ops[1] = getValue(I.getArgOperand(0)); 5827 Ops[2] = getValue(I.getArgOperand(1)); 5828 Ops[3] = getValue(I.getArgOperand(2)); 5829 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5830 Ops[5] = DAG.getSrcValue(F); 5831 5832 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5833 5834 DAG.setRoot(Res); 5835 return nullptr; 5836 } 5837 case Intrinsic::adjust_trampoline: 5838 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5839 TLI.getPointerTy(DAG.getDataLayout()), 5840 getValue(I.getArgOperand(0)))); 5841 return nullptr; 5842 case Intrinsic::gcroot: { 5843 assert(DAG.getMachineFunction().getFunction().hasGC() && 5844 "only valid in functions with gc specified, enforced by Verifier"); 5845 assert(GFI && "implied by previous"); 5846 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5847 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5848 5849 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5850 GFI->addStackRoot(FI->getIndex(), TypeMap); 5851 return nullptr; 5852 } 5853 case Intrinsic::gcread: 5854 case Intrinsic::gcwrite: 5855 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5856 case Intrinsic::flt_rounds: 5857 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5858 return nullptr; 5859 5860 case Intrinsic::expect: 5861 // Just replace __builtin_expect(exp, c) with EXP. 5862 setValue(&I, getValue(I.getArgOperand(0))); 5863 return nullptr; 5864 5865 case Intrinsic::debugtrap: 5866 case Intrinsic::trap: { 5867 StringRef TrapFuncName = 5868 I.getAttributes() 5869 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5870 .getValueAsString(); 5871 if (TrapFuncName.empty()) { 5872 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5873 ISD::TRAP : ISD::DEBUGTRAP; 5874 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5875 return nullptr; 5876 } 5877 TargetLowering::ArgListTy Args; 5878 5879 TargetLowering::CallLoweringInfo CLI(DAG); 5880 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5881 CallingConv::C, I.getType(), 5882 DAG.getExternalSymbol(TrapFuncName.data(), 5883 TLI.getPointerTy(DAG.getDataLayout())), 5884 std::move(Args)); 5885 5886 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5887 DAG.setRoot(Result.second); 5888 return nullptr; 5889 } 5890 5891 case Intrinsic::uadd_with_overflow: 5892 case Intrinsic::sadd_with_overflow: 5893 case Intrinsic::usub_with_overflow: 5894 case Intrinsic::ssub_with_overflow: 5895 case Intrinsic::umul_with_overflow: 5896 case Intrinsic::smul_with_overflow: { 5897 ISD::NodeType Op; 5898 switch (Intrinsic) { 5899 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5900 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5901 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5902 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5903 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5904 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5905 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5906 } 5907 SDValue Op1 = getValue(I.getArgOperand(0)); 5908 SDValue Op2 = getValue(I.getArgOperand(1)); 5909 5910 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5911 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5912 return nullptr; 5913 } 5914 case Intrinsic::prefetch: { 5915 SDValue Ops[5]; 5916 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5917 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 5918 Ops[0] = DAG.getRoot(); 5919 Ops[1] = getValue(I.getArgOperand(0)); 5920 Ops[2] = getValue(I.getArgOperand(1)); 5921 Ops[3] = getValue(I.getArgOperand(2)); 5922 Ops[4] = getValue(I.getArgOperand(3)); 5923 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5924 DAG.getVTList(MVT::Other), Ops, 5925 EVT::getIntegerVT(*Context, 8), 5926 MachinePointerInfo(I.getArgOperand(0)), 5927 0, /* align */ 5928 Flags); 5929 5930 // Chain the prefetch in parallell with any pending loads, to stay out of 5931 // the way of later optimizations. 5932 PendingLoads.push_back(Result); 5933 Result = getRoot(); 5934 DAG.setRoot(Result); 5935 return nullptr; 5936 } 5937 case Intrinsic::lifetime_start: 5938 case Intrinsic::lifetime_end: { 5939 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5940 // Stack coloring is not enabled in O0, discard region information. 5941 if (TM.getOptLevel() == CodeGenOpt::None) 5942 return nullptr; 5943 5944 SmallVector<Value *, 4> Allocas; 5945 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5946 5947 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5948 E = Allocas.end(); Object != E; ++Object) { 5949 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5950 5951 // Could not find an Alloca. 5952 if (!LifetimeObject) 5953 continue; 5954 5955 // First check that the Alloca is static, otherwise it won't have a 5956 // valid frame index. 5957 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5958 if (SI == FuncInfo.StaticAllocaMap.end()) 5959 return nullptr; 5960 5961 int FI = SI->second; 5962 5963 SDValue Ops[2]; 5964 Ops[0] = getRoot(); 5965 Ops[1] = 5966 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 5967 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5968 5969 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5970 DAG.setRoot(Res); 5971 } 5972 return nullptr; 5973 } 5974 case Intrinsic::invariant_start: 5975 // Discard region information. 5976 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5977 return nullptr; 5978 case Intrinsic::invariant_end: 5979 // Discard region information. 5980 return nullptr; 5981 case Intrinsic::clear_cache: 5982 return TLI.getClearCacheBuiltinName(); 5983 case Intrinsic::donothing: 5984 // ignore 5985 return nullptr; 5986 case Intrinsic::experimental_stackmap: 5987 visitStackmap(I); 5988 return nullptr; 5989 case Intrinsic::experimental_patchpoint_void: 5990 case Intrinsic::experimental_patchpoint_i64: 5991 visitPatchpoint(&I); 5992 return nullptr; 5993 case Intrinsic::experimental_gc_statepoint: 5994 LowerStatepoint(ImmutableStatepoint(&I)); 5995 return nullptr; 5996 case Intrinsic::experimental_gc_result: 5997 visitGCResult(cast<GCResultInst>(I)); 5998 return nullptr; 5999 case Intrinsic::experimental_gc_relocate: 6000 visitGCRelocate(cast<GCRelocateInst>(I)); 6001 return nullptr; 6002 case Intrinsic::instrprof_increment: 6003 llvm_unreachable("instrprof failed to lower an increment"); 6004 case Intrinsic::instrprof_value_profile: 6005 llvm_unreachable("instrprof failed to lower a value profiling call"); 6006 case Intrinsic::localescape: { 6007 MachineFunction &MF = DAG.getMachineFunction(); 6008 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6009 6010 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6011 // is the same on all targets. 6012 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6013 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6014 if (isa<ConstantPointerNull>(Arg)) 6015 continue; // Skip null pointers. They represent a hole in index space. 6016 AllocaInst *Slot = cast<AllocaInst>(Arg); 6017 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6018 "can only escape static allocas"); 6019 int FI = FuncInfo.StaticAllocaMap[Slot]; 6020 MCSymbol *FrameAllocSym = 6021 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6022 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6024 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6025 .addSym(FrameAllocSym) 6026 .addFrameIndex(FI); 6027 } 6028 6029 return nullptr; 6030 } 6031 6032 case Intrinsic::localrecover: { 6033 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6034 MachineFunction &MF = DAG.getMachineFunction(); 6035 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6036 6037 // Get the symbol that defines the frame offset. 6038 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6039 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6040 unsigned IdxVal = 6041 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6042 MCSymbol *FrameAllocSym = 6043 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6044 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6045 6046 // Create a MCSymbol for the label to avoid any target lowering 6047 // that would make this PC relative. 6048 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6049 SDValue OffsetVal = 6050 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6051 6052 // Add the offset to the FP. 6053 Value *FP = I.getArgOperand(1); 6054 SDValue FPVal = getValue(FP); 6055 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6056 setValue(&I, Add); 6057 6058 return nullptr; 6059 } 6060 6061 case Intrinsic::eh_exceptionpointer: 6062 case Intrinsic::eh_exceptioncode: { 6063 // Get the exception pointer vreg, copy from it, and resize it to fit. 6064 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6065 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6066 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6067 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6068 SDValue N = 6069 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6070 if (Intrinsic == Intrinsic::eh_exceptioncode) 6071 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6072 setValue(&I, N); 6073 return nullptr; 6074 } 6075 case Intrinsic::xray_customevent: { 6076 // Here we want to make sure that the intrinsic behaves as if it has a 6077 // specific calling convention, and only for x86_64. 6078 // FIXME: Support other platforms later. 6079 const auto &Triple = DAG.getTarget().getTargetTriple(); 6080 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6081 return nullptr; 6082 6083 SDLoc DL = getCurSDLoc(); 6084 SmallVector<SDValue, 8> Ops; 6085 6086 // We want to say that we always want the arguments in registers. 6087 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6088 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6089 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6090 SDValue Chain = getRoot(); 6091 Ops.push_back(LogEntryVal); 6092 Ops.push_back(StrSizeVal); 6093 Ops.push_back(Chain); 6094 6095 // We need to enforce the calling convention for the callsite, so that 6096 // argument ordering is enforced correctly, and that register allocation can 6097 // see that some registers may be assumed clobbered and have to preserve 6098 // them across calls to the intrinsic. 6099 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6100 DL, NodeTys, Ops); 6101 SDValue patchableNode = SDValue(MN, 0); 6102 DAG.setRoot(patchableNode); 6103 setValue(&I, patchableNode); 6104 return nullptr; 6105 } 6106 case Intrinsic::xray_typedevent: { 6107 // Here we want to make sure that the intrinsic behaves as if it has a 6108 // specific calling convention, and only for x86_64. 6109 // FIXME: Support other platforms later. 6110 const auto &Triple = DAG.getTarget().getTargetTriple(); 6111 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6112 return nullptr; 6113 6114 SDLoc DL = getCurSDLoc(); 6115 SmallVector<SDValue, 8> Ops; 6116 6117 // We want to say that we always want the arguments in registers. 6118 // It's unclear to me how manipulating the selection DAG here forces callers 6119 // to provide arguments in registers instead of on the stack. 6120 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6121 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6122 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6123 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6124 SDValue Chain = getRoot(); 6125 Ops.push_back(LogTypeId); 6126 Ops.push_back(LogEntryVal); 6127 Ops.push_back(StrSizeVal); 6128 Ops.push_back(Chain); 6129 6130 // We need to enforce the calling convention for the callsite, so that 6131 // argument ordering is enforced correctly, and that register allocation can 6132 // see that some registers may be assumed clobbered and have to preserve 6133 // them across calls to the intrinsic. 6134 MachineSDNode *MN = DAG.getMachineNode( 6135 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6136 SDValue patchableNode = SDValue(MN, 0); 6137 DAG.setRoot(patchableNode); 6138 setValue(&I, patchableNode); 6139 return nullptr; 6140 } 6141 case Intrinsic::experimental_deoptimize: 6142 LowerDeoptimizeCall(&I); 6143 return nullptr; 6144 6145 case Intrinsic::experimental_vector_reduce_fadd: 6146 case Intrinsic::experimental_vector_reduce_fmul: 6147 case Intrinsic::experimental_vector_reduce_add: 6148 case Intrinsic::experimental_vector_reduce_mul: 6149 case Intrinsic::experimental_vector_reduce_and: 6150 case Intrinsic::experimental_vector_reduce_or: 6151 case Intrinsic::experimental_vector_reduce_xor: 6152 case Intrinsic::experimental_vector_reduce_smax: 6153 case Intrinsic::experimental_vector_reduce_smin: 6154 case Intrinsic::experimental_vector_reduce_umax: 6155 case Intrinsic::experimental_vector_reduce_umin: 6156 case Intrinsic::experimental_vector_reduce_fmax: 6157 case Intrinsic::experimental_vector_reduce_fmin: 6158 visitVectorReduce(I, Intrinsic); 6159 return nullptr; 6160 6161 case Intrinsic::icall_branch_funnel: { 6162 SmallVector<SDValue, 16> Ops; 6163 Ops.push_back(DAG.getRoot()); 6164 Ops.push_back(getValue(I.getArgOperand(0))); 6165 6166 int64_t Offset; 6167 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6168 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6169 if (!Base) 6170 report_fatal_error( 6171 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6172 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6173 6174 struct BranchFunnelTarget { 6175 int64_t Offset; 6176 SDValue Target; 6177 }; 6178 SmallVector<BranchFunnelTarget, 8> Targets; 6179 6180 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6181 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6182 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6183 if (ElemBase != Base) 6184 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6185 "to the same GlobalValue"); 6186 6187 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6188 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6189 if (!GA) 6190 report_fatal_error( 6191 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6192 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6193 GA->getGlobal(), getCurSDLoc(), 6194 Val.getValueType(), GA->getOffset())}); 6195 } 6196 llvm::sort(Targets.begin(), Targets.end(), 6197 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6198 return T1.Offset < T2.Offset; 6199 }); 6200 6201 for (auto &T : Targets) { 6202 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6203 Ops.push_back(T.Target); 6204 } 6205 6206 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6207 getCurSDLoc(), MVT::Other, Ops), 6208 0); 6209 DAG.setRoot(N); 6210 setValue(&I, N); 6211 HasTailCall = true; 6212 return nullptr; 6213 } 6214 6215 case Intrinsic::wasm_landingpad_index: { 6216 // TODO store landing pad index in a map, which will be used when generating 6217 // LSDA information 6218 return nullptr; 6219 } 6220 } 6221 } 6222 6223 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6224 const ConstrainedFPIntrinsic &FPI) { 6225 SDLoc sdl = getCurSDLoc(); 6226 unsigned Opcode; 6227 switch (FPI.getIntrinsicID()) { 6228 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6229 case Intrinsic::experimental_constrained_fadd: 6230 Opcode = ISD::STRICT_FADD; 6231 break; 6232 case Intrinsic::experimental_constrained_fsub: 6233 Opcode = ISD::STRICT_FSUB; 6234 break; 6235 case Intrinsic::experimental_constrained_fmul: 6236 Opcode = ISD::STRICT_FMUL; 6237 break; 6238 case Intrinsic::experimental_constrained_fdiv: 6239 Opcode = ISD::STRICT_FDIV; 6240 break; 6241 case Intrinsic::experimental_constrained_frem: 6242 Opcode = ISD::STRICT_FREM; 6243 break; 6244 case Intrinsic::experimental_constrained_fma: 6245 Opcode = ISD::STRICT_FMA; 6246 break; 6247 case Intrinsic::experimental_constrained_sqrt: 6248 Opcode = ISD::STRICT_FSQRT; 6249 break; 6250 case Intrinsic::experimental_constrained_pow: 6251 Opcode = ISD::STRICT_FPOW; 6252 break; 6253 case Intrinsic::experimental_constrained_powi: 6254 Opcode = ISD::STRICT_FPOWI; 6255 break; 6256 case Intrinsic::experimental_constrained_sin: 6257 Opcode = ISD::STRICT_FSIN; 6258 break; 6259 case Intrinsic::experimental_constrained_cos: 6260 Opcode = ISD::STRICT_FCOS; 6261 break; 6262 case Intrinsic::experimental_constrained_exp: 6263 Opcode = ISD::STRICT_FEXP; 6264 break; 6265 case Intrinsic::experimental_constrained_exp2: 6266 Opcode = ISD::STRICT_FEXP2; 6267 break; 6268 case Intrinsic::experimental_constrained_log: 6269 Opcode = ISD::STRICT_FLOG; 6270 break; 6271 case Intrinsic::experimental_constrained_log10: 6272 Opcode = ISD::STRICT_FLOG10; 6273 break; 6274 case Intrinsic::experimental_constrained_log2: 6275 Opcode = ISD::STRICT_FLOG2; 6276 break; 6277 case Intrinsic::experimental_constrained_rint: 6278 Opcode = ISD::STRICT_FRINT; 6279 break; 6280 case Intrinsic::experimental_constrained_nearbyint: 6281 Opcode = ISD::STRICT_FNEARBYINT; 6282 break; 6283 } 6284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6285 SDValue Chain = getRoot(); 6286 SmallVector<EVT, 4> ValueVTs; 6287 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6288 ValueVTs.push_back(MVT::Other); // Out chain 6289 6290 SDVTList VTs = DAG.getVTList(ValueVTs); 6291 SDValue Result; 6292 if (FPI.isUnaryOp()) 6293 Result = DAG.getNode(Opcode, sdl, VTs, 6294 { Chain, getValue(FPI.getArgOperand(0)) }); 6295 else if (FPI.isTernaryOp()) 6296 Result = DAG.getNode(Opcode, sdl, VTs, 6297 { Chain, getValue(FPI.getArgOperand(0)), 6298 getValue(FPI.getArgOperand(1)), 6299 getValue(FPI.getArgOperand(2)) }); 6300 else 6301 Result = DAG.getNode(Opcode, sdl, VTs, 6302 { Chain, getValue(FPI.getArgOperand(0)), 6303 getValue(FPI.getArgOperand(1)) }); 6304 6305 assert(Result.getNode()->getNumValues() == 2); 6306 SDValue OutChain = Result.getValue(1); 6307 DAG.setRoot(OutChain); 6308 SDValue FPResult = Result.getValue(0); 6309 setValue(&FPI, FPResult); 6310 } 6311 6312 std::pair<SDValue, SDValue> 6313 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6314 const BasicBlock *EHPadBB) { 6315 MachineFunction &MF = DAG.getMachineFunction(); 6316 MachineModuleInfo &MMI = MF.getMMI(); 6317 MCSymbol *BeginLabel = nullptr; 6318 6319 if (EHPadBB) { 6320 // Insert a label before the invoke call to mark the try range. This can be 6321 // used to detect deletion of the invoke via the MachineModuleInfo. 6322 BeginLabel = MMI.getContext().createTempSymbol(); 6323 6324 // For SjLj, keep track of which landing pads go with which invokes 6325 // so as to maintain the ordering of pads in the LSDA. 6326 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6327 if (CallSiteIndex) { 6328 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6329 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6330 6331 // Now that the call site is handled, stop tracking it. 6332 MMI.setCurrentCallSite(0); 6333 } 6334 6335 // Both PendingLoads and PendingExports must be flushed here; 6336 // this call might not return. 6337 (void)getRoot(); 6338 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6339 6340 CLI.setChain(getRoot()); 6341 } 6342 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6343 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6344 6345 assert((CLI.IsTailCall || Result.second.getNode()) && 6346 "Non-null chain expected with non-tail call!"); 6347 assert((Result.second.getNode() || !Result.first.getNode()) && 6348 "Null value expected with tail call!"); 6349 6350 if (!Result.second.getNode()) { 6351 // As a special case, a null chain means that a tail call has been emitted 6352 // and the DAG root is already updated. 6353 HasTailCall = true; 6354 6355 // Since there's no actual continuation from this block, nothing can be 6356 // relying on us setting vregs for them. 6357 PendingExports.clear(); 6358 } else { 6359 DAG.setRoot(Result.second); 6360 } 6361 6362 if (EHPadBB) { 6363 // Insert a label at the end of the invoke call to mark the try range. This 6364 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6365 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6366 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6367 6368 // Inform MachineModuleInfo of range. 6369 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6370 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6371 // actually use outlined funclets and their LSDA info style. 6372 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6373 assert(CLI.CS); 6374 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6375 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6376 BeginLabel, EndLabel); 6377 } else { 6378 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6379 } 6380 } 6381 6382 return Result; 6383 } 6384 6385 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6386 bool isTailCall, 6387 const BasicBlock *EHPadBB) { 6388 auto &DL = DAG.getDataLayout(); 6389 FunctionType *FTy = CS.getFunctionType(); 6390 Type *RetTy = CS.getType(); 6391 6392 TargetLowering::ArgListTy Args; 6393 Args.reserve(CS.arg_size()); 6394 6395 const Value *SwiftErrorVal = nullptr; 6396 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6397 6398 // We can't tail call inside a function with a swifterror argument. Lowering 6399 // does not support this yet. It would have to move into the swifterror 6400 // register before the call. 6401 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6402 if (TLI.supportSwiftError() && 6403 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6404 isTailCall = false; 6405 6406 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6407 i != e; ++i) { 6408 TargetLowering::ArgListEntry Entry; 6409 const Value *V = *i; 6410 6411 // Skip empty types 6412 if (V->getType()->isEmptyTy()) 6413 continue; 6414 6415 SDValue ArgNode = getValue(V); 6416 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6417 6418 Entry.setAttributes(&CS, i - CS.arg_begin()); 6419 6420 // Use swifterror virtual register as input to the call. 6421 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6422 SwiftErrorVal = V; 6423 // We find the virtual register for the actual swifterror argument. 6424 // Instead of using the Value, we use the virtual register instead. 6425 Entry.Node = DAG.getRegister(FuncInfo 6426 .getOrCreateSwiftErrorVRegUseAt( 6427 CS.getInstruction(), FuncInfo.MBB, V) 6428 .first, 6429 EVT(TLI.getPointerTy(DL))); 6430 } 6431 6432 Args.push_back(Entry); 6433 6434 // If we have an explicit sret argument that is an Instruction, (i.e., it 6435 // might point to function-local memory), we can't meaningfully tail-call. 6436 if (Entry.IsSRet && isa<Instruction>(V)) 6437 isTailCall = false; 6438 } 6439 6440 // Check if target-independent constraints permit a tail call here. 6441 // Target-dependent constraints are checked within TLI->LowerCallTo. 6442 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6443 isTailCall = false; 6444 6445 // Disable tail calls if there is an swifterror argument. Targets have not 6446 // been updated to support tail calls. 6447 if (TLI.supportSwiftError() && SwiftErrorVal) 6448 isTailCall = false; 6449 6450 TargetLowering::CallLoweringInfo CLI(DAG); 6451 CLI.setDebugLoc(getCurSDLoc()) 6452 .setChain(getRoot()) 6453 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6454 .setTailCall(isTailCall) 6455 .setConvergent(CS.isConvergent()); 6456 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6457 6458 if (Result.first.getNode()) { 6459 const Instruction *Inst = CS.getInstruction(); 6460 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6461 setValue(Inst, Result.first); 6462 } 6463 6464 // The last element of CLI.InVals has the SDValue for swifterror return. 6465 // Here we copy it to a virtual register and update SwiftErrorMap for 6466 // book-keeping. 6467 if (SwiftErrorVal && TLI.supportSwiftError()) { 6468 // Get the last element of InVals. 6469 SDValue Src = CLI.InVals.back(); 6470 unsigned VReg; bool CreatedVReg; 6471 std::tie(VReg, CreatedVReg) = 6472 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6473 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6474 // We update the virtual register for the actual swifterror argument. 6475 if (CreatedVReg) 6476 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6477 DAG.setRoot(CopyNode); 6478 } 6479 } 6480 6481 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6482 SelectionDAGBuilder &Builder) { 6483 // Check to see if this load can be trivially constant folded, e.g. if the 6484 // input is from a string literal. 6485 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6486 // Cast pointer to the type we really want to load. 6487 Type *LoadTy = 6488 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6489 if (LoadVT.isVector()) 6490 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6491 6492 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6493 PointerType::getUnqual(LoadTy)); 6494 6495 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6496 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6497 return Builder.getValue(LoadCst); 6498 } 6499 6500 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6501 // still constant memory, the input chain can be the entry node. 6502 SDValue Root; 6503 bool ConstantMemory = false; 6504 6505 // Do not serialize (non-volatile) loads of constant memory with anything. 6506 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6507 Root = Builder.DAG.getEntryNode(); 6508 ConstantMemory = true; 6509 } else { 6510 // Do not serialize non-volatile loads against each other. 6511 Root = Builder.DAG.getRoot(); 6512 } 6513 6514 SDValue Ptr = Builder.getValue(PtrVal); 6515 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6516 Ptr, MachinePointerInfo(PtrVal), 6517 /* Alignment = */ 1); 6518 6519 if (!ConstantMemory) 6520 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6521 return LoadVal; 6522 } 6523 6524 /// Record the value for an instruction that produces an integer result, 6525 /// converting the type where necessary. 6526 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6527 SDValue Value, 6528 bool IsSigned) { 6529 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6530 I.getType(), true); 6531 if (IsSigned) 6532 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6533 else 6534 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6535 setValue(&I, Value); 6536 } 6537 6538 /// See if we can lower a memcmp call into an optimized form. If so, return 6539 /// true and lower it. Otherwise return false, and it will be lowered like a 6540 /// normal call. 6541 /// The caller already checked that \p I calls the appropriate LibFunc with a 6542 /// correct prototype. 6543 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6544 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6545 const Value *Size = I.getArgOperand(2); 6546 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6547 if (CSize && CSize->getZExtValue() == 0) { 6548 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6549 I.getType(), true); 6550 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6551 return true; 6552 } 6553 6554 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6555 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6556 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6557 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6558 if (Res.first.getNode()) { 6559 processIntegerCallValue(I, Res.first, true); 6560 PendingLoads.push_back(Res.second); 6561 return true; 6562 } 6563 6564 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6565 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6566 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6567 return false; 6568 6569 // If the target has a fast compare for the given size, it will return a 6570 // preferred load type for that size. Require that the load VT is legal and 6571 // that the target supports unaligned loads of that type. Otherwise, return 6572 // INVALID. 6573 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6575 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6576 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6577 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6578 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6579 // TODO: Check alignment of src and dest ptrs. 6580 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6581 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6582 if (!TLI.isTypeLegal(LVT) || 6583 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6584 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6585 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6586 } 6587 6588 return LVT; 6589 }; 6590 6591 // This turns into unaligned loads. We only do this if the target natively 6592 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6593 // we'll only produce a small number of byte loads. 6594 MVT LoadVT; 6595 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6596 switch (NumBitsToCompare) { 6597 default: 6598 return false; 6599 case 16: 6600 LoadVT = MVT::i16; 6601 break; 6602 case 32: 6603 LoadVT = MVT::i32; 6604 break; 6605 case 64: 6606 case 128: 6607 case 256: 6608 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6609 break; 6610 } 6611 6612 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6613 return false; 6614 6615 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6616 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6617 6618 // Bitcast to a wide integer type if the loads are vectors. 6619 if (LoadVT.isVector()) { 6620 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6621 LoadL = DAG.getBitcast(CmpVT, LoadL); 6622 LoadR = DAG.getBitcast(CmpVT, LoadR); 6623 } 6624 6625 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6626 processIntegerCallValue(I, Cmp, false); 6627 return true; 6628 } 6629 6630 /// See if we can lower a memchr call into an optimized form. If so, return 6631 /// true and lower it. Otherwise return false, and it will be lowered like a 6632 /// normal call. 6633 /// The caller already checked that \p I calls the appropriate LibFunc with a 6634 /// correct prototype. 6635 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6636 const Value *Src = I.getArgOperand(0); 6637 const Value *Char = I.getArgOperand(1); 6638 const Value *Length = I.getArgOperand(2); 6639 6640 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6641 std::pair<SDValue, SDValue> Res = 6642 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6643 getValue(Src), getValue(Char), getValue(Length), 6644 MachinePointerInfo(Src)); 6645 if (Res.first.getNode()) { 6646 setValue(&I, Res.first); 6647 PendingLoads.push_back(Res.second); 6648 return true; 6649 } 6650 6651 return false; 6652 } 6653 6654 /// See if we can lower a mempcpy call into an optimized form. If so, return 6655 /// true and lower it. Otherwise return false, and it will be lowered like a 6656 /// normal call. 6657 /// The caller already checked that \p I calls the appropriate LibFunc with a 6658 /// correct prototype. 6659 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6660 SDValue Dst = getValue(I.getArgOperand(0)); 6661 SDValue Src = getValue(I.getArgOperand(1)); 6662 SDValue Size = getValue(I.getArgOperand(2)); 6663 6664 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6665 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6666 unsigned Align = std::min(DstAlign, SrcAlign); 6667 if (Align == 0) // Alignment of one or both could not be inferred. 6668 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6669 6670 bool isVol = false; 6671 SDLoc sdl = getCurSDLoc(); 6672 6673 // In the mempcpy context we need to pass in a false value for isTailCall 6674 // because the return pointer needs to be adjusted by the size of 6675 // the copied memory. 6676 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6677 false, /*isTailCall=*/false, 6678 MachinePointerInfo(I.getArgOperand(0)), 6679 MachinePointerInfo(I.getArgOperand(1))); 6680 assert(MC.getNode() != nullptr && 6681 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6682 DAG.setRoot(MC); 6683 6684 // Check if Size needs to be truncated or extended. 6685 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6686 6687 // Adjust return pointer to point just past the last dst byte. 6688 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6689 Dst, Size); 6690 setValue(&I, DstPlusSize); 6691 return true; 6692 } 6693 6694 /// See if we can lower a strcpy call into an optimized form. If so, return 6695 /// true and lower it, otherwise return false and it will be lowered like a 6696 /// normal call. 6697 /// The caller already checked that \p I calls the appropriate LibFunc with a 6698 /// correct prototype. 6699 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6700 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6701 6702 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6703 std::pair<SDValue, SDValue> Res = 6704 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6705 getValue(Arg0), getValue(Arg1), 6706 MachinePointerInfo(Arg0), 6707 MachinePointerInfo(Arg1), isStpcpy); 6708 if (Res.first.getNode()) { 6709 setValue(&I, Res.first); 6710 DAG.setRoot(Res.second); 6711 return true; 6712 } 6713 6714 return false; 6715 } 6716 6717 /// See if we can lower a strcmp call into an optimized form. If so, return 6718 /// true and lower it, otherwise return false and it will be lowered like a 6719 /// normal call. 6720 /// The caller already checked that \p I calls the appropriate LibFunc with a 6721 /// correct prototype. 6722 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6723 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6724 6725 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6726 std::pair<SDValue, SDValue> Res = 6727 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6728 getValue(Arg0), getValue(Arg1), 6729 MachinePointerInfo(Arg0), 6730 MachinePointerInfo(Arg1)); 6731 if (Res.first.getNode()) { 6732 processIntegerCallValue(I, Res.first, true); 6733 PendingLoads.push_back(Res.second); 6734 return true; 6735 } 6736 6737 return false; 6738 } 6739 6740 /// See if we can lower a strlen call into an optimized form. If so, return 6741 /// true and lower it, otherwise return false and it will be lowered like a 6742 /// normal call. 6743 /// The caller already checked that \p I calls the appropriate LibFunc with a 6744 /// correct prototype. 6745 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6746 const Value *Arg0 = I.getArgOperand(0); 6747 6748 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6749 std::pair<SDValue, SDValue> Res = 6750 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6751 getValue(Arg0), MachinePointerInfo(Arg0)); 6752 if (Res.first.getNode()) { 6753 processIntegerCallValue(I, Res.first, false); 6754 PendingLoads.push_back(Res.second); 6755 return true; 6756 } 6757 6758 return false; 6759 } 6760 6761 /// See if we can lower a strnlen call into an optimized form. If so, return 6762 /// true and lower it, otherwise return false and it will be lowered like a 6763 /// normal call. 6764 /// The caller already checked that \p I calls the appropriate LibFunc with a 6765 /// correct prototype. 6766 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6767 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6768 6769 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6770 std::pair<SDValue, SDValue> Res = 6771 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6772 getValue(Arg0), getValue(Arg1), 6773 MachinePointerInfo(Arg0)); 6774 if (Res.first.getNode()) { 6775 processIntegerCallValue(I, Res.first, false); 6776 PendingLoads.push_back(Res.second); 6777 return true; 6778 } 6779 6780 return false; 6781 } 6782 6783 /// See if we can lower a unary floating-point operation into an SDNode with 6784 /// the specified Opcode. If so, return true and lower it, otherwise return 6785 /// false and it will be lowered like a normal call. 6786 /// The caller already checked that \p I calls the appropriate LibFunc with a 6787 /// correct prototype. 6788 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6789 unsigned Opcode) { 6790 // We already checked this call's prototype; verify it doesn't modify errno. 6791 if (!I.onlyReadsMemory()) 6792 return false; 6793 6794 SDValue Tmp = getValue(I.getArgOperand(0)); 6795 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6796 return true; 6797 } 6798 6799 /// See if we can lower a binary floating-point operation into an SDNode with 6800 /// the specified Opcode. If so, return true and lower it. Otherwise return 6801 /// false, and it will be lowered like a normal call. 6802 /// The caller already checked that \p I calls the appropriate LibFunc with a 6803 /// correct prototype. 6804 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6805 unsigned Opcode) { 6806 // We already checked this call's prototype; verify it doesn't modify errno. 6807 if (!I.onlyReadsMemory()) 6808 return false; 6809 6810 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6811 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6812 EVT VT = Tmp0.getValueType(); 6813 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6814 return true; 6815 } 6816 6817 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6818 // Handle inline assembly differently. 6819 if (isa<InlineAsm>(I.getCalledValue())) { 6820 visitInlineAsm(&I); 6821 return; 6822 } 6823 6824 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6825 computeUsesVAFloatArgument(I, MMI); 6826 6827 const char *RenameFn = nullptr; 6828 if (Function *F = I.getCalledFunction()) { 6829 if (F->isDeclaration()) { 6830 // Is this an LLVM intrinsic or a target-specific intrinsic? 6831 unsigned IID = F->getIntrinsicID(); 6832 if (!IID) 6833 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6834 IID = II->getIntrinsicID(F); 6835 6836 if (IID) { 6837 RenameFn = visitIntrinsicCall(I, IID); 6838 if (!RenameFn) 6839 return; 6840 } 6841 } 6842 6843 // Check for well-known libc/libm calls. If the function is internal, it 6844 // can't be a library call. Don't do the check if marked as nobuiltin for 6845 // some reason or the call site requires strict floating point semantics. 6846 LibFunc Func; 6847 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6848 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6849 LibInfo->hasOptimizedCodeGen(Func)) { 6850 switch (Func) { 6851 default: break; 6852 case LibFunc_copysign: 6853 case LibFunc_copysignf: 6854 case LibFunc_copysignl: 6855 // We already checked this call's prototype; verify it doesn't modify 6856 // errno. 6857 if (I.onlyReadsMemory()) { 6858 SDValue LHS = getValue(I.getArgOperand(0)); 6859 SDValue RHS = getValue(I.getArgOperand(1)); 6860 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6861 LHS.getValueType(), LHS, RHS)); 6862 return; 6863 } 6864 break; 6865 case LibFunc_fabs: 6866 case LibFunc_fabsf: 6867 case LibFunc_fabsl: 6868 if (visitUnaryFloatCall(I, ISD::FABS)) 6869 return; 6870 break; 6871 case LibFunc_fmin: 6872 case LibFunc_fminf: 6873 case LibFunc_fminl: 6874 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6875 return; 6876 break; 6877 case LibFunc_fmax: 6878 case LibFunc_fmaxf: 6879 case LibFunc_fmaxl: 6880 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6881 return; 6882 break; 6883 case LibFunc_sin: 6884 case LibFunc_sinf: 6885 case LibFunc_sinl: 6886 if (visitUnaryFloatCall(I, ISD::FSIN)) 6887 return; 6888 break; 6889 case LibFunc_cos: 6890 case LibFunc_cosf: 6891 case LibFunc_cosl: 6892 if (visitUnaryFloatCall(I, ISD::FCOS)) 6893 return; 6894 break; 6895 case LibFunc_sqrt: 6896 case LibFunc_sqrtf: 6897 case LibFunc_sqrtl: 6898 case LibFunc_sqrt_finite: 6899 case LibFunc_sqrtf_finite: 6900 case LibFunc_sqrtl_finite: 6901 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6902 return; 6903 break; 6904 case LibFunc_floor: 6905 case LibFunc_floorf: 6906 case LibFunc_floorl: 6907 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6908 return; 6909 break; 6910 case LibFunc_nearbyint: 6911 case LibFunc_nearbyintf: 6912 case LibFunc_nearbyintl: 6913 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6914 return; 6915 break; 6916 case LibFunc_ceil: 6917 case LibFunc_ceilf: 6918 case LibFunc_ceill: 6919 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6920 return; 6921 break; 6922 case LibFunc_rint: 6923 case LibFunc_rintf: 6924 case LibFunc_rintl: 6925 if (visitUnaryFloatCall(I, ISD::FRINT)) 6926 return; 6927 break; 6928 case LibFunc_round: 6929 case LibFunc_roundf: 6930 case LibFunc_roundl: 6931 if (visitUnaryFloatCall(I, ISD::FROUND)) 6932 return; 6933 break; 6934 case LibFunc_trunc: 6935 case LibFunc_truncf: 6936 case LibFunc_truncl: 6937 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6938 return; 6939 break; 6940 case LibFunc_log2: 6941 case LibFunc_log2f: 6942 case LibFunc_log2l: 6943 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6944 return; 6945 break; 6946 case LibFunc_exp2: 6947 case LibFunc_exp2f: 6948 case LibFunc_exp2l: 6949 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6950 return; 6951 break; 6952 case LibFunc_memcmp: 6953 if (visitMemCmpCall(I)) 6954 return; 6955 break; 6956 case LibFunc_mempcpy: 6957 if (visitMemPCpyCall(I)) 6958 return; 6959 break; 6960 case LibFunc_memchr: 6961 if (visitMemChrCall(I)) 6962 return; 6963 break; 6964 case LibFunc_strcpy: 6965 if (visitStrCpyCall(I, false)) 6966 return; 6967 break; 6968 case LibFunc_stpcpy: 6969 if (visitStrCpyCall(I, true)) 6970 return; 6971 break; 6972 case LibFunc_strcmp: 6973 if (visitStrCmpCall(I)) 6974 return; 6975 break; 6976 case LibFunc_strlen: 6977 if (visitStrLenCall(I)) 6978 return; 6979 break; 6980 case LibFunc_strnlen: 6981 if (visitStrNLenCall(I)) 6982 return; 6983 break; 6984 } 6985 } 6986 } 6987 6988 SDValue Callee; 6989 if (!RenameFn) 6990 Callee = getValue(I.getCalledValue()); 6991 else 6992 Callee = DAG.getExternalSymbol( 6993 RenameFn, 6994 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6995 6996 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 6997 // have to do anything here to lower funclet bundles. 6998 assert(!I.hasOperandBundlesOtherThan( 6999 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7000 "Cannot lower calls with arbitrary operand bundles!"); 7001 7002 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7003 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7004 else 7005 // Check if we can potentially perform a tail call. More detailed checking 7006 // is be done within LowerCallTo, after more information about the call is 7007 // known. 7008 LowerCallTo(&I, Callee, I.isTailCall()); 7009 } 7010 7011 namespace { 7012 7013 /// AsmOperandInfo - This contains information for each constraint that we are 7014 /// lowering. 7015 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7016 public: 7017 /// CallOperand - If this is the result output operand or a clobber 7018 /// this is null, otherwise it is the incoming operand to the CallInst. 7019 /// This gets modified as the asm is processed. 7020 SDValue CallOperand; 7021 7022 /// AssignedRegs - If this is a register or register class operand, this 7023 /// contains the set of register corresponding to the operand. 7024 RegsForValue AssignedRegs; 7025 7026 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7027 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7028 } 7029 7030 /// Whether or not this operand accesses memory 7031 bool hasMemory(const TargetLowering &TLI) const { 7032 // Indirect operand accesses access memory. 7033 if (isIndirect) 7034 return true; 7035 7036 for (const auto &Code : Codes) 7037 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7038 return true; 7039 7040 return false; 7041 } 7042 7043 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7044 /// corresponds to. If there is no Value* for this operand, it returns 7045 /// MVT::Other. 7046 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7047 const DataLayout &DL) const { 7048 if (!CallOperandVal) return MVT::Other; 7049 7050 if (isa<BasicBlock>(CallOperandVal)) 7051 return TLI.getPointerTy(DL); 7052 7053 llvm::Type *OpTy = CallOperandVal->getType(); 7054 7055 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7056 // If this is an indirect operand, the operand is a pointer to the 7057 // accessed type. 7058 if (isIndirect) { 7059 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7060 if (!PtrTy) 7061 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7062 OpTy = PtrTy->getElementType(); 7063 } 7064 7065 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7066 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7067 if (STy->getNumElements() == 1) 7068 OpTy = STy->getElementType(0); 7069 7070 // If OpTy is not a single value, it may be a struct/union that we 7071 // can tile with integers. 7072 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7073 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7074 switch (BitSize) { 7075 default: break; 7076 case 1: 7077 case 8: 7078 case 16: 7079 case 32: 7080 case 64: 7081 case 128: 7082 OpTy = IntegerType::get(Context, BitSize); 7083 break; 7084 } 7085 } 7086 7087 return TLI.getValueType(DL, OpTy, true); 7088 } 7089 }; 7090 7091 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7092 7093 } // end anonymous namespace 7094 7095 /// Make sure that the output operand \p OpInfo and its corresponding input 7096 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7097 /// out). 7098 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7099 SDISelAsmOperandInfo &MatchingOpInfo, 7100 SelectionDAG &DAG) { 7101 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7102 return; 7103 7104 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7105 const auto &TLI = DAG.getTargetLoweringInfo(); 7106 7107 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7108 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7109 OpInfo.ConstraintVT); 7110 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7111 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7112 MatchingOpInfo.ConstraintVT); 7113 if ((OpInfo.ConstraintVT.isInteger() != 7114 MatchingOpInfo.ConstraintVT.isInteger()) || 7115 (MatchRC.second != InputRC.second)) { 7116 // FIXME: error out in a more elegant fashion 7117 report_fatal_error("Unsupported asm: input constraint" 7118 " with a matching output constraint of" 7119 " incompatible type!"); 7120 } 7121 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7122 } 7123 7124 /// Get a direct memory input to behave well as an indirect operand. 7125 /// This may introduce stores, hence the need for a \p Chain. 7126 /// \return The (possibly updated) chain. 7127 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7128 SDISelAsmOperandInfo &OpInfo, 7129 SelectionDAG &DAG) { 7130 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7131 7132 // If we don't have an indirect input, put it in the constpool if we can, 7133 // otherwise spill it to a stack slot. 7134 // TODO: This isn't quite right. We need to handle these according to 7135 // the addressing mode that the constraint wants. Also, this may take 7136 // an additional register for the computation and we don't want that 7137 // either. 7138 7139 // If the operand is a float, integer, or vector constant, spill to a 7140 // constant pool entry to get its address. 7141 const Value *OpVal = OpInfo.CallOperandVal; 7142 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7143 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7144 OpInfo.CallOperand = DAG.getConstantPool( 7145 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7146 return Chain; 7147 } 7148 7149 // Otherwise, create a stack slot and emit a store to it before the asm. 7150 Type *Ty = OpVal->getType(); 7151 auto &DL = DAG.getDataLayout(); 7152 uint64_t TySize = DL.getTypeAllocSize(Ty); 7153 unsigned Align = DL.getPrefTypeAlignment(Ty); 7154 MachineFunction &MF = DAG.getMachineFunction(); 7155 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7156 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7157 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7158 MachinePointerInfo::getFixedStack(MF, SSFI)); 7159 OpInfo.CallOperand = StackSlot; 7160 7161 return Chain; 7162 } 7163 7164 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7165 /// specified operand. We prefer to assign virtual registers, to allow the 7166 /// register allocator to handle the assignment process. However, if the asm 7167 /// uses features that we can't model on machineinstrs, we have SDISel do the 7168 /// allocation. This produces generally horrible, but correct, code. 7169 /// 7170 /// OpInfo describes the operand. 7171 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 7172 const SDLoc &DL, 7173 SDISelAsmOperandInfo &OpInfo) { 7174 LLVMContext &Context = *DAG.getContext(); 7175 7176 MachineFunction &MF = DAG.getMachineFunction(); 7177 SmallVector<unsigned, 4> Regs; 7178 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7179 7180 // If this is a constraint for a single physreg, or a constraint for a 7181 // register class, find it. 7182 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 7183 TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode, 7184 OpInfo.ConstraintVT); 7185 7186 unsigned NumRegs = 1; 7187 if (OpInfo.ConstraintVT != MVT::Other) { 7188 // If this is a FP operand in an integer register (or visa versa), or more 7189 // generally if the operand value disagrees with the register class we plan 7190 // to stick it in, fix the operand type. 7191 // 7192 // If this is an input value, the bitcast to the new type is done now. 7193 // Bitcast for output value is done at the end of visitInlineAsm(). 7194 if ((OpInfo.Type == InlineAsm::isOutput || 7195 OpInfo.Type == InlineAsm::isInput) && 7196 PhysReg.second && 7197 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 7198 // Try to convert to the first EVT that the reg class contains. If the 7199 // types are identical size, use a bitcast to convert (e.g. two differing 7200 // vector types). Note: output bitcast is done at the end of 7201 // visitInlineAsm(). 7202 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 7203 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7204 // Exclude indirect inputs while they are unsupported because the code 7205 // to perform the load is missing and thus OpInfo.CallOperand still 7206 // refer to the input address rather than the pointed-to value. 7207 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7208 OpInfo.CallOperand = 7209 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7210 OpInfo.ConstraintVT = RegVT; 7211 // If the operand is a FP value and we want it in integer registers, 7212 // use the corresponding integer type. This turns an f64 value into 7213 // i64, which can be passed with two i32 values on a 32-bit machine. 7214 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7215 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7216 if (OpInfo.Type == InlineAsm::isInput) 7217 OpInfo.CallOperand = 7218 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7219 OpInfo.ConstraintVT = RegVT; 7220 } 7221 } 7222 7223 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7224 } 7225 7226 MVT RegVT; 7227 EVT ValueVT = OpInfo.ConstraintVT; 7228 7229 // If this is a constraint for a specific physical register, like {r17}, 7230 // assign it now. 7231 if (unsigned AssignedReg = PhysReg.first) { 7232 const TargetRegisterClass *RC = PhysReg.second; 7233 if (OpInfo.ConstraintVT == MVT::Other) 7234 ValueVT = *TRI.legalclasstypes_begin(*RC); 7235 7236 // Get the actual register value type. This is important, because the user 7237 // may have asked for (e.g.) the AX register in i32 type. We need to 7238 // remember that AX is actually i16 to get the right extension. 7239 RegVT = *TRI.legalclasstypes_begin(*RC); 7240 7241 // This is a explicit reference to a physical register. 7242 Regs.push_back(AssignedReg); 7243 7244 // If this is an expanded reference, add the rest of the regs to Regs. 7245 if (NumRegs != 1) { 7246 TargetRegisterClass::iterator I = RC->begin(); 7247 for (; *I != AssignedReg; ++I) 7248 assert(I != RC->end() && "Didn't find reg!"); 7249 7250 // Already added the first reg. 7251 --NumRegs; ++I; 7252 for (; NumRegs; --NumRegs, ++I) { 7253 assert(I != RC->end() && "Ran out of registers to allocate!"); 7254 Regs.push_back(*I); 7255 } 7256 } 7257 7258 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7259 return; 7260 } 7261 7262 // Otherwise, if this was a reference to an LLVM register class, create vregs 7263 // for this reference. 7264 if (const TargetRegisterClass *RC = PhysReg.second) { 7265 RegVT = *TRI.legalclasstypes_begin(*RC); 7266 if (OpInfo.ConstraintVT == MVT::Other) 7267 ValueVT = RegVT; 7268 7269 // Create the appropriate number of virtual registers. 7270 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7271 for (; NumRegs; --NumRegs) 7272 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7273 7274 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7275 return; 7276 } 7277 7278 // Otherwise, we couldn't allocate enough registers for this. 7279 } 7280 7281 static unsigned 7282 findMatchingInlineAsmOperand(unsigned OperandNo, 7283 const std::vector<SDValue> &AsmNodeOperands) { 7284 // Scan until we find the definition we already emitted of this operand. 7285 unsigned CurOp = InlineAsm::Op_FirstOperand; 7286 for (; OperandNo; --OperandNo) { 7287 // Advance to the next operand. 7288 unsigned OpFlag = 7289 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7290 assert((InlineAsm::isRegDefKind(OpFlag) || 7291 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7292 InlineAsm::isMemKind(OpFlag)) && 7293 "Skipped past definitions?"); 7294 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7295 } 7296 return CurOp; 7297 } 7298 7299 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7300 /// \return true if it has succeeded, false otherwise 7301 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7302 MVT RegVT, SelectionDAG &DAG) { 7303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7304 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7305 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7306 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7307 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7308 else 7309 return false; 7310 } 7311 return true; 7312 } 7313 7314 namespace { 7315 7316 class ExtraFlags { 7317 unsigned Flags = 0; 7318 7319 public: 7320 explicit ExtraFlags(ImmutableCallSite CS) { 7321 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7322 if (IA->hasSideEffects()) 7323 Flags |= InlineAsm::Extra_HasSideEffects; 7324 if (IA->isAlignStack()) 7325 Flags |= InlineAsm::Extra_IsAlignStack; 7326 if (CS.isConvergent()) 7327 Flags |= InlineAsm::Extra_IsConvergent; 7328 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7329 } 7330 7331 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7332 // Ideally, we would only check against memory constraints. However, the 7333 // meaning of an Other constraint can be target-specific and we can't easily 7334 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7335 // for Other constraints as well. 7336 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7337 OpInfo.ConstraintType == TargetLowering::C_Other) { 7338 if (OpInfo.Type == InlineAsm::isInput) 7339 Flags |= InlineAsm::Extra_MayLoad; 7340 else if (OpInfo.Type == InlineAsm::isOutput) 7341 Flags |= InlineAsm::Extra_MayStore; 7342 else if (OpInfo.Type == InlineAsm::isClobber) 7343 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7344 } 7345 } 7346 7347 unsigned get() const { return Flags; } 7348 }; 7349 7350 } // end anonymous namespace 7351 7352 /// visitInlineAsm - Handle a call to an InlineAsm object. 7353 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7354 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7355 7356 /// ConstraintOperands - Information about all of the constraints. 7357 SDISelAsmOperandInfoVector ConstraintOperands; 7358 7359 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7360 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7361 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7362 7363 bool hasMemory = false; 7364 7365 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7366 ExtraFlags ExtraInfo(CS); 7367 7368 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7369 unsigned ResNo = 0; // ResNo - The result number of the next output. 7370 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7371 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7372 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7373 7374 MVT OpVT = MVT::Other; 7375 7376 // Compute the value type for each operand. 7377 if (OpInfo.Type == InlineAsm::isInput || 7378 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7379 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7380 7381 // Process the call argument. BasicBlocks are labels, currently appearing 7382 // only in asm's. 7383 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7384 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7385 } else { 7386 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7387 } 7388 7389 OpVT = 7390 OpInfo 7391 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7392 .getSimpleVT(); 7393 } 7394 7395 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7396 // The return value of the call is this value. As such, there is no 7397 // corresponding argument. 7398 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7399 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7400 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7401 STy->getElementType(ResNo)); 7402 } else { 7403 assert(ResNo == 0 && "Asm only has one result!"); 7404 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7405 } 7406 ++ResNo; 7407 } 7408 7409 OpInfo.ConstraintVT = OpVT; 7410 7411 if (!hasMemory) 7412 hasMemory = OpInfo.hasMemory(TLI); 7413 7414 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7415 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7416 auto TargetConstraint = TargetConstraints[i]; 7417 7418 // Compute the constraint code and ConstraintType to use. 7419 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7420 7421 ExtraInfo.update(TargetConstraint); 7422 } 7423 7424 SDValue Chain, Flag; 7425 7426 // We won't need to flush pending loads if this asm doesn't touch 7427 // memory and is nonvolatile. 7428 if (hasMemory || IA->hasSideEffects()) 7429 Chain = getRoot(); 7430 else 7431 Chain = DAG.getRoot(); 7432 7433 // Second pass over the constraints: compute which constraint option to use 7434 // and assign registers to constraints that want a specific physreg. 7435 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7436 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7437 7438 // If this is an output operand with a matching input operand, look up the 7439 // matching input. If their types mismatch, e.g. one is an integer, the 7440 // other is floating point, or their sizes are different, flag it as an 7441 // error. 7442 if (OpInfo.hasMatchingInput()) { 7443 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7444 patchMatchingInput(OpInfo, Input, DAG); 7445 } 7446 7447 // Compute the constraint code and ConstraintType to use. 7448 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7449 7450 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7451 OpInfo.Type == InlineAsm::isClobber) 7452 continue; 7453 7454 // If this is a memory input, and if the operand is not indirect, do what we 7455 // need to provide an address for the memory input. 7456 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7457 !OpInfo.isIndirect) { 7458 assert((OpInfo.isMultipleAlternative || 7459 (OpInfo.Type == InlineAsm::isInput)) && 7460 "Can only indirectify direct input operands!"); 7461 7462 // Memory operands really want the address of the value. 7463 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7464 7465 // There is no longer a Value* corresponding to this operand. 7466 OpInfo.CallOperandVal = nullptr; 7467 7468 // It is now an indirect operand. 7469 OpInfo.isIndirect = true; 7470 } 7471 7472 // If this constraint is for a specific register, allocate it before 7473 // anything else. 7474 if (OpInfo.ConstraintType == TargetLowering::C_Register) 7475 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7476 } 7477 7478 // Third pass - Loop over all of the operands, assigning virtual or physregs 7479 // to register class operands. 7480 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7481 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7482 7483 // C_Register operands have already been allocated, Other/Memory don't need 7484 // to be. 7485 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7486 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7487 } 7488 7489 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7490 std::vector<SDValue> AsmNodeOperands; 7491 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7492 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7493 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7494 7495 // If we have a !srcloc metadata node associated with it, we want to attach 7496 // this to the ultimately generated inline asm machineinstr. To do this, we 7497 // pass in the third operand as this (potentially null) inline asm MDNode. 7498 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7499 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7500 7501 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7502 // bits as operand 3. 7503 AsmNodeOperands.push_back(DAG.getTargetConstant( 7504 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7505 7506 // Loop over all of the inputs, copying the operand values into the 7507 // appropriate registers and processing the output regs. 7508 RegsForValue RetValRegs; 7509 7510 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7511 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7512 7513 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7514 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7515 7516 switch (OpInfo.Type) { 7517 case InlineAsm::isOutput: 7518 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7519 OpInfo.ConstraintType != TargetLowering::C_Register) { 7520 // Memory output, or 'other' output (e.g. 'X' constraint). 7521 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7522 7523 unsigned ConstraintID = 7524 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7525 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7526 "Failed to convert memory constraint code to constraint id."); 7527 7528 // Add information to the INLINEASM node to know about this output. 7529 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7530 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7531 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7532 MVT::i32)); 7533 AsmNodeOperands.push_back(OpInfo.CallOperand); 7534 break; 7535 } 7536 7537 // Otherwise, this is a register or register class output. 7538 7539 // Copy the output from the appropriate register. Find a register that 7540 // we can use. 7541 if (OpInfo.AssignedRegs.Regs.empty()) { 7542 emitInlineAsmError( 7543 CS, "couldn't allocate output register for constraint '" + 7544 Twine(OpInfo.ConstraintCode) + "'"); 7545 return; 7546 } 7547 7548 // If this is an indirect operand, store through the pointer after the 7549 // asm. 7550 if (OpInfo.isIndirect) { 7551 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7552 OpInfo.CallOperandVal)); 7553 } else { 7554 // This is the result value of the call. 7555 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7556 // Concatenate this output onto the outputs list. 7557 RetValRegs.append(OpInfo.AssignedRegs); 7558 } 7559 7560 // Add information to the INLINEASM node to know that this register is 7561 // set. 7562 OpInfo.AssignedRegs 7563 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7564 ? InlineAsm::Kind_RegDefEarlyClobber 7565 : InlineAsm::Kind_RegDef, 7566 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7567 break; 7568 7569 case InlineAsm::isInput: { 7570 SDValue InOperandVal = OpInfo.CallOperand; 7571 7572 if (OpInfo.isMatchingInputConstraint()) { 7573 // If this is required to match an output register we have already set, 7574 // just use its register. 7575 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7576 AsmNodeOperands); 7577 unsigned OpFlag = 7578 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7579 if (InlineAsm::isRegDefKind(OpFlag) || 7580 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7581 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7582 if (OpInfo.isIndirect) { 7583 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7584 emitInlineAsmError(CS, "inline asm not supported yet:" 7585 " don't know how to handle tied " 7586 "indirect register inputs"); 7587 return; 7588 } 7589 7590 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7591 SmallVector<unsigned, 4> Regs; 7592 7593 if (!createVirtualRegs(Regs, 7594 InlineAsm::getNumOperandRegisters(OpFlag), 7595 RegVT, DAG)) { 7596 emitInlineAsmError(CS, "inline asm error: This value type register " 7597 "class is not natively supported!"); 7598 return; 7599 } 7600 7601 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7602 7603 SDLoc dl = getCurSDLoc(); 7604 // Use the produced MatchedRegs object to 7605 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7606 CS.getInstruction()); 7607 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7608 true, OpInfo.getMatchedOperand(), dl, 7609 DAG, AsmNodeOperands); 7610 break; 7611 } 7612 7613 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7614 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7615 "Unexpected number of operands"); 7616 // Add information to the INLINEASM node to know about this input. 7617 // See InlineAsm.h isUseOperandTiedToDef. 7618 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7619 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7620 OpInfo.getMatchedOperand()); 7621 AsmNodeOperands.push_back(DAG.getTargetConstant( 7622 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7623 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7624 break; 7625 } 7626 7627 // Treat indirect 'X' constraint as memory. 7628 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7629 OpInfo.isIndirect) 7630 OpInfo.ConstraintType = TargetLowering::C_Memory; 7631 7632 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7633 std::vector<SDValue> Ops; 7634 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7635 Ops, DAG); 7636 if (Ops.empty()) { 7637 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7638 Twine(OpInfo.ConstraintCode) + "'"); 7639 return; 7640 } 7641 7642 // Add information to the INLINEASM node to know about this input. 7643 unsigned ResOpType = 7644 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7645 AsmNodeOperands.push_back(DAG.getTargetConstant( 7646 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7647 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7648 break; 7649 } 7650 7651 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7652 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7653 assert(InOperandVal.getValueType() == 7654 TLI.getPointerTy(DAG.getDataLayout()) && 7655 "Memory operands expect pointer values"); 7656 7657 unsigned ConstraintID = 7658 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7659 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7660 "Failed to convert memory constraint code to constraint id."); 7661 7662 // Add information to the INLINEASM node to know about this input. 7663 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7664 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7665 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7666 getCurSDLoc(), 7667 MVT::i32)); 7668 AsmNodeOperands.push_back(InOperandVal); 7669 break; 7670 } 7671 7672 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7673 OpInfo.ConstraintType == TargetLowering::C_Register) && 7674 "Unknown constraint type!"); 7675 7676 // TODO: Support this. 7677 if (OpInfo.isIndirect) { 7678 emitInlineAsmError( 7679 CS, "Don't know how to handle indirect register inputs yet " 7680 "for constraint '" + 7681 Twine(OpInfo.ConstraintCode) + "'"); 7682 return; 7683 } 7684 7685 // Copy the input into the appropriate registers. 7686 if (OpInfo.AssignedRegs.Regs.empty()) { 7687 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7688 Twine(OpInfo.ConstraintCode) + "'"); 7689 return; 7690 } 7691 7692 SDLoc dl = getCurSDLoc(); 7693 7694 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7695 Chain, &Flag, CS.getInstruction()); 7696 7697 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7698 dl, DAG, AsmNodeOperands); 7699 break; 7700 } 7701 case InlineAsm::isClobber: 7702 // Add the clobbered value to the operand list, so that the register 7703 // allocator is aware that the physreg got clobbered. 7704 if (!OpInfo.AssignedRegs.Regs.empty()) 7705 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7706 false, 0, getCurSDLoc(), DAG, 7707 AsmNodeOperands); 7708 break; 7709 } 7710 } 7711 7712 // Finish up input operands. Set the input chain and add the flag last. 7713 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7714 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7715 7716 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7717 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7718 Flag = Chain.getValue(1); 7719 7720 // If this asm returns a register value, copy the result from that register 7721 // and set it as the value of the call. 7722 if (!RetValRegs.Regs.empty()) { 7723 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7724 Chain, &Flag, CS.getInstruction()); 7725 7726 // FIXME: Why don't we do this for inline asms with MRVs? 7727 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7728 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7729 7730 // If the type of the inline asm call site return value is different but 7731 // has same size as the type of the asm output bitcast it. One example 7732 // of this is for vectors with different width / number of elements. 7733 // This can happen for register classes that can contain multiple 7734 // different value types. The preg or vreg allocated may not have the 7735 // same VT as was expected. 7736 // 7737 // This can also happen for a return value that disagrees with the 7738 // register class it is put in, eg. a double in a general-purpose 7739 // register on a 32-bit machine. 7740 if (ResultType != Val.getValueType() && 7741 ResultType.getSizeInBits() == Val.getValueSizeInBits()) { 7742 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7743 ResultType, Val); 7744 7745 } else if (ResultType != Val.getValueType() && 7746 ResultType.isInteger() && Val.getValueType().isInteger()) { 7747 // If a result value was tied to an input value, the computed result may 7748 // have a wider width than the expected result. Extract the relevant 7749 // portion. 7750 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7751 } 7752 7753 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7754 } 7755 7756 setValue(CS.getInstruction(), Val); 7757 // Don't need to use this as a chain in this case. 7758 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7759 return; 7760 } 7761 7762 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7763 7764 // Process indirect outputs, first output all of the flagged copies out of 7765 // physregs. 7766 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7767 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7768 const Value *Ptr = IndirectStoresToEmit[i].second; 7769 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7770 Chain, &Flag, IA); 7771 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7772 } 7773 7774 // Emit the non-flagged stores from the physregs. 7775 SmallVector<SDValue, 8> OutChains; 7776 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7777 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7778 getValue(StoresToEmit[i].second), 7779 MachinePointerInfo(StoresToEmit[i].second)); 7780 OutChains.push_back(Val); 7781 } 7782 7783 if (!OutChains.empty()) 7784 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7785 7786 DAG.setRoot(Chain); 7787 } 7788 7789 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7790 const Twine &Message) { 7791 LLVMContext &Ctx = *DAG.getContext(); 7792 Ctx.emitError(CS.getInstruction(), Message); 7793 7794 // Make sure we leave the DAG in a valid state 7795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7796 SmallVector<EVT, 1> ValueVTs; 7797 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7798 7799 if (ValueVTs.empty()) 7800 return; 7801 7802 SmallVector<SDValue, 1> Ops; 7803 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7804 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7805 7806 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7807 } 7808 7809 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7810 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7811 MVT::Other, getRoot(), 7812 getValue(I.getArgOperand(0)), 7813 DAG.getSrcValue(I.getArgOperand(0)))); 7814 } 7815 7816 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7818 const DataLayout &DL = DAG.getDataLayout(); 7819 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7820 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7821 DAG.getSrcValue(I.getOperand(0)), 7822 DL.getABITypeAlignment(I.getType())); 7823 setValue(&I, V); 7824 DAG.setRoot(V.getValue(1)); 7825 } 7826 7827 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7828 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7829 MVT::Other, getRoot(), 7830 getValue(I.getArgOperand(0)), 7831 DAG.getSrcValue(I.getArgOperand(0)))); 7832 } 7833 7834 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7835 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7836 MVT::Other, getRoot(), 7837 getValue(I.getArgOperand(0)), 7838 getValue(I.getArgOperand(1)), 7839 DAG.getSrcValue(I.getArgOperand(0)), 7840 DAG.getSrcValue(I.getArgOperand(1)))); 7841 } 7842 7843 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7844 const Instruction &I, 7845 SDValue Op) { 7846 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7847 if (!Range) 7848 return Op; 7849 7850 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7851 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7852 return Op; 7853 7854 APInt Lo = CR.getUnsignedMin(); 7855 if (!Lo.isMinValue()) 7856 return Op; 7857 7858 APInt Hi = CR.getUnsignedMax(); 7859 unsigned Bits = Hi.getActiveBits(); 7860 7861 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7862 7863 SDLoc SL = getCurSDLoc(); 7864 7865 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7866 DAG.getValueType(SmallVT)); 7867 unsigned NumVals = Op.getNode()->getNumValues(); 7868 if (NumVals == 1) 7869 return ZExt; 7870 7871 SmallVector<SDValue, 4> Ops; 7872 7873 Ops.push_back(ZExt); 7874 for (unsigned I = 1; I != NumVals; ++I) 7875 Ops.push_back(Op.getValue(I)); 7876 7877 return DAG.getMergeValues(Ops, SL); 7878 } 7879 7880 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 7881 /// the call being lowered. 7882 /// 7883 /// This is a helper for lowering intrinsics that follow a target calling 7884 /// convention or require stack pointer adjustment. Only a subset of the 7885 /// intrinsic's operands need to participate in the calling convention. 7886 void SelectionDAGBuilder::populateCallLoweringInfo( 7887 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7888 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7889 bool IsPatchPoint) { 7890 TargetLowering::ArgListTy Args; 7891 Args.reserve(NumArgs); 7892 7893 // Populate the argument list. 7894 // Attributes for args start at offset 1, after the return attribute. 7895 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7896 ArgI != ArgE; ++ArgI) { 7897 const Value *V = CS->getOperand(ArgI); 7898 7899 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7900 7901 TargetLowering::ArgListEntry Entry; 7902 Entry.Node = getValue(V); 7903 Entry.Ty = V->getType(); 7904 Entry.setAttributes(&CS, ArgI); 7905 Args.push_back(Entry); 7906 } 7907 7908 CLI.setDebugLoc(getCurSDLoc()) 7909 .setChain(getRoot()) 7910 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7911 .setDiscardResult(CS->use_empty()) 7912 .setIsPatchPoint(IsPatchPoint); 7913 } 7914 7915 /// Add a stack map intrinsic call's live variable operands to a stackmap 7916 /// or patchpoint target node's operand list. 7917 /// 7918 /// Constants are converted to TargetConstants purely as an optimization to 7919 /// avoid constant materialization and register allocation. 7920 /// 7921 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7922 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7923 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7924 /// address materialization and register allocation, but may also be required 7925 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7926 /// alloca in the entry block, then the runtime may assume that the alloca's 7927 /// StackMap location can be read immediately after compilation and that the 7928 /// location is valid at any point during execution (this is similar to the 7929 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7930 /// only available in a register, then the runtime would need to trap when 7931 /// execution reaches the StackMap in order to read the alloca's location. 7932 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7933 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7934 SelectionDAGBuilder &Builder) { 7935 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7936 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7937 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7938 Ops.push_back( 7939 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7940 Ops.push_back( 7941 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7942 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7943 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7944 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7945 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 7946 } else 7947 Ops.push_back(OpVal); 7948 } 7949 } 7950 7951 /// Lower llvm.experimental.stackmap directly to its target opcode. 7952 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7953 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7954 // [live variables...]) 7955 7956 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7957 7958 SDValue Chain, InFlag, Callee, NullPtr; 7959 SmallVector<SDValue, 32> Ops; 7960 7961 SDLoc DL = getCurSDLoc(); 7962 Callee = getValue(CI.getCalledValue()); 7963 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7964 7965 // The stackmap intrinsic only records the live variables (the arguemnts 7966 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7967 // intrinsic, this won't be lowered to a function call. This means we don't 7968 // have to worry about calling conventions and target specific lowering code. 7969 // Instead we perform the call lowering right here. 7970 // 7971 // chain, flag = CALLSEQ_START(chain, 0, 0) 7972 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7973 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7974 // 7975 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 7976 InFlag = Chain.getValue(1); 7977 7978 // Add the <id> and <numBytes> constants. 7979 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7980 Ops.push_back(DAG.getTargetConstant( 7981 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7982 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 7983 Ops.push_back(DAG.getTargetConstant( 7984 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 7985 MVT::i32)); 7986 7987 // Push live variables for the stack map. 7988 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 7989 7990 // We are not pushing any register mask info here on the operands list, 7991 // because the stackmap doesn't clobber anything. 7992 7993 // Push the chain and the glue flag. 7994 Ops.push_back(Chain); 7995 Ops.push_back(InFlag); 7996 7997 // Create the STACKMAP node. 7998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7999 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8000 Chain = SDValue(SM, 0); 8001 InFlag = Chain.getValue(1); 8002 8003 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8004 8005 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8006 8007 // Set the root to the target-lowered call chain. 8008 DAG.setRoot(Chain); 8009 8010 // Inform the Frame Information that we have a stackmap in this function. 8011 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8012 } 8013 8014 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8015 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8016 const BasicBlock *EHPadBB) { 8017 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8018 // i32 <numBytes>, 8019 // i8* <target>, 8020 // i32 <numArgs>, 8021 // [Args...], 8022 // [live variables...]) 8023 8024 CallingConv::ID CC = CS.getCallingConv(); 8025 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8026 bool HasDef = !CS->getType()->isVoidTy(); 8027 SDLoc dl = getCurSDLoc(); 8028 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8029 8030 // Handle immediate and symbolic callees. 8031 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8032 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8033 /*isTarget=*/true); 8034 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8035 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8036 SDLoc(SymbolicCallee), 8037 SymbolicCallee->getValueType(0)); 8038 8039 // Get the real number of arguments participating in the call <numArgs> 8040 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8041 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8042 8043 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8044 // Intrinsics include all meta-operands up to but not including CC. 8045 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8046 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8047 "Not enough arguments provided to the patchpoint intrinsic"); 8048 8049 // For AnyRegCC the arguments are lowered later on manually. 8050 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8051 Type *ReturnTy = 8052 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8053 8054 TargetLowering::CallLoweringInfo CLI(DAG); 8055 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8056 true); 8057 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8058 8059 SDNode *CallEnd = Result.second.getNode(); 8060 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8061 CallEnd = CallEnd->getOperand(0).getNode(); 8062 8063 /// Get a call instruction from the call sequence chain. 8064 /// Tail calls are not allowed. 8065 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8066 "Expected a callseq node."); 8067 SDNode *Call = CallEnd->getOperand(0).getNode(); 8068 bool HasGlue = Call->getGluedNode(); 8069 8070 // Replace the target specific call node with the patchable intrinsic. 8071 SmallVector<SDValue, 8> Ops; 8072 8073 // Add the <id> and <numBytes> constants. 8074 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8075 Ops.push_back(DAG.getTargetConstant( 8076 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8077 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8078 Ops.push_back(DAG.getTargetConstant( 8079 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8080 MVT::i32)); 8081 8082 // Add the callee. 8083 Ops.push_back(Callee); 8084 8085 // Adjust <numArgs> to account for any arguments that have been passed on the 8086 // stack instead. 8087 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8088 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8089 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8090 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8091 8092 // Add the calling convention 8093 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8094 8095 // Add the arguments we omitted previously. The register allocator should 8096 // place these in any free register. 8097 if (IsAnyRegCC) 8098 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8099 Ops.push_back(getValue(CS.getArgument(i))); 8100 8101 // Push the arguments from the call instruction up to the register mask. 8102 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8103 Ops.append(Call->op_begin() + 2, e); 8104 8105 // Push live variables for the stack map. 8106 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8107 8108 // Push the register mask info. 8109 if (HasGlue) 8110 Ops.push_back(*(Call->op_end()-2)); 8111 else 8112 Ops.push_back(*(Call->op_end()-1)); 8113 8114 // Push the chain (this is originally the first operand of the call, but 8115 // becomes now the last or second to last operand). 8116 Ops.push_back(*(Call->op_begin())); 8117 8118 // Push the glue flag (last operand). 8119 if (HasGlue) 8120 Ops.push_back(*(Call->op_end()-1)); 8121 8122 SDVTList NodeTys; 8123 if (IsAnyRegCC && HasDef) { 8124 // Create the return types based on the intrinsic definition 8125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8126 SmallVector<EVT, 3> ValueVTs; 8127 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8128 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8129 8130 // There is always a chain and a glue type at the end 8131 ValueVTs.push_back(MVT::Other); 8132 ValueVTs.push_back(MVT::Glue); 8133 NodeTys = DAG.getVTList(ValueVTs); 8134 } else 8135 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8136 8137 // Replace the target specific call node with a PATCHPOINT node. 8138 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8139 dl, NodeTys, Ops); 8140 8141 // Update the NodeMap. 8142 if (HasDef) { 8143 if (IsAnyRegCC) 8144 setValue(CS.getInstruction(), SDValue(MN, 0)); 8145 else 8146 setValue(CS.getInstruction(), Result.first); 8147 } 8148 8149 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8150 // call sequence. Furthermore the location of the chain and glue can change 8151 // when the AnyReg calling convention is used and the intrinsic returns a 8152 // value. 8153 if (IsAnyRegCC && HasDef) { 8154 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8155 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8156 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8157 } else 8158 DAG.ReplaceAllUsesWith(Call, MN); 8159 DAG.DeleteNode(Call); 8160 8161 // Inform the Frame Information that we have a patchpoint in this function. 8162 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8163 } 8164 8165 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8166 unsigned Intrinsic) { 8167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8168 SDValue Op1 = getValue(I.getArgOperand(0)); 8169 SDValue Op2; 8170 if (I.getNumArgOperands() > 1) 8171 Op2 = getValue(I.getArgOperand(1)); 8172 SDLoc dl = getCurSDLoc(); 8173 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8174 SDValue Res; 8175 FastMathFlags FMF; 8176 if (isa<FPMathOperator>(I)) 8177 FMF = I.getFastMathFlags(); 8178 8179 switch (Intrinsic) { 8180 case Intrinsic::experimental_vector_reduce_fadd: 8181 if (FMF.isFast()) 8182 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8183 else 8184 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8185 break; 8186 case Intrinsic::experimental_vector_reduce_fmul: 8187 if (FMF.isFast()) 8188 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8189 else 8190 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8191 break; 8192 case Intrinsic::experimental_vector_reduce_add: 8193 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8194 break; 8195 case Intrinsic::experimental_vector_reduce_mul: 8196 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8197 break; 8198 case Intrinsic::experimental_vector_reduce_and: 8199 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8200 break; 8201 case Intrinsic::experimental_vector_reduce_or: 8202 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8203 break; 8204 case Intrinsic::experimental_vector_reduce_xor: 8205 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8206 break; 8207 case Intrinsic::experimental_vector_reduce_smax: 8208 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8209 break; 8210 case Intrinsic::experimental_vector_reduce_smin: 8211 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8212 break; 8213 case Intrinsic::experimental_vector_reduce_umax: 8214 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8215 break; 8216 case Intrinsic::experimental_vector_reduce_umin: 8217 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8218 break; 8219 case Intrinsic::experimental_vector_reduce_fmax: 8220 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8221 break; 8222 case Intrinsic::experimental_vector_reduce_fmin: 8223 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8224 break; 8225 default: 8226 llvm_unreachable("Unhandled vector reduce intrinsic"); 8227 } 8228 setValue(&I, Res); 8229 } 8230 8231 /// Returns an AttributeList representing the attributes applied to the return 8232 /// value of the given call. 8233 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8234 SmallVector<Attribute::AttrKind, 2> Attrs; 8235 if (CLI.RetSExt) 8236 Attrs.push_back(Attribute::SExt); 8237 if (CLI.RetZExt) 8238 Attrs.push_back(Attribute::ZExt); 8239 if (CLI.IsInReg) 8240 Attrs.push_back(Attribute::InReg); 8241 8242 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8243 Attrs); 8244 } 8245 8246 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8247 /// implementation, which just calls LowerCall. 8248 /// FIXME: When all targets are 8249 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8250 std::pair<SDValue, SDValue> 8251 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8252 // Handle the incoming return values from the call. 8253 CLI.Ins.clear(); 8254 Type *OrigRetTy = CLI.RetTy; 8255 SmallVector<EVT, 4> RetTys; 8256 SmallVector<uint64_t, 4> Offsets; 8257 auto &DL = CLI.DAG.getDataLayout(); 8258 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8259 8260 if (CLI.IsPostTypeLegalization) { 8261 // If we are lowering a libcall after legalization, split the return type. 8262 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8263 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8264 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8265 EVT RetVT = OldRetTys[i]; 8266 uint64_t Offset = OldOffsets[i]; 8267 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8268 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8269 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8270 RetTys.append(NumRegs, RegisterVT); 8271 for (unsigned j = 0; j != NumRegs; ++j) 8272 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8273 } 8274 } 8275 8276 SmallVector<ISD::OutputArg, 4> Outs; 8277 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8278 8279 bool CanLowerReturn = 8280 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8281 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8282 8283 SDValue DemoteStackSlot; 8284 int DemoteStackIdx = -100; 8285 if (!CanLowerReturn) { 8286 // FIXME: equivalent assert? 8287 // assert(!CS.hasInAllocaArgument() && 8288 // "sret demotion is incompatible with inalloca"); 8289 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8290 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8291 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8292 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8293 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 8294 8295 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8296 ArgListEntry Entry; 8297 Entry.Node = DemoteStackSlot; 8298 Entry.Ty = StackSlotPtrType; 8299 Entry.IsSExt = false; 8300 Entry.IsZExt = false; 8301 Entry.IsInReg = false; 8302 Entry.IsSRet = true; 8303 Entry.IsNest = false; 8304 Entry.IsByVal = false; 8305 Entry.IsReturned = false; 8306 Entry.IsSwiftSelf = false; 8307 Entry.IsSwiftError = false; 8308 Entry.Alignment = Align; 8309 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8310 CLI.NumFixedArgs += 1; 8311 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8312 8313 // sret demotion isn't compatible with tail-calls, since the sret argument 8314 // points into the callers stack frame. 8315 CLI.IsTailCall = false; 8316 } else { 8317 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8318 EVT VT = RetTys[I]; 8319 MVT RegisterVT = 8320 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8321 unsigned NumRegs = 8322 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8323 for (unsigned i = 0; i != NumRegs; ++i) { 8324 ISD::InputArg MyFlags; 8325 MyFlags.VT = RegisterVT; 8326 MyFlags.ArgVT = VT; 8327 MyFlags.Used = CLI.IsReturnValueUsed; 8328 if (CLI.RetSExt) 8329 MyFlags.Flags.setSExt(); 8330 if (CLI.RetZExt) 8331 MyFlags.Flags.setZExt(); 8332 if (CLI.IsInReg) 8333 MyFlags.Flags.setInReg(); 8334 CLI.Ins.push_back(MyFlags); 8335 } 8336 } 8337 } 8338 8339 // We push in swifterror return as the last element of CLI.Ins. 8340 ArgListTy &Args = CLI.getArgs(); 8341 if (supportSwiftError()) { 8342 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8343 if (Args[i].IsSwiftError) { 8344 ISD::InputArg MyFlags; 8345 MyFlags.VT = getPointerTy(DL); 8346 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8347 MyFlags.Flags.setSwiftError(); 8348 CLI.Ins.push_back(MyFlags); 8349 } 8350 } 8351 } 8352 8353 // Handle all of the outgoing arguments. 8354 CLI.Outs.clear(); 8355 CLI.OutVals.clear(); 8356 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8357 SmallVector<EVT, 4> ValueVTs; 8358 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8359 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8360 Type *FinalType = Args[i].Ty; 8361 if (Args[i].IsByVal) 8362 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8363 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8364 FinalType, CLI.CallConv, CLI.IsVarArg); 8365 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8366 ++Value) { 8367 EVT VT = ValueVTs[Value]; 8368 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8369 SDValue Op = SDValue(Args[i].Node.getNode(), 8370 Args[i].Node.getResNo() + Value); 8371 ISD::ArgFlagsTy Flags; 8372 8373 // Certain targets (such as MIPS), may have a different ABI alignment 8374 // for a type depending on the context. Give the target a chance to 8375 // specify the alignment it wants. 8376 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8377 8378 if (Args[i].IsZExt) 8379 Flags.setZExt(); 8380 if (Args[i].IsSExt) 8381 Flags.setSExt(); 8382 if (Args[i].IsInReg) { 8383 // If we are using vectorcall calling convention, a structure that is 8384 // passed InReg - is surely an HVA 8385 if (CLI.CallConv == CallingConv::X86_VectorCall && 8386 isa<StructType>(FinalType)) { 8387 // The first value of a structure is marked 8388 if (0 == Value) 8389 Flags.setHvaStart(); 8390 Flags.setHva(); 8391 } 8392 // Set InReg Flag 8393 Flags.setInReg(); 8394 } 8395 if (Args[i].IsSRet) 8396 Flags.setSRet(); 8397 if (Args[i].IsSwiftSelf) 8398 Flags.setSwiftSelf(); 8399 if (Args[i].IsSwiftError) 8400 Flags.setSwiftError(); 8401 if (Args[i].IsByVal) 8402 Flags.setByVal(); 8403 if (Args[i].IsInAlloca) { 8404 Flags.setInAlloca(); 8405 // Set the byval flag for CCAssignFn callbacks that don't know about 8406 // inalloca. This way we can know how many bytes we should've allocated 8407 // and how many bytes a callee cleanup function will pop. If we port 8408 // inalloca to more targets, we'll have to add custom inalloca handling 8409 // in the various CC lowering callbacks. 8410 Flags.setByVal(); 8411 } 8412 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8413 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8414 Type *ElementTy = Ty->getElementType(); 8415 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8416 // For ByVal, alignment should come from FE. BE will guess if this 8417 // info is not there but there are cases it cannot get right. 8418 unsigned FrameAlign; 8419 if (Args[i].Alignment) 8420 FrameAlign = Args[i].Alignment; 8421 else 8422 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8423 Flags.setByValAlign(FrameAlign); 8424 } 8425 if (Args[i].IsNest) 8426 Flags.setNest(); 8427 if (NeedsRegBlock) 8428 Flags.setInConsecutiveRegs(); 8429 Flags.setOrigAlign(OriginalAlignment); 8430 8431 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8432 unsigned NumParts = 8433 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8434 SmallVector<SDValue, 4> Parts(NumParts); 8435 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8436 8437 if (Args[i].IsSExt) 8438 ExtendKind = ISD::SIGN_EXTEND; 8439 else if (Args[i].IsZExt) 8440 ExtendKind = ISD::ZERO_EXTEND; 8441 8442 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8443 // for now. 8444 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8445 CanLowerReturn) { 8446 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8447 "unexpected use of 'returned'"); 8448 // Before passing 'returned' to the target lowering code, ensure that 8449 // either the register MVT and the actual EVT are the same size or that 8450 // the return value and argument are extended in the same way; in these 8451 // cases it's safe to pass the argument register value unchanged as the 8452 // return register value (although it's at the target's option whether 8453 // to do so) 8454 // TODO: allow code generation to take advantage of partially preserved 8455 // registers rather than clobbering the entire register when the 8456 // parameter extension method is not compatible with the return 8457 // extension method 8458 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8459 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8460 CLI.RetZExt == Args[i].IsZExt)) 8461 Flags.setReturned(); 8462 } 8463 8464 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8465 CLI.CS.getInstruction(), ExtendKind, true); 8466 8467 for (unsigned j = 0; j != NumParts; ++j) { 8468 // if it isn't first piece, alignment must be 1 8469 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8470 i < CLI.NumFixedArgs, 8471 i, j*Parts[j].getValueType().getStoreSize()); 8472 if (NumParts > 1 && j == 0) 8473 MyFlags.Flags.setSplit(); 8474 else if (j != 0) { 8475 MyFlags.Flags.setOrigAlign(1); 8476 if (j == NumParts - 1) 8477 MyFlags.Flags.setSplitEnd(); 8478 } 8479 8480 CLI.Outs.push_back(MyFlags); 8481 CLI.OutVals.push_back(Parts[j]); 8482 } 8483 8484 if (NeedsRegBlock && Value == NumValues - 1) 8485 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8486 } 8487 } 8488 8489 SmallVector<SDValue, 4> InVals; 8490 CLI.Chain = LowerCall(CLI, InVals); 8491 8492 // Update CLI.InVals to use outside of this function. 8493 CLI.InVals = InVals; 8494 8495 // Verify that the target's LowerCall behaved as expected. 8496 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8497 "LowerCall didn't return a valid chain!"); 8498 assert((!CLI.IsTailCall || InVals.empty()) && 8499 "LowerCall emitted a return value for a tail call!"); 8500 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8501 "LowerCall didn't emit the correct number of values!"); 8502 8503 // For a tail call, the return value is merely live-out and there aren't 8504 // any nodes in the DAG representing it. Return a special value to 8505 // indicate that a tail call has been emitted and no more Instructions 8506 // should be processed in the current block. 8507 if (CLI.IsTailCall) { 8508 CLI.DAG.setRoot(CLI.Chain); 8509 return std::make_pair(SDValue(), SDValue()); 8510 } 8511 8512 #ifndef NDEBUG 8513 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8514 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8515 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8516 "LowerCall emitted a value with the wrong type!"); 8517 } 8518 #endif 8519 8520 SmallVector<SDValue, 4> ReturnValues; 8521 if (!CanLowerReturn) { 8522 // The instruction result is the result of loading from the 8523 // hidden sret parameter. 8524 SmallVector<EVT, 1> PVTs; 8525 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8526 8527 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8528 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8529 EVT PtrVT = PVTs[0]; 8530 8531 unsigned NumValues = RetTys.size(); 8532 ReturnValues.resize(NumValues); 8533 SmallVector<SDValue, 4> Chains(NumValues); 8534 8535 // An aggregate return value cannot wrap around the address space, so 8536 // offsets to its parts don't wrap either. 8537 SDNodeFlags Flags; 8538 Flags.setNoUnsignedWrap(true); 8539 8540 for (unsigned i = 0; i < NumValues; ++i) { 8541 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8542 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8543 PtrVT), Flags); 8544 SDValue L = CLI.DAG.getLoad( 8545 RetTys[i], CLI.DL, CLI.Chain, Add, 8546 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8547 DemoteStackIdx, Offsets[i]), 8548 /* Alignment = */ 1); 8549 ReturnValues[i] = L; 8550 Chains[i] = L.getValue(1); 8551 } 8552 8553 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8554 } else { 8555 // Collect the legal value parts into potentially illegal values 8556 // that correspond to the original function's return values. 8557 Optional<ISD::NodeType> AssertOp; 8558 if (CLI.RetSExt) 8559 AssertOp = ISD::AssertSext; 8560 else if (CLI.RetZExt) 8561 AssertOp = ISD::AssertZext; 8562 unsigned CurReg = 0; 8563 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8564 EVT VT = RetTys[I]; 8565 MVT RegisterVT = 8566 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8567 unsigned NumRegs = 8568 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8569 8570 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8571 NumRegs, RegisterVT, VT, nullptr, 8572 AssertOp, true)); 8573 CurReg += NumRegs; 8574 } 8575 8576 // For a function returning void, there is no return value. We can't create 8577 // such a node, so we just return a null return value in that case. In 8578 // that case, nothing will actually look at the value. 8579 if (ReturnValues.empty()) 8580 return std::make_pair(SDValue(), CLI.Chain); 8581 } 8582 8583 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8584 CLI.DAG.getVTList(RetTys), ReturnValues); 8585 return std::make_pair(Res, CLI.Chain); 8586 } 8587 8588 void TargetLowering::LowerOperationWrapper(SDNode *N, 8589 SmallVectorImpl<SDValue> &Results, 8590 SelectionDAG &DAG) const { 8591 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8592 Results.push_back(Res); 8593 } 8594 8595 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8596 llvm_unreachable("LowerOperation not implemented for this target!"); 8597 } 8598 8599 void 8600 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8601 SDValue Op = getNonRegisterValue(V); 8602 assert((Op.getOpcode() != ISD::CopyFromReg || 8603 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8604 "Copy from a reg to the same reg!"); 8605 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8606 8607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8608 // If this is an InlineAsm we have to match the registers required, not the 8609 // notional registers required by the type. 8610 8611 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 8612 V->getType(), isABIRegCopy(V)); 8613 SDValue Chain = DAG.getEntryNode(); 8614 8615 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8616 FuncInfo.PreferredExtendType.end()) 8617 ? ISD::ANY_EXTEND 8618 : FuncInfo.PreferredExtendType[V]; 8619 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8620 PendingExports.push_back(Chain); 8621 } 8622 8623 #include "llvm/CodeGen/SelectionDAGISel.h" 8624 8625 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8626 /// entry block, return true. This includes arguments used by switches, since 8627 /// the switch may expand into multiple basic blocks. 8628 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8629 // With FastISel active, we may be splitting blocks, so force creation 8630 // of virtual registers for all non-dead arguments. 8631 if (FastISel) 8632 return A->use_empty(); 8633 8634 const BasicBlock &Entry = A->getParent()->front(); 8635 for (const User *U : A->users()) 8636 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8637 return false; // Use not in entry block. 8638 8639 return true; 8640 } 8641 8642 using ArgCopyElisionMapTy = 8643 DenseMap<const Argument *, 8644 std::pair<const AllocaInst *, const StoreInst *>>; 8645 8646 /// Scan the entry block of the function in FuncInfo for arguments that look 8647 /// like copies into a local alloca. Record any copied arguments in 8648 /// ArgCopyElisionCandidates. 8649 static void 8650 findArgumentCopyElisionCandidates(const DataLayout &DL, 8651 FunctionLoweringInfo *FuncInfo, 8652 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8653 // Record the state of every static alloca used in the entry block. Argument 8654 // allocas are all used in the entry block, so we need approximately as many 8655 // entries as we have arguments. 8656 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8657 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8658 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8659 StaticAllocas.reserve(NumArgs * 2); 8660 8661 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8662 if (!V) 8663 return nullptr; 8664 V = V->stripPointerCasts(); 8665 const auto *AI = dyn_cast<AllocaInst>(V); 8666 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8667 return nullptr; 8668 auto Iter = StaticAllocas.insert({AI, Unknown}); 8669 return &Iter.first->second; 8670 }; 8671 8672 // Look for stores of arguments to static allocas. Look through bitcasts and 8673 // GEPs to handle type coercions, as long as the alloca is fully initialized 8674 // by the store. Any non-store use of an alloca escapes it and any subsequent 8675 // unanalyzed store might write it. 8676 // FIXME: Handle structs initialized with multiple stores. 8677 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8678 // Look for stores, and handle non-store uses conservatively. 8679 const auto *SI = dyn_cast<StoreInst>(&I); 8680 if (!SI) { 8681 // We will look through cast uses, so ignore them completely. 8682 if (I.isCast()) 8683 continue; 8684 // Ignore debug info intrinsics, they don't escape or store to allocas. 8685 if (isa<DbgInfoIntrinsic>(I)) 8686 continue; 8687 // This is an unknown instruction. Assume it escapes or writes to all 8688 // static alloca operands. 8689 for (const Use &U : I.operands()) { 8690 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8691 *Info = StaticAllocaInfo::Clobbered; 8692 } 8693 continue; 8694 } 8695 8696 // If the stored value is a static alloca, mark it as escaped. 8697 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8698 *Info = StaticAllocaInfo::Clobbered; 8699 8700 // Check if the destination is a static alloca. 8701 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8702 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8703 if (!Info) 8704 continue; 8705 const AllocaInst *AI = cast<AllocaInst>(Dst); 8706 8707 // Skip allocas that have been initialized or clobbered. 8708 if (*Info != StaticAllocaInfo::Unknown) 8709 continue; 8710 8711 // Check if the stored value is an argument, and that this store fully 8712 // initializes the alloca. Don't elide copies from the same argument twice. 8713 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8714 const auto *Arg = dyn_cast<Argument>(Val); 8715 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8716 Arg->getType()->isEmptyTy() || 8717 DL.getTypeStoreSize(Arg->getType()) != 8718 DL.getTypeAllocSize(AI->getAllocatedType()) || 8719 ArgCopyElisionCandidates.count(Arg)) { 8720 *Info = StaticAllocaInfo::Clobbered; 8721 continue; 8722 } 8723 8724 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8725 << '\n'); 8726 8727 // Mark this alloca and store for argument copy elision. 8728 *Info = StaticAllocaInfo::Elidable; 8729 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8730 8731 // Stop scanning if we've seen all arguments. This will happen early in -O0 8732 // builds, which is useful, because -O0 builds have large entry blocks and 8733 // many allocas. 8734 if (ArgCopyElisionCandidates.size() == NumArgs) 8735 break; 8736 } 8737 } 8738 8739 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8740 /// ArgVal is a load from a suitable fixed stack object. 8741 static void tryToElideArgumentCopy( 8742 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8743 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8744 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8745 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8746 SDValue ArgVal, bool &ArgHasUses) { 8747 // Check if this is a load from a fixed stack object. 8748 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8749 if (!LNode) 8750 return; 8751 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8752 if (!FINode) 8753 return; 8754 8755 // Check that the fixed stack object is the right size and alignment. 8756 // Look at the alignment that the user wrote on the alloca instead of looking 8757 // at the stack object. 8758 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8759 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8760 const AllocaInst *AI = ArgCopyIter->second.first; 8761 int FixedIndex = FINode->getIndex(); 8762 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8763 int OldIndex = AllocaIndex; 8764 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8765 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8766 LLVM_DEBUG( 8767 dbgs() << " argument copy elision failed due to bad fixed stack " 8768 "object size\n"); 8769 return; 8770 } 8771 unsigned RequiredAlignment = AI->getAlignment(); 8772 if (!RequiredAlignment) { 8773 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8774 AI->getAllocatedType()); 8775 } 8776 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8777 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8778 "greater than stack argument alignment (" 8779 << RequiredAlignment << " vs " 8780 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8781 return; 8782 } 8783 8784 // Perform the elision. Delete the old stack object and replace its only use 8785 // in the variable info map. Mark the stack object as mutable. 8786 LLVM_DEBUG({ 8787 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8788 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8789 << '\n'; 8790 }); 8791 MFI.RemoveStackObject(OldIndex); 8792 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8793 AllocaIndex = FixedIndex; 8794 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8795 Chains.push_back(ArgVal.getValue(1)); 8796 8797 // Avoid emitting code for the store implementing the copy. 8798 const StoreInst *SI = ArgCopyIter->second.second; 8799 ElidedArgCopyInstrs.insert(SI); 8800 8801 // Check for uses of the argument again so that we can avoid exporting ArgVal 8802 // if it is't used by anything other than the store. 8803 for (const Value *U : Arg.users()) { 8804 if (U != SI) { 8805 ArgHasUses = true; 8806 break; 8807 } 8808 } 8809 } 8810 8811 void SelectionDAGISel::LowerArguments(const Function &F) { 8812 SelectionDAG &DAG = SDB->DAG; 8813 SDLoc dl = SDB->getCurSDLoc(); 8814 const DataLayout &DL = DAG.getDataLayout(); 8815 SmallVector<ISD::InputArg, 16> Ins; 8816 8817 if (!FuncInfo->CanLowerReturn) { 8818 // Put in an sret pointer parameter before all the other parameters. 8819 SmallVector<EVT, 1> ValueVTs; 8820 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8821 F.getReturnType()->getPointerTo( 8822 DAG.getDataLayout().getAllocaAddrSpace()), 8823 ValueVTs); 8824 8825 // NOTE: Assuming that a pointer will never break down to more than one VT 8826 // or one register. 8827 ISD::ArgFlagsTy Flags; 8828 Flags.setSRet(); 8829 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8830 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8831 ISD::InputArg::NoArgIndex, 0); 8832 Ins.push_back(RetArg); 8833 } 8834 8835 // Look for stores of arguments to static allocas. Mark such arguments with a 8836 // flag to ask the target to give us the memory location of that argument if 8837 // available. 8838 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8839 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8840 8841 // Set up the incoming argument description vector. 8842 for (const Argument &Arg : F.args()) { 8843 unsigned ArgNo = Arg.getArgNo(); 8844 SmallVector<EVT, 4> ValueVTs; 8845 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8846 bool isArgValueUsed = !Arg.use_empty(); 8847 unsigned PartBase = 0; 8848 Type *FinalType = Arg.getType(); 8849 if (Arg.hasAttribute(Attribute::ByVal)) 8850 FinalType = cast<PointerType>(FinalType)->getElementType(); 8851 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8852 FinalType, F.getCallingConv(), F.isVarArg()); 8853 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8854 Value != NumValues; ++Value) { 8855 EVT VT = ValueVTs[Value]; 8856 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8857 ISD::ArgFlagsTy Flags; 8858 8859 // Certain targets (such as MIPS), may have a different ABI alignment 8860 // for a type depending on the context. Give the target a chance to 8861 // specify the alignment it wants. 8862 unsigned OriginalAlignment = 8863 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8864 8865 if (Arg.hasAttribute(Attribute::ZExt)) 8866 Flags.setZExt(); 8867 if (Arg.hasAttribute(Attribute::SExt)) 8868 Flags.setSExt(); 8869 if (Arg.hasAttribute(Attribute::InReg)) { 8870 // If we are using vectorcall calling convention, a structure that is 8871 // passed InReg - is surely an HVA 8872 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8873 isa<StructType>(Arg.getType())) { 8874 // The first value of a structure is marked 8875 if (0 == Value) 8876 Flags.setHvaStart(); 8877 Flags.setHva(); 8878 } 8879 // Set InReg Flag 8880 Flags.setInReg(); 8881 } 8882 if (Arg.hasAttribute(Attribute::StructRet)) 8883 Flags.setSRet(); 8884 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8885 Flags.setSwiftSelf(); 8886 if (Arg.hasAttribute(Attribute::SwiftError)) 8887 Flags.setSwiftError(); 8888 if (Arg.hasAttribute(Attribute::ByVal)) 8889 Flags.setByVal(); 8890 if (Arg.hasAttribute(Attribute::InAlloca)) { 8891 Flags.setInAlloca(); 8892 // Set the byval flag for CCAssignFn callbacks that don't know about 8893 // inalloca. This way we can know how many bytes we should've allocated 8894 // and how many bytes a callee cleanup function will pop. If we port 8895 // inalloca to more targets, we'll have to add custom inalloca handling 8896 // in the various CC lowering callbacks. 8897 Flags.setByVal(); 8898 } 8899 if (F.getCallingConv() == CallingConv::X86_INTR) { 8900 // IA Interrupt passes frame (1st parameter) by value in the stack. 8901 if (ArgNo == 0) 8902 Flags.setByVal(); 8903 } 8904 if (Flags.isByVal() || Flags.isInAlloca()) { 8905 PointerType *Ty = cast<PointerType>(Arg.getType()); 8906 Type *ElementTy = Ty->getElementType(); 8907 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8908 // For ByVal, alignment should be passed from FE. BE will guess if 8909 // this info is not there but there are cases it cannot get right. 8910 unsigned FrameAlign; 8911 if (Arg.getParamAlignment()) 8912 FrameAlign = Arg.getParamAlignment(); 8913 else 8914 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8915 Flags.setByValAlign(FrameAlign); 8916 } 8917 if (Arg.hasAttribute(Attribute::Nest)) 8918 Flags.setNest(); 8919 if (NeedsRegBlock) 8920 Flags.setInConsecutiveRegs(); 8921 Flags.setOrigAlign(OriginalAlignment); 8922 if (ArgCopyElisionCandidates.count(&Arg)) 8923 Flags.setCopyElisionCandidate(); 8924 8925 MVT RegisterVT = 8926 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8927 unsigned NumRegs = 8928 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8929 for (unsigned i = 0; i != NumRegs; ++i) { 8930 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8931 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 8932 if (NumRegs > 1 && i == 0) 8933 MyFlags.Flags.setSplit(); 8934 // if it isn't first piece, alignment must be 1 8935 else if (i > 0) { 8936 MyFlags.Flags.setOrigAlign(1); 8937 if (i == NumRegs - 1) 8938 MyFlags.Flags.setSplitEnd(); 8939 } 8940 Ins.push_back(MyFlags); 8941 } 8942 if (NeedsRegBlock && Value == NumValues - 1) 8943 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8944 PartBase += VT.getStoreSize(); 8945 } 8946 } 8947 8948 // Call the target to set up the argument values. 8949 SmallVector<SDValue, 8> InVals; 8950 SDValue NewRoot = TLI->LowerFormalArguments( 8951 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 8952 8953 // Verify that the target's LowerFormalArguments behaved as expected. 8954 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 8955 "LowerFormalArguments didn't return a valid chain!"); 8956 assert(InVals.size() == Ins.size() && 8957 "LowerFormalArguments didn't emit the correct number of values!"); 8958 LLVM_DEBUG({ 8959 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 8960 assert(InVals[i].getNode() && 8961 "LowerFormalArguments emitted a null value!"); 8962 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 8963 "LowerFormalArguments emitted a value with the wrong type!"); 8964 } 8965 }); 8966 8967 // Update the DAG with the new chain value resulting from argument lowering. 8968 DAG.setRoot(NewRoot); 8969 8970 // Set up the argument values. 8971 unsigned i = 0; 8972 if (!FuncInfo->CanLowerReturn) { 8973 // Create a virtual register for the sret pointer, and put in a copy 8974 // from the sret argument into it. 8975 SmallVector<EVT, 1> ValueVTs; 8976 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8977 F.getReturnType()->getPointerTo( 8978 DAG.getDataLayout().getAllocaAddrSpace()), 8979 ValueVTs); 8980 MVT VT = ValueVTs[0].getSimpleVT(); 8981 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8982 Optional<ISD::NodeType> AssertOp = None; 8983 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 8984 RegVT, VT, nullptr, AssertOp); 8985 8986 MachineFunction& MF = SDB->DAG.getMachineFunction(); 8987 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 8988 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 8989 FuncInfo->DemoteRegister = SRetReg; 8990 NewRoot = 8991 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 8992 DAG.setRoot(NewRoot); 8993 8994 // i indexes lowered arguments. Bump it past the hidden sret argument. 8995 ++i; 8996 } 8997 8998 SmallVector<SDValue, 4> Chains; 8999 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9000 for (const Argument &Arg : F.args()) { 9001 SmallVector<SDValue, 4> ArgValues; 9002 SmallVector<EVT, 4> ValueVTs; 9003 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9004 unsigned NumValues = ValueVTs.size(); 9005 if (NumValues == 0) 9006 continue; 9007 9008 bool ArgHasUses = !Arg.use_empty(); 9009 9010 // Elide the copying store if the target loaded this argument from a 9011 // suitable fixed stack object. 9012 if (Ins[i].Flags.isCopyElisionCandidate()) { 9013 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9014 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9015 InVals[i], ArgHasUses); 9016 } 9017 9018 // If this argument is unused then remember its value. It is used to generate 9019 // debugging information. 9020 bool isSwiftErrorArg = 9021 TLI->supportSwiftError() && 9022 Arg.hasAttribute(Attribute::SwiftError); 9023 if (!ArgHasUses && !isSwiftErrorArg) { 9024 SDB->setUnusedArgValue(&Arg, InVals[i]); 9025 9026 // Also remember any frame index for use in FastISel. 9027 if (FrameIndexSDNode *FI = 9028 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9029 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9030 } 9031 9032 for (unsigned Val = 0; Val != NumValues; ++Val) { 9033 EVT VT = ValueVTs[Val]; 9034 MVT PartVT = 9035 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 9036 unsigned NumParts = 9037 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 9038 9039 // Even an apparant 'unused' swifterror argument needs to be returned. So 9040 // we do generate a copy for it that can be used on return from the 9041 // function. 9042 if (ArgHasUses || isSwiftErrorArg) { 9043 Optional<ISD::NodeType> AssertOp; 9044 if (Arg.hasAttribute(Attribute::SExt)) 9045 AssertOp = ISD::AssertSext; 9046 else if (Arg.hasAttribute(Attribute::ZExt)) 9047 AssertOp = ISD::AssertZext; 9048 9049 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9050 PartVT, VT, nullptr, AssertOp, 9051 true)); 9052 } 9053 9054 i += NumParts; 9055 } 9056 9057 // We don't need to do anything else for unused arguments. 9058 if (ArgValues.empty()) 9059 continue; 9060 9061 // Note down frame index. 9062 if (FrameIndexSDNode *FI = 9063 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9064 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9065 9066 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9067 SDB->getCurSDLoc()); 9068 9069 SDB->setValue(&Arg, Res); 9070 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9071 // We want to associate the argument with the frame index, among 9072 // involved operands, that correspond to the lowest address. The 9073 // getCopyFromParts function, called earlier, is swapping the order of 9074 // the operands to BUILD_PAIR depending on endianness. The result of 9075 // that swapping is that the least significant bits of the argument will 9076 // be in the first operand of the BUILD_PAIR node, and the most 9077 // significant bits will be in the second operand. 9078 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9079 if (LoadSDNode *LNode = 9080 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9081 if (FrameIndexSDNode *FI = 9082 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9083 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9084 } 9085 9086 // Update the SwiftErrorVRegDefMap. 9087 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9088 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9089 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9090 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9091 FuncInfo->SwiftErrorArg, Reg); 9092 } 9093 9094 // If this argument is live outside of the entry block, insert a copy from 9095 // wherever we got it to the vreg that other BB's will reference it as. 9096 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9097 // If we can, though, try to skip creating an unnecessary vreg. 9098 // FIXME: This isn't very clean... it would be nice to make this more 9099 // general. It's also subtly incompatible with the hacks FastISel 9100 // uses with vregs. 9101 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9102 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9103 FuncInfo->ValueMap[&Arg] = Reg; 9104 continue; 9105 } 9106 } 9107 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9108 FuncInfo->InitializeRegForValue(&Arg); 9109 SDB->CopyToExportRegsIfNeeded(&Arg); 9110 } 9111 } 9112 9113 if (!Chains.empty()) { 9114 Chains.push_back(NewRoot); 9115 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9116 } 9117 9118 DAG.setRoot(NewRoot); 9119 9120 assert(i == InVals.size() && "Argument register count mismatch!"); 9121 9122 // If any argument copy elisions occurred and we have debug info, update the 9123 // stale frame indices used in the dbg.declare variable info table. 9124 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9125 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9126 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9127 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9128 if (I != ArgCopyElisionFrameIndexMap.end()) 9129 VI.Slot = I->second; 9130 } 9131 } 9132 9133 // Finally, if the target has anything special to do, allow it to do so. 9134 EmitFunctionEntryCode(); 9135 } 9136 9137 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9138 /// ensure constants are generated when needed. Remember the virtual registers 9139 /// that need to be added to the Machine PHI nodes as input. We cannot just 9140 /// directly add them, because expansion might result in multiple MBB's for one 9141 /// BB. As such, the start of the BB might correspond to a different MBB than 9142 /// the end. 9143 void 9144 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9145 const TerminatorInst *TI = LLVMBB->getTerminator(); 9146 9147 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9148 9149 // Check PHI nodes in successors that expect a value to be available from this 9150 // block. 9151 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9152 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9153 if (!isa<PHINode>(SuccBB->begin())) continue; 9154 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9155 9156 // If this terminator has multiple identical successors (common for 9157 // switches), only handle each succ once. 9158 if (!SuccsHandled.insert(SuccMBB).second) 9159 continue; 9160 9161 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9162 9163 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9164 // nodes and Machine PHI nodes, but the incoming operands have not been 9165 // emitted yet. 9166 for (const PHINode &PN : SuccBB->phis()) { 9167 // Ignore dead phi's. 9168 if (PN.use_empty()) 9169 continue; 9170 9171 // Skip empty types 9172 if (PN.getType()->isEmptyTy()) 9173 continue; 9174 9175 unsigned Reg; 9176 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9177 9178 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9179 unsigned &RegOut = ConstantsOut[C]; 9180 if (RegOut == 0) { 9181 RegOut = FuncInfo.CreateRegs(C->getType()); 9182 CopyValueToVirtualRegister(C, RegOut); 9183 } 9184 Reg = RegOut; 9185 } else { 9186 DenseMap<const Value *, unsigned>::iterator I = 9187 FuncInfo.ValueMap.find(PHIOp); 9188 if (I != FuncInfo.ValueMap.end()) 9189 Reg = I->second; 9190 else { 9191 assert(isa<AllocaInst>(PHIOp) && 9192 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9193 "Didn't codegen value into a register!??"); 9194 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9195 CopyValueToVirtualRegister(PHIOp, Reg); 9196 } 9197 } 9198 9199 // Remember that this register needs to added to the machine PHI node as 9200 // the input for this MBB. 9201 SmallVector<EVT, 4> ValueVTs; 9202 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9203 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9204 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9205 EVT VT = ValueVTs[vti]; 9206 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9207 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9208 FuncInfo.PHINodesToUpdate.push_back( 9209 std::make_pair(&*MBBI++, Reg + i)); 9210 Reg += NumRegisters; 9211 } 9212 } 9213 } 9214 9215 ConstantsOut.clear(); 9216 } 9217 9218 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9219 /// is 0. 9220 MachineBasicBlock * 9221 SelectionDAGBuilder::StackProtectorDescriptor:: 9222 AddSuccessorMBB(const BasicBlock *BB, 9223 MachineBasicBlock *ParentMBB, 9224 bool IsLikely, 9225 MachineBasicBlock *SuccMBB) { 9226 // If SuccBB has not been created yet, create it. 9227 if (!SuccMBB) { 9228 MachineFunction *MF = ParentMBB->getParent(); 9229 MachineFunction::iterator BBI(ParentMBB); 9230 SuccMBB = MF->CreateMachineBasicBlock(BB); 9231 MF->insert(++BBI, SuccMBB); 9232 } 9233 // Add it as a successor of ParentMBB. 9234 ParentMBB->addSuccessor( 9235 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9236 return SuccMBB; 9237 } 9238 9239 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9240 MachineFunction::iterator I(MBB); 9241 if (++I == FuncInfo.MF->end()) 9242 return nullptr; 9243 return &*I; 9244 } 9245 9246 /// During lowering new call nodes can be created (such as memset, etc.). 9247 /// Those will become new roots of the current DAG, but complications arise 9248 /// when they are tail calls. In such cases, the call lowering will update 9249 /// the root, but the builder still needs to know that a tail call has been 9250 /// lowered in order to avoid generating an additional return. 9251 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9252 // If the node is null, we do have a tail call. 9253 if (MaybeTC.getNode() != nullptr) 9254 DAG.setRoot(MaybeTC); 9255 else 9256 HasTailCall = true; 9257 } 9258 9259 uint64_t 9260 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9261 unsigned First, unsigned Last) const { 9262 assert(Last >= First); 9263 const APInt &LowCase = Clusters[First].Low->getValue(); 9264 const APInt &HighCase = Clusters[Last].High->getValue(); 9265 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9266 9267 // FIXME: A range of consecutive cases has 100% density, but only requires one 9268 // comparison to lower. We should discriminate against such consecutive ranges 9269 // in jump tables. 9270 9271 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9272 } 9273 9274 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9275 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9276 unsigned Last) const { 9277 assert(Last >= First); 9278 assert(TotalCases[Last] >= TotalCases[First]); 9279 uint64_t NumCases = 9280 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9281 return NumCases; 9282 } 9283 9284 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9285 unsigned First, unsigned Last, 9286 const SwitchInst *SI, 9287 MachineBasicBlock *DefaultMBB, 9288 CaseCluster &JTCluster) { 9289 assert(First <= Last); 9290 9291 auto Prob = BranchProbability::getZero(); 9292 unsigned NumCmps = 0; 9293 std::vector<MachineBasicBlock*> Table; 9294 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9295 9296 // Initialize probabilities in JTProbs. 9297 for (unsigned I = First; I <= Last; ++I) 9298 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9299 9300 for (unsigned I = First; I <= Last; ++I) { 9301 assert(Clusters[I].Kind == CC_Range); 9302 Prob += Clusters[I].Prob; 9303 const APInt &Low = Clusters[I].Low->getValue(); 9304 const APInt &High = Clusters[I].High->getValue(); 9305 NumCmps += (Low == High) ? 1 : 2; 9306 if (I != First) { 9307 // Fill the gap between this and the previous cluster. 9308 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9309 assert(PreviousHigh.slt(Low)); 9310 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9311 for (uint64_t J = 0; J < Gap; J++) 9312 Table.push_back(DefaultMBB); 9313 } 9314 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9315 for (uint64_t J = 0; J < ClusterSize; ++J) 9316 Table.push_back(Clusters[I].MBB); 9317 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9318 } 9319 9320 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9321 unsigned NumDests = JTProbs.size(); 9322 if (TLI.isSuitableForBitTests( 9323 NumDests, NumCmps, Clusters[First].Low->getValue(), 9324 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9325 // Clusters[First..Last] should be lowered as bit tests instead. 9326 return false; 9327 } 9328 9329 // Create the MBB that will load from and jump through the table. 9330 // Note: We create it here, but it's not inserted into the function yet. 9331 MachineFunction *CurMF = FuncInfo.MF; 9332 MachineBasicBlock *JumpTableMBB = 9333 CurMF->CreateMachineBasicBlock(SI->getParent()); 9334 9335 // Add successors. Note: use table order for determinism. 9336 SmallPtrSet<MachineBasicBlock *, 8> Done; 9337 for (MachineBasicBlock *Succ : Table) { 9338 if (Done.count(Succ)) 9339 continue; 9340 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9341 Done.insert(Succ); 9342 } 9343 JumpTableMBB->normalizeSuccProbs(); 9344 9345 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9346 ->createJumpTableIndex(Table); 9347 9348 // Set up the jump table info. 9349 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9350 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9351 Clusters[Last].High->getValue(), SI->getCondition(), 9352 nullptr, false); 9353 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9354 9355 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9356 JTCases.size() - 1, Prob); 9357 return true; 9358 } 9359 9360 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9361 const SwitchInst *SI, 9362 MachineBasicBlock *DefaultMBB) { 9363 #ifndef NDEBUG 9364 // Clusters must be non-empty, sorted, and only contain Range clusters. 9365 assert(!Clusters.empty()); 9366 for (CaseCluster &C : Clusters) 9367 assert(C.Kind == CC_Range); 9368 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9369 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9370 #endif 9371 9372 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9373 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9374 return; 9375 9376 const int64_t N = Clusters.size(); 9377 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9378 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9379 9380 if (N < 2 || N < MinJumpTableEntries) 9381 return; 9382 9383 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9384 SmallVector<unsigned, 8> TotalCases(N); 9385 for (unsigned i = 0; i < N; ++i) { 9386 const APInt &Hi = Clusters[i].High->getValue(); 9387 const APInt &Lo = Clusters[i].Low->getValue(); 9388 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9389 if (i != 0) 9390 TotalCases[i] += TotalCases[i - 1]; 9391 } 9392 9393 // Cheap case: the whole range may be suitable for jump table. 9394 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9395 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9396 assert(NumCases < UINT64_MAX / 100); 9397 assert(Range >= NumCases); 9398 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9399 CaseCluster JTCluster; 9400 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9401 Clusters[0] = JTCluster; 9402 Clusters.resize(1); 9403 return; 9404 } 9405 } 9406 9407 // The algorithm below is not suitable for -O0. 9408 if (TM.getOptLevel() == CodeGenOpt::None) 9409 return; 9410 9411 // Split Clusters into minimum number of dense partitions. The algorithm uses 9412 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9413 // for the Case Statement'" (1994), but builds the MinPartitions array in 9414 // reverse order to make it easier to reconstruct the partitions in ascending 9415 // order. In the choice between two optimal partitionings, it picks the one 9416 // which yields more jump tables. 9417 9418 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9419 SmallVector<unsigned, 8> MinPartitions(N); 9420 // LastElement[i] is the last element of the partition starting at i. 9421 SmallVector<unsigned, 8> LastElement(N); 9422 // PartitionsScore[i] is used to break ties when choosing between two 9423 // partitionings resulting in the same number of partitions. 9424 SmallVector<unsigned, 8> PartitionsScore(N); 9425 // For PartitionsScore, a small number of comparisons is considered as good as 9426 // a jump table and a single comparison is considered better than a jump 9427 // table. 9428 enum PartitionScores : unsigned { 9429 NoTable = 0, 9430 Table = 1, 9431 FewCases = 1, 9432 SingleCase = 2 9433 }; 9434 9435 // Base case: There is only one way to partition Clusters[N-1]. 9436 MinPartitions[N - 1] = 1; 9437 LastElement[N - 1] = N - 1; 9438 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9439 9440 // Note: loop indexes are signed to avoid underflow. 9441 for (int64_t i = N - 2; i >= 0; i--) { 9442 // Find optimal partitioning of Clusters[i..N-1]. 9443 // Baseline: Put Clusters[i] into a partition on its own. 9444 MinPartitions[i] = MinPartitions[i + 1] + 1; 9445 LastElement[i] = i; 9446 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9447 9448 // Search for a solution that results in fewer partitions. 9449 for (int64_t j = N - 1; j > i; j--) { 9450 // Try building a partition from Clusters[i..j]. 9451 uint64_t Range = getJumpTableRange(Clusters, i, j); 9452 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9453 assert(NumCases < UINT64_MAX / 100); 9454 assert(Range >= NumCases); 9455 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9456 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9457 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9458 int64_t NumEntries = j - i + 1; 9459 9460 if (NumEntries == 1) 9461 Score += PartitionScores::SingleCase; 9462 else if (NumEntries <= SmallNumberOfEntries) 9463 Score += PartitionScores::FewCases; 9464 else if (NumEntries >= MinJumpTableEntries) 9465 Score += PartitionScores::Table; 9466 9467 // If this leads to fewer partitions, or to the same number of 9468 // partitions with better score, it is a better partitioning. 9469 if (NumPartitions < MinPartitions[i] || 9470 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9471 MinPartitions[i] = NumPartitions; 9472 LastElement[i] = j; 9473 PartitionsScore[i] = Score; 9474 } 9475 } 9476 } 9477 } 9478 9479 // Iterate over the partitions, replacing some with jump tables in-place. 9480 unsigned DstIndex = 0; 9481 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9482 Last = LastElement[First]; 9483 assert(Last >= First); 9484 assert(DstIndex <= First); 9485 unsigned NumClusters = Last - First + 1; 9486 9487 CaseCluster JTCluster; 9488 if (NumClusters >= MinJumpTableEntries && 9489 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9490 Clusters[DstIndex++] = JTCluster; 9491 } else { 9492 for (unsigned I = First; I <= Last; ++I) 9493 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9494 } 9495 } 9496 Clusters.resize(DstIndex); 9497 } 9498 9499 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9500 unsigned First, unsigned Last, 9501 const SwitchInst *SI, 9502 CaseCluster &BTCluster) { 9503 assert(First <= Last); 9504 if (First == Last) 9505 return false; 9506 9507 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9508 unsigned NumCmps = 0; 9509 for (int64_t I = First; I <= Last; ++I) { 9510 assert(Clusters[I].Kind == CC_Range); 9511 Dests.set(Clusters[I].MBB->getNumber()); 9512 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9513 } 9514 unsigned NumDests = Dests.count(); 9515 9516 APInt Low = Clusters[First].Low->getValue(); 9517 APInt High = Clusters[Last].High->getValue(); 9518 assert(Low.slt(High)); 9519 9520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9521 const DataLayout &DL = DAG.getDataLayout(); 9522 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9523 return false; 9524 9525 APInt LowBound; 9526 APInt CmpRange; 9527 9528 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9529 assert(TLI.rangeFitsInWord(Low, High, DL) && 9530 "Case range must fit in bit mask!"); 9531 9532 // Check if the clusters cover a contiguous range such that no value in the 9533 // range will jump to the default statement. 9534 bool ContiguousRange = true; 9535 for (int64_t I = First + 1; I <= Last; ++I) { 9536 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9537 ContiguousRange = false; 9538 break; 9539 } 9540 } 9541 9542 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9543 // Optimize the case where all the case values fit in a word without having 9544 // to subtract minValue. In this case, we can optimize away the subtraction. 9545 LowBound = APInt::getNullValue(Low.getBitWidth()); 9546 CmpRange = High; 9547 ContiguousRange = false; 9548 } else { 9549 LowBound = Low; 9550 CmpRange = High - Low; 9551 } 9552 9553 CaseBitsVector CBV; 9554 auto TotalProb = BranchProbability::getZero(); 9555 for (unsigned i = First; i <= Last; ++i) { 9556 // Find the CaseBits for this destination. 9557 unsigned j; 9558 for (j = 0; j < CBV.size(); ++j) 9559 if (CBV[j].BB == Clusters[i].MBB) 9560 break; 9561 if (j == CBV.size()) 9562 CBV.push_back( 9563 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9564 CaseBits *CB = &CBV[j]; 9565 9566 // Update Mask, Bits and ExtraProb. 9567 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9568 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9569 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9570 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9571 CB->Bits += Hi - Lo + 1; 9572 CB->ExtraProb += Clusters[i].Prob; 9573 TotalProb += Clusters[i].Prob; 9574 } 9575 9576 BitTestInfo BTI; 9577 llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9578 // Sort by probability first, number of bits second, bit mask third. 9579 if (a.ExtraProb != b.ExtraProb) 9580 return a.ExtraProb > b.ExtraProb; 9581 if (a.Bits != b.Bits) 9582 return a.Bits > b.Bits; 9583 return a.Mask < b.Mask; 9584 }); 9585 9586 for (auto &CB : CBV) { 9587 MachineBasicBlock *BitTestBB = 9588 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9589 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9590 } 9591 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9592 SI->getCondition(), -1U, MVT::Other, false, 9593 ContiguousRange, nullptr, nullptr, std::move(BTI), 9594 TotalProb); 9595 9596 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9597 BitTestCases.size() - 1, TotalProb); 9598 return true; 9599 } 9600 9601 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9602 const SwitchInst *SI) { 9603 // Partition Clusters into as few subsets as possible, where each subset has a 9604 // range that fits in a machine word and has <= 3 unique destinations. 9605 9606 #ifndef NDEBUG 9607 // Clusters must be sorted and contain Range or JumpTable clusters. 9608 assert(!Clusters.empty()); 9609 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9610 for (const CaseCluster &C : Clusters) 9611 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9612 for (unsigned i = 1; i < Clusters.size(); ++i) 9613 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9614 #endif 9615 9616 // The algorithm below is not suitable for -O0. 9617 if (TM.getOptLevel() == CodeGenOpt::None) 9618 return; 9619 9620 // If target does not have legal shift left, do not emit bit tests at all. 9621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9622 const DataLayout &DL = DAG.getDataLayout(); 9623 9624 EVT PTy = TLI.getPointerTy(DL); 9625 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9626 return; 9627 9628 int BitWidth = PTy.getSizeInBits(); 9629 const int64_t N = Clusters.size(); 9630 9631 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9632 SmallVector<unsigned, 8> MinPartitions(N); 9633 // LastElement[i] is the last element of the partition starting at i. 9634 SmallVector<unsigned, 8> LastElement(N); 9635 9636 // FIXME: This might not be the best algorithm for finding bit test clusters. 9637 9638 // Base case: There is only one way to partition Clusters[N-1]. 9639 MinPartitions[N - 1] = 1; 9640 LastElement[N - 1] = N - 1; 9641 9642 // Note: loop indexes are signed to avoid underflow. 9643 for (int64_t i = N - 2; i >= 0; --i) { 9644 // Find optimal partitioning of Clusters[i..N-1]. 9645 // Baseline: Put Clusters[i] into a partition on its own. 9646 MinPartitions[i] = MinPartitions[i + 1] + 1; 9647 LastElement[i] = i; 9648 9649 // Search for a solution that results in fewer partitions. 9650 // Note: the search is limited by BitWidth, reducing time complexity. 9651 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9652 // Try building a partition from Clusters[i..j]. 9653 9654 // Check the range. 9655 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9656 Clusters[j].High->getValue(), DL)) 9657 continue; 9658 9659 // Check nbr of destinations and cluster types. 9660 // FIXME: This works, but doesn't seem very efficient. 9661 bool RangesOnly = true; 9662 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9663 for (int64_t k = i; k <= j; k++) { 9664 if (Clusters[k].Kind != CC_Range) { 9665 RangesOnly = false; 9666 break; 9667 } 9668 Dests.set(Clusters[k].MBB->getNumber()); 9669 } 9670 if (!RangesOnly || Dests.count() > 3) 9671 break; 9672 9673 // Check if it's a better partition. 9674 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9675 if (NumPartitions < MinPartitions[i]) { 9676 // Found a better partition. 9677 MinPartitions[i] = NumPartitions; 9678 LastElement[i] = j; 9679 } 9680 } 9681 } 9682 9683 // Iterate over the partitions, replacing with bit-test clusters in-place. 9684 unsigned DstIndex = 0; 9685 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9686 Last = LastElement[First]; 9687 assert(First <= Last); 9688 assert(DstIndex <= First); 9689 9690 CaseCluster BitTestCluster; 9691 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9692 Clusters[DstIndex++] = BitTestCluster; 9693 } else { 9694 size_t NumClusters = Last - First + 1; 9695 std::memmove(&Clusters[DstIndex], &Clusters[First], 9696 sizeof(Clusters[0]) * NumClusters); 9697 DstIndex += NumClusters; 9698 } 9699 } 9700 Clusters.resize(DstIndex); 9701 } 9702 9703 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9704 MachineBasicBlock *SwitchMBB, 9705 MachineBasicBlock *DefaultMBB) { 9706 MachineFunction *CurMF = FuncInfo.MF; 9707 MachineBasicBlock *NextMBB = nullptr; 9708 MachineFunction::iterator BBI(W.MBB); 9709 if (++BBI != FuncInfo.MF->end()) 9710 NextMBB = &*BBI; 9711 9712 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9713 9714 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9715 9716 if (Size == 2 && W.MBB == SwitchMBB) { 9717 // If any two of the cases has the same destination, and if one value 9718 // is the same as the other, but has one bit unset that the other has set, 9719 // use bit manipulation to do two compares at once. For example: 9720 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9721 // TODO: This could be extended to merge any 2 cases in switches with 3 9722 // cases. 9723 // TODO: Handle cases where W.CaseBB != SwitchBB. 9724 CaseCluster &Small = *W.FirstCluster; 9725 CaseCluster &Big = *W.LastCluster; 9726 9727 if (Small.Low == Small.High && Big.Low == Big.High && 9728 Small.MBB == Big.MBB) { 9729 const APInt &SmallValue = Small.Low->getValue(); 9730 const APInt &BigValue = Big.Low->getValue(); 9731 9732 // Check that there is only one bit different. 9733 APInt CommonBit = BigValue ^ SmallValue; 9734 if (CommonBit.isPowerOf2()) { 9735 SDValue CondLHS = getValue(Cond); 9736 EVT VT = CondLHS.getValueType(); 9737 SDLoc DL = getCurSDLoc(); 9738 9739 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9740 DAG.getConstant(CommonBit, DL, VT)); 9741 SDValue Cond = DAG.getSetCC( 9742 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9743 ISD::SETEQ); 9744 9745 // Update successor info. 9746 // Both Small and Big will jump to Small.BB, so we sum up the 9747 // probabilities. 9748 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9749 if (BPI) 9750 addSuccessorWithProb( 9751 SwitchMBB, DefaultMBB, 9752 // The default destination is the first successor in IR. 9753 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9754 else 9755 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9756 9757 // Insert the true branch. 9758 SDValue BrCond = 9759 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9760 DAG.getBasicBlock(Small.MBB)); 9761 // Insert the false branch. 9762 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9763 DAG.getBasicBlock(DefaultMBB)); 9764 9765 DAG.setRoot(BrCond); 9766 return; 9767 } 9768 } 9769 } 9770 9771 if (TM.getOptLevel() != CodeGenOpt::None) { 9772 // Here, we order cases by probability so the most likely case will be 9773 // checked first. However, two clusters can have the same probability in 9774 // which case their relative ordering is non-deterministic. So we use Low 9775 // as a tie-breaker as clusters are guaranteed to never overlap. 9776 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9777 [](const CaseCluster &a, const CaseCluster &b) { 9778 return a.Prob != b.Prob ? 9779 a.Prob > b.Prob : 9780 a.Low->getValue().slt(b.Low->getValue()); 9781 }); 9782 9783 // Rearrange the case blocks so that the last one falls through if possible 9784 // without changing the order of probabilities. 9785 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9786 --I; 9787 if (I->Prob > W.LastCluster->Prob) 9788 break; 9789 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9790 std::swap(*I, *W.LastCluster); 9791 break; 9792 } 9793 } 9794 } 9795 9796 // Compute total probability. 9797 BranchProbability DefaultProb = W.DefaultProb; 9798 BranchProbability UnhandledProbs = DefaultProb; 9799 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9800 UnhandledProbs += I->Prob; 9801 9802 MachineBasicBlock *CurMBB = W.MBB; 9803 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9804 MachineBasicBlock *Fallthrough; 9805 if (I == W.LastCluster) { 9806 // For the last cluster, fall through to the default destination. 9807 Fallthrough = DefaultMBB; 9808 } else { 9809 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9810 CurMF->insert(BBI, Fallthrough); 9811 // Put Cond in a virtual register to make it available from the new blocks. 9812 ExportFromCurrentBlock(Cond); 9813 } 9814 UnhandledProbs -= I->Prob; 9815 9816 switch (I->Kind) { 9817 case CC_JumpTable: { 9818 // FIXME: Optimize away range check based on pivot comparisons. 9819 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9820 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9821 9822 // The jump block hasn't been inserted yet; insert it here. 9823 MachineBasicBlock *JumpMBB = JT->MBB; 9824 CurMF->insert(BBI, JumpMBB); 9825 9826 auto JumpProb = I->Prob; 9827 auto FallthroughProb = UnhandledProbs; 9828 9829 // If the default statement is a target of the jump table, we evenly 9830 // distribute the default probability to successors of CurMBB. Also 9831 // update the probability on the edge from JumpMBB to Fallthrough. 9832 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9833 SE = JumpMBB->succ_end(); 9834 SI != SE; ++SI) { 9835 if (*SI == DefaultMBB) { 9836 JumpProb += DefaultProb / 2; 9837 FallthroughProb -= DefaultProb / 2; 9838 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9839 JumpMBB->normalizeSuccProbs(); 9840 break; 9841 } 9842 } 9843 9844 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9845 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9846 CurMBB->normalizeSuccProbs(); 9847 9848 // The jump table header will be inserted in our current block, do the 9849 // range check, and fall through to our fallthrough block. 9850 JTH->HeaderBB = CurMBB; 9851 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9852 9853 // If we're in the right place, emit the jump table header right now. 9854 if (CurMBB == SwitchMBB) { 9855 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9856 JTH->Emitted = true; 9857 } 9858 break; 9859 } 9860 case CC_BitTests: { 9861 // FIXME: Optimize away range check based on pivot comparisons. 9862 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9863 9864 // The bit test blocks haven't been inserted yet; insert them here. 9865 for (BitTestCase &BTC : BTB->Cases) 9866 CurMF->insert(BBI, BTC.ThisBB); 9867 9868 // Fill in fields of the BitTestBlock. 9869 BTB->Parent = CurMBB; 9870 BTB->Default = Fallthrough; 9871 9872 BTB->DefaultProb = UnhandledProbs; 9873 // If the cases in bit test don't form a contiguous range, we evenly 9874 // distribute the probability on the edge to Fallthrough to two 9875 // successors of CurMBB. 9876 if (!BTB->ContiguousRange) { 9877 BTB->Prob += DefaultProb / 2; 9878 BTB->DefaultProb -= DefaultProb / 2; 9879 } 9880 9881 // If we're in the right place, emit the bit test header right now. 9882 if (CurMBB == SwitchMBB) { 9883 visitBitTestHeader(*BTB, SwitchMBB); 9884 BTB->Emitted = true; 9885 } 9886 break; 9887 } 9888 case CC_Range: { 9889 const Value *RHS, *LHS, *MHS; 9890 ISD::CondCode CC; 9891 if (I->Low == I->High) { 9892 // Check Cond == I->Low. 9893 CC = ISD::SETEQ; 9894 LHS = Cond; 9895 RHS=I->Low; 9896 MHS = nullptr; 9897 } else { 9898 // Check I->Low <= Cond <= I->High. 9899 CC = ISD::SETLE; 9900 LHS = I->Low; 9901 MHS = Cond; 9902 RHS = I->High; 9903 } 9904 9905 // The false probability is the sum of all unhandled cases. 9906 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9907 getCurSDLoc(), I->Prob, UnhandledProbs); 9908 9909 if (CurMBB == SwitchMBB) 9910 visitSwitchCase(CB, SwitchMBB); 9911 else 9912 SwitchCases.push_back(CB); 9913 9914 break; 9915 } 9916 } 9917 CurMBB = Fallthrough; 9918 } 9919 } 9920 9921 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 9922 CaseClusterIt First, 9923 CaseClusterIt Last) { 9924 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 9925 if (X.Prob != CC.Prob) 9926 return X.Prob > CC.Prob; 9927 9928 // Ties are broken by comparing the case value. 9929 return X.Low->getValue().slt(CC.Low->getValue()); 9930 }); 9931 } 9932 9933 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9934 const SwitchWorkListItem &W, 9935 Value *Cond, 9936 MachineBasicBlock *SwitchMBB) { 9937 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9938 "Clusters not sorted?"); 9939 9940 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9941 9942 // Balance the tree based on branch probabilities to create a near-optimal (in 9943 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9944 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 9945 CaseClusterIt LastLeft = W.FirstCluster; 9946 CaseClusterIt FirstRight = W.LastCluster; 9947 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 9948 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 9949 9950 // Move LastLeft and FirstRight towards each other from opposite directions to 9951 // find a partitioning of the clusters which balances the probability on both 9952 // sides. If LeftProb and RightProb are equal, alternate which side is 9953 // taken to ensure 0-probability nodes are distributed evenly. 9954 unsigned I = 0; 9955 while (LastLeft + 1 < FirstRight) { 9956 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 9957 LeftProb += (++LastLeft)->Prob; 9958 else 9959 RightProb += (--FirstRight)->Prob; 9960 I++; 9961 } 9962 9963 while (true) { 9964 // Our binary search tree differs from a typical BST in that ours can have up 9965 // to three values in each leaf. The pivot selection above doesn't take that 9966 // into account, which means the tree might require more nodes and be less 9967 // efficient. We compensate for this here. 9968 9969 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 9970 unsigned NumRight = W.LastCluster - FirstRight + 1; 9971 9972 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 9973 // If one side has less than 3 clusters, and the other has more than 3, 9974 // consider taking a cluster from the other side. 9975 9976 if (NumLeft < NumRight) { 9977 // Consider moving the first cluster on the right to the left side. 9978 CaseCluster &CC = *FirstRight; 9979 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9980 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9981 if (LeftSideRank <= RightSideRank) { 9982 // Moving the cluster to the left does not demote it. 9983 ++LastLeft; 9984 ++FirstRight; 9985 continue; 9986 } 9987 } else { 9988 assert(NumRight < NumLeft); 9989 // Consider moving the last element on the left to the right side. 9990 CaseCluster &CC = *LastLeft; 9991 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9992 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9993 if (RightSideRank <= LeftSideRank) { 9994 // Moving the cluster to the right does not demot it. 9995 --LastLeft; 9996 --FirstRight; 9997 continue; 9998 } 9999 } 10000 } 10001 break; 10002 } 10003 10004 assert(LastLeft + 1 == FirstRight); 10005 assert(LastLeft >= W.FirstCluster); 10006 assert(FirstRight <= W.LastCluster); 10007 10008 // Use the first element on the right as pivot since we will make less-than 10009 // comparisons against it. 10010 CaseClusterIt PivotCluster = FirstRight; 10011 assert(PivotCluster > W.FirstCluster); 10012 assert(PivotCluster <= W.LastCluster); 10013 10014 CaseClusterIt FirstLeft = W.FirstCluster; 10015 CaseClusterIt LastRight = W.LastCluster; 10016 10017 const ConstantInt *Pivot = PivotCluster->Low; 10018 10019 // New blocks will be inserted immediately after the current one. 10020 MachineFunction::iterator BBI(W.MBB); 10021 ++BBI; 10022 10023 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10024 // we can branch to its destination directly if it's squeezed exactly in 10025 // between the known lower bound and Pivot - 1. 10026 MachineBasicBlock *LeftMBB; 10027 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10028 FirstLeft->Low == W.GE && 10029 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10030 LeftMBB = FirstLeft->MBB; 10031 } else { 10032 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10033 FuncInfo.MF->insert(BBI, LeftMBB); 10034 WorkList.push_back( 10035 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10036 // Put Cond in a virtual register to make it available from the new blocks. 10037 ExportFromCurrentBlock(Cond); 10038 } 10039 10040 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10041 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10042 // directly if RHS.High equals the current upper bound. 10043 MachineBasicBlock *RightMBB; 10044 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10045 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10046 RightMBB = FirstRight->MBB; 10047 } else { 10048 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10049 FuncInfo.MF->insert(BBI, RightMBB); 10050 WorkList.push_back( 10051 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10052 // Put Cond in a virtual register to make it available from the new blocks. 10053 ExportFromCurrentBlock(Cond); 10054 } 10055 10056 // Create the CaseBlock record that will be used to lower the branch. 10057 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10058 getCurSDLoc(), LeftProb, RightProb); 10059 10060 if (W.MBB == SwitchMBB) 10061 visitSwitchCase(CB, SwitchMBB); 10062 else 10063 SwitchCases.push_back(CB); 10064 } 10065 10066 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10067 // from the swith statement. 10068 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10069 BranchProbability PeeledCaseProb) { 10070 if (PeeledCaseProb == BranchProbability::getOne()) 10071 return BranchProbability::getZero(); 10072 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10073 10074 uint32_t Numerator = CaseProb.getNumerator(); 10075 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10076 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10077 } 10078 10079 // Try to peel the top probability case if it exceeds the threshold. 10080 // Return current MachineBasicBlock for the switch statement if the peeling 10081 // does not occur. 10082 // If the peeling is performed, return the newly created MachineBasicBlock 10083 // for the peeled switch statement. Also update Clusters to remove the peeled 10084 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10085 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10086 const SwitchInst &SI, CaseClusterVector &Clusters, 10087 BranchProbability &PeeledCaseProb) { 10088 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10089 // Don't perform if there is only one cluster or optimizing for size. 10090 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10091 TM.getOptLevel() == CodeGenOpt::None || 10092 SwitchMBB->getParent()->getFunction().optForMinSize()) 10093 return SwitchMBB; 10094 10095 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10096 unsigned PeeledCaseIndex = 0; 10097 bool SwitchPeeled = false; 10098 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10099 CaseCluster &CC = Clusters[Index]; 10100 if (CC.Prob < TopCaseProb) 10101 continue; 10102 TopCaseProb = CC.Prob; 10103 PeeledCaseIndex = Index; 10104 SwitchPeeled = true; 10105 } 10106 if (!SwitchPeeled) 10107 return SwitchMBB; 10108 10109 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10110 << TopCaseProb << "\n"); 10111 10112 // Record the MBB for the peeled switch statement. 10113 MachineFunction::iterator BBI(SwitchMBB); 10114 ++BBI; 10115 MachineBasicBlock *PeeledSwitchMBB = 10116 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10117 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10118 10119 ExportFromCurrentBlock(SI.getCondition()); 10120 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10121 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10122 nullptr, nullptr, TopCaseProb.getCompl()}; 10123 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10124 10125 Clusters.erase(PeeledCaseIt); 10126 for (CaseCluster &CC : Clusters) { 10127 LLVM_DEBUG( 10128 dbgs() << "Scale the probablity for one cluster, before scaling: " 10129 << CC.Prob << "\n"); 10130 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10131 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10132 } 10133 PeeledCaseProb = TopCaseProb; 10134 return PeeledSwitchMBB; 10135 } 10136 10137 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10138 // Extract cases from the switch. 10139 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10140 CaseClusterVector Clusters; 10141 Clusters.reserve(SI.getNumCases()); 10142 for (auto I : SI.cases()) { 10143 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10144 const ConstantInt *CaseVal = I.getCaseValue(); 10145 BranchProbability Prob = 10146 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10147 : BranchProbability(1, SI.getNumCases() + 1); 10148 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10149 } 10150 10151 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10152 10153 // Cluster adjacent cases with the same destination. We do this at all 10154 // optimization levels because it's cheap to do and will make codegen faster 10155 // if there are many clusters. 10156 sortAndRangeify(Clusters); 10157 10158 if (TM.getOptLevel() != CodeGenOpt::None) { 10159 // Replace an unreachable default with the most popular destination. 10160 // FIXME: Exploit unreachable default more aggressively. 10161 bool UnreachableDefault = 10162 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10163 if (UnreachableDefault && !Clusters.empty()) { 10164 DenseMap<const BasicBlock *, unsigned> Popularity; 10165 unsigned MaxPop = 0; 10166 const BasicBlock *MaxBB = nullptr; 10167 for (auto I : SI.cases()) { 10168 const BasicBlock *BB = I.getCaseSuccessor(); 10169 if (++Popularity[BB] > MaxPop) { 10170 MaxPop = Popularity[BB]; 10171 MaxBB = BB; 10172 } 10173 } 10174 // Set new default. 10175 assert(MaxPop > 0 && MaxBB); 10176 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10177 10178 // Remove cases that were pointing to the destination that is now the 10179 // default. 10180 CaseClusterVector New; 10181 New.reserve(Clusters.size()); 10182 for (CaseCluster &CC : Clusters) { 10183 if (CC.MBB != DefaultMBB) 10184 New.push_back(CC); 10185 } 10186 Clusters = std::move(New); 10187 } 10188 } 10189 10190 // The branch probablity of the peeled case. 10191 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10192 MachineBasicBlock *PeeledSwitchMBB = 10193 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10194 10195 // If there is only the default destination, jump there directly. 10196 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10197 if (Clusters.empty()) { 10198 assert(PeeledSwitchMBB == SwitchMBB); 10199 SwitchMBB->addSuccessor(DefaultMBB); 10200 if (DefaultMBB != NextBlock(SwitchMBB)) { 10201 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10202 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10203 } 10204 return; 10205 } 10206 10207 findJumpTables(Clusters, &SI, DefaultMBB); 10208 findBitTestClusters(Clusters, &SI); 10209 10210 LLVM_DEBUG({ 10211 dbgs() << "Case clusters: "; 10212 for (const CaseCluster &C : Clusters) { 10213 if (C.Kind == CC_JumpTable) 10214 dbgs() << "JT:"; 10215 if (C.Kind == CC_BitTests) 10216 dbgs() << "BT:"; 10217 10218 C.Low->getValue().print(dbgs(), true); 10219 if (C.Low != C.High) { 10220 dbgs() << '-'; 10221 C.High->getValue().print(dbgs(), true); 10222 } 10223 dbgs() << ' '; 10224 } 10225 dbgs() << '\n'; 10226 }); 10227 10228 assert(!Clusters.empty()); 10229 SwitchWorkList WorkList; 10230 CaseClusterIt First = Clusters.begin(); 10231 CaseClusterIt Last = Clusters.end() - 1; 10232 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10233 // Scale the branchprobability for DefaultMBB if the peel occurs and 10234 // DefaultMBB is not replaced. 10235 if (PeeledCaseProb != BranchProbability::getZero() && 10236 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10237 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10238 WorkList.push_back( 10239 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10240 10241 while (!WorkList.empty()) { 10242 SwitchWorkListItem W = WorkList.back(); 10243 WorkList.pop_back(); 10244 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10245 10246 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10247 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10248 // For optimized builds, lower large range as a balanced binary tree. 10249 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10250 continue; 10251 } 10252 10253 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10254 } 10255 } 10256