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/BitVector.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BranchProbabilityInfo.h" 22 #include "llvm/Analysis/ConstantFolding.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/CodeGen/FastISel.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GCMetadata.h" 28 #include "llvm/CodeGen/GCStrategy.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineJumpTableInfo.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/CodeGen/StackMaps.h" 37 #include "llvm/CodeGen/WinEHFuncInfo.h" 38 #include "llvm/IR/CallingConv.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DebugInfo.h" 42 #include "llvm/IR/DerivedTypes.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/GlobalVariable.h" 45 #include "llvm/IR/InlineAsm.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/IntrinsicInst.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/IR/Statepoint.h" 52 #include "llvm/MC/MCSymbol.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/MathExtras.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Target/TargetFrameLowering.h" 59 #include "llvm/Target/TargetInstrInfo.h" 60 #include "llvm/Target/TargetIntrinsicInfo.h" 61 #include "llvm/Target/TargetLowering.h" 62 #include "llvm/Target/TargetOptions.h" 63 #include "llvm/Target/TargetSelectionDAGInfo.h" 64 #include "llvm/Target/TargetSubtargetInfo.h" 65 #include <algorithm> 66 using namespace llvm; 67 68 #define DEBUG_TYPE "isel" 69 70 /// LimitFloatPrecision - Generate low-precision inline sequences for 71 /// some float libcalls (6, 8 or 12 bits). 72 static unsigned LimitFloatPrecision; 73 74 static cl::opt<unsigned, true> 75 LimitFPPrecision("limit-float-precision", 76 cl::desc("Generate low-precision inline sequences " 77 "for some float libcalls"), 78 cl::location(LimitFloatPrecision), 79 cl::init(0)); 80 81 static cl::opt<bool> 82 EnableFMFInDAG("enable-fmf-dag", cl::init(false), cl::Hidden, 83 cl::desc("Enable fast-math-flags for DAG nodes")); 84 85 // Limit the width of DAG chains. This is important in general to prevent 86 // DAG-based analysis from blowing up. For example, alias analysis and 87 // load clustering may not complete in reasonable time. It is difficult to 88 // recognize and avoid this situation within each individual analysis, and 89 // future analyses are likely to have the same behavior. Limiting DAG width is 90 // the safe approach and will be especially important with global DAGs. 91 // 92 // MaxParallelChains default is arbitrarily high to avoid affecting 93 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 94 // sequence over this should have been converted to llvm.memcpy by the 95 // frontend. It easy to induce this behavior with .ll code such as: 96 // %buffer = alloca [4096 x i8] 97 // %data = load [4096 x i8]* %argPtr 98 // store [4096 x i8] %data, [4096 x i8]* %buffer 99 static const unsigned MaxParallelChains = 64; 100 101 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 102 const SDValue *Parts, unsigned NumParts, 103 MVT PartVT, EVT ValueVT, const Value *V); 104 105 /// getCopyFromParts - Create a value that contains the specified legal parts 106 /// combined into the value they represent. If the parts combine to a type 107 /// larger then ValueVT then AssertOp can be used to specify whether the extra 108 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 109 /// (ISD::AssertSext). 110 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL, 111 const SDValue *Parts, 112 unsigned NumParts, MVT PartVT, EVT ValueVT, 113 const Value *V, 114 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 115 if (ValueVT.isVector()) 116 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 117 PartVT, ValueVT, V); 118 119 assert(NumParts > 0 && "No parts to assemble!"); 120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 121 SDValue Val = Parts[0]; 122 123 if (NumParts > 1) { 124 // Assemble the value from multiple parts. 125 if (ValueVT.isInteger()) { 126 unsigned PartBits = PartVT.getSizeInBits(); 127 unsigned ValueBits = ValueVT.getSizeInBits(); 128 129 // Assemble the power of 2 part. 130 unsigned RoundParts = NumParts & (NumParts - 1) ? 131 1 << Log2_32(NumParts) : NumParts; 132 unsigned RoundBits = PartBits * RoundParts; 133 EVT RoundVT = RoundBits == ValueBits ? 134 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 135 SDValue Lo, Hi; 136 137 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 138 139 if (RoundParts > 2) { 140 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 141 PartVT, HalfVT, V); 142 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 143 RoundParts / 2, PartVT, HalfVT, V); 144 } else { 145 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 146 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 147 } 148 149 if (DAG.getDataLayout().isBigEndian()) 150 std::swap(Lo, Hi); 151 152 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 153 154 if (RoundParts < NumParts) { 155 // Assemble the trailing non-power-of-2 part. 156 unsigned OddParts = NumParts - RoundParts; 157 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 158 Hi = getCopyFromParts(DAG, DL, 159 Parts + RoundParts, OddParts, PartVT, OddVT, V); 160 161 // Combine the round and odd parts. 162 Lo = Val; 163 if (DAG.getDataLayout().isBigEndian()) 164 std::swap(Lo, Hi); 165 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 166 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 167 Hi = 168 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 169 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL, 170 TLI.getPointerTy(DAG.getDataLayout()))); 171 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 172 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 173 } 174 } else if (PartVT.isFloatingPoint()) { 175 // FP split into multiple FP parts (for ppcf128) 176 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 177 "Unexpected split"); 178 SDValue Lo, Hi; 179 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 180 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 181 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 182 std::swap(Lo, Hi); 183 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 184 } else { 185 // FP split into integer parts (soft fp) 186 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 187 !PartVT.isVector() && "Unexpected split"); 188 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 189 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 190 } 191 } 192 193 // There is now one part, held in Val. Correct it to match ValueVT. 194 EVT PartEVT = Val.getValueType(); 195 196 if (PartEVT == ValueVT) 197 return Val; 198 199 if (PartEVT.isInteger() && ValueVT.isInteger()) { 200 if (ValueVT.bitsLT(PartEVT)) { 201 // For a truncate, see if we have any information to 202 // indicate whether the truncated bits will always be 203 // zero or sign-extension. 204 if (AssertOp != ISD::DELETED_NODE) 205 Val = DAG.getNode(AssertOp, DL, PartEVT, Val, 206 DAG.getValueType(ValueVT)); 207 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 208 } 209 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 210 } 211 212 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 213 // FP_ROUND's are always exact here. 214 if (ValueVT.bitsLT(Val.getValueType())) 215 return DAG.getNode( 216 ISD::FP_ROUND, DL, ValueVT, Val, 217 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 218 219 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 220 } 221 222 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 223 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 224 225 llvm_unreachable("Unknown mismatch!"); 226 } 227 228 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 229 const Twine &ErrMsg) { 230 const Instruction *I = dyn_cast_or_null<Instruction>(V); 231 if (!V) 232 return Ctx.emitError(ErrMsg); 233 234 const char *AsmError = ", possible invalid constraint for vector type"; 235 if (const CallInst *CI = dyn_cast<CallInst>(I)) 236 if (isa<InlineAsm>(CI->getCalledValue())) 237 return Ctx.emitError(I, ErrMsg + AsmError); 238 239 return Ctx.emitError(I, ErrMsg); 240 } 241 242 /// getCopyFromPartsVector - Create a value that contains the specified legal 243 /// parts combined into the value they represent. If the parts combine to a 244 /// type larger then ValueVT then AssertOp can be used to specify whether the 245 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 246 /// ValueVT (ISD::AssertSext). 247 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 248 const SDValue *Parts, unsigned NumParts, 249 MVT PartVT, EVT ValueVT, const Value *V) { 250 assert(ValueVT.isVector() && "Not a vector value"); 251 assert(NumParts > 0 && "No parts to assemble!"); 252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 253 SDValue Val = Parts[0]; 254 255 // Handle a multi-element vector. 256 if (NumParts > 1) { 257 EVT IntermediateVT; 258 MVT RegisterVT; 259 unsigned NumIntermediates; 260 unsigned NumRegs = 261 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 262 NumIntermediates, RegisterVT); 263 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 264 NumParts = NumRegs; // Silence a compiler warning. 265 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 266 assert(RegisterVT.getSizeInBits() == 267 Parts[0].getSimpleValueType().getSizeInBits() && 268 "Part type sizes don't match!"); 269 270 // Assemble the parts into intermediate operands. 271 SmallVector<SDValue, 8> Ops(NumIntermediates); 272 if (NumIntermediates == NumParts) { 273 // If the register was not expanded, truncate or copy the value, 274 // as appropriate. 275 for (unsigned i = 0; i != NumParts; ++i) 276 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 277 PartVT, IntermediateVT, V); 278 } else if (NumParts > 0) { 279 // If the intermediate type was expanded, build the intermediate 280 // operands from the parts. 281 assert(NumParts % NumIntermediates == 0 && 282 "Must expand into a divisible number of parts!"); 283 unsigned Factor = NumParts / NumIntermediates; 284 for (unsigned i = 0; i != NumIntermediates; ++i) 285 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 286 PartVT, IntermediateVT, V); 287 } 288 289 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 290 // intermediate operands. 291 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 292 : ISD::BUILD_VECTOR, 293 DL, ValueVT, Ops); 294 } 295 296 // There is now one part, held in Val. Correct it to match ValueVT. 297 EVT PartEVT = Val.getValueType(); 298 299 if (PartEVT == ValueVT) 300 return Val; 301 302 if (PartEVT.isVector()) { 303 // If the element type of the source/dest vectors are the same, but the 304 // parts vector has more elements than the value vector, then we have a 305 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 306 // elements we want. 307 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 308 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 309 "Cannot narrow, it would be a lossy transformation"); 310 return DAG.getNode( 311 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 312 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 313 } 314 315 // Vector/Vector bitcast. 316 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 317 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 318 319 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 320 "Cannot handle this kind of promotion"); 321 // Promoted vector extract 322 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 323 324 } 325 326 // Trivial bitcast if the types are the same size and the destination 327 // vector type is legal. 328 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 329 TLI.isTypeLegal(ValueVT)) 330 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 331 332 // Handle cases such as i8 -> <1 x i1> 333 if (ValueVT.getVectorNumElements() != 1) { 334 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 335 "non-trivial scalar-to-vector conversion"); 336 return DAG.getUNDEF(ValueVT); 337 } 338 339 if (ValueVT.getVectorNumElements() == 1 && 340 ValueVT.getVectorElementType() != PartEVT) 341 Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType()); 342 343 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 344 } 345 346 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl, 347 SDValue Val, SDValue *Parts, unsigned NumParts, 348 MVT PartVT, const Value *V); 349 350 /// getCopyToParts - Create a series of nodes that contain the specified value 351 /// split into legal parts. If the parts contain more bits than Val, then, for 352 /// integers, ExtendKind can be used to specify how to generate the extra bits. 353 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL, 354 SDValue Val, SDValue *Parts, unsigned NumParts, 355 MVT PartVT, const Value *V, 356 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 357 EVT ValueVT = Val.getValueType(); 358 359 // Handle the vector case separately. 360 if (ValueVT.isVector()) 361 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V); 362 363 unsigned PartBits = PartVT.getSizeInBits(); 364 unsigned OrigNumParts = NumParts; 365 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 366 "Copying to an illegal type!"); 367 368 if (NumParts == 0) 369 return; 370 371 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 372 EVT PartEVT = PartVT; 373 if (PartEVT == ValueVT) { 374 assert(NumParts == 1 && "No-op copy with multiple parts!"); 375 Parts[0] = Val; 376 return; 377 } 378 379 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 380 // If the parts cover more bits than the value has, promote the value. 381 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 382 assert(NumParts == 1 && "Do not know what to promote to!"); 383 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 384 } else { 385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 386 ValueVT.isInteger() && 387 "Unknown mismatch!"); 388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 389 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 390 if (PartVT == MVT::x86mmx) 391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 392 } 393 } else if (PartBits == ValueVT.getSizeInBits()) { 394 // Different types of the same size. 395 assert(NumParts == 1 && PartEVT != ValueVT); 396 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 397 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 398 // If the parts cover less bits than value has, truncate the value. 399 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 400 ValueVT.isInteger() && 401 "Unknown mismatch!"); 402 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 403 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 404 if (PartVT == MVT::x86mmx) 405 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 406 } 407 408 // The value may have changed - recompute ValueVT. 409 ValueVT = Val.getValueType(); 410 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 411 "Failed to tile the value with PartVT!"); 412 413 if (NumParts == 1) { 414 if (PartEVT != ValueVT) 415 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 416 "scalar-to-vector conversion failed"); 417 418 Parts[0] = Val; 419 return; 420 } 421 422 // Expand the value into multiple parts. 423 if (NumParts & (NumParts - 1)) { 424 // The number of parts is not a power of 2. Split off and copy the tail. 425 assert(PartVT.isInteger() && ValueVT.isInteger() && 426 "Do not know what to expand to!"); 427 unsigned RoundParts = 1 << Log2_32(NumParts); 428 unsigned RoundBits = RoundParts * PartBits; 429 unsigned OddParts = NumParts - RoundParts; 430 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 431 DAG.getIntPtrConstant(RoundBits, DL)); 432 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 433 434 if (DAG.getDataLayout().isBigEndian()) 435 // The odd parts were reversed by getCopyToParts - unreverse them. 436 std::reverse(Parts + RoundParts, Parts + NumParts); 437 438 NumParts = RoundParts; 439 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 440 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 441 } 442 443 // The number of parts is a power of 2. Repeatedly bisect the value using 444 // EXTRACT_ELEMENT. 445 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 446 EVT::getIntegerVT(*DAG.getContext(), 447 ValueVT.getSizeInBits()), 448 Val); 449 450 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 451 for (unsigned i = 0; i < NumParts; i += StepSize) { 452 unsigned ThisBits = StepSize * PartBits / 2; 453 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 454 SDValue &Part0 = Parts[i]; 455 SDValue &Part1 = Parts[i+StepSize/2]; 456 457 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 458 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 459 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 460 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 461 462 if (ThisBits == PartBits && ThisVT != PartVT) { 463 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 464 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 465 } 466 } 467 } 468 469 if (DAG.getDataLayout().isBigEndian()) 470 std::reverse(Parts, Parts + OrigNumParts); 471 } 472 473 474 /// getCopyToPartsVector - Create a series of nodes that contain the specified 475 /// value split into legal parts. 476 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL, 477 SDValue Val, SDValue *Parts, unsigned NumParts, 478 MVT PartVT, const Value *V) { 479 EVT ValueVT = Val.getValueType(); 480 assert(ValueVT.isVector() && "Not a vector"); 481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 482 483 if (NumParts == 1) { 484 EVT PartEVT = PartVT; 485 if (PartEVT == ValueVT) { 486 // Nothing to do. 487 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 488 // Bitconvert vector->vector case. 489 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 490 } else if (PartVT.isVector() && 491 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 492 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 493 EVT ElementVT = PartVT.getVectorElementType(); 494 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 495 // undef elements. 496 SmallVector<SDValue, 16> Ops; 497 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 498 Ops.push_back(DAG.getNode( 499 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 500 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 501 502 for (unsigned i = ValueVT.getVectorNumElements(), 503 e = PartVT.getVectorNumElements(); i != e; ++i) 504 Ops.push_back(DAG.getUNDEF(ElementVT)); 505 506 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops); 507 508 // FIXME: Use CONCAT for 2x -> 4x. 509 510 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 511 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 512 } else if (PartVT.isVector() && 513 PartEVT.getVectorElementType().bitsGE( 514 ValueVT.getVectorElementType()) && 515 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 516 517 // Promoted vector extract 518 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 519 } else{ 520 // Vector -> scalar conversion. 521 assert(ValueVT.getVectorNumElements() == 1 && 522 "Only trivial vector-to-scalar conversions should get here!"); 523 Val = DAG.getNode( 524 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 525 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 526 527 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 528 } 529 530 Parts[0] = Val; 531 return; 532 } 533 534 // Handle a multi-element vector. 535 EVT IntermediateVT; 536 MVT RegisterVT; 537 unsigned NumIntermediates; 538 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 539 IntermediateVT, 540 NumIntermediates, RegisterVT); 541 unsigned NumElements = ValueVT.getVectorNumElements(); 542 543 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 544 NumParts = NumRegs; // Silence a compiler warning. 545 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 546 547 // Split the vector into intermediate operands. 548 SmallVector<SDValue, 8> Ops(NumIntermediates); 549 for (unsigned i = 0; i != NumIntermediates; ++i) { 550 if (IntermediateVT.isVector()) 551 Ops[i] = 552 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 553 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 554 TLI.getVectorIdxTy(DAG.getDataLayout()))); 555 else 556 Ops[i] = DAG.getNode( 557 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 558 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 559 } 560 561 // Split the intermediate operands into legal parts. 562 if (NumParts == NumIntermediates) { 563 // If the register was not expanded, promote or copy the value, 564 // as appropriate. 565 for (unsigned i = 0; i != NumParts; ++i) 566 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 567 } else if (NumParts > 0) { 568 // If the intermediate type was expanded, split each the value into 569 // legal parts. 570 assert(NumIntermediates != 0 && "division by zero"); 571 assert(NumParts % NumIntermediates == 0 && 572 "Must expand into a divisible number of parts!"); 573 unsigned Factor = NumParts / NumIntermediates; 574 for (unsigned i = 0; i != NumIntermediates; ++i) 575 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 576 } 577 } 578 579 RegsForValue::RegsForValue() {} 580 581 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 582 EVT valuevt) 583 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 584 585 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 586 const DataLayout &DL, unsigned Reg, Type *Ty) { 587 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 588 589 for (EVT ValueVT : ValueVTs) { 590 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT); 591 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT); 592 for (unsigned i = 0; i != NumRegs; ++i) 593 Regs.push_back(Reg + i); 594 RegVTs.push_back(RegisterVT); 595 Reg += NumRegs; 596 } 597 } 598 599 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 600 /// this value and returns the result as a ValueVT value. This uses 601 /// Chain/Flag as the input and updates them for the output Chain/Flag. 602 /// If the Flag pointer is NULL, no flag is used. 603 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 604 FunctionLoweringInfo &FuncInfo, 605 SDLoc dl, 606 SDValue &Chain, SDValue *Flag, 607 const Value *V) const { 608 // A Value with type {} or [0 x %t] needs no registers. 609 if (ValueVTs.empty()) 610 return SDValue(); 611 612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 613 614 // Assemble the legal parts into the final values. 615 SmallVector<SDValue, 4> Values(ValueVTs.size()); 616 SmallVector<SDValue, 8> Parts; 617 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 618 // Copy the legal parts from the registers. 619 EVT ValueVT = ValueVTs[Value]; 620 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 621 MVT RegisterVT = RegVTs[Value]; 622 623 Parts.resize(NumRegs); 624 for (unsigned i = 0; i != NumRegs; ++i) { 625 SDValue P; 626 if (!Flag) { 627 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 628 } else { 629 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 630 *Flag = P.getValue(2); 631 } 632 633 Chain = P.getValue(1); 634 Parts[i] = P; 635 636 // If the source register was virtual and if we know something about it, 637 // add an assert node. 638 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 639 !RegisterVT.isInteger() || RegisterVT.isVector()) 640 continue; 641 642 const FunctionLoweringInfo::LiveOutInfo *LOI = 643 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 644 if (!LOI) 645 continue; 646 647 unsigned RegSize = RegisterVT.getSizeInBits(); 648 unsigned NumSignBits = LOI->NumSignBits; 649 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); 650 651 if (NumZeroBits == RegSize) { 652 // The current value is a zero. 653 // Explicitly express that as it would be easier for 654 // optimizations to kick in. 655 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 656 continue; 657 } 658 659 // FIXME: We capture more information than the dag can represent. For 660 // now, just use the tightest assertzext/assertsext possible. 661 bool isSExt = true; 662 EVT FromVT(MVT::Other); 663 if (NumSignBits == RegSize) 664 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 665 else if (NumZeroBits >= RegSize-1) 666 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 667 else if (NumSignBits > RegSize-8) 668 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 669 else if (NumZeroBits >= RegSize-8) 670 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 671 else if (NumSignBits > RegSize-16) 672 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 673 else if (NumZeroBits >= RegSize-16) 674 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 675 else if (NumSignBits > RegSize-32) 676 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 677 else if (NumZeroBits >= RegSize-32) 678 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 679 else 680 continue; 681 682 // Add an assertion node. 683 assert(FromVT != MVT::Other); 684 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 685 RegisterVT, P, DAG.getValueType(FromVT)); 686 } 687 688 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 689 NumRegs, RegisterVT, ValueVT, V); 690 Part += NumRegs; 691 Parts.clear(); 692 } 693 694 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 695 } 696 697 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 698 /// specified value into the registers specified by this object. This uses 699 /// Chain/Flag as the input and updates them for the output Chain/Flag. 700 /// If the Flag pointer is NULL, no flag is used. 701 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, 702 SDValue &Chain, SDValue *Flag, const Value *V, 703 ISD::NodeType PreferredExtendType) const { 704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 705 ISD::NodeType ExtendKind = PreferredExtendType; 706 707 // Get the list of the values's legal parts. 708 unsigned NumRegs = Regs.size(); 709 SmallVector<SDValue, 8> Parts(NumRegs); 710 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 711 EVT ValueVT = ValueVTs[Value]; 712 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 713 MVT RegisterVT = RegVTs[Value]; 714 715 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 716 ExtendKind = ISD::ZERO_EXTEND; 717 718 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 719 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 720 Part += NumParts; 721 } 722 723 // Copy the parts into the registers. 724 SmallVector<SDValue, 8> Chains(NumRegs); 725 for (unsigned i = 0; i != NumRegs; ++i) { 726 SDValue Part; 727 if (!Flag) { 728 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 729 } else { 730 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 731 *Flag = Part.getValue(1); 732 } 733 734 Chains[i] = Part.getValue(0); 735 } 736 737 if (NumRegs == 1 || Flag) 738 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 739 // flagged to it. That is the CopyToReg nodes and the user are considered 740 // a single scheduling unit. If we create a TokenFactor and return it as 741 // chain, then the TokenFactor is both a predecessor (operand) of the 742 // user as well as a successor (the TF operands are flagged to the user). 743 // c1, f1 = CopyToReg 744 // c2, f2 = CopyToReg 745 // c3 = TokenFactor c1, c2 746 // ... 747 // = op c3, ..., f2 748 Chain = Chains[NumRegs-1]; 749 else 750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 751 } 752 753 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 754 /// operand list. This adds the code marker and includes the number of 755 /// values added into it. 756 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 757 unsigned MatchingIdx, SDLoc dl, 758 SelectionDAG &DAG, 759 std::vector<SDValue> &Ops) const { 760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 761 762 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 763 if (HasMatching) 764 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 765 else if (!Regs.empty() && 766 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 767 // Put the register class of the virtual registers in the flag word. That 768 // way, later passes can recompute register class constraints for inline 769 // assembly as well as normal instructions. 770 // Don't do this for tied operands that can use the regclass information 771 // from the def. 772 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 773 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 774 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 775 } 776 777 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 778 Ops.push_back(Res); 779 780 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 781 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 782 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 783 MVT RegisterVT = RegVTs[Value]; 784 for (unsigned i = 0; i != NumRegs; ++i) { 785 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 786 unsigned TheReg = Regs[Reg++]; 787 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 788 789 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) { 790 // If we clobbered the stack pointer, MFI should know about it. 791 assert(DAG.getMachineFunction().getFrameInfo()-> 792 hasOpaqueSPAdjustment()); 793 } 794 } 795 } 796 } 797 798 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, 799 const TargetLibraryInfo *li) { 800 AA = &aa; 801 GFI = gfi; 802 LibInfo = li; 803 DL = &DAG.getDataLayout(); 804 Context = DAG.getContext(); 805 LPadToCallSiteMap.clear(); 806 } 807 808 /// clear - Clear out the current SelectionDAG and the associated 809 /// state and prepare this SelectionDAGBuilder object to be used 810 /// for a new block. This doesn't clear out information about 811 /// additional blocks that are needed to complete switch lowering 812 /// or PHI node updating; that information is cleared out as it is 813 /// consumed. 814 void SelectionDAGBuilder::clear() { 815 NodeMap.clear(); 816 UnusedArgNodeMap.clear(); 817 PendingLoads.clear(); 818 PendingExports.clear(); 819 CurInst = nullptr; 820 HasTailCall = false; 821 SDNodeOrder = LowestSDNodeOrder; 822 StatepointLowering.clear(); 823 } 824 825 /// clearDanglingDebugInfo - Clear the dangling debug information 826 /// map. This function is separated from the clear so that debug 827 /// information that is dangling in a basic block can be properly 828 /// resolved in a different basic block. This allows the 829 /// SelectionDAG to resolve dangling debug information attached 830 /// to PHI nodes. 831 void SelectionDAGBuilder::clearDanglingDebugInfo() { 832 DanglingDebugInfoMap.clear(); 833 } 834 835 /// getRoot - Return the current virtual root of the Selection DAG, 836 /// flushing any PendingLoad items. This must be done before emitting 837 /// a store or any other node that may need to be ordered after any 838 /// prior load instructions. 839 /// 840 SDValue SelectionDAGBuilder::getRoot() { 841 if (PendingLoads.empty()) 842 return DAG.getRoot(); 843 844 if (PendingLoads.size() == 1) { 845 SDValue Root = PendingLoads[0]; 846 DAG.setRoot(Root); 847 PendingLoads.clear(); 848 return Root; 849 } 850 851 // Otherwise, we have to make a token factor node. 852 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 853 PendingLoads); 854 PendingLoads.clear(); 855 DAG.setRoot(Root); 856 return Root; 857 } 858 859 /// getControlRoot - Similar to getRoot, but instead of flushing all the 860 /// PendingLoad items, flush all the PendingExports items. It is necessary 861 /// to do this before emitting a terminator instruction. 862 /// 863 SDValue SelectionDAGBuilder::getControlRoot() { 864 SDValue Root = DAG.getRoot(); 865 866 if (PendingExports.empty()) 867 return Root; 868 869 // Turn all of the CopyToReg chains into one factored node. 870 if (Root.getOpcode() != ISD::EntryToken) { 871 unsigned i = 0, e = PendingExports.size(); 872 for (; i != e; ++i) { 873 assert(PendingExports[i].getNode()->getNumOperands() > 1); 874 if (PendingExports[i].getNode()->getOperand(0) == Root) 875 break; // Don't add the root if we already indirectly depend on it. 876 } 877 878 if (i == e) 879 PendingExports.push_back(Root); 880 } 881 882 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 883 PendingExports); 884 PendingExports.clear(); 885 DAG.setRoot(Root); 886 return Root; 887 } 888 889 void SelectionDAGBuilder::visit(const Instruction &I) { 890 // Set up outgoing PHI node register values before emitting the terminator. 891 if (isa<TerminatorInst>(&I)) 892 HandlePHINodesInSuccessorBlocks(I.getParent()); 893 894 ++SDNodeOrder; 895 896 CurInst = &I; 897 898 visit(I.getOpcode(), I); 899 900 if (!isa<TerminatorInst>(&I) && !HasTailCall) 901 CopyToExportRegsIfNeeded(&I); 902 903 CurInst = nullptr; 904 } 905 906 void SelectionDAGBuilder::visitPHI(const PHINode &) { 907 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 908 } 909 910 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 911 // Note: this doesn't use InstVisitor, because it has to work with 912 // ConstantExpr's in addition to instructions. 913 switch (Opcode) { 914 default: llvm_unreachable("Unknown instruction type encountered!"); 915 // Build the switch statement using the Instruction.def file. 916 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 917 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 918 #include "llvm/IR/Instruction.def" 919 } 920 } 921 922 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 923 // generate the debug data structures now that we've seen its definition. 924 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 925 SDValue Val) { 926 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 927 if (DDI.getDI()) { 928 const DbgValueInst *DI = DDI.getDI(); 929 DebugLoc dl = DDI.getdl(); 930 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 931 DILocalVariable *Variable = DI->getVariable(); 932 DIExpression *Expr = DI->getExpression(); 933 assert(Variable->isValidLocationForIntrinsic(dl) && 934 "Expected inlined-at fields to agree"); 935 uint64_t Offset = DI->getOffset(); 936 // A dbg.value for an alloca is always indirect. 937 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0; 938 SDDbgValue *SDV; 939 if (Val.getNode()) { 940 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect, 941 Val)) { 942 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(), 943 IsIndirect, Offset, dl, DbgSDNodeOrder); 944 DAG.AddDbgValue(SDV, Val.getNode(), false); 945 } 946 } else 947 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 948 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 949 } 950 } 951 952 /// getCopyFromRegs - If there was virtual register allocated for the value V 953 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 954 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 955 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 956 SDValue Result; 957 958 if (It != FuncInfo.ValueMap.end()) { 959 unsigned InReg = It->second; 960 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 961 DAG.getDataLayout(), InReg, Ty); 962 SDValue Chain = DAG.getEntryNode(); 963 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 964 resolveDanglingDebugInfo(V, Result); 965 } 966 967 return Result; 968 } 969 970 /// getValue - Return an SDValue for the given Value. 971 SDValue SelectionDAGBuilder::getValue(const Value *V) { 972 // If we already have an SDValue for this value, use it. It's important 973 // to do this first, so that we don't create a CopyFromReg if we already 974 // have a regular SDValue. 975 SDValue &N = NodeMap[V]; 976 if (N.getNode()) return N; 977 978 // If there's a virtual register allocated and initialized for this 979 // value, use it. 980 SDValue copyFromReg = getCopyFromRegs(V, V->getType()); 981 if (copyFromReg.getNode()) { 982 return copyFromReg; 983 } 984 985 // Otherwise create a new SDValue and remember it. 986 SDValue Val = getValueImpl(V); 987 NodeMap[V] = Val; 988 resolveDanglingDebugInfo(V, Val); 989 return Val; 990 } 991 992 // Return true if SDValue exists for the given Value 993 bool SelectionDAGBuilder::findValue(const Value *V) const { 994 return (NodeMap.find(V) != NodeMap.end()) || 995 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 996 } 997 998 /// getNonRegisterValue - Return an SDValue for the given Value, but 999 /// don't look in FuncInfo.ValueMap for a virtual register. 1000 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1001 // If we already have an SDValue for this value, use it. 1002 SDValue &N = NodeMap[V]; 1003 if (N.getNode()) { 1004 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1005 // Remove the debug location from the node as the node is about to be used 1006 // in a location which may differ from the original debug location. This 1007 // is relevant to Constant and ConstantFP nodes because they can appear 1008 // as constant expressions inside PHI nodes. 1009 N->setDebugLoc(DebugLoc()); 1010 } 1011 return N; 1012 } 1013 1014 // Otherwise create a new SDValue and remember it. 1015 SDValue Val = getValueImpl(V); 1016 NodeMap[V] = Val; 1017 resolveDanglingDebugInfo(V, Val); 1018 return Val; 1019 } 1020 1021 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1022 /// Create an SDValue for the given value. 1023 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1025 1026 if (const Constant *C = dyn_cast<Constant>(V)) { 1027 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1028 1029 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1030 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1031 1032 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1033 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1034 1035 if (isa<ConstantPointerNull>(C)) { 1036 unsigned AS = V->getType()->getPointerAddressSpace(); 1037 return DAG.getConstant(0, getCurSDLoc(), 1038 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1039 } 1040 1041 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1042 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1043 1044 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1045 return DAG.getUNDEF(VT); 1046 1047 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1048 visit(CE->getOpcode(), *CE); 1049 SDValue N1 = NodeMap[V]; 1050 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1051 return N1; 1052 } 1053 1054 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1055 SmallVector<SDValue, 4> Constants; 1056 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1057 OI != OE; ++OI) { 1058 SDNode *Val = getValue(*OI).getNode(); 1059 // If the operand is an empty aggregate, there are no values. 1060 if (!Val) continue; 1061 // Add each leaf value from the operand to the Constants list 1062 // to form a flattened list of all the values. 1063 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1064 Constants.push_back(SDValue(Val, i)); 1065 } 1066 1067 return DAG.getMergeValues(Constants, getCurSDLoc()); 1068 } 1069 1070 if (const ConstantDataSequential *CDS = 1071 dyn_cast<ConstantDataSequential>(C)) { 1072 SmallVector<SDValue, 4> Ops; 1073 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1074 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1075 // Add each leaf value from the operand to the Constants list 1076 // to form a flattened list of all the values. 1077 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1078 Ops.push_back(SDValue(Val, i)); 1079 } 1080 1081 if (isa<ArrayType>(CDS->getType())) 1082 return DAG.getMergeValues(Ops, getCurSDLoc()); 1083 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 1084 VT, Ops); 1085 } 1086 1087 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1088 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1089 "Unknown struct or array constant!"); 1090 1091 SmallVector<EVT, 4> ValueVTs; 1092 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1093 unsigned NumElts = ValueVTs.size(); 1094 if (NumElts == 0) 1095 return SDValue(); // empty struct 1096 SmallVector<SDValue, 4> Constants(NumElts); 1097 for (unsigned i = 0; i != NumElts; ++i) { 1098 EVT EltVT = ValueVTs[i]; 1099 if (isa<UndefValue>(C)) 1100 Constants[i] = DAG.getUNDEF(EltVT); 1101 else if (EltVT.isFloatingPoint()) 1102 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1103 else 1104 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1105 } 1106 1107 return DAG.getMergeValues(Constants, getCurSDLoc()); 1108 } 1109 1110 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1111 return DAG.getBlockAddress(BA, VT); 1112 1113 VectorType *VecTy = cast<VectorType>(V->getType()); 1114 unsigned NumElements = VecTy->getNumElements(); 1115 1116 // Now that we know the number and type of the elements, get that number of 1117 // elements into the Ops array based on what kind of constant it is. 1118 SmallVector<SDValue, 16> Ops; 1119 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1120 for (unsigned i = 0; i != NumElements; ++i) 1121 Ops.push_back(getValue(CV->getOperand(i))); 1122 } else { 1123 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1124 EVT EltVT = 1125 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1126 1127 SDValue Op; 1128 if (EltVT.isFloatingPoint()) 1129 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1130 else 1131 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1132 Ops.assign(NumElements, Op); 1133 } 1134 1135 // Create a BUILD_VECTOR node. 1136 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops); 1137 } 1138 1139 // If this is a static alloca, generate it as the frameindex instead of 1140 // computation. 1141 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1142 DenseMap<const AllocaInst*, int>::iterator SI = 1143 FuncInfo.StaticAllocaMap.find(AI); 1144 if (SI != FuncInfo.StaticAllocaMap.end()) 1145 return DAG.getFrameIndex(SI->second, 1146 TLI.getPointerTy(DAG.getDataLayout())); 1147 } 1148 1149 // If this is an instruction which fast-isel has deferred, select it now. 1150 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1151 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1152 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1153 Inst->getType()); 1154 SDValue Chain = DAG.getEntryNode(); 1155 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1156 } 1157 1158 llvm_unreachable("Can't get register for value!"); 1159 } 1160 1161 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1162 // Update machine-CFG edges. 1163 MachineBasicBlock *PadMBB = FuncInfo.MBB; 1164 MachineBasicBlock *CatchingMBB = FuncInfo.MBBMap[I.getNormalDest()]; 1165 MachineBasicBlock *UnwindMBB = FuncInfo.MBBMap[I.getUnwindDest()]; 1166 PadMBB->addSuccessor(CatchingMBB); 1167 PadMBB->addSuccessor(UnwindMBB); 1168 1169 CatchingMBB->setIsEHFuncletEntry(); 1170 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 1171 MMI.setHasEHFunclets(true); 1172 } 1173 1174 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1175 // Update machine-CFG edge. 1176 MachineBasicBlock *PadMBB = FuncInfo.MBB; 1177 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1178 PadMBB->addSuccessor(TargetMBB); 1179 1180 // Create the terminator node. 1181 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1182 getControlRoot(), DAG.getBasicBlock(TargetMBB)); 1183 DAG.setRoot(Ret); 1184 } 1185 1186 void SelectionDAGBuilder::visitCatchEndPad(const CatchEndPadInst &I) { 1187 // If this unwinds to caller, we don't need a DAG node hanging around. 1188 if (!I.hasUnwindDest()) 1189 return; 1190 1191 // Update machine-CFG edge. 1192 MachineBasicBlock *PadMBB = FuncInfo.MBB; 1193 MachineBasicBlock *UnwindMBB = FuncInfo.MBBMap[I.getUnwindDest()]; 1194 PadMBB->addSuccessor(UnwindMBB); 1195 } 1196 1197 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1198 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 1199 MMI.setHasEHFunclets(true); 1200 report_fatal_error("visitCleanupPad not yet implemented!"); 1201 } 1202 1203 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1204 report_fatal_error("visitCleanupRet not yet implemented!"); 1205 } 1206 1207 void SelectionDAGBuilder::visitTerminatePad(const TerminatePadInst &TPI) { 1208 report_fatal_error("visitTerminatePad not yet implemented!"); 1209 } 1210 1211 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1212 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1213 auto &DL = DAG.getDataLayout(); 1214 SDValue Chain = getControlRoot(); 1215 SmallVector<ISD::OutputArg, 8> Outs; 1216 SmallVector<SDValue, 8> OutVals; 1217 1218 if (!FuncInfo.CanLowerReturn) { 1219 unsigned DemoteReg = FuncInfo.DemoteRegister; 1220 const Function *F = I.getParent()->getParent(); 1221 1222 // Emit a store of the return value through the virtual register. 1223 // Leave Outs empty so that LowerReturn won't try to load return 1224 // registers the usual way. 1225 SmallVector<EVT, 1> PtrValueVTs; 1226 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()), 1227 PtrValueVTs); 1228 1229 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 1230 SDValue RetOp = getValue(I.getOperand(0)); 1231 1232 SmallVector<EVT, 4> ValueVTs; 1233 SmallVector<uint64_t, 4> Offsets; 1234 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1235 unsigned NumValues = ValueVTs.size(); 1236 1237 SmallVector<SDValue, 4> Chains(NumValues); 1238 for (unsigned i = 0; i != NumValues; ++i) { 1239 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), 1240 RetPtr.getValueType(), RetPtr, 1241 DAG.getIntPtrConstant(Offsets[i], 1242 getCurSDLoc())); 1243 Chains[i] = 1244 DAG.getStore(Chain, getCurSDLoc(), 1245 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1246 // FIXME: better loc info would be nice. 1247 Add, MachinePointerInfo(), false, false, 0); 1248 } 1249 1250 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1251 MVT::Other, Chains); 1252 } else if (I.getNumOperands() != 0) { 1253 SmallVector<EVT, 4> ValueVTs; 1254 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1255 unsigned NumValues = ValueVTs.size(); 1256 if (NumValues) { 1257 SDValue RetOp = getValue(I.getOperand(0)); 1258 1259 const Function *F = I.getParent()->getParent(); 1260 1261 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1262 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1263 Attribute::SExt)) 1264 ExtendKind = ISD::SIGN_EXTEND; 1265 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1266 Attribute::ZExt)) 1267 ExtendKind = ISD::ZERO_EXTEND; 1268 1269 LLVMContext &Context = F->getContext(); 1270 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1271 Attribute::InReg); 1272 1273 for (unsigned j = 0; j != NumValues; ++j) { 1274 EVT VT = ValueVTs[j]; 1275 1276 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1277 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind); 1278 1279 unsigned NumParts = TLI.getNumRegisters(Context, VT); 1280 MVT PartVT = TLI.getRegisterType(Context, VT); 1281 SmallVector<SDValue, 4> Parts(NumParts); 1282 getCopyToParts(DAG, getCurSDLoc(), 1283 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1284 &Parts[0], NumParts, PartVT, &I, ExtendKind); 1285 1286 // 'inreg' on function refers to return value 1287 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1288 if (RetInReg) 1289 Flags.setInReg(); 1290 1291 // Propagate extension type if any 1292 if (ExtendKind == ISD::SIGN_EXTEND) 1293 Flags.setSExt(); 1294 else if (ExtendKind == ISD::ZERO_EXTEND) 1295 Flags.setZExt(); 1296 1297 for (unsigned i = 0; i < NumParts; ++i) { 1298 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1299 VT, /*isfixed=*/true, 0, 0)); 1300 OutVals.push_back(Parts[i]); 1301 } 1302 } 1303 } 1304 } 1305 1306 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1307 CallingConv::ID CallConv = 1308 DAG.getMachineFunction().getFunction()->getCallingConv(); 1309 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1310 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1311 1312 // Verify that the target's LowerReturn behaved as expected. 1313 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1314 "LowerReturn didn't return a valid chain!"); 1315 1316 // Update the DAG with the new chain value resulting from return lowering. 1317 DAG.setRoot(Chain); 1318 } 1319 1320 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1321 /// created for it, emit nodes to copy the value into the virtual 1322 /// registers. 1323 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1324 // Skip empty types 1325 if (V->getType()->isEmptyTy()) 1326 return; 1327 1328 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1329 if (VMI != FuncInfo.ValueMap.end()) { 1330 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1331 CopyValueToVirtualRegister(V, VMI->second); 1332 } 1333 } 1334 1335 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1336 /// the current basic block, add it to ValueMap now so that we'll get a 1337 /// CopyTo/FromReg. 1338 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1339 // No need to export constants. 1340 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1341 1342 // Already exported? 1343 if (FuncInfo.isExportedInst(V)) return; 1344 1345 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1346 CopyValueToVirtualRegister(V, Reg); 1347 } 1348 1349 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1350 const BasicBlock *FromBB) { 1351 // The operands of the setcc have to be in this block. We don't know 1352 // how to export them from some other block. 1353 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1354 // Can export from current BB. 1355 if (VI->getParent() == FromBB) 1356 return true; 1357 1358 // Is already exported, noop. 1359 return FuncInfo.isExportedInst(V); 1360 } 1361 1362 // If this is an argument, we can export it if the BB is the entry block or 1363 // if it is already exported. 1364 if (isa<Argument>(V)) { 1365 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1366 return true; 1367 1368 // Otherwise, can only export this if it is already exported. 1369 return FuncInfo.isExportedInst(V); 1370 } 1371 1372 // Otherwise, constants can always be exported. 1373 return true; 1374 } 1375 1376 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1377 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src, 1378 const MachineBasicBlock *Dst) const { 1379 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1380 if (!BPI) 1381 return 0; 1382 const BasicBlock *SrcBB = Src->getBasicBlock(); 1383 const BasicBlock *DstBB = Dst->getBasicBlock(); 1384 return BPI->getEdgeWeight(SrcBB, DstBB); 1385 } 1386 1387 void SelectionDAGBuilder:: 1388 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, 1389 uint32_t Weight /* = 0 */) { 1390 if (!Weight) 1391 Weight = getEdgeWeight(Src, Dst); 1392 Src->addSuccessor(Dst, Weight); 1393 } 1394 1395 1396 static bool InBlock(const Value *V, const BasicBlock *BB) { 1397 if (const Instruction *I = dyn_cast<Instruction>(V)) 1398 return I->getParent() == BB; 1399 return true; 1400 } 1401 1402 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1403 /// This function emits a branch and is used at the leaves of an OR or an 1404 /// AND operator tree. 1405 /// 1406 void 1407 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1408 MachineBasicBlock *TBB, 1409 MachineBasicBlock *FBB, 1410 MachineBasicBlock *CurBB, 1411 MachineBasicBlock *SwitchBB, 1412 uint32_t TWeight, 1413 uint32_t FWeight) { 1414 const BasicBlock *BB = CurBB->getBasicBlock(); 1415 1416 // If the leaf of the tree is a comparison, merge the condition into 1417 // the caseblock. 1418 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1419 // The operands of the cmp have to be in this block. We don't know 1420 // how to export them from some other block. If this is the first block 1421 // of the sequence, no exporting is needed. 1422 if (CurBB == SwitchBB || 1423 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1424 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1425 ISD::CondCode Condition; 1426 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1427 Condition = getICmpCondCode(IC->getPredicate()); 1428 } else { 1429 const FCmpInst *FC = cast<FCmpInst>(Cond); 1430 Condition = getFCmpCondCode(FC->getPredicate()); 1431 if (TM.Options.NoNaNsFPMath) 1432 Condition = getFCmpCodeWithoutNaN(Condition); 1433 } 1434 1435 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1436 TBB, FBB, CurBB, TWeight, FWeight); 1437 SwitchCases.push_back(CB); 1438 return; 1439 } 1440 } 1441 1442 // Create a CaseBlock record representing this branch. 1443 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1444 nullptr, TBB, FBB, CurBB, TWeight, FWeight); 1445 SwitchCases.push_back(CB); 1446 } 1447 1448 /// Scale down both weights to fit into uint32_t. 1449 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { 1450 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; 1451 uint32_t Scale = (NewMax / UINT32_MAX) + 1; 1452 NewTrue = NewTrue / Scale; 1453 NewFalse = NewFalse / Scale; 1454 } 1455 1456 /// FindMergedConditions - If Cond is an expression like 1457 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1458 MachineBasicBlock *TBB, 1459 MachineBasicBlock *FBB, 1460 MachineBasicBlock *CurBB, 1461 MachineBasicBlock *SwitchBB, 1462 Instruction::BinaryOps Opc, 1463 uint32_t TWeight, 1464 uint32_t FWeight) { 1465 // If this node is not part of the or/and tree, emit it as a branch. 1466 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1467 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1468 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1469 BOp->getParent() != CurBB->getBasicBlock() || 1470 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1471 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1472 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1473 TWeight, FWeight); 1474 return; 1475 } 1476 1477 // Create TmpBB after CurBB. 1478 MachineFunction::iterator BBI = CurBB; 1479 MachineFunction &MF = DAG.getMachineFunction(); 1480 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1481 CurBB->getParent()->insert(++BBI, TmpBB); 1482 1483 if (Opc == Instruction::Or) { 1484 // Codegen X | Y as: 1485 // BB1: 1486 // jmp_if_X TBB 1487 // jmp TmpBB 1488 // TmpBB: 1489 // jmp_if_Y TBB 1490 // jmp FBB 1491 // 1492 1493 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1494 // The requirement is that 1495 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1496 // = TrueProb for original BB. 1497 // Assuming the original weights are A and B, one choice is to set BB1's 1498 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice 1499 // assumes that 1500 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1501 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1502 // TmpBB, but the math is more complicated. 1503 1504 uint64_t NewTrueWeight = TWeight; 1505 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight; 1506 ScaleWeights(NewTrueWeight, NewFalseWeight); 1507 // Emit the LHS condition. 1508 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1509 NewTrueWeight, NewFalseWeight); 1510 1511 NewTrueWeight = TWeight; 1512 NewFalseWeight = 2 * (uint64_t)FWeight; 1513 ScaleWeights(NewTrueWeight, NewFalseWeight); 1514 // Emit the RHS condition into TmpBB. 1515 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1516 NewTrueWeight, NewFalseWeight); 1517 } else { 1518 assert(Opc == Instruction::And && "Unknown merge op!"); 1519 // Codegen X & Y as: 1520 // BB1: 1521 // jmp_if_X TmpBB 1522 // jmp FBB 1523 // TmpBB: 1524 // jmp_if_Y TBB 1525 // jmp FBB 1526 // 1527 // This requires creation of TmpBB after CurBB. 1528 1529 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1530 // The requirement is that 1531 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1532 // = FalseProb for original BB. 1533 // Assuming the original weights are A and B, one choice is to set BB1's 1534 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice 1535 // assumes that 1536 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. 1537 1538 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight; 1539 uint64_t NewFalseWeight = FWeight; 1540 ScaleWeights(NewTrueWeight, NewFalseWeight); 1541 // Emit the LHS condition. 1542 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1543 NewTrueWeight, NewFalseWeight); 1544 1545 NewTrueWeight = 2 * (uint64_t)TWeight; 1546 NewFalseWeight = FWeight; 1547 ScaleWeights(NewTrueWeight, NewFalseWeight); 1548 // Emit the RHS condition into TmpBB. 1549 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1550 NewTrueWeight, NewFalseWeight); 1551 } 1552 } 1553 1554 /// If the set of cases should be emitted as a series of branches, return true. 1555 /// If we should emit this as a bunch of and/or'd together conditions, return 1556 /// false. 1557 bool 1558 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1559 if (Cases.size() != 2) return true; 1560 1561 // If this is two comparisons of the same values or'd or and'd together, they 1562 // will get folded into a single comparison, so don't emit two blocks. 1563 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1564 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1565 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1566 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1567 return false; 1568 } 1569 1570 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1571 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1572 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1573 Cases[0].CC == Cases[1].CC && 1574 isa<Constant>(Cases[0].CmpRHS) && 1575 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1576 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1577 return false; 1578 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1579 return false; 1580 } 1581 1582 return true; 1583 } 1584 1585 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1586 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1587 1588 // Update machine-CFG edges. 1589 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1590 1591 if (I.isUnconditional()) { 1592 // Update machine-CFG edges. 1593 BrMBB->addSuccessor(Succ0MBB); 1594 1595 // If this is not a fall-through branch or optimizations are switched off, 1596 // emit the branch. 1597 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1598 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1599 MVT::Other, getControlRoot(), 1600 DAG.getBasicBlock(Succ0MBB))); 1601 1602 return; 1603 } 1604 1605 // If this condition is one of the special cases we handle, do special stuff 1606 // now. 1607 const Value *CondVal = I.getCondition(); 1608 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1609 1610 // If this is a series of conditions that are or'd or and'd together, emit 1611 // this as a sequence of branches instead of setcc's with and/or operations. 1612 // As long as jumps are not expensive, this should improve performance. 1613 // For example, instead of something like: 1614 // cmp A, B 1615 // C = seteq 1616 // cmp D, E 1617 // F = setle 1618 // or C, F 1619 // jnz foo 1620 // Emit: 1621 // cmp A, B 1622 // je foo 1623 // cmp D, E 1624 // jle foo 1625 // 1626 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1627 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && 1628 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And || 1629 BOp->getOpcode() == Instruction::Or)) { 1630 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1631 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB), 1632 getEdgeWeight(BrMBB, Succ1MBB)); 1633 // If the compares in later blocks need to use values not currently 1634 // exported from this block, export them now. This block should always 1635 // be the first entry. 1636 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1637 1638 // Allow some cases to be rejected. 1639 if (ShouldEmitAsBranches(SwitchCases)) { 1640 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1641 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1642 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1643 } 1644 1645 // Emit the branch for this block. 1646 visitSwitchCase(SwitchCases[0], BrMBB); 1647 SwitchCases.erase(SwitchCases.begin()); 1648 return; 1649 } 1650 1651 // Okay, we decided not to do this, remove any inserted MBB's and clear 1652 // SwitchCases. 1653 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1654 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1655 1656 SwitchCases.clear(); 1657 } 1658 } 1659 1660 // Create a CaseBlock record representing this branch. 1661 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1662 nullptr, Succ0MBB, Succ1MBB, BrMBB); 1663 1664 // Use visitSwitchCase to actually insert the fast branch sequence for this 1665 // cond branch. 1666 visitSwitchCase(CB, BrMBB); 1667 } 1668 1669 /// visitSwitchCase - Emits the necessary code to represent a single node in 1670 /// the binary search tree resulting from lowering a switch instruction. 1671 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1672 MachineBasicBlock *SwitchBB) { 1673 SDValue Cond; 1674 SDValue CondLHS = getValue(CB.CmpLHS); 1675 SDLoc dl = getCurSDLoc(); 1676 1677 // Build the setcc now. 1678 if (!CB.CmpMHS) { 1679 // Fold "(X == true)" to X and "(X == false)" to !X to 1680 // handle common cases produced by branch lowering. 1681 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1682 CB.CC == ISD::SETEQ) 1683 Cond = CondLHS; 1684 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1685 CB.CC == ISD::SETEQ) { 1686 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 1687 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1688 } else 1689 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1690 } else { 1691 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1692 1693 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1694 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1695 1696 SDValue CmpOp = getValue(CB.CmpMHS); 1697 EVT VT = CmpOp.getValueType(); 1698 1699 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1700 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 1701 ISD::SETLE); 1702 } else { 1703 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1704 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 1705 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1706 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 1707 } 1708 } 1709 1710 // Update successor info 1711 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight); 1712 // TrueBB and FalseBB are always different unless the incoming IR is 1713 // degenerate. This only happens when running llc on weird IR. 1714 if (CB.TrueBB != CB.FalseBB) 1715 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight); 1716 1717 // If the lhs block is the next block, invert the condition so that we can 1718 // fall through to the lhs instead of the rhs block. 1719 if (CB.TrueBB == NextBlock(SwitchBB)) { 1720 std::swap(CB.TrueBB, CB.FalseBB); 1721 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 1722 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1723 } 1724 1725 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1726 MVT::Other, getControlRoot(), Cond, 1727 DAG.getBasicBlock(CB.TrueBB)); 1728 1729 // Insert the false branch. Do this even if it's a fall through branch, 1730 // this makes it easier to do DAG optimizations which require inverting 1731 // the branch condition. 1732 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1733 DAG.getBasicBlock(CB.FalseBB)); 1734 1735 DAG.setRoot(BrCond); 1736 } 1737 1738 /// visitJumpTable - Emit JumpTable node in the current MBB 1739 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1740 // Emit the code for the jump table 1741 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1742 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1743 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 1744 JT.Reg, PTy); 1745 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1746 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 1747 MVT::Other, Index.getValue(1), 1748 Table, Index); 1749 DAG.setRoot(BrJumpTable); 1750 } 1751 1752 /// visitJumpTableHeader - This function emits necessary code to produce index 1753 /// in the JumpTable from switch case. 1754 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1755 JumpTableHeader &JTH, 1756 MachineBasicBlock *SwitchBB) { 1757 SDLoc dl = getCurSDLoc(); 1758 1759 // Subtract the lowest switch case value from the value being switched on and 1760 // conditional branch to default mbb if the result is greater than the 1761 // difference between smallest and largest cases. 1762 SDValue SwitchOp = getValue(JTH.SValue); 1763 EVT VT = SwitchOp.getValueType(); 1764 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 1765 DAG.getConstant(JTH.First, dl, VT)); 1766 1767 // The SDNode we just created, which holds the value being switched on minus 1768 // the smallest case value, needs to be copied to a virtual register so it 1769 // can be used as an index into the jump table in a subsequent basic block. 1770 // This value may be smaller or larger than the target's pointer type, and 1771 // therefore require extension or truncating. 1772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1773 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 1774 1775 unsigned JumpTableReg = 1776 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 1777 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 1778 JumpTableReg, SwitchOp); 1779 JT.Reg = JumpTableReg; 1780 1781 // Emit the range check for the jump table, and branch to the default block 1782 // for the switch statement if the value being switched on exceeds the largest 1783 // case in the switch. 1784 SDValue CMP = DAG.getSetCC( 1785 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 1786 Sub.getValueType()), 1787 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 1788 1789 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1790 MVT::Other, CopyTo, CMP, 1791 DAG.getBasicBlock(JT.Default)); 1792 1793 // Avoid emitting unnecessary branches to the next block. 1794 if (JT.MBB != NextBlock(SwitchBB)) 1795 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1796 DAG.getBasicBlock(JT.MBB)); 1797 1798 DAG.setRoot(BrCond); 1799 } 1800 1801 /// Codegen a new tail for a stack protector check ParentMBB which has had its 1802 /// tail spliced into a stack protector check success bb. 1803 /// 1804 /// For a high level explanation of how this fits into the stack protector 1805 /// generation see the comment on the declaration of class 1806 /// StackProtectorDescriptor. 1807 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 1808 MachineBasicBlock *ParentBB) { 1809 1810 // First create the loads to the guard/stack slot for the comparison. 1811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1812 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 1813 1814 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo(); 1815 int FI = MFI->getStackProtectorIndex(); 1816 1817 const Value *IRGuard = SPD.getGuard(); 1818 SDValue GuardPtr = getValue(IRGuard); 1819 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 1820 1821 unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType()); 1822 1823 SDValue Guard; 1824 SDLoc dl = getCurSDLoc(); 1825 1826 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the 1827 // guard value from the virtual register holding the value. Otherwise, emit a 1828 // volatile load to retrieve the stack guard value. 1829 unsigned GuardReg = SPD.getGuardReg(); 1830 1831 if (GuardReg && TLI.useLoadStackGuardNode()) 1832 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg, 1833 PtrTy); 1834 else 1835 Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(), 1836 GuardPtr, MachinePointerInfo(IRGuard, 0), 1837 true, false, false, Align); 1838 1839 SDValue StackSlot = DAG.getLoad( 1840 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 1841 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), true, 1842 false, false, Align); 1843 1844 // Perform the comparison via a subtract/getsetcc. 1845 EVT VT = Guard.getValueType(); 1846 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot); 1847 1848 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 1849 *DAG.getContext(), 1850 Sub.getValueType()), 1851 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 1852 1853 // If the sub is not 0, then we know the guard/stackslot do not equal, so 1854 // branch to failure MBB. 1855 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1856 MVT::Other, StackSlot.getOperand(0), 1857 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 1858 // Otherwise branch to success MBB. 1859 SDValue Br = DAG.getNode(ISD::BR, dl, 1860 MVT::Other, BrCond, 1861 DAG.getBasicBlock(SPD.getSuccessMBB())); 1862 1863 DAG.setRoot(Br); 1864 } 1865 1866 /// Codegen the failure basic block for a stack protector check. 1867 /// 1868 /// A failure stack protector machine basic block consists simply of a call to 1869 /// __stack_chk_fail(). 1870 /// 1871 /// For a high level explanation of how this fits into the stack protector 1872 /// generation see the comment on the declaration of class 1873 /// StackProtectorDescriptor. 1874 void 1875 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 1876 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1877 SDValue Chain = 1878 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 1879 nullptr, 0, false, getCurSDLoc(), false, false).second; 1880 DAG.setRoot(Chain); 1881 } 1882 1883 /// visitBitTestHeader - This function emits necessary code to produce value 1884 /// suitable for "bit tests" 1885 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1886 MachineBasicBlock *SwitchBB) { 1887 SDLoc dl = getCurSDLoc(); 1888 1889 // Subtract the minimum value 1890 SDValue SwitchOp = getValue(B.SValue); 1891 EVT VT = SwitchOp.getValueType(); 1892 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 1893 DAG.getConstant(B.First, dl, VT)); 1894 1895 // Check range 1896 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1897 SDValue RangeCmp = DAG.getSetCC( 1898 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 1899 Sub.getValueType()), 1900 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 1901 1902 // Determine the type of the test operands. 1903 bool UsePtrType = false; 1904 if (!TLI.isTypeLegal(VT)) 1905 UsePtrType = true; 1906 else { 1907 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 1908 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 1909 // Switch table case range are encoded into series of masks. 1910 // Just use pointer type, it's guaranteed to fit. 1911 UsePtrType = true; 1912 break; 1913 } 1914 } 1915 if (UsePtrType) { 1916 VT = TLI.getPointerTy(DAG.getDataLayout()); 1917 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 1918 } 1919 1920 B.RegVT = VT.getSimpleVT(); 1921 B.Reg = FuncInfo.CreateReg(B.RegVT); 1922 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 1923 1924 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1925 1926 uint32_t DefaultWeight = getEdgeWeight(SwitchBB, B.Default); 1927 addSuccessorWithWeight(SwitchBB, B.Default, DefaultWeight); 1928 addSuccessorWithWeight(SwitchBB, MBB, B.Weight); 1929 1930 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 1931 MVT::Other, CopyTo, RangeCmp, 1932 DAG.getBasicBlock(B.Default)); 1933 1934 // Avoid emitting unnecessary branches to the next block. 1935 if (MBB != NextBlock(SwitchBB)) 1936 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 1937 DAG.getBasicBlock(MBB)); 1938 1939 DAG.setRoot(BrRange); 1940 } 1941 1942 /// visitBitTestCase - this function produces one "bit test" 1943 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 1944 MachineBasicBlock* NextMBB, 1945 uint32_t BranchWeightToNext, 1946 unsigned Reg, 1947 BitTestCase &B, 1948 MachineBasicBlock *SwitchBB) { 1949 SDLoc dl = getCurSDLoc(); 1950 MVT VT = BB.RegVT; 1951 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 1952 SDValue Cmp; 1953 unsigned PopCount = countPopulation(B.Mask); 1954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1955 if (PopCount == 1) { 1956 // Testing for a single bit; just compare the shift count with what it 1957 // would need to be to shift a 1 bit in that position. 1958 Cmp = DAG.getSetCC( 1959 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1960 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 1961 ISD::SETEQ); 1962 } else if (PopCount == BB.Range) { 1963 // There is only one zero bit in the range, test for it directly. 1964 Cmp = DAG.getSetCC( 1965 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1966 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 1967 ISD::SETNE); 1968 } else { 1969 // Make desired shift 1970 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 1971 DAG.getConstant(1, dl, VT), ShiftOp); 1972 1973 // Emit bit tests and jumps 1974 SDValue AndOp = DAG.getNode(ISD::AND, dl, 1975 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 1976 Cmp = DAG.getSetCC( 1977 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1978 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 1979 } 1980 1981 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight. 1982 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight); 1983 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext. 1984 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext); 1985 1986 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 1987 MVT::Other, getControlRoot(), 1988 Cmp, DAG.getBasicBlock(B.TargetBB)); 1989 1990 // Avoid emitting unnecessary branches to the next block. 1991 if (NextMBB != NextBlock(SwitchBB)) 1992 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 1993 DAG.getBasicBlock(NextMBB)); 1994 1995 DAG.setRoot(BrAnd); 1996 } 1997 1998 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1999 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2000 2001 // Retrieve successors. 2002 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2003 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 2004 2005 const Value *Callee(I.getCalledValue()); 2006 const Function *Fn = dyn_cast<Function>(Callee); 2007 if (isa<InlineAsm>(Callee)) 2008 visitInlineAsm(&I); 2009 else if (Fn && Fn->isIntrinsic()) { 2010 switch (Fn->getIntrinsicID()) { 2011 default: 2012 llvm_unreachable("Cannot invoke this intrinsic"); 2013 case Intrinsic::donothing: 2014 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2015 break; 2016 case Intrinsic::experimental_patchpoint_void: 2017 case Intrinsic::experimental_patchpoint_i64: 2018 visitPatchpoint(&I, LandingPad); 2019 break; 2020 case Intrinsic::experimental_gc_statepoint: 2021 LowerStatepoint(ImmutableStatepoint(&I), LandingPad); 2022 break; 2023 } 2024 } else 2025 LowerCallTo(&I, getValue(Callee), false, LandingPad); 2026 2027 // If the value of the invoke is used outside of its defining block, make it 2028 // available as a virtual register. 2029 // We already took care of the exported value for the statepoint instruction 2030 // during call to the LowerStatepoint. 2031 if (!isStatepoint(I)) { 2032 CopyToExportRegsIfNeeded(&I); 2033 } 2034 2035 // Update successor info 2036 addSuccessorWithWeight(InvokeMBB, Return); 2037 addSuccessorWithWeight(InvokeMBB, LandingPad); 2038 2039 // Drop into normal successor. 2040 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2041 MVT::Other, getControlRoot(), 2042 DAG.getBasicBlock(Return))); 2043 } 2044 2045 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2046 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2047 } 2048 2049 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2050 assert(FuncInfo.MBB->isEHPad() && 2051 "Call to landingpad not in landing pad!"); 2052 2053 MachineBasicBlock *MBB = FuncInfo.MBB; 2054 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 2055 AddLandingPadInfo(LP, MMI, MBB); 2056 2057 // If there aren't registers to copy the values into (e.g., during SjLj 2058 // exceptions), then don't bother to create these DAG nodes. 2059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2060 if (TLI.getExceptionPointerRegister() == 0 && 2061 TLI.getExceptionSelectorRegister() == 0) 2062 return; 2063 2064 SmallVector<EVT, 2> ValueVTs; 2065 SDLoc dl = getCurSDLoc(); 2066 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2067 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2068 2069 // Get the two live-in registers as SDValues. The physregs have already been 2070 // copied into virtual registers. 2071 SDValue Ops[2]; 2072 if (FuncInfo.ExceptionPointerVirtReg) { 2073 Ops[0] = DAG.getZExtOrTrunc( 2074 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2075 FuncInfo.ExceptionPointerVirtReg, 2076 TLI.getPointerTy(DAG.getDataLayout())), 2077 dl, ValueVTs[0]); 2078 } else { 2079 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2080 } 2081 Ops[1] = DAG.getZExtOrTrunc( 2082 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2083 FuncInfo.ExceptionSelectorVirtReg, 2084 TLI.getPointerTy(DAG.getDataLayout())), 2085 dl, ValueVTs[1]); 2086 2087 // Merge into one. 2088 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2089 DAG.getVTList(ValueVTs), Ops); 2090 setValue(&LP, Res); 2091 } 2092 2093 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2094 #ifndef NDEBUG 2095 for (const CaseCluster &CC : Clusters) 2096 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2097 #endif 2098 2099 std::sort(Clusters.begin(), Clusters.end(), 2100 [](const CaseCluster &a, const CaseCluster &b) { 2101 return a.Low->getValue().slt(b.Low->getValue()); 2102 }); 2103 2104 // Merge adjacent clusters with the same destination. 2105 const unsigned N = Clusters.size(); 2106 unsigned DstIndex = 0; 2107 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2108 CaseCluster &CC = Clusters[SrcIndex]; 2109 const ConstantInt *CaseVal = CC.Low; 2110 MachineBasicBlock *Succ = CC.MBB; 2111 2112 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2113 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2114 // If this case has the same successor and is a neighbour, merge it into 2115 // the previous cluster. 2116 Clusters[DstIndex - 1].High = CaseVal; 2117 Clusters[DstIndex - 1].Weight += CC.Weight; 2118 assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!"); 2119 } else { 2120 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2121 sizeof(Clusters[SrcIndex])); 2122 } 2123 } 2124 Clusters.resize(DstIndex); 2125 } 2126 2127 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2128 MachineBasicBlock *Last) { 2129 // Update JTCases. 2130 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2131 if (JTCases[i].first.HeaderBB == First) 2132 JTCases[i].first.HeaderBB = Last; 2133 2134 // Update BitTestCases. 2135 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2136 if (BitTestCases[i].Parent == First) 2137 BitTestCases[i].Parent = Last; 2138 } 2139 2140 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2141 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2142 2143 // Update machine-CFG edges with unique successors. 2144 SmallSet<BasicBlock*, 32> Done; 2145 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2146 BasicBlock *BB = I.getSuccessor(i); 2147 bool Inserted = Done.insert(BB).second; 2148 if (!Inserted) 2149 continue; 2150 2151 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2152 addSuccessorWithWeight(IndirectBrMBB, Succ); 2153 } 2154 2155 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2156 MVT::Other, getControlRoot(), 2157 getValue(I.getAddress()))); 2158 } 2159 2160 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2161 if (DAG.getTarget().Options.TrapUnreachable) 2162 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2163 } 2164 2165 void SelectionDAGBuilder::visitFSub(const User &I) { 2166 // -0.0 - X --> fneg 2167 Type *Ty = I.getType(); 2168 if (isa<Constant>(I.getOperand(0)) && 2169 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2170 SDValue Op2 = getValue(I.getOperand(1)); 2171 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2172 Op2.getValueType(), Op2)); 2173 return; 2174 } 2175 2176 visitBinary(I, ISD::FSUB); 2177 } 2178 2179 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2180 SDValue Op1 = getValue(I.getOperand(0)); 2181 SDValue Op2 = getValue(I.getOperand(1)); 2182 2183 bool nuw = false; 2184 bool nsw = false; 2185 bool exact = false; 2186 FastMathFlags FMF; 2187 2188 if (const OverflowingBinaryOperator *OFBinOp = 2189 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2190 nuw = OFBinOp->hasNoUnsignedWrap(); 2191 nsw = OFBinOp->hasNoSignedWrap(); 2192 } 2193 if (const PossiblyExactOperator *ExactOp = 2194 dyn_cast<const PossiblyExactOperator>(&I)) 2195 exact = ExactOp->isExact(); 2196 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I)) 2197 FMF = FPOp->getFastMathFlags(); 2198 2199 SDNodeFlags Flags; 2200 Flags.setExact(exact); 2201 Flags.setNoSignedWrap(nsw); 2202 Flags.setNoUnsignedWrap(nuw); 2203 if (EnableFMFInDAG) { 2204 Flags.setAllowReciprocal(FMF.allowReciprocal()); 2205 Flags.setNoInfs(FMF.noInfs()); 2206 Flags.setNoNaNs(FMF.noNaNs()); 2207 Flags.setNoSignedZeros(FMF.noSignedZeros()); 2208 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra()); 2209 } 2210 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(), 2211 Op1, Op2, &Flags); 2212 setValue(&I, BinNodeValue); 2213 } 2214 2215 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2216 SDValue Op1 = getValue(I.getOperand(0)); 2217 SDValue Op2 = getValue(I.getOperand(1)); 2218 2219 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2220 Op2.getValueType(), DAG.getDataLayout()); 2221 2222 // Coerce the shift amount to the right type if we can. 2223 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2224 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2225 unsigned Op2Size = Op2.getValueType().getSizeInBits(); 2226 SDLoc DL = getCurSDLoc(); 2227 2228 // If the operand is smaller than the shift count type, promote it. 2229 if (ShiftSize > Op2Size) 2230 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2231 2232 // If the operand is larger than the shift count type but the shift 2233 // count type has enough bits to represent any shift value, truncate 2234 // it now. This is a common case and it exposes the truncate to 2235 // optimization early. 2236 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2237 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2238 // Otherwise we'll need to temporarily settle for some other convenient 2239 // type. Type legalization will make adjustments once the shiftee is split. 2240 else 2241 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2242 } 2243 2244 bool nuw = false; 2245 bool nsw = false; 2246 bool exact = false; 2247 2248 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2249 2250 if (const OverflowingBinaryOperator *OFBinOp = 2251 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2252 nuw = OFBinOp->hasNoUnsignedWrap(); 2253 nsw = OFBinOp->hasNoSignedWrap(); 2254 } 2255 if (const PossiblyExactOperator *ExactOp = 2256 dyn_cast<const PossiblyExactOperator>(&I)) 2257 exact = ExactOp->isExact(); 2258 } 2259 SDNodeFlags Flags; 2260 Flags.setExact(exact); 2261 Flags.setNoSignedWrap(nsw); 2262 Flags.setNoUnsignedWrap(nuw); 2263 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2264 &Flags); 2265 setValue(&I, Res); 2266 } 2267 2268 void SelectionDAGBuilder::visitSDiv(const User &I) { 2269 SDValue Op1 = getValue(I.getOperand(0)); 2270 SDValue Op2 = getValue(I.getOperand(1)); 2271 2272 SDNodeFlags Flags; 2273 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2274 cast<PossiblyExactOperator>(&I)->isExact()); 2275 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2276 Op2, &Flags)); 2277 } 2278 2279 void SelectionDAGBuilder::visitICmp(const User &I) { 2280 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2281 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2282 predicate = IC->getPredicate(); 2283 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2284 predicate = ICmpInst::Predicate(IC->getPredicate()); 2285 SDValue Op1 = getValue(I.getOperand(0)); 2286 SDValue Op2 = getValue(I.getOperand(1)); 2287 ISD::CondCode Opcode = getICmpCondCode(predicate); 2288 2289 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2290 I.getType()); 2291 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2292 } 2293 2294 void SelectionDAGBuilder::visitFCmp(const User &I) { 2295 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2296 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2297 predicate = FC->getPredicate(); 2298 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2299 predicate = FCmpInst::Predicate(FC->getPredicate()); 2300 SDValue Op1 = getValue(I.getOperand(0)); 2301 SDValue Op2 = getValue(I.getOperand(1)); 2302 ISD::CondCode Condition = getFCmpCondCode(predicate); 2303 if (TM.Options.NoNaNsFPMath) 2304 Condition = getFCmpCodeWithoutNaN(Condition); 2305 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2306 I.getType()); 2307 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2308 } 2309 2310 void SelectionDAGBuilder::visitSelect(const User &I) { 2311 SmallVector<EVT, 4> ValueVTs; 2312 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2313 ValueVTs); 2314 unsigned NumValues = ValueVTs.size(); 2315 if (NumValues == 0) return; 2316 2317 SmallVector<SDValue, 4> Values(NumValues); 2318 SDValue Cond = getValue(I.getOperand(0)); 2319 SDValue LHSVal = getValue(I.getOperand(1)); 2320 SDValue RHSVal = getValue(I.getOperand(2)); 2321 auto BaseOps = {Cond}; 2322 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2323 ISD::VSELECT : ISD::SELECT; 2324 2325 // Min/max matching is only viable if all output VTs are the same. 2326 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2327 EVT VT = ValueVTs[0]; 2328 LLVMContext &Ctx = *DAG.getContext(); 2329 auto &TLI = DAG.getTargetLoweringInfo(); 2330 while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector) 2331 VT = TLI.getTypeToTransformTo(Ctx, VT); 2332 2333 Value *LHS, *RHS; 2334 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2335 ISD::NodeType Opc = ISD::DELETED_NODE; 2336 switch (SPR.Flavor) { 2337 case SPF_UMAX: Opc = ISD::UMAX; break; 2338 case SPF_UMIN: Opc = ISD::UMIN; break; 2339 case SPF_SMAX: Opc = ISD::SMAX; break; 2340 case SPF_SMIN: Opc = ISD::SMIN; break; 2341 case SPF_FMINNUM: 2342 switch (SPR.NaNBehavior) { 2343 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2344 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2345 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2346 case SPNB_RETURNS_ANY: 2347 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ? ISD::FMINNUM 2348 : ISD::FMINNAN; 2349 break; 2350 } 2351 break; 2352 case SPF_FMAXNUM: 2353 switch (SPR.NaNBehavior) { 2354 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2355 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2356 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2357 case SPNB_RETURNS_ANY: 2358 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ? ISD::FMAXNUM 2359 : ISD::FMAXNAN; 2360 break; 2361 } 2362 break; 2363 default: break; 2364 } 2365 2366 if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT) && 2367 // If the underlying comparison instruction is used by any other instruction, 2368 // the consumed instructions won't be destroyed, so it is not profitable 2369 // to convert to a min/max. 2370 cast<SelectInst>(&I)->getCondition()->hasOneUse()) { 2371 OpCode = Opc; 2372 LHSVal = getValue(LHS); 2373 RHSVal = getValue(RHS); 2374 BaseOps = {}; 2375 } 2376 } 2377 2378 for (unsigned i = 0; i != NumValues; ++i) { 2379 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2380 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2381 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 2382 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2383 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 2384 Ops); 2385 } 2386 2387 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2388 DAG.getVTList(ValueVTs), Values)); 2389 } 2390 2391 void SelectionDAGBuilder::visitTrunc(const User &I) { 2392 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2393 SDValue N = getValue(I.getOperand(0)); 2394 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2395 I.getType()); 2396 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2397 } 2398 2399 void SelectionDAGBuilder::visitZExt(const User &I) { 2400 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2401 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2402 SDValue N = getValue(I.getOperand(0)); 2403 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2404 I.getType()); 2405 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 2406 } 2407 2408 void SelectionDAGBuilder::visitSExt(const User &I) { 2409 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2410 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2411 SDValue N = getValue(I.getOperand(0)); 2412 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2413 I.getType()); 2414 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 2415 } 2416 2417 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2418 // FPTrunc is never a no-op cast, no need to check 2419 SDValue N = getValue(I.getOperand(0)); 2420 SDLoc dl = getCurSDLoc(); 2421 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2422 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2423 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 2424 DAG.getTargetConstant( 2425 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 2426 } 2427 2428 void SelectionDAGBuilder::visitFPExt(const User &I) { 2429 // FPExt is never a no-op cast, no need to check 2430 SDValue N = getValue(I.getOperand(0)); 2431 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2432 I.getType()); 2433 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 2434 } 2435 2436 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2437 // FPToUI is never a no-op cast, no need to check 2438 SDValue N = getValue(I.getOperand(0)); 2439 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2440 I.getType()); 2441 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 2442 } 2443 2444 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2445 // FPToSI is never a no-op cast, no need to check 2446 SDValue N = getValue(I.getOperand(0)); 2447 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2448 I.getType()); 2449 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 2450 } 2451 2452 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2453 // UIToFP is never a no-op cast, no need to check 2454 SDValue N = getValue(I.getOperand(0)); 2455 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2456 I.getType()); 2457 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 2458 } 2459 2460 void SelectionDAGBuilder::visitSIToFP(const User &I) { 2461 // SIToFP is never a no-op cast, no need to check 2462 SDValue N = getValue(I.getOperand(0)); 2463 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2464 I.getType()); 2465 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 2466 } 2467 2468 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2469 // What to do depends on the size of the integer and the size of the pointer. 2470 // We can either truncate, zero extend, or no-op, accordingly. 2471 SDValue N = getValue(I.getOperand(0)); 2472 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2473 I.getType()); 2474 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2475 } 2476 2477 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2478 // What to do depends on the size of the integer and the size of the pointer. 2479 // We can either truncate, zero extend, or no-op, accordingly. 2480 SDValue N = getValue(I.getOperand(0)); 2481 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2482 I.getType()); 2483 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2484 } 2485 2486 void SelectionDAGBuilder::visitBitCast(const User &I) { 2487 SDValue N = getValue(I.getOperand(0)); 2488 SDLoc dl = getCurSDLoc(); 2489 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2490 I.getType()); 2491 2492 // BitCast assures us that source and destination are the same size so this is 2493 // either a BITCAST or a no-op. 2494 if (DestVT != N.getValueType()) 2495 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 2496 DestVT, N)); // convert types. 2497 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 2498 // might fold any kind of constant expression to an integer constant and that 2499 // is not what we are looking for. Only regcognize a bitcast of a genuine 2500 // constant integer as an opaque constant. 2501 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 2502 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 2503 /*isOpaque*/true)); 2504 else 2505 setValue(&I, N); // noop cast. 2506 } 2507 2508 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 2509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2510 const Value *SV = I.getOperand(0); 2511 SDValue N = getValue(SV); 2512 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2513 2514 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 2515 unsigned DestAS = I.getType()->getPointerAddressSpace(); 2516 2517 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 2518 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 2519 2520 setValue(&I, N); 2521 } 2522 2523 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2525 SDValue InVec = getValue(I.getOperand(0)); 2526 SDValue InVal = getValue(I.getOperand(1)); 2527 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 2528 TLI.getVectorIdxTy(DAG.getDataLayout())); 2529 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 2530 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2531 InVec, InVal, InIdx)); 2532 } 2533 2534 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2536 SDValue InVec = getValue(I.getOperand(0)); 2537 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 2538 TLI.getVectorIdxTy(DAG.getDataLayout())); 2539 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 2540 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2541 InVec, InIdx)); 2542 } 2543 2544 // Utility for visitShuffleVector - Return true if every element in Mask, 2545 // beginning from position Pos and ending in Pos+Size, falls within the 2546 // specified sequential range [L, L+Pos). or is undef. 2547 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask, 2548 unsigned Pos, unsigned Size, int Low) { 2549 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 2550 if (Mask[i] >= 0 && Mask[i] != Low) 2551 return false; 2552 return true; 2553 } 2554 2555 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2556 SDValue Src1 = getValue(I.getOperand(0)); 2557 SDValue Src2 = getValue(I.getOperand(1)); 2558 2559 SmallVector<int, 8> Mask; 2560 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 2561 unsigned MaskNumElts = Mask.size(); 2562 2563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2564 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2565 EVT SrcVT = Src1.getValueType(); 2566 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2567 2568 if (SrcNumElts == MaskNumElts) { 2569 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2570 &Mask[0])); 2571 return; 2572 } 2573 2574 // Normalize the shuffle vector since mask and vector length don't match. 2575 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2576 // Mask is longer than the source vectors and is a multiple of the source 2577 // vectors. We can use concatenate vector to make the mask and vectors 2578 // lengths match. 2579 if (SrcNumElts*2 == MaskNumElts) { 2580 // First check for Src1 in low and Src2 in high 2581 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) && 2582 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) { 2583 // The shuffle is concatenating two vectors together. 2584 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 2585 VT, Src1, Src2)); 2586 return; 2587 } 2588 // Then check for Src2 in low and Src1 in high 2589 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) && 2590 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) { 2591 // The shuffle is concatenating two vectors together. 2592 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 2593 VT, Src2, Src1)); 2594 return; 2595 } 2596 } 2597 2598 // Pad both vectors with undefs to make them the same length as the mask. 2599 unsigned NumConcat = MaskNumElts / SrcNumElts; 2600 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2601 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2602 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2603 2604 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2605 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2606 MOps1[0] = Src1; 2607 MOps2[0] = Src2; 2608 2609 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2610 getCurSDLoc(), VT, MOps1); 2611 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2612 getCurSDLoc(), VT, MOps2); 2613 2614 // Readjust mask for new input vector length. 2615 SmallVector<int, 8> MappedOps; 2616 for (unsigned i = 0; i != MaskNumElts; ++i) { 2617 int Idx = Mask[i]; 2618 if (Idx >= (int)SrcNumElts) 2619 Idx -= SrcNumElts - MaskNumElts; 2620 MappedOps.push_back(Idx); 2621 } 2622 2623 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2624 &MappedOps[0])); 2625 return; 2626 } 2627 2628 if (SrcNumElts > MaskNumElts) { 2629 // Analyze the access pattern of the vector to see if we can extract 2630 // two subvectors and do the shuffle. The analysis is done by calculating 2631 // the range of elements the mask access on both vectors. 2632 int MinRange[2] = { static_cast<int>(SrcNumElts), 2633 static_cast<int>(SrcNumElts)}; 2634 int MaxRange[2] = {-1, -1}; 2635 2636 for (unsigned i = 0; i != MaskNumElts; ++i) { 2637 int Idx = Mask[i]; 2638 unsigned Input = 0; 2639 if (Idx < 0) 2640 continue; 2641 2642 if (Idx >= (int)SrcNumElts) { 2643 Input = 1; 2644 Idx -= SrcNumElts; 2645 } 2646 if (Idx > MaxRange[Input]) 2647 MaxRange[Input] = Idx; 2648 if (Idx < MinRange[Input]) 2649 MinRange[Input] = Idx; 2650 } 2651 2652 // Check if the access is smaller than the vector size and can we find 2653 // a reasonable extract index. 2654 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not 2655 // Extract. 2656 int StartIdx[2]; // StartIdx to extract from 2657 for (unsigned Input = 0; Input < 2; ++Input) { 2658 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) { 2659 RangeUse[Input] = 0; // Unused 2660 StartIdx[Input] = 0; 2661 continue; 2662 } 2663 2664 // Find a good start index that is a multiple of the mask length. Then 2665 // see if the rest of the elements are in range. 2666 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2667 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2668 StartIdx[Input] + MaskNumElts <= SrcNumElts) 2669 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2670 } 2671 2672 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2673 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 2674 return; 2675 } 2676 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) { 2677 // Extract appropriate subvector and generate a vector shuffle 2678 for (unsigned Input = 0; Input < 2; ++Input) { 2679 SDValue &Src = Input == 0 ? Src1 : Src2; 2680 if (RangeUse[Input] == 0) 2681 Src = DAG.getUNDEF(VT); 2682 else { 2683 SDLoc dl = getCurSDLoc(); 2684 Src = DAG.getNode( 2685 ISD::EXTRACT_SUBVECTOR, dl, VT, Src, 2686 DAG.getConstant(StartIdx[Input], dl, 2687 TLI.getVectorIdxTy(DAG.getDataLayout()))); 2688 } 2689 } 2690 2691 // Calculate new mask. 2692 SmallVector<int, 8> MappedOps; 2693 for (unsigned i = 0; i != MaskNumElts; ++i) { 2694 int Idx = Mask[i]; 2695 if (Idx >= 0) { 2696 if (Idx < (int)SrcNumElts) 2697 Idx -= StartIdx[0]; 2698 else 2699 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 2700 } 2701 MappedOps.push_back(Idx); 2702 } 2703 2704 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2705 &MappedOps[0])); 2706 return; 2707 } 2708 } 2709 2710 // We can't use either concat vectors or extract subvectors so fall back to 2711 // replacing the shuffle with extract and build vector. 2712 // to insert and build vector. 2713 EVT EltVT = VT.getVectorElementType(); 2714 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 2715 SDLoc dl = getCurSDLoc(); 2716 SmallVector<SDValue,8> Ops; 2717 for (unsigned i = 0; i != MaskNumElts; ++i) { 2718 int Idx = Mask[i]; 2719 SDValue Res; 2720 2721 if (Idx < 0) { 2722 Res = DAG.getUNDEF(EltVT); 2723 } else { 2724 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 2725 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 2726 2727 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 2728 EltVT, Src, DAG.getConstant(Idx, dl, IdxVT)); 2729 } 2730 2731 Ops.push_back(Res); 2732 } 2733 2734 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops)); 2735 } 2736 2737 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 2738 const Value *Op0 = I.getOperand(0); 2739 const Value *Op1 = I.getOperand(1); 2740 Type *AggTy = I.getType(); 2741 Type *ValTy = Op1->getType(); 2742 bool IntoUndef = isa<UndefValue>(Op0); 2743 bool FromUndef = isa<UndefValue>(Op1); 2744 2745 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2746 2747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2748 SmallVector<EVT, 4> AggValueVTs; 2749 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 2750 SmallVector<EVT, 4> ValValueVTs; 2751 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 2752 2753 unsigned NumAggValues = AggValueVTs.size(); 2754 unsigned NumValValues = ValValueVTs.size(); 2755 SmallVector<SDValue, 4> Values(NumAggValues); 2756 2757 // Ignore an insertvalue that produces an empty object 2758 if (!NumAggValues) { 2759 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 2760 return; 2761 } 2762 2763 SDValue Agg = getValue(Op0); 2764 unsigned i = 0; 2765 // Copy the beginning value(s) from the original aggregate. 2766 for (; i != LinearIndex; ++i) 2767 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2768 SDValue(Agg.getNode(), Agg.getResNo() + i); 2769 // Copy values from the inserted value(s). 2770 if (NumValValues) { 2771 SDValue Val = getValue(Op1); 2772 for (; i != LinearIndex + NumValValues; ++i) 2773 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2774 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2775 } 2776 // Copy remaining value(s) from the original aggregate. 2777 for (; i != NumAggValues; ++i) 2778 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2779 SDValue(Agg.getNode(), Agg.getResNo() + i); 2780 2781 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2782 DAG.getVTList(AggValueVTs), Values)); 2783 } 2784 2785 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 2786 const Value *Op0 = I.getOperand(0); 2787 Type *AggTy = Op0->getType(); 2788 Type *ValTy = I.getType(); 2789 bool OutOfUndef = isa<UndefValue>(Op0); 2790 2791 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2792 2793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2794 SmallVector<EVT, 4> ValValueVTs; 2795 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 2796 2797 unsigned NumValValues = ValValueVTs.size(); 2798 2799 // Ignore a extractvalue that produces an empty object 2800 if (!NumValValues) { 2801 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 2802 return; 2803 } 2804 2805 SmallVector<SDValue, 4> Values(NumValValues); 2806 2807 SDValue Agg = getValue(Op0); 2808 // Copy out the selected value(s). 2809 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2810 Values[i - LinearIndex] = 2811 OutOfUndef ? 2812 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2813 SDValue(Agg.getNode(), Agg.getResNo() + i); 2814 2815 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2816 DAG.getVTList(ValValueVTs), Values)); 2817 } 2818 2819 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 2820 Value *Op0 = I.getOperand(0); 2821 // Note that the pointer operand may be a vector of pointers. Take the scalar 2822 // element which holds a pointer. 2823 Type *Ty = Op0->getType()->getScalarType(); 2824 unsigned AS = Ty->getPointerAddressSpace(); 2825 SDValue N = getValue(Op0); 2826 SDLoc dl = getCurSDLoc(); 2827 2828 // Normalize Vector GEP - all scalar operands should be converted to the 2829 // splat vector. 2830 unsigned VectorWidth = I.getType()->isVectorTy() ? 2831 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 2832 2833 if (VectorWidth && !N.getValueType().isVector()) { 2834 MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth); 2835 SmallVector<SDValue, 16> Ops(VectorWidth, N); 2836 N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 2837 } 2838 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 2839 OI != E; ++OI) { 2840 const Value *Idx = *OI; 2841 if (StructType *StTy = dyn_cast<StructType>(Ty)) { 2842 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 2843 if (Field) { 2844 // N = N + Offset 2845 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 2846 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 2847 DAG.getConstant(Offset, dl, N.getValueType())); 2848 } 2849 2850 Ty = StTy->getElementType(Field); 2851 } else { 2852 Ty = cast<SequentialType>(Ty)->getElementType(); 2853 MVT PtrTy = 2854 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS); 2855 unsigned PtrSize = PtrTy.getSizeInBits(); 2856 APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty)); 2857 2858 // If this is a scalar constant or a splat vector of constants, 2859 // handle it quickly. 2860 const auto *CI = dyn_cast<ConstantInt>(Idx); 2861 if (!CI && isa<ConstantDataVector>(Idx) && 2862 cast<ConstantDataVector>(Idx)->getSplatValue()) 2863 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 2864 2865 if (CI) { 2866 if (CI->isZero()) 2867 continue; 2868 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize); 2869 SDValue OffsVal = VectorWidth ? 2870 DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) : 2871 DAG.getConstant(Offs, dl, PtrTy); 2872 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal); 2873 continue; 2874 } 2875 2876 // N = N + Idx * ElementSize; 2877 SDValue IdxN = getValue(Idx); 2878 2879 if (!IdxN.getValueType().isVector() && VectorWidth) { 2880 MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth); 2881 SmallVector<SDValue, 16> Ops(VectorWidth, IdxN); 2882 IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 2883 } 2884 // If the index is smaller or larger than intptr_t, truncate or extend 2885 // it. 2886 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 2887 2888 // If this is a multiply by a power of two, turn it into a shl 2889 // immediately. This is a very common case. 2890 if (ElementSize != 1) { 2891 if (ElementSize.isPowerOf2()) { 2892 unsigned Amt = ElementSize.logBase2(); 2893 IdxN = DAG.getNode(ISD::SHL, dl, 2894 N.getValueType(), IdxN, 2895 DAG.getConstant(Amt, dl, IdxN.getValueType())); 2896 } else { 2897 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 2898 IdxN = DAG.getNode(ISD::MUL, dl, 2899 N.getValueType(), IdxN, Scale); 2900 } 2901 } 2902 2903 N = DAG.getNode(ISD::ADD, dl, 2904 N.getValueType(), N, IdxN); 2905 } 2906 } 2907 2908 setValue(&I, N); 2909 } 2910 2911 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 2912 // If this is a fixed sized alloca in the entry block of the function, 2913 // allocate it statically on the stack. 2914 if (FuncInfo.StaticAllocaMap.count(&I)) 2915 return; // getValue will auto-populate this. 2916 2917 SDLoc dl = getCurSDLoc(); 2918 Type *Ty = I.getAllocatedType(); 2919 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2920 auto &DL = DAG.getDataLayout(); 2921 uint64_t TySize = DL.getTypeAllocSize(Ty); 2922 unsigned Align = 2923 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 2924 2925 SDValue AllocSize = getValue(I.getArraySize()); 2926 2927 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout()); 2928 if (AllocSize.getValueType() != IntPtr) 2929 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 2930 2931 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 2932 AllocSize, 2933 DAG.getConstant(TySize, dl, IntPtr)); 2934 2935 // Handle alignment. If the requested alignment is less than or equal to 2936 // the stack alignment, ignore it. If the size is greater than or equal to 2937 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2938 unsigned StackAlign = 2939 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 2940 if (Align <= StackAlign) 2941 Align = 0; 2942 2943 // Round the size of the allocation up to the stack alignment size 2944 // by add SA-1 to the size. 2945 AllocSize = DAG.getNode(ISD::ADD, dl, 2946 AllocSize.getValueType(), AllocSize, 2947 DAG.getIntPtrConstant(StackAlign - 1, dl)); 2948 2949 // Mask out the low bits for alignment purposes. 2950 AllocSize = DAG.getNode(ISD::AND, dl, 2951 AllocSize.getValueType(), AllocSize, 2952 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1), 2953 dl)); 2954 2955 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) }; 2956 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2957 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 2958 setValue(&I, DSA); 2959 DAG.setRoot(DSA.getValue(1)); 2960 2961 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects()); 2962 } 2963 2964 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 2965 if (I.isAtomic()) 2966 return visitAtomicLoad(I); 2967 2968 const Value *SV = I.getOperand(0); 2969 SDValue Ptr = getValue(SV); 2970 2971 Type *Ty = I.getType(); 2972 2973 bool isVolatile = I.isVolatile(); 2974 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 2975 2976 // The IR notion of invariant_load only guarantees that all *non-faulting* 2977 // invariant loads result in the same value. The MI notion of invariant load 2978 // guarantees that the load can be legally moved to any location within its 2979 // containing function. The MI notion of invariant_load is stronger than the 2980 // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load 2981 // with a guarantee that the location being loaded from is dereferenceable 2982 // throughout the function's lifetime. 2983 2984 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr && 2985 isDereferenceablePointer(SV, DAG.getDataLayout()); 2986 unsigned Alignment = I.getAlignment(); 2987 2988 AAMDNodes AAInfo; 2989 I.getAAMetadata(AAInfo); 2990 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 2991 2992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2993 SmallVector<EVT, 4> ValueVTs; 2994 SmallVector<uint64_t, 4> Offsets; 2995 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 2996 unsigned NumValues = ValueVTs.size(); 2997 if (NumValues == 0) 2998 return; 2999 3000 SDValue Root; 3001 bool ConstantMemory = false; 3002 if (isVolatile || NumValues > MaxParallelChains) 3003 // Serialize volatile loads with other side effects. 3004 Root = getRoot(); 3005 else if (AA->pointsToConstantMemory(MemoryLocation( 3006 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3007 // Do not serialize (non-volatile) loads of constant memory with anything. 3008 Root = DAG.getEntryNode(); 3009 ConstantMemory = true; 3010 } else { 3011 // Do not serialize non-volatile loads against each other. 3012 Root = DAG.getRoot(); 3013 } 3014 3015 SDLoc dl = getCurSDLoc(); 3016 3017 if (isVolatile) 3018 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3019 3020 SmallVector<SDValue, 4> Values(NumValues); 3021 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3022 EVT PtrVT = Ptr.getValueType(); 3023 unsigned ChainI = 0; 3024 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3025 // Serializing loads here may result in excessive register pressure, and 3026 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3027 // could recover a bit by hoisting nodes upward in the chain by recognizing 3028 // they are side-effect free or do not alias. The optimizer should really 3029 // avoid this case by converting large object/array copies to llvm.memcpy 3030 // (MaxParallelChains should always remain as failsafe). 3031 if (ChainI == MaxParallelChains) { 3032 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3033 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3034 makeArrayRef(Chains.data(), ChainI)); 3035 Root = Chain; 3036 ChainI = 0; 3037 } 3038 SDValue A = DAG.getNode(ISD::ADD, dl, 3039 PtrVT, Ptr, 3040 DAG.getConstant(Offsets[i], dl, PtrVT)); 3041 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, 3042 A, MachinePointerInfo(SV, Offsets[i]), isVolatile, 3043 isNonTemporal, isInvariant, Alignment, AAInfo, 3044 Ranges); 3045 3046 Values[i] = L; 3047 Chains[ChainI] = L.getValue(1); 3048 } 3049 3050 if (!ConstantMemory) { 3051 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3052 makeArrayRef(Chains.data(), ChainI)); 3053 if (isVolatile) 3054 DAG.setRoot(Chain); 3055 else 3056 PendingLoads.push_back(Chain); 3057 } 3058 3059 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3060 DAG.getVTList(ValueVTs), Values)); 3061 } 3062 3063 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3064 if (I.isAtomic()) 3065 return visitAtomicStore(I); 3066 3067 const Value *SrcV = I.getOperand(0); 3068 const Value *PtrV = I.getOperand(1); 3069 3070 SmallVector<EVT, 4> ValueVTs; 3071 SmallVector<uint64_t, 4> Offsets; 3072 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3073 SrcV->getType(), ValueVTs, &Offsets); 3074 unsigned NumValues = ValueVTs.size(); 3075 if (NumValues == 0) 3076 return; 3077 3078 // Get the lowered operands. Note that we do this after 3079 // checking if NumResults is zero, because with zero results 3080 // the operands won't have values in the map. 3081 SDValue Src = getValue(SrcV); 3082 SDValue Ptr = getValue(PtrV); 3083 3084 SDValue Root = getRoot(); 3085 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3086 EVT PtrVT = Ptr.getValueType(); 3087 bool isVolatile = I.isVolatile(); 3088 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3089 unsigned Alignment = I.getAlignment(); 3090 SDLoc dl = getCurSDLoc(); 3091 3092 AAMDNodes AAInfo; 3093 I.getAAMetadata(AAInfo); 3094 3095 unsigned ChainI = 0; 3096 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3097 // See visitLoad comments. 3098 if (ChainI == MaxParallelChains) { 3099 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3100 makeArrayRef(Chains.data(), ChainI)); 3101 Root = Chain; 3102 ChainI = 0; 3103 } 3104 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3105 DAG.getConstant(Offsets[i], dl, PtrVT)); 3106 SDValue St = DAG.getStore(Root, dl, 3107 SDValue(Src.getNode(), Src.getResNo() + i), 3108 Add, MachinePointerInfo(PtrV, Offsets[i]), 3109 isVolatile, isNonTemporal, Alignment, AAInfo); 3110 Chains[ChainI] = St; 3111 } 3112 3113 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3114 makeArrayRef(Chains.data(), ChainI)); 3115 DAG.setRoot(StoreNode); 3116 } 3117 3118 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) { 3119 SDLoc sdl = getCurSDLoc(); 3120 3121 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3122 Value *PtrOperand = I.getArgOperand(1); 3123 SDValue Ptr = getValue(PtrOperand); 3124 SDValue Src0 = getValue(I.getArgOperand(0)); 3125 SDValue Mask = getValue(I.getArgOperand(3)); 3126 EVT VT = Src0.getValueType(); 3127 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3128 if (!Alignment) 3129 Alignment = DAG.getEVTAlignment(VT); 3130 3131 AAMDNodes AAInfo; 3132 I.getAAMetadata(AAInfo); 3133 3134 MachineMemOperand *MMO = 3135 DAG.getMachineFunction(). 3136 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3137 MachineMemOperand::MOStore, VT.getStoreSize(), 3138 Alignment, AAInfo); 3139 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3140 MMO, false); 3141 DAG.setRoot(StoreNode); 3142 setValue(&I, StoreNode); 3143 } 3144 3145 // Gather/scatter receive a vector of pointers. 3146 // This vector of pointers may be represented as a base pointer + vector of 3147 // indices, it depends on GEP and instruction preceding GEP 3148 // that calculates indices 3149 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index, 3150 SelectionDAGBuilder* SDB) { 3151 3152 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 3153 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 3154 if (!Gep || Gep->getNumOperands() > 2) 3155 return false; 3156 ShuffleVectorInst *ShuffleInst = 3157 dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand()); 3158 if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() || 3159 cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() != 3160 Instruction::InsertElement) 3161 return false; 3162 3163 Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1); 3164 3165 SelectionDAG& DAG = SDB->DAG; 3166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3167 // Check is the Ptr is inside current basic block 3168 // If not, look for the shuffle instruction 3169 if (SDB->findValue(Ptr)) 3170 Base = SDB->getValue(Ptr); 3171 else if (SDB->findValue(ShuffleInst)) { 3172 SDValue ShuffleNode = SDB->getValue(ShuffleInst); 3173 SDLoc sdl = ShuffleNode; 3174 Base = DAG.getNode( 3175 ISD::EXTRACT_VECTOR_ELT, sdl, 3176 ShuffleNode.getValueType().getScalarType(), ShuffleNode, 3177 DAG.getConstant(0, sdl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3178 SDB->setValue(Ptr, Base); 3179 } 3180 else 3181 return false; 3182 3183 Value *IndexVal = Gep->getOperand(1); 3184 if (SDB->findValue(IndexVal)) { 3185 Index = SDB->getValue(IndexVal); 3186 3187 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) { 3188 IndexVal = Sext->getOperand(0); 3189 if (SDB->findValue(IndexVal)) 3190 Index = SDB->getValue(IndexVal); 3191 } 3192 return true; 3193 } 3194 return false; 3195 } 3196 3197 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3198 SDLoc sdl = getCurSDLoc(); 3199 3200 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3201 Value *Ptr = I.getArgOperand(1); 3202 SDValue Src0 = getValue(I.getArgOperand(0)); 3203 SDValue Mask = getValue(I.getArgOperand(3)); 3204 EVT VT = Src0.getValueType(); 3205 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3206 if (!Alignment) 3207 Alignment = DAG.getEVTAlignment(VT); 3208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3209 3210 AAMDNodes AAInfo; 3211 I.getAAMetadata(AAInfo); 3212 3213 SDValue Base; 3214 SDValue Index; 3215 Value *BasePtr = Ptr; 3216 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3217 3218 Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3219 MachineMemOperand *MMO = DAG.getMachineFunction(). 3220 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3221 MachineMemOperand::MOStore, VT.getStoreSize(), 3222 Alignment, AAInfo); 3223 if (!UniformBase) { 3224 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3225 Index = getValue(Ptr); 3226 } 3227 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index }; 3228 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 3229 Ops, MMO); 3230 DAG.setRoot(Scatter); 3231 setValue(&I, Scatter); 3232 } 3233 3234 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) { 3235 SDLoc sdl = getCurSDLoc(); 3236 3237 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 3238 Value *PtrOperand = I.getArgOperand(0); 3239 SDValue Ptr = getValue(PtrOperand); 3240 SDValue Src0 = getValue(I.getArgOperand(3)); 3241 SDValue Mask = getValue(I.getArgOperand(2)); 3242 3243 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3244 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3245 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3246 if (!Alignment) 3247 Alignment = DAG.getEVTAlignment(VT); 3248 3249 AAMDNodes AAInfo; 3250 I.getAAMetadata(AAInfo); 3251 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3252 3253 SDValue InChain = DAG.getRoot(); 3254 if (AA->pointsToConstantMemory(MemoryLocation( 3255 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), 3256 AAInfo))) { 3257 // Do not serialize (non-volatile) loads of constant memory with anything. 3258 InChain = DAG.getEntryNode(); 3259 } 3260 3261 MachineMemOperand *MMO = 3262 DAG.getMachineFunction(). 3263 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3264 MachineMemOperand::MOLoad, VT.getStoreSize(), 3265 Alignment, AAInfo, Ranges); 3266 3267 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 3268 ISD::NON_EXTLOAD); 3269 SDValue OutChain = Load.getValue(1); 3270 DAG.setRoot(OutChain); 3271 setValue(&I, Load); 3272 } 3273 3274 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 3275 SDLoc sdl = getCurSDLoc(); 3276 3277 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 3278 Value *Ptr = I.getArgOperand(0); 3279 SDValue Src0 = getValue(I.getArgOperand(3)); 3280 SDValue Mask = getValue(I.getArgOperand(2)); 3281 3282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3283 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3284 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3285 if (!Alignment) 3286 Alignment = DAG.getEVTAlignment(VT); 3287 3288 AAMDNodes AAInfo; 3289 I.getAAMetadata(AAInfo); 3290 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3291 3292 SDValue Root = DAG.getRoot(); 3293 SDValue Base; 3294 SDValue Index; 3295 Value *BasePtr = Ptr; 3296 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3297 bool ConstantMemory = false; 3298 if (UniformBase && 3299 AA->pointsToConstantMemory(MemoryLocation( 3300 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 3301 AAInfo))) { 3302 // Do not serialize (non-volatile) loads of constant memory with anything. 3303 Root = DAG.getEntryNode(); 3304 ConstantMemory = true; 3305 } 3306 3307 MachineMemOperand *MMO = 3308 DAG.getMachineFunction(). 3309 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 3310 MachineMemOperand::MOLoad, VT.getStoreSize(), 3311 Alignment, AAInfo, Ranges); 3312 3313 if (!UniformBase) { 3314 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3315 Index = getValue(Ptr); 3316 } 3317 SDValue Ops[] = { Root, Src0, Mask, Base, Index }; 3318 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 3319 Ops, MMO); 3320 3321 SDValue OutChain = Gather.getValue(1); 3322 if (!ConstantMemory) 3323 PendingLoads.push_back(OutChain); 3324 setValue(&I, Gather); 3325 } 3326 3327 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3328 SDLoc dl = getCurSDLoc(); 3329 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 3330 AtomicOrdering FailureOrder = I.getFailureOrdering(); 3331 SynchronizationScope Scope = I.getSynchScope(); 3332 3333 SDValue InChain = getRoot(); 3334 3335 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 3336 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 3337 SDValue L = DAG.getAtomicCmpSwap( 3338 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 3339 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 3340 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 3341 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope); 3342 3343 SDValue OutChain = L.getValue(2); 3344 3345 setValue(&I, L); 3346 DAG.setRoot(OutChain); 3347 } 3348 3349 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3350 SDLoc dl = getCurSDLoc(); 3351 ISD::NodeType NT; 3352 switch (I.getOperation()) { 3353 default: llvm_unreachable("Unknown atomicrmw operation"); 3354 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3355 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3356 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3357 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3358 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3359 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3360 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3361 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3362 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3363 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3364 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3365 } 3366 AtomicOrdering Order = I.getOrdering(); 3367 SynchronizationScope Scope = I.getSynchScope(); 3368 3369 SDValue InChain = getRoot(); 3370 3371 SDValue L = 3372 DAG.getAtomic(NT, dl, 3373 getValue(I.getValOperand()).getSimpleValueType(), 3374 InChain, 3375 getValue(I.getPointerOperand()), 3376 getValue(I.getValOperand()), 3377 I.getPointerOperand(), 3378 /* Alignment=*/ 0, Order, Scope); 3379 3380 SDValue OutChain = L.getValue(1); 3381 3382 setValue(&I, L); 3383 DAG.setRoot(OutChain); 3384 } 3385 3386 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3387 SDLoc dl = getCurSDLoc(); 3388 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3389 SDValue Ops[3]; 3390 Ops[0] = getRoot(); 3391 Ops[1] = DAG.getConstant(I.getOrdering(), dl, 3392 TLI.getPointerTy(DAG.getDataLayout())); 3393 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, 3394 TLI.getPointerTy(DAG.getDataLayout())); 3395 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 3396 } 3397 3398 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 3399 SDLoc dl = getCurSDLoc(); 3400 AtomicOrdering Order = I.getOrdering(); 3401 SynchronizationScope Scope = I.getSynchScope(); 3402 3403 SDValue InChain = getRoot(); 3404 3405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3406 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3407 3408 if (I.getAlignment() < VT.getSizeInBits() / 8) 3409 report_fatal_error("Cannot generate unaligned atomic load"); 3410 3411 MachineMemOperand *MMO = 3412 DAG.getMachineFunction(). 3413 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 3414 MachineMemOperand::MOVolatile | 3415 MachineMemOperand::MOLoad, 3416 VT.getStoreSize(), 3417 I.getAlignment() ? I.getAlignment() : 3418 DAG.getEVTAlignment(VT)); 3419 3420 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 3421 SDValue L = 3422 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 3423 getValue(I.getPointerOperand()), MMO, 3424 Order, Scope); 3425 3426 SDValue OutChain = L.getValue(1); 3427 3428 setValue(&I, L); 3429 DAG.setRoot(OutChain); 3430 } 3431 3432 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 3433 SDLoc dl = getCurSDLoc(); 3434 3435 AtomicOrdering Order = I.getOrdering(); 3436 SynchronizationScope Scope = I.getSynchScope(); 3437 3438 SDValue InChain = getRoot(); 3439 3440 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3441 EVT VT = 3442 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 3443 3444 if (I.getAlignment() < VT.getSizeInBits() / 8) 3445 report_fatal_error("Cannot generate unaligned atomic store"); 3446 3447 SDValue OutChain = 3448 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 3449 InChain, 3450 getValue(I.getPointerOperand()), 3451 getValue(I.getValueOperand()), 3452 I.getPointerOperand(), I.getAlignment(), 3453 Order, Scope); 3454 3455 DAG.setRoot(OutChain); 3456 } 3457 3458 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 3459 /// node. 3460 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 3461 unsigned Intrinsic) { 3462 bool HasChain = !I.doesNotAccessMemory(); 3463 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 3464 3465 // Build the operand list. 3466 SmallVector<SDValue, 8> Ops; 3467 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3468 if (OnlyLoad) { 3469 // We don't need to serialize loads against other loads. 3470 Ops.push_back(DAG.getRoot()); 3471 } else { 3472 Ops.push_back(getRoot()); 3473 } 3474 } 3475 3476 // Info is set by getTgtMemInstrinsic 3477 TargetLowering::IntrinsicInfo Info; 3478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3479 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 3480 3481 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3482 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 3483 Info.opc == ISD::INTRINSIC_W_CHAIN) 3484 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 3485 TLI.getPointerTy(DAG.getDataLayout()))); 3486 3487 // Add all operands of the call to the operand list. 3488 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 3489 SDValue Op = getValue(I.getArgOperand(i)); 3490 Ops.push_back(Op); 3491 } 3492 3493 SmallVector<EVT, 4> ValueVTs; 3494 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 3495 3496 if (HasChain) 3497 ValueVTs.push_back(MVT::Other); 3498 3499 SDVTList VTs = DAG.getVTList(ValueVTs); 3500 3501 // Create the node. 3502 SDValue Result; 3503 if (IsTgtIntrinsic) { 3504 // This is target intrinsic that touches memory 3505 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 3506 VTs, Ops, Info.memVT, 3507 MachinePointerInfo(Info.ptrVal, Info.offset), 3508 Info.align, Info.vol, 3509 Info.readMem, Info.writeMem, Info.size); 3510 } else if (!HasChain) { 3511 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 3512 } else if (!I.getType()->isVoidTy()) { 3513 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 3514 } else { 3515 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 3516 } 3517 3518 if (HasChain) { 3519 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3520 if (OnlyLoad) 3521 PendingLoads.push_back(Chain); 3522 else 3523 DAG.setRoot(Chain); 3524 } 3525 3526 if (!I.getType()->isVoidTy()) { 3527 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3528 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 3529 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 3530 } 3531 3532 setValue(&I, Result); 3533 } 3534 } 3535 3536 /// GetSignificand - Get the significand and build it into a floating-point 3537 /// number with exponent of 1: 3538 /// 3539 /// Op = (Op & 0x007fffff) | 0x3f800000; 3540 /// 3541 /// where Op is the hexadecimal representation of floating point value. 3542 static SDValue 3543 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) { 3544 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3545 DAG.getConstant(0x007fffff, dl, MVT::i32)); 3546 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3547 DAG.getConstant(0x3f800000, dl, MVT::i32)); 3548 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 3549 } 3550 3551 /// GetExponent - Get the exponent: 3552 /// 3553 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3554 /// 3555 /// where Op is the hexadecimal representation of floating point value. 3556 static SDValue 3557 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3558 SDLoc dl) { 3559 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3560 DAG.getConstant(0x7f800000, dl, MVT::i32)); 3561 SDValue t1 = DAG.getNode( 3562 ISD::SRL, dl, MVT::i32, t0, 3563 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 3564 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3565 DAG.getConstant(127, dl, MVT::i32)); 3566 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3567 } 3568 3569 /// getF32Constant - Get 32-bit floating point constant. 3570 static SDValue 3571 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) { 3572 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl, 3573 MVT::f32); 3574 } 3575 3576 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl, 3577 SelectionDAG &DAG) { 3578 // IntegerPartOfX = ((int32_t)(t0); 3579 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3580 3581 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 3582 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3583 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3584 3585 // IntegerPartOfX <<= 23; 3586 IntegerPartOfX = DAG.getNode( 3587 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3588 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 3589 DAG.getDataLayout()))); 3590 3591 SDValue TwoToFractionalPartOfX; 3592 if (LimitFloatPrecision <= 6) { 3593 // For floating-point precision of 6: 3594 // 3595 // TwoToFractionalPartOfX = 3596 // 0.997535578f + 3597 // (0.735607626f + 0.252464424f * x) * x; 3598 // 3599 // error 0.0144103317, which is 6 bits 3600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3601 getF32Constant(DAG, 0x3e814304, dl)); 3602 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3603 getF32Constant(DAG, 0x3f3c50c8, dl)); 3604 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3605 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3606 getF32Constant(DAG, 0x3f7f5e7e, dl)); 3607 } else if (LimitFloatPrecision <= 12) { 3608 // For floating-point precision of 12: 3609 // 3610 // TwoToFractionalPartOfX = 3611 // 0.999892986f + 3612 // (0.696457318f + 3613 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3614 // 3615 // error 0.000107046256, which is 13 to 14 bits 3616 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3617 getF32Constant(DAG, 0x3da235e3, dl)); 3618 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3619 getF32Constant(DAG, 0x3e65b8f3, dl)); 3620 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3621 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3622 getF32Constant(DAG, 0x3f324b07, dl)); 3623 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3624 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3625 getF32Constant(DAG, 0x3f7ff8fd, dl)); 3626 } else { // LimitFloatPrecision <= 18 3627 // For floating-point precision of 18: 3628 // 3629 // TwoToFractionalPartOfX = 3630 // 0.999999982f + 3631 // (0.693148872f + 3632 // (0.240227044f + 3633 // (0.554906021e-1f + 3634 // (0.961591928e-2f + 3635 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3636 // error 2.47208000*10^(-7), which is better than 18 bits 3637 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3638 getF32Constant(DAG, 0x3924b03e, dl)); 3639 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3640 getF32Constant(DAG, 0x3ab24b87, dl)); 3641 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3642 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3643 getF32Constant(DAG, 0x3c1d8c17, dl)); 3644 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3645 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3646 getF32Constant(DAG, 0x3d634a1d, dl)); 3647 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3648 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3649 getF32Constant(DAG, 0x3e75fe14, dl)); 3650 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3651 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3652 getF32Constant(DAG, 0x3f317234, dl)); 3653 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3654 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3655 getF32Constant(DAG, 0x3f800000, dl)); 3656 } 3657 3658 // Add the exponent into the result in integer domain. 3659 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 3660 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 3661 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 3662 } 3663 3664 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 3665 /// limited-precision mode. 3666 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3667 const TargetLowering &TLI) { 3668 if (Op.getValueType() == MVT::f32 && 3669 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3670 3671 // Put the exponent in the right bit position for later addition to the 3672 // final result: 3673 // 3674 // #define LOG2OFe 1.4426950f 3675 // t0 = Op * LOG2OFe 3676 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3677 getF32Constant(DAG, 0x3fb8aa3b, dl)); 3678 return getLimitedPrecisionExp2(t0, dl, DAG); 3679 } 3680 3681 // No special expansion. 3682 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 3683 } 3684 3685 /// expandLog - Lower a log intrinsic. Handles the special sequences for 3686 /// limited-precision mode. 3687 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3688 const TargetLowering &TLI) { 3689 if (Op.getValueType() == MVT::f32 && 3690 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3691 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3692 3693 // Scale the exponent by log(2) [0.69314718f]. 3694 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3695 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3696 getF32Constant(DAG, 0x3f317218, dl)); 3697 3698 // Get the significand and build it into a floating-point number with 3699 // exponent of 1. 3700 SDValue X = GetSignificand(DAG, Op1, dl); 3701 3702 SDValue LogOfMantissa; 3703 if (LimitFloatPrecision <= 6) { 3704 // For floating-point precision of 6: 3705 // 3706 // LogofMantissa = 3707 // -1.1609546f + 3708 // (1.4034025f - 0.23903021f * x) * x; 3709 // 3710 // error 0.0034276066, which is better than 8 bits 3711 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3712 getF32Constant(DAG, 0xbe74c456, dl)); 3713 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3714 getF32Constant(DAG, 0x3fb3a2b1, dl)); 3715 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3716 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3717 getF32Constant(DAG, 0x3f949a29, dl)); 3718 } else if (LimitFloatPrecision <= 12) { 3719 // For floating-point precision of 12: 3720 // 3721 // LogOfMantissa = 3722 // -1.7417939f + 3723 // (2.8212026f + 3724 // (-1.4699568f + 3725 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3726 // 3727 // error 0.000061011436, which is 14 bits 3728 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3729 getF32Constant(DAG, 0xbd67b6d6, dl)); 3730 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3731 getF32Constant(DAG, 0x3ee4f4b8, dl)); 3732 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3733 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3734 getF32Constant(DAG, 0x3fbc278b, dl)); 3735 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3736 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3737 getF32Constant(DAG, 0x40348e95, dl)); 3738 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3739 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3740 getF32Constant(DAG, 0x3fdef31a, dl)); 3741 } else { // LimitFloatPrecision <= 18 3742 // For floating-point precision of 18: 3743 // 3744 // LogOfMantissa = 3745 // -2.1072184f + 3746 // (4.2372794f + 3747 // (-3.7029485f + 3748 // (2.2781945f + 3749 // (-0.87823314f + 3750 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3751 // 3752 // error 0.0000023660568, which is better than 18 bits 3753 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3754 getF32Constant(DAG, 0xbc91e5ac, dl)); 3755 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3756 getF32Constant(DAG, 0x3e4350aa, dl)); 3757 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3758 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3759 getF32Constant(DAG, 0x3f60d3e3, dl)); 3760 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3761 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3762 getF32Constant(DAG, 0x4011cdf0, dl)); 3763 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3764 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3765 getF32Constant(DAG, 0x406cfd1c, dl)); 3766 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3767 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3768 getF32Constant(DAG, 0x408797cb, dl)); 3769 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3770 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3771 getF32Constant(DAG, 0x4006dcab, dl)); 3772 } 3773 3774 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 3775 } 3776 3777 // No special expansion. 3778 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 3779 } 3780 3781 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 3782 /// limited-precision mode. 3783 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3784 const TargetLowering &TLI) { 3785 if (Op.getValueType() == MVT::f32 && 3786 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3787 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3788 3789 // Get the exponent. 3790 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3791 3792 // Get the significand and build it into a floating-point number with 3793 // exponent of 1. 3794 SDValue X = GetSignificand(DAG, Op1, dl); 3795 3796 // Different possible minimax approximations of significand in 3797 // floating-point for various degrees of accuracy over [1,2]. 3798 SDValue Log2ofMantissa; 3799 if (LimitFloatPrecision <= 6) { 3800 // For floating-point precision of 6: 3801 // 3802 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3803 // 3804 // error 0.0049451742, which is more than 7 bits 3805 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3806 getF32Constant(DAG, 0xbeb08fe0, dl)); 3807 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3808 getF32Constant(DAG, 0x40019463, dl)); 3809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3810 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3811 getF32Constant(DAG, 0x3fd6633d, dl)); 3812 } else if (LimitFloatPrecision <= 12) { 3813 // For floating-point precision of 12: 3814 // 3815 // Log2ofMantissa = 3816 // -2.51285454f + 3817 // (4.07009056f + 3818 // (-2.12067489f + 3819 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3820 // 3821 // error 0.0000876136000, which is better than 13 bits 3822 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3823 getF32Constant(DAG, 0xbda7262e, dl)); 3824 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3825 getF32Constant(DAG, 0x3f25280b, dl)); 3826 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3827 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3828 getF32Constant(DAG, 0x4007b923, dl)); 3829 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3830 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3831 getF32Constant(DAG, 0x40823e2f, dl)); 3832 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3833 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3834 getF32Constant(DAG, 0x4020d29c, dl)); 3835 } else { // LimitFloatPrecision <= 18 3836 // For floating-point precision of 18: 3837 // 3838 // Log2ofMantissa = 3839 // -3.0400495f + 3840 // (6.1129976f + 3841 // (-5.3420409f + 3842 // (3.2865683f + 3843 // (-1.2669343f + 3844 // (0.27515199f - 3845 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3846 // 3847 // error 0.0000018516, which is better than 18 bits 3848 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3849 getF32Constant(DAG, 0xbcd2769e, dl)); 3850 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3851 getF32Constant(DAG, 0x3e8ce0b9, dl)); 3852 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3853 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3854 getF32Constant(DAG, 0x3fa22ae7, dl)); 3855 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3856 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3857 getF32Constant(DAG, 0x40525723, dl)); 3858 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3859 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3860 getF32Constant(DAG, 0x40aaf200, dl)); 3861 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3862 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3863 getF32Constant(DAG, 0x40c39dad, dl)); 3864 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3865 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3866 getF32Constant(DAG, 0x4042902c, dl)); 3867 } 3868 3869 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 3870 } 3871 3872 // No special expansion. 3873 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 3874 } 3875 3876 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 3877 /// limited-precision mode. 3878 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3879 const TargetLowering &TLI) { 3880 if (Op.getValueType() == MVT::f32 && 3881 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3882 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3883 3884 // Scale the exponent by log10(2) [0.30102999f]. 3885 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3886 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3887 getF32Constant(DAG, 0x3e9a209a, dl)); 3888 3889 // Get the significand and build it into a floating-point number with 3890 // exponent of 1. 3891 SDValue X = GetSignificand(DAG, Op1, dl); 3892 3893 SDValue Log10ofMantissa; 3894 if (LimitFloatPrecision <= 6) { 3895 // For floating-point precision of 6: 3896 // 3897 // Log10ofMantissa = 3898 // -0.50419619f + 3899 // (0.60948995f - 0.10380950f * x) * x; 3900 // 3901 // error 0.0014886165, which is 6 bits 3902 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3903 getF32Constant(DAG, 0xbdd49a13, dl)); 3904 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3905 getF32Constant(DAG, 0x3f1c0789, dl)); 3906 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3907 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3908 getF32Constant(DAG, 0x3f011300, dl)); 3909 } else if (LimitFloatPrecision <= 12) { 3910 // For floating-point precision of 12: 3911 // 3912 // Log10ofMantissa = 3913 // -0.64831180f + 3914 // (0.91751397f + 3915 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3916 // 3917 // error 0.00019228036, which is better than 12 bits 3918 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3919 getF32Constant(DAG, 0x3d431f31, dl)); 3920 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3921 getF32Constant(DAG, 0x3ea21fb2, dl)); 3922 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3923 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3924 getF32Constant(DAG, 0x3f6ae232, dl)); 3925 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3926 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3927 getF32Constant(DAG, 0x3f25f7c3, dl)); 3928 } else { // LimitFloatPrecision <= 18 3929 // For floating-point precision of 18: 3930 // 3931 // Log10ofMantissa = 3932 // -0.84299375f + 3933 // (1.5327582f + 3934 // (-1.0688956f + 3935 // (0.49102474f + 3936 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3937 // 3938 // error 0.0000037995730, which is better than 18 bits 3939 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3940 getF32Constant(DAG, 0x3c5d51ce, dl)); 3941 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3942 getF32Constant(DAG, 0x3e00685a, dl)); 3943 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3944 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3945 getF32Constant(DAG, 0x3efb6798, dl)); 3946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3947 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3948 getF32Constant(DAG, 0x3f88d192, dl)); 3949 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3950 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3951 getF32Constant(DAG, 0x3fc4316c, dl)); 3952 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3953 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3954 getF32Constant(DAG, 0x3f57ce70, dl)); 3955 } 3956 3957 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 3958 } 3959 3960 // No special expansion. 3961 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 3962 } 3963 3964 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3965 /// limited-precision mode. 3966 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3967 const TargetLowering &TLI) { 3968 if (Op.getValueType() == MVT::f32 && 3969 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 3970 return getLimitedPrecisionExp2(Op, dl, DAG); 3971 3972 // No special expansion. 3973 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 3974 } 3975 3976 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3977 /// limited-precision mode with x == 10.0f. 3978 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS, 3979 SelectionDAG &DAG, const TargetLowering &TLI) { 3980 bool IsExp10 = false; 3981 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 3982 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3983 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 3984 APFloat Ten(10.0f); 3985 IsExp10 = LHSC->isExactlyValue(Ten); 3986 } 3987 } 3988 3989 if (IsExp10) { 3990 // Put the exponent in the right bit position for later addition to the 3991 // final result: 3992 // 3993 // #define LOG2OF10 3.3219281f 3994 // t0 = Op * LOG2OF10; 3995 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 3996 getF32Constant(DAG, 0x40549a78, dl)); 3997 return getLimitedPrecisionExp2(t0, dl, DAG); 3998 } 3999 4000 // No special expansion. 4001 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4002 } 4003 4004 4005 /// ExpandPowI - Expand a llvm.powi intrinsic. 4006 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS, 4007 SelectionDAG &DAG) { 4008 // If RHS is a constant, we can expand this out to a multiplication tree, 4009 // otherwise we end up lowering to a call to __powidf2 (for example). When 4010 // optimizing for size, we only want to do this if the expansion would produce 4011 // a small number of multiplies, otherwise we do the full expansion. 4012 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4013 // Get the exponent as a positive value. 4014 unsigned Val = RHSC->getSExtValue(); 4015 if ((int)Val < 0) Val = -Val; 4016 4017 // powi(x, 0) -> 1.0 4018 if (Val == 0) 4019 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4020 4021 const Function *F = DAG.getMachineFunction().getFunction(); 4022 if (!F->optForSize() || 4023 // If optimizing for size, don't insert too many multiplies. 4024 // This inserts up to 5 multiplies. 4025 countPopulation(Val) + Log2_32(Val) < 7) { 4026 // We use the simple binary decomposition method to generate the multiply 4027 // sequence. There are more optimal ways to do this (for example, 4028 // powi(x,15) generates one more multiply than it should), but this has 4029 // the benefit of being both really simple and much better than a libcall. 4030 SDValue Res; // Logically starts equal to 1.0 4031 SDValue CurSquare = LHS; 4032 while (Val) { 4033 if (Val & 1) { 4034 if (Res.getNode()) 4035 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4036 else 4037 Res = CurSquare; // 1.0*CurSquare. 4038 } 4039 4040 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4041 CurSquare, CurSquare); 4042 Val >>= 1; 4043 } 4044 4045 // If the original was negative, invert the result, producing 1/(x*x*x). 4046 if (RHSC->getSExtValue() < 0) 4047 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4048 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4049 return Res; 4050 } 4051 } 4052 4053 // Otherwise, expand to a libcall. 4054 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4055 } 4056 4057 // getTruncatedArgReg - Find underlying register used for an truncated 4058 // argument. 4059 static unsigned getTruncatedArgReg(const SDValue &N) { 4060 if (N.getOpcode() != ISD::TRUNCATE) 4061 return 0; 4062 4063 const SDValue &Ext = N.getOperand(0); 4064 if (Ext.getOpcode() == ISD::AssertZext || 4065 Ext.getOpcode() == ISD::AssertSext) { 4066 const SDValue &CFR = Ext.getOperand(0); 4067 if (CFR.getOpcode() == ISD::CopyFromReg) 4068 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg(); 4069 if (CFR.getOpcode() == ISD::TRUNCATE) 4070 return getTruncatedArgReg(CFR); 4071 } 4072 return 0; 4073 } 4074 4075 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4076 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4077 /// At the end of instruction selection, they will be inserted to the entry BB. 4078 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4079 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4080 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) { 4081 const Argument *Arg = dyn_cast<Argument>(V); 4082 if (!Arg) 4083 return false; 4084 4085 MachineFunction &MF = DAG.getMachineFunction(); 4086 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4087 4088 // Ignore inlined function arguments here. 4089 // 4090 // FIXME: Should we be checking DL->inlinedAt() to determine this? 4091 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction())) 4092 return false; 4093 4094 Optional<MachineOperand> Op; 4095 // Some arguments' frame index is recorded during argument lowering. 4096 if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) 4097 Op = MachineOperand::CreateFI(FI); 4098 4099 if (!Op && N.getNode()) { 4100 unsigned Reg; 4101 if (N.getOpcode() == ISD::CopyFromReg) 4102 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4103 else 4104 Reg = getTruncatedArgReg(N); 4105 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4106 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4107 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4108 if (PR) 4109 Reg = PR; 4110 } 4111 if (Reg) 4112 Op = MachineOperand::CreateReg(Reg, false); 4113 } 4114 4115 if (!Op) { 4116 // Check if ValueMap has reg number. 4117 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4118 if (VMI != FuncInfo.ValueMap.end()) 4119 Op = MachineOperand::CreateReg(VMI->second, false); 4120 } 4121 4122 if (!Op && N.getNode()) 4123 // Check if frame index is available. 4124 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4125 if (FrameIndexSDNode *FINode = 4126 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4127 Op = MachineOperand::CreateFI(FINode->getIndex()); 4128 4129 if (!Op) 4130 return false; 4131 4132 assert(Variable->isValidLocationForIntrinsic(DL) && 4133 "Expected inlined-at fields to agree"); 4134 if (Op->isReg()) 4135 FuncInfo.ArgDbgValues.push_back( 4136 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4137 Op->getReg(), Offset, Variable, Expr)); 4138 else 4139 FuncInfo.ArgDbgValues.push_back( 4140 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4141 .addOperand(*Op) 4142 .addImm(Offset) 4143 .addMetadata(Variable) 4144 .addMetadata(Expr)); 4145 4146 return true; 4147 } 4148 4149 // VisualStudio defines setjmp as _setjmp 4150 #if defined(_MSC_VER) && defined(setjmp) && \ 4151 !defined(setjmp_undefined_for_msvc) 4152 # pragma push_macro("setjmp") 4153 # undef setjmp 4154 # define setjmp_undefined_for_msvc 4155 #endif 4156 4157 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4158 /// we want to emit this as a call to a named external function, return the name 4159 /// otherwise lower it and return null. 4160 const char * 4161 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4163 SDLoc sdl = getCurSDLoc(); 4164 DebugLoc dl = getCurDebugLoc(); 4165 SDValue Res; 4166 4167 switch (Intrinsic) { 4168 default: 4169 // By default, turn this into a target intrinsic node. 4170 visitTargetIntrinsic(I, Intrinsic); 4171 return nullptr; 4172 case Intrinsic::vastart: visitVAStart(I); return nullptr; 4173 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 4174 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 4175 case Intrinsic::returnaddress: 4176 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 4177 TLI.getPointerTy(DAG.getDataLayout()), 4178 getValue(I.getArgOperand(0)))); 4179 return nullptr; 4180 case Intrinsic::frameaddress: 4181 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 4182 TLI.getPointerTy(DAG.getDataLayout()), 4183 getValue(I.getArgOperand(0)))); 4184 return nullptr; 4185 case Intrinsic::read_register: { 4186 Value *Reg = I.getArgOperand(0); 4187 SDValue Chain = getRoot(); 4188 SDValue RegName = 4189 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4190 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4191 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 4192 DAG.getVTList(VT, MVT::Other), Chain, RegName); 4193 setValue(&I, Res); 4194 DAG.setRoot(Res.getValue(1)); 4195 return nullptr; 4196 } 4197 case Intrinsic::write_register: { 4198 Value *Reg = I.getArgOperand(0); 4199 Value *RegValue = I.getArgOperand(1); 4200 SDValue Chain = getRoot(); 4201 SDValue RegName = 4202 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4203 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 4204 RegName, getValue(RegValue))); 4205 return nullptr; 4206 } 4207 case Intrinsic::setjmp: 4208 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 4209 case Intrinsic::longjmp: 4210 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 4211 case Intrinsic::memcpy: { 4212 // FIXME: this definition of "user defined address space" is x86-specific 4213 // Assert for address < 256 since we support only user defined address 4214 // spaces. 4215 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4216 < 256 && 4217 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4218 < 256 && 4219 "Unknown address space"); 4220 SDValue Op1 = getValue(I.getArgOperand(0)); 4221 SDValue Op2 = getValue(I.getArgOperand(1)); 4222 SDValue Op3 = getValue(I.getArgOperand(2)); 4223 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4224 if (!Align) 4225 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 4226 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4227 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4228 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4229 false, isTC, 4230 MachinePointerInfo(I.getArgOperand(0)), 4231 MachinePointerInfo(I.getArgOperand(1))); 4232 updateDAGForMaybeTailCall(MC); 4233 return nullptr; 4234 } 4235 case Intrinsic::memset: { 4236 // FIXME: this definition of "user defined address space" is x86-specific 4237 // Assert for address < 256 since we support only user defined address 4238 // spaces. 4239 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4240 < 256 && 4241 "Unknown address space"); 4242 SDValue Op1 = getValue(I.getArgOperand(0)); 4243 SDValue Op2 = getValue(I.getArgOperand(1)); 4244 SDValue Op3 = getValue(I.getArgOperand(2)); 4245 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4246 if (!Align) 4247 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 4248 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4249 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4250 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4251 isTC, MachinePointerInfo(I.getArgOperand(0))); 4252 updateDAGForMaybeTailCall(MS); 4253 return nullptr; 4254 } 4255 case Intrinsic::memmove: { 4256 // FIXME: this definition of "user defined address space" is x86-specific 4257 // Assert for address < 256 since we support only user defined address 4258 // spaces. 4259 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4260 < 256 && 4261 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4262 < 256 && 4263 "Unknown address space"); 4264 SDValue Op1 = getValue(I.getArgOperand(0)); 4265 SDValue Op2 = getValue(I.getArgOperand(1)); 4266 SDValue Op3 = getValue(I.getArgOperand(2)); 4267 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4268 if (!Align) 4269 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 4270 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4271 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4272 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4273 isTC, MachinePointerInfo(I.getArgOperand(0)), 4274 MachinePointerInfo(I.getArgOperand(1))); 4275 updateDAGForMaybeTailCall(MM); 4276 return nullptr; 4277 } 4278 case Intrinsic::dbg_declare: { 4279 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4280 DILocalVariable *Variable = DI.getVariable(); 4281 DIExpression *Expression = DI.getExpression(); 4282 const Value *Address = DI.getAddress(); 4283 assert(Variable && "Missing variable"); 4284 if (!Address) { 4285 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4286 return nullptr; 4287 } 4288 4289 // Check if address has undef value. 4290 if (isa<UndefValue>(Address) || 4291 (Address->use_empty() && !isa<Argument>(Address))) { 4292 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4293 return nullptr; 4294 } 4295 4296 SDValue &N = NodeMap[Address]; 4297 if (!N.getNode() && isa<Argument>(Address)) 4298 // Check unused arguments map. 4299 N = UnusedArgNodeMap[Address]; 4300 SDDbgValue *SDV; 4301 if (N.getNode()) { 4302 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4303 Address = BCI->getOperand(0); 4304 // Parameters are handled specially. 4305 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 4306 4307 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4308 4309 if (isParameter && !AI) { 4310 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4311 if (FINode) 4312 // Byval parameter. We have a frame index at this point. 4313 SDV = DAG.getFrameIndexDbgValue( 4314 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder); 4315 else { 4316 // Address is an argument, so try to emit its dbg value using 4317 // virtual register info from the FuncInfo.ValueMap. 4318 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4319 N); 4320 return nullptr; 4321 } 4322 } else if (AI) 4323 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4324 true, 0, dl, SDNodeOrder); 4325 else { 4326 // Can't do anything with other non-AI cases yet. 4327 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4328 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t"); 4329 DEBUG(Address->dump()); 4330 return nullptr; 4331 } 4332 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4333 } else { 4334 // If Address is an argument then try to emit its dbg value using 4335 // virtual register info from the FuncInfo.ValueMap. 4336 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4337 N)) { 4338 // If variable is pinned by a alloca in dominating bb then 4339 // use StaticAllocaMap. 4340 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4341 if (AI->getParent() != DI.getParent()) { 4342 DenseMap<const AllocaInst*, int>::iterator SI = 4343 FuncInfo.StaticAllocaMap.find(AI); 4344 if (SI != FuncInfo.StaticAllocaMap.end()) { 4345 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 4346 0, dl, SDNodeOrder); 4347 DAG.AddDbgValue(SDV, nullptr, false); 4348 return nullptr; 4349 } 4350 } 4351 } 4352 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4353 } 4354 } 4355 return nullptr; 4356 } 4357 case Intrinsic::dbg_value: { 4358 const DbgValueInst &DI = cast<DbgValueInst>(I); 4359 assert(DI.getVariable() && "Missing variable"); 4360 4361 DILocalVariable *Variable = DI.getVariable(); 4362 DIExpression *Expression = DI.getExpression(); 4363 uint64_t Offset = DI.getOffset(); 4364 const Value *V = DI.getValue(); 4365 if (!V) 4366 return nullptr; 4367 4368 SDDbgValue *SDV; 4369 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 4370 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl, 4371 SDNodeOrder); 4372 DAG.AddDbgValue(SDV, nullptr, false); 4373 } else { 4374 // Do not use getValue() in here; we don't want to generate code at 4375 // this point if it hasn't been done yet. 4376 SDValue N = NodeMap[V]; 4377 if (!N.getNode() && isa<Argument>(V)) 4378 // Check unused arguments map. 4379 N = UnusedArgNodeMap[V]; 4380 if (N.getNode()) { 4381 // A dbg.value for an alloca is always indirect. 4382 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0; 4383 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset, 4384 IsIndirect, N)) { 4385 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4386 IsIndirect, Offset, dl, SDNodeOrder); 4387 DAG.AddDbgValue(SDV, N.getNode(), false); 4388 } 4389 } else if (!V->use_empty() ) { 4390 // Do not call getValue(V) yet, as we don't want to generate code. 4391 // Remember it for later. 4392 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4393 DanglingDebugInfoMap[V] = DDI; 4394 } else { 4395 // We may expand this to cover more cases. One case where we have no 4396 // data available is an unreferenced parameter. 4397 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4398 } 4399 } 4400 4401 // Build a debug info table entry. 4402 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4403 V = BCI->getOperand(0); 4404 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4405 // Don't handle byval struct arguments or VLAs, for example. 4406 if (!AI) { 4407 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 4408 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 4409 return nullptr; 4410 } 4411 DenseMap<const AllocaInst*, int>::iterator SI = 4412 FuncInfo.StaticAllocaMap.find(AI); 4413 if (SI == FuncInfo.StaticAllocaMap.end()) 4414 return nullptr; // VLAs. 4415 return nullptr; 4416 } 4417 4418 case Intrinsic::eh_typeid_for: { 4419 // Find the type id for the given typeinfo. 4420 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 4421 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4422 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 4423 setValue(&I, Res); 4424 return nullptr; 4425 } 4426 4427 case Intrinsic::eh_return_i32: 4428 case Intrinsic::eh_return_i64: 4429 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4430 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 4431 MVT::Other, 4432 getControlRoot(), 4433 getValue(I.getArgOperand(0)), 4434 getValue(I.getArgOperand(1)))); 4435 return nullptr; 4436 case Intrinsic::eh_unwind_init: 4437 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4438 return nullptr; 4439 case Intrinsic::eh_dwarf_cfa: { 4440 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl, 4441 TLI.getPointerTy(DAG.getDataLayout())); 4442 SDValue Offset = DAG.getNode(ISD::ADD, sdl, 4443 CfaArg.getValueType(), 4444 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl, 4445 CfaArg.getValueType()), 4446 CfaArg); 4447 SDValue FA = DAG.getNode( 4448 ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()), 4449 DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 4450 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(), 4451 FA, Offset)); 4452 return nullptr; 4453 } 4454 case Intrinsic::eh_sjlj_callsite: { 4455 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4456 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 4457 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4458 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4459 4460 MMI.setCurrentCallSite(CI->getZExtValue()); 4461 return nullptr; 4462 } 4463 case Intrinsic::eh_sjlj_functioncontext: { 4464 // Get and store the index of the function context. 4465 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4466 AllocaInst *FnCtx = 4467 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 4468 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 4469 MFI->setFunctionContextIndex(FI); 4470 return nullptr; 4471 } 4472 case Intrinsic::eh_sjlj_setjmp: { 4473 SDValue Ops[2]; 4474 Ops[0] = getRoot(); 4475 Ops[1] = getValue(I.getArgOperand(0)); 4476 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 4477 DAG.getVTList(MVT::i32, MVT::Other), Ops); 4478 setValue(&I, Op.getValue(0)); 4479 DAG.setRoot(Op.getValue(1)); 4480 return nullptr; 4481 } 4482 case Intrinsic::eh_sjlj_longjmp: { 4483 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 4484 getRoot(), getValue(I.getArgOperand(0)))); 4485 return nullptr; 4486 } 4487 case Intrinsic::eh_sjlj_setup_dispatch: { 4488 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 4489 getRoot())); 4490 return nullptr; 4491 } 4492 4493 case Intrinsic::masked_gather: 4494 visitMaskedGather(I); 4495 return nullptr; 4496 case Intrinsic::masked_load: 4497 visitMaskedLoad(I); 4498 return nullptr; 4499 case Intrinsic::masked_scatter: 4500 visitMaskedScatter(I); 4501 return nullptr; 4502 case Intrinsic::masked_store: 4503 visitMaskedStore(I); 4504 return nullptr; 4505 case Intrinsic::x86_mmx_pslli_w: 4506 case Intrinsic::x86_mmx_pslli_d: 4507 case Intrinsic::x86_mmx_pslli_q: 4508 case Intrinsic::x86_mmx_psrli_w: 4509 case Intrinsic::x86_mmx_psrli_d: 4510 case Intrinsic::x86_mmx_psrli_q: 4511 case Intrinsic::x86_mmx_psrai_w: 4512 case Intrinsic::x86_mmx_psrai_d: { 4513 SDValue ShAmt = getValue(I.getArgOperand(1)); 4514 if (isa<ConstantSDNode>(ShAmt)) { 4515 visitTargetIntrinsic(I, Intrinsic); 4516 return nullptr; 4517 } 4518 unsigned NewIntrinsic = 0; 4519 EVT ShAmtVT = MVT::v2i32; 4520 switch (Intrinsic) { 4521 case Intrinsic::x86_mmx_pslli_w: 4522 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 4523 break; 4524 case Intrinsic::x86_mmx_pslli_d: 4525 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 4526 break; 4527 case Intrinsic::x86_mmx_pslli_q: 4528 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 4529 break; 4530 case Intrinsic::x86_mmx_psrli_w: 4531 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 4532 break; 4533 case Intrinsic::x86_mmx_psrli_d: 4534 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 4535 break; 4536 case Intrinsic::x86_mmx_psrli_q: 4537 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 4538 break; 4539 case Intrinsic::x86_mmx_psrai_w: 4540 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 4541 break; 4542 case Intrinsic::x86_mmx_psrai_d: 4543 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 4544 break; 4545 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4546 } 4547 4548 // The vector shift intrinsics with scalars uses 32b shift amounts but 4549 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 4550 // to be zero. 4551 // We must do this early because v2i32 is not a legal type. 4552 SDValue ShOps[2]; 4553 ShOps[0] = ShAmt; 4554 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 4555 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps); 4556 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4557 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 4558 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 4559 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 4560 getValue(I.getArgOperand(0)), ShAmt); 4561 setValue(&I, Res); 4562 return nullptr; 4563 } 4564 case Intrinsic::convertff: 4565 case Intrinsic::convertfsi: 4566 case Intrinsic::convertfui: 4567 case Intrinsic::convertsif: 4568 case Intrinsic::convertuif: 4569 case Intrinsic::convertss: 4570 case Intrinsic::convertsu: 4571 case Intrinsic::convertus: 4572 case Intrinsic::convertuu: { 4573 ISD::CvtCode Code = ISD::CVT_INVALID; 4574 switch (Intrinsic) { 4575 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4576 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4577 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4578 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4579 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4580 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4581 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4582 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4583 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4584 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4585 } 4586 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4587 const Value *Op1 = I.getArgOperand(0); 4588 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1), 4589 DAG.getValueType(DestVT), 4590 DAG.getValueType(getValue(Op1).getValueType()), 4591 getValue(I.getArgOperand(1)), 4592 getValue(I.getArgOperand(2)), 4593 Code); 4594 setValue(&I, Res); 4595 return nullptr; 4596 } 4597 case Intrinsic::powi: 4598 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 4599 getValue(I.getArgOperand(1)), DAG)); 4600 return nullptr; 4601 case Intrinsic::log: 4602 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4603 return nullptr; 4604 case Intrinsic::log2: 4605 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4606 return nullptr; 4607 case Intrinsic::log10: 4608 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4609 return nullptr; 4610 case Intrinsic::exp: 4611 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4612 return nullptr; 4613 case Intrinsic::exp2: 4614 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4615 return nullptr; 4616 case Intrinsic::pow: 4617 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 4618 getValue(I.getArgOperand(1)), DAG, TLI)); 4619 return nullptr; 4620 case Intrinsic::sqrt: 4621 case Intrinsic::fabs: 4622 case Intrinsic::sin: 4623 case Intrinsic::cos: 4624 case Intrinsic::floor: 4625 case Intrinsic::ceil: 4626 case Intrinsic::trunc: 4627 case Intrinsic::rint: 4628 case Intrinsic::nearbyint: 4629 case Intrinsic::round: { 4630 unsigned Opcode; 4631 switch (Intrinsic) { 4632 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4633 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 4634 case Intrinsic::fabs: Opcode = ISD::FABS; break; 4635 case Intrinsic::sin: Opcode = ISD::FSIN; break; 4636 case Intrinsic::cos: Opcode = ISD::FCOS; break; 4637 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 4638 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 4639 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 4640 case Intrinsic::rint: Opcode = ISD::FRINT; break; 4641 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 4642 case Intrinsic::round: Opcode = ISD::FROUND; break; 4643 } 4644 4645 setValue(&I, DAG.getNode(Opcode, sdl, 4646 getValue(I.getArgOperand(0)).getValueType(), 4647 getValue(I.getArgOperand(0)))); 4648 return nullptr; 4649 } 4650 case Intrinsic::minnum: 4651 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 4652 getValue(I.getArgOperand(0)).getValueType(), 4653 getValue(I.getArgOperand(0)), 4654 getValue(I.getArgOperand(1)))); 4655 return nullptr; 4656 case Intrinsic::maxnum: 4657 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 4658 getValue(I.getArgOperand(0)).getValueType(), 4659 getValue(I.getArgOperand(0)), 4660 getValue(I.getArgOperand(1)))); 4661 return nullptr; 4662 case Intrinsic::copysign: 4663 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 4664 getValue(I.getArgOperand(0)).getValueType(), 4665 getValue(I.getArgOperand(0)), 4666 getValue(I.getArgOperand(1)))); 4667 return nullptr; 4668 case Intrinsic::fma: 4669 setValue(&I, DAG.getNode(ISD::FMA, sdl, 4670 getValue(I.getArgOperand(0)).getValueType(), 4671 getValue(I.getArgOperand(0)), 4672 getValue(I.getArgOperand(1)), 4673 getValue(I.getArgOperand(2)))); 4674 return nullptr; 4675 case Intrinsic::fmuladd: { 4676 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4677 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 4678 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 4679 setValue(&I, DAG.getNode(ISD::FMA, sdl, 4680 getValue(I.getArgOperand(0)).getValueType(), 4681 getValue(I.getArgOperand(0)), 4682 getValue(I.getArgOperand(1)), 4683 getValue(I.getArgOperand(2)))); 4684 } else { 4685 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 4686 getValue(I.getArgOperand(0)).getValueType(), 4687 getValue(I.getArgOperand(0)), 4688 getValue(I.getArgOperand(1))); 4689 SDValue Add = DAG.getNode(ISD::FADD, sdl, 4690 getValue(I.getArgOperand(0)).getValueType(), 4691 Mul, 4692 getValue(I.getArgOperand(2))); 4693 setValue(&I, Add); 4694 } 4695 return nullptr; 4696 } 4697 case Intrinsic::convert_to_fp16: 4698 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 4699 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 4700 getValue(I.getArgOperand(0)), 4701 DAG.getTargetConstant(0, sdl, 4702 MVT::i32)))); 4703 return nullptr; 4704 case Intrinsic::convert_from_fp16: 4705 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 4706 TLI.getValueType(DAG.getDataLayout(), I.getType()), 4707 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 4708 getValue(I.getArgOperand(0))))); 4709 return nullptr; 4710 case Intrinsic::pcmarker: { 4711 SDValue Tmp = getValue(I.getArgOperand(0)); 4712 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 4713 return nullptr; 4714 } 4715 case Intrinsic::readcyclecounter: { 4716 SDValue Op = getRoot(); 4717 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 4718 DAG.getVTList(MVT::i64, MVT::Other), Op); 4719 setValue(&I, Res); 4720 DAG.setRoot(Res.getValue(1)); 4721 return nullptr; 4722 } 4723 case Intrinsic::bswap: 4724 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 4725 getValue(I.getArgOperand(0)).getValueType(), 4726 getValue(I.getArgOperand(0)))); 4727 return nullptr; 4728 case Intrinsic::uabsdiff: 4729 setValue(&I, DAG.getNode(ISD::UABSDIFF, sdl, 4730 getValue(I.getArgOperand(0)).getValueType(), 4731 getValue(I.getArgOperand(0)), 4732 getValue(I.getArgOperand(1)))); 4733 return nullptr; 4734 case Intrinsic::sabsdiff: 4735 setValue(&I, DAG.getNode(ISD::SABSDIFF, sdl, 4736 getValue(I.getArgOperand(0)).getValueType(), 4737 getValue(I.getArgOperand(0)), 4738 getValue(I.getArgOperand(1)))); 4739 return nullptr; 4740 case Intrinsic::cttz: { 4741 SDValue Arg = getValue(I.getArgOperand(0)); 4742 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 4743 EVT Ty = Arg.getValueType(); 4744 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 4745 sdl, Ty, Arg)); 4746 return nullptr; 4747 } 4748 case Intrinsic::ctlz: { 4749 SDValue Arg = getValue(I.getArgOperand(0)); 4750 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 4751 EVT Ty = Arg.getValueType(); 4752 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 4753 sdl, Ty, Arg)); 4754 return nullptr; 4755 } 4756 case Intrinsic::ctpop: { 4757 SDValue Arg = getValue(I.getArgOperand(0)); 4758 EVT Ty = Arg.getValueType(); 4759 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 4760 return nullptr; 4761 } 4762 case Intrinsic::stacksave: { 4763 SDValue Op = getRoot(); 4764 Res = DAG.getNode( 4765 ISD::STACKSAVE, sdl, 4766 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 4767 setValue(&I, Res); 4768 DAG.setRoot(Res.getValue(1)); 4769 return nullptr; 4770 } 4771 case Intrinsic::stackrestore: { 4772 Res = getValue(I.getArgOperand(0)); 4773 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 4774 return nullptr; 4775 } 4776 case Intrinsic::stackprotector: { 4777 // Emit code into the DAG to store the stack guard onto the stack. 4778 MachineFunction &MF = DAG.getMachineFunction(); 4779 MachineFrameInfo *MFI = MF.getFrameInfo(); 4780 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 4781 SDValue Src, Chain = getRoot(); 4782 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand(); 4783 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr); 4784 4785 // See if Ptr is a bitcast. If it is, look through it and see if we can get 4786 // global variable __stack_chk_guard. 4787 if (!GV) 4788 if (const Operator *BC = dyn_cast<Operator>(Ptr)) 4789 if (BC->getOpcode() == Instruction::BitCast) 4790 GV = dyn_cast<GlobalVariable>(BC->getOperand(0)); 4791 4792 if (GV && TLI.useLoadStackGuardNode()) { 4793 // Emit a LOAD_STACK_GUARD node. 4794 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, 4795 sdl, PtrTy, Chain); 4796 MachinePointerInfo MPInfo(GV); 4797 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 4798 unsigned Flags = MachineMemOperand::MOLoad | 4799 MachineMemOperand::MOInvariant; 4800 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, 4801 PtrTy.getSizeInBits() / 8, 4802 DAG.getEVTAlignment(PtrTy)); 4803 Node->setMemRefs(MemRefs, MemRefs + 1); 4804 4805 // Copy the guard value to a virtual register so that it can be 4806 // retrieved in the epilogue. 4807 Src = SDValue(Node, 0); 4808 const TargetRegisterClass *RC = 4809 TLI.getRegClassFor(Src.getSimpleValueType()); 4810 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC); 4811 4812 SPDescriptor.setGuardReg(Reg); 4813 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src); 4814 } else { 4815 Src = getValue(I.getArgOperand(0)); // The guard's value. 4816 } 4817 4818 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 4819 4820 int FI = FuncInfo.StaticAllocaMap[Slot]; 4821 MFI->setStackProtectorIndex(FI); 4822 4823 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4824 4825 // Store the stack protector onto the stack. 4826 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 4827 DAG.getMachineFunction(), FI), 4828 true, false, 0); 4829 setValue(&I, Res); 4830 DAG.setRoot(Res); 4831 return nullptr; 4832 } 4833 case Intrinsic::objectsize: { 4834 // If we don't know by now, we're never going to know. 4835 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 4836 4837 assert(CI && "Non-constant type in __builtin_object_size?"); 4838 4839 SDValue Arg = getValue(I.getCalledValue()); 4840 EVT Ty = Arg.getValueType(); 4841 4842 if (CI->isZero()) 4843 Res = DAG.getConstant(-1ULL, sdl, Ty); 4844 else 4845 Res = DAG.getConstant(0, sdl, Ty); 4846 4847 setValue(&I, Res); 4848 return nullptr; 4849 } 4850 case Intrinsic::annotation: 4851 case Intrinsic::ptr_annotation: 4852 // Drop the intrinsic, but forward the value 4853 setValue(&I, getValue(I.getOperand(0))); 4854 return nullptr; 4855 case Intrinsic::assume: 4856 case Intrinsic::var_annotation: 4857 // Discard annotate attributes and assumptions 4858 return nullptr; 4859 4860 case Intrinsic::init_trampoline: { 4861 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 4862 4863 SDValue Ops[6]; 4864 Ops[0] = getRoot(); 4865 Ops[1] = getValue(I.getArgOperand(0)); 4866 Ops[2] = getValue(I.getArgOperand(1)); 4867 Ops[3] = getValue(I.getArgOperand(2)); 4868 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 4869 Ops[5] = DAG.getSrcValue(F); 4870 4871 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 4872 4873 DAG.setRoot(Res); 4874 return nullptr; 4875 } 4876 case Intrinsic::adjust_trampoline: { 4877 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 4878 TLI.getPointerTy(DAG.getDataLayout()), 4879 getValue(I.getArgOperand(0)))); 4880 return nullptr; 4881 } 4882 case Intrinsic::gcroot: 4883 if (GFI) { 4884 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 4885 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 4886 4887 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4888 GFI->addStackRoot(FI->getIndex(), TypeMap); 4889 } 4890 return nullptr; 4891 case Intrinsic::gcread: 4892 case Intrinsic::gcwrite: 4893 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4894 case Intrinsic::flt_rounds: 4895 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 4896 return nullptr; 4897 4898 case Intrinsic::expect: { 4899 // Just replace __builtin_expect(exp, c) with EXP. 4900 setValue(&I, getValue(I.getArgOperand(0))); 4901 return nullptr; 4902 } 4903 4904 case Intrinsic::debugtrap: 4905 case Intrinsic::trap: { 4906 StringRef TrapFuncName = 4907 I.getAttributes() 4908 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name") 4909 .getValueAsString(); 4910 if (TrapFuncName.empty()) { 4911 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 4912 ISD::TRAP : ISD::DEBUGTRAP; 4913 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 4914 return nullptr; 4915 } 4916 TargetLowering::ArgListTy Args; 4917 4918 TargetLowering::CallLoweringInfo CLI(DAG); 4919 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee( 4920 CallingConv::C, I.getType(), 4921 DAG.getExternalSymbol(TrapFuncName.data(), 4922 TLI.getPointerTy(DAG.getDataLayout())), 4923 std::move(Args), 0); 4924 4925 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 4926 DAG.setRoot(Result.second); 4927 return nullptr; 4928 } 4929 4930 case Intrinsic::uadd_with_overflow: 4931 case Intrinsic::sadd_with_overflow: 4932 case Intrinsic::usub_with_overflow: 4933 case Intrinsic::ssub_with_overflow: 4934 case Intrinsic::umul_with_overflow: 4935 case Intrinsic::smul_with_overflow: { 4936 ISD::NodeType Op; 4937 switch (Intrinsic) { 4938 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4939 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 4940 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 4941 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 4942 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 4943 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 4944 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 4945 } 4946 SDValue Op1 = getValue(I.getArgOperand(0)); 4947 SDValue Op2 = getValue(I.getArgOperand(1)); 4948 4949 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 4950 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 4951 return nullptr; 4952 } 4953 case Intrinsic::prefetch: { 4954 SDValue Ops[5]; 4955 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4956 Ops[0] = getRoot(); 4957 Ops[1] = getValue(I.getArgOperand(0)); 4958 Ops[2] = getValue(I.getArgOperand(1)); 4959 Ops[3] = getValue(I.getArgOperand(2)); 4960 Ops[4] = getValue(I.getArgOperand(3)); 4961 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 4962 DAG.getVTList(MVT::Other), Ops, 4963 EVT::getIntegerVT(*Context, 8), 4964 MachinePointerInfo(I.getArgOperand(0)), 4965 0, /* align */ 4966 false, /* volatile */ 4967 rw==0, /* read */ 4968 rw==1)); /* write */ 4969 return nullptr; 4970 } 4971 case Intrinsic::lifetime_start: 4972 case Intrinsic::lifetime_end: { 4973 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 4974 // Stack coloring is not enabled in O0, discard region information. 4975 if (TM.getOptLevel() == CodeGenOpt::None) 4976 return nullptr; 4977 4978 SmallVector<Value *, 4> Allocas; 4979 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 4980 4981 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 4982 E = Allocas.end(); Object != E; ++Object) { 4983 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 4984 4985 // Could not find an Alloca. 4986 if (!LifetimeObject) 4987 continue; 4988 4989 // First check that the Alloca is static, otherwise it won't have a 4990 // valid frame index. 4991 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 4992 if (SI == FuncInfo.StaticAllocaMap.end()) 4993 return nullptr; 4994 4995 int FI = SI->second; 4996 4997 SDValue Ops[2]; 4998 Ops[0] = getRoot(); 4999 Ops[1] = 5000 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true); 5001 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5002 5003 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5004 DAG.setRoot(Res); 5005 } 5006 return nullptr; 5007 } 5008 case Intrinsic::invariant_start: 5009 // Discard region information. 5010 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5011 return nullptr; 5012 case Intrinsic::invariant_end: 5013 // Discard region information. 5014 return nullptr; 5015 case Intrinsic::stackprotectorcheck: { 5016 // Do not actually emit anything for this basic block. Instead we initialize 5017 // the stack protector descriptor and export the guard variable so we can 5018 // access it in FinishBasicBlock. 5019 const BasicBlock *BB = I.getParent(); 5020 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I); 5021 ExportFromCurrentBlock(SPDescriptor.getGuard()); 5022 5023 // Flush our exports since we are going to process a terminator. 5024 (void)getControlRoot(); 5025 return nullptr; 5026 } 5027 case Intrinsic::clear_cache: 5028 return TLI.getClearCacheBuiltinName(); 5029 case Intrinsic::eh_actions: 5030 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5031 return nullptr; 5032 case Intrinsic::donothing: 5033 // ignore 5034 return nullptr; 5035 case Intrinsic::experimental_stackmap: { 5036 visitStackmap(I); 5037 return nullptr; 5038 } 5039 case Intrinsic::experimental_patchpoint_void: 5040 case Intrinsic::experimental_patchpoint_i64: { 5041 visitPatchpoint(&I); 5042 return nullptr; 5043 } 5044 case Intrinsic::experimental_gc_statepoint: { 5045 visitStatepoint(I); 5046 return nullptr; 5047 } 5048 case Intrinsic::experimental_gc_result_int: 5049 case Intrinsic::experimental_gc_result_float: 5050 case Intrinsic::experimental_gc_result_ptr: 5051 case Intrinsic::experimental_gc_result: { 5052 visitGCResult(I); 5053 return nullptr; 5054 } 5055 case Intrinsic::experimental_gc_relocate: { 5056 visitGCRelocate(I); 5057 return nullptr; 5058 } 5059 case Intrinsic::instrprof_increment: 5060 llvm_unreachable("instrprof failed to lower an increment"); 5061 5062 case Intrinsic::localescape: { 5063 MachineFunction &MF = DAG.getMachineFunction(); 5064 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5065 5066 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5067 // is the same on all targets. 5068 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5069 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5070 if (isa<ConstantPointerNull>(Arg)) 5071 continue; // Skip null pointers. They represent a hole in index space. 5072 AllocaInst *Slot = cast<AllocaInst>(Arg); 5073 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5074 "can only escape static allocas"); 5075 int FI = FuncInfo.StaticAllocaMap[Slot]; 5076 MCSymbol *FrameAllocSym = 5077 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5078 GlobalValue::getRealLinkageName(MF.getName()), Idx); 5079 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5080 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5081 .addSym(FrameAllocSym) 5082 .addFrameIndex(FI); 5083 } 5084 5085 return nullptr; 5086 } 5087 5088 case Intrinsic::localrecover: { 5089 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 5090 MachineFunction &MF = DAG.getMachineFunction(); 5091 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 5092 5093 // Get the symbol that defines the frame offset. 5094 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 5095 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 5096 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX)); 5097 MCSymbol *FrameAllocSym = 5098 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5099 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal); 5100 5101 // Create a MCSymbol for the label to avoid any target lowering 5102 // that would make this PC relative. 5103 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 5104 SDValue OffsetVal = 5105 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 5106 5107 // Add the offset to the FP. 5108 Value *FP = I.getArgOperand(1); 5109 SDValue FPVal = getValue(FP); 5110 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 5111 setValue(&I, Add); 5112 5113 return nullptr; 5114 } 5115 case Intrinsic::eh_begincatch: 5116 case Intrinsic::eh_endcatch: 5117 llvm_unreachable("begin/end catch intrinsics not lowered in codegen"); 5118 case Intrinsic::eh_exceptioncode: { 5119 unsigned Reg = TLI.getExceptionPointerRegister(); 5120 assert(Reg && "cannot get exception code on this platform"); 5121 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 5122 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 5123 assert(FuncInfo.MBB->isEHPad() && "eh.exceptioncode in non-lpad"); 5124 unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC); 5125 SDValue N = 5126 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 5127 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 5128 setValue(&I, N); 5129 return nullptr; 5130 } 5131 } 5132 } 5133 5134 std::pair<SDValue, SDValue> 5135 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 5136 MachineBasicBlock *LandingPad) { 5137 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5138 MCSymbol *BeginLabel = nullptr; 5139 5140 if (LandingPad) { 5141 // Insert a label before the invoke call to mark the try range. This can be 5142 // used to detect deletion of the invoke via the MachineModuleInfo. 5143 BeginLabel = MMI.getContext().createTempSymbol(); 5144 5145 // For SjLj, keep track of which landing pads go with which invokes 5146 // so as to maintain the ordering of pads in the LSDA. 5147 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5148 if (CallSiteIndex) { 5149 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5150 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex); 5151 5152 // Now that the call site is handled, stop tracking it. 5153 MMI.setCurrentCallSite(0); 5154 } 5155 5156 // Both PendingLoads and PendingExports must be flushed here; 5157 // this call might not return. 5158 (void)getRoot(); 5159 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 5160 5161 CLI.setChain(getRoot()); 5162 } 5163 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5164 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5165 5166 assert((CLI.IsTailCall || Result.second.getNode()) && 5167 "Non-null chain expected with non-tail call!"); 5168 assert((Result.second.getNode() || !Result.first.getNode()) && 5169 "Null value expected with tail call!"); 5170 5171 if (!Result.second.getNode()) { 5172 // As a special case, a null chain means that a tail call has been emitted 5173 // and the DAG root is already updated. 5174 HasTailCall = true; 5175 5176 // Since there's no actual continuation from this block, nothing can be 5177 // relying on us setting vregs for them. 5178 PendingExports.clear(); 5179 } else { 5180 DAG.setRoot(Result.second); 5181 } 5182 5183 if (LandingPad) { 5184 // Insert a label at the end of the invoke call to mark the try range. This 5185 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5186 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 5187 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 5188 5189 // Inform MachineModuleInfo of range. 5190 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 5191 } 5192 5193 return Result; 5194 } 5195 5196 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 5197 bool isTailCall, 5198 MachineBasicBlock *LandingPad) { 5199 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 5200 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 5201 Type *RetTy = FTy->getReturnType(); 5202 5203 TargetLowering::ArgListTy Args; 5204 TargetLowering::ArgListEntry Entry; 5205 Args.reserve(CS.arg_size()); 5206 5207 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5208 i != e; ++i) { 5209 const Value *V = *i; 5210 5211 // Skip empty types 5212 if (V->getType()->isEmptyTy()) 5213 continue; 5214 5215 SDValue ArgNode = getValue(V); 5216 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5217 5218 // Skip the first return-type Attribute to get to params. 5219 Entry.setAttributes(&CS, i - CS.arg_begin() + 1); 5220 Args.push_back(Entry); 5221 5222 // If we have an explicit sret argument that is an Instruction, (i.e., it 5223 // might point to function-local memory), we can't meaningfully tail-call. 5224 if (Entry.isSRet && isa<Instruction>(V)) 5225 isTailCall = false; 5226 } 5227 5228 // Check if target-independent constraints permit a tail call here. 5229 // Target-dependent constraints are checked within TLI->LowerCallTo. 5230 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 5231 isTailCall = false; 5232 5233 TargetLowering::CallLoweringInfo CLI(DAG); 5234 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot()) 5235 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 5236 .setTailCall(isTailCall); 5237 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad); 5238 5239 if (Result.first.getNode()) 5240 setValue(CS.getInstruction(), Result.first); 5241 } 5242 5243 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5244 /// value is equal or not-equal to zero. 5245 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5246 for (const User *U : V->users()) { 5247 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U)) 5248 if (IC->isEquality()) 5249 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5250 if (C->isNullValue()) 5251 continue; 5252 // Unknown instruction. 5253 return false; 5254 } 5255 return true; 5256 } 5257 5258 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5259 Type *LoadTy, 5260 SelectionDAGBuilder &Builder) { 5261 5262 // Check to see if this load can be trivially constant folded, e.g. if the 5263 // input is from a string literal. 5264 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5265 // Cast pointer to the type we really want to load. 5266 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5267 PointerType::getUnqual(LoadTy)); 5268 5269 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 5270 const_cast<Constant *>(LoadInput), *Builder.DL)) 5271 return Builder.getValue(LoadCst); 5272 } 5273 5274 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5275 // still constant memory, the input chain can be the entry node. 5276 SDValue Root; 5277 bool ConstantMemory = false; 5278 5279 // Do not serialize (non-volatile) loads of constant memory with anything. 5280 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5281 Root = Builder.DAG.getEntryNode(); 5282 ConstantMemory = true; 5283 } else { 5284 // Do not serialize non-volatile loads against each other. 5285 Root = Builder.DAG.getRoot(); 5286 } 5287 5288 SDValue Ptr = Builder.getValue(PtrVal); 5289 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 5290 Ptr, MachinePointerInfo(PtrVal), 5291 false /*volatile*/, 5292 false /*nontemporal*/, 5293 false /*isinvariant*/, 1 /* align=1 */); 5294 5295 if (!ConstantMemory) 5296 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5297 return LoadVal; 5298 } 5299 5300 /// processIntegerCallValue - Record the value for an instruction that 5301 /// produces an integer result, converting the type where necessary. 5302 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 5303 SDValue Value, 5304 bool IsSigned) { 5305 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5306 I.getType(), true); 5307 if (IsSigned) 5308 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 5309 else 5310 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 5311 setValue(&I, Value); 5312 } 5313 5314 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5315 /// If so, return true and lower it, otherwise return false and it will be 5316 /// lowered like a normal call. 5317 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5318 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5319 if (I.getNumArgOperands() != 3) 5320 return false; 5321 5322 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5323 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5324 !I.getArgOperand(2)->getType()->isIntegerTy() || 5325 !I.getType()->isIntegerTy()) 5326 return false; 5327 5328 const Value *Size = I.getArgOperand(2); 5329 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 5330 if (CSize && CSize->getZExtValue() == 0) { 5331 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5332 I.getType(), true); 5333 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 5334 return true; 5335 } 5336 5337 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5338 std::pair<SDValue, SDValue> Res = 5339 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5340 getValue(LHS), getValue(RHS), getValue(Size), 5341 MachinePointerInfo(LHS), 5342 MachinePointerInfo(RHS)); 5343 if (Res.first.getNode()) { 5344 processIntegerCallValue(I, Res.first, true); 5345 PendingLoads.push_back(Res.second); 5346 return true; 5347 } 5348 5349 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5350 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5351 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) { 5352 bool ActuallyDoIt = true; 5353 MVT LoadVT; 5354 Type *LoadTy; 5355 switch (CSize->getZExtValue()) { 5356 default: 5357 LoadVT = MVT::Other; 5358 LoadTy = nullptr; 5359 ActuallyDoIt = false; 5360 break; 5361 case 2: 5362 LoadVT = MVT::i16; 5363 LoadTy = Type::getInt16Ty(CSize->getContext()); 5364 break; 5365 case 4: 5366 LoadVT = MVT::i32; 5367 LoadTy = Type::getInt32Ty(CSize->getContext()); 5368 break; 5369 case 8: 5370 LoadVT = MVT::i64; 5371 LoadTy = Type::getInt64Ty(CSize->getContext()); 5372 break; 5373 /* 5374 case 16: 5375 LoadVT = MVT::v4i32; 5376 LoadTy = Type::getInt32Ty(CSize->getContext()); 5377 LoadTy = VectorType::get(LoadTy, 4); 5378 break; 5379 */ 5380 } 5381 5382 // This turns into unaligned loads. We only do this if the target natively 5383 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5384 // we'll only produce a small number of byte loads. 5385 5386 // Require that we can find a legal MVT, and only do this if the target 5387 // supports unaligned loads of that type. Expanding into byte loads would 5388 // bloat the code. 5389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5390 if (ActuallyDoIt && CSize->getZExtValue() > 4) { 5391 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 5392 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 5393 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5394 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5395 // TODO: Check alignment of src and dest ptrs. 5396 if (!TLI.isTypeLegal(LoadVT) || 5397 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) || 5398 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS)) 5399 ActuallyDoIt = false; 5400 } 5401 5402 if (ActuallyDoIt) { 5403 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5404 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5405 5406 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal, 5407 ISD::SETNE); 5408 processIntegerCallValue(I, Res, false); 5409 return true; 5410 } 5411 } 5412 5413 5414 return false; 5415 } 5416 5417 /// visitMemChrCall -- See if we can lower a memchr call into an optimized 5418 /// form. If so, return true and lower it, otherwise return false and it 5419 /// will be lowered like a normal call. 5420 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 5421 // Verify that the prototype makes sense. void *memchr(void *, int, size_t) 5422 if (I.getNumArgOperands() != 3) 5423 return false; 5424 5425 const Value *Src = I.getArgOperand(0); 5426 const Value *Char = I.getArgOperand(1); 5427 const Value *Length = I.getArgOperand(2); 5428 if (!Src->getType()->isPointerTy() || 5429 !Char->getType()->isIntegerTy() || 5430 !Length->getType()->isIntegerTy() || 5431 !I.getType()->isPointerTy()) 5432 return false; 5433 5434 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5435 std::pair<SDValue, SDValue> Res = 5436 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 5437 getValue(Src), getValue(Char), getValue(Length), 5438 MachinePointerInfo(Src)); 5439 if (Res.first.getNode()) { 5440 setValue(&I, Res.first); 5441 PendingLoads.push_back(Res.second); 5442 return true; 5443 } 5444 5445 return false; 5446 } 5447 5448 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an 5449 /// optimized form. If so, return true and lower it, otherwise return false 5450 /// and it will be lowered like a normal call. 5451 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 5452 // Verify that the prototype makes sense. char *strcpy(char *, char *) 5453 if (I.getNumArgOperands() != 2) 5454 return false; 5455 5456 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5457 if (!Arg0->getType()->isPointerTy() || 5458 !Arg1->getType()->isPointerTy() || 5459 !I.getType()->isPointerTy()) 5460 return false; 5461 5462 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5463 std::pair<SDValue, SDValue> Res = 5464 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 5465 getValue(Arg0), getValue(Arg1), 5466 MachinePointerInfo(Arg0), 5467 MachinePointerInfo(Arg1), isStpcpy); 5468 if (Res.first.getNode()) { 5469 setValue(&I, Res.first); 5470 DAG.setRoot(Res.second); 5471 return true; 5472 } 5473 5474 return false; 5475 } 5476 5477 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form. 5478 /// If so, return true and lower it, otherwise return false and it will be 5479 /// lowered like a normal call. 5480 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 5481 // Verify that the prototype makes sense. int strcmp(void*,void*) 5482 if (I.getNumArgOperands() != 2) 5483 return false; 5484 5485 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5486 if (!Arg0->getType()->isPointerTy() || 5487 !Arg1->getType()->isPointerTy() || 5488 !I.getType()->isIntegerTy()) 5489 return false; 5490 5491 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5492 std::pair<SDValue, SDValue> Res = 5493 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5494 getValue(Arg0), getValue(Arg1), 5495 MachinePointerInfo(Arg0), 5496 MachinePointerInfo(Arg1)); 5497 if (Res.first.getNode()) { 5498 processIntegerCallValue(I, Res.first, true); 5499 PendingLoads.push_back(Res.second); 5500 return true; 5501 } 5502 5503 return false; 5504 } 5505 5506 /// visitStrLenCall -- See if we can lower a strlen call into an optimized 5507 /// form. If so, return true and lower it, otherwise return false and it 5508 /// will be lowered like a normal call. 5509 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 5510 // Verify that the prototype makes sense. size_t strlen(char *) 5511 if (I.getNumArgOperands() != 1) 5512 return false; 5513 5514 const Value *Arg0 = I.getArgOperand(0); 5515 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy()) 5516 return false; 5517 5518 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5519 std::pair<SDValue, SDValue> Res = 5520 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 5521 getValue(Arg0), MachinePointerInfo(Arg0)); 5522 if (Res.first.getNode()) { 5523 processIntegerCallValue(I, Res.first, false); 5524 PendingLoads.push_back(Res.second); 5525 return true; 5526 } 5527 5528 return false; 5529 } 5530 5531 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized 5532 /// form. If so, return true and lower it, otherwise return false and it 5533 /// will be lowered like a normal call. 5534 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 5535 // Verify that the prototype makes sense. size_t strnlen(char *, size_t) 5536 if (I.getNumArgOperands() != 2) 5537 return false; 5538 5539 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5540 if (!Arg0->getType()->isPointerTy() || 5541 !Arg1->getType()->isIntegerTy() || 5542 !I.getType()->isIntegerTy()) 5543 return false; 5544 5545 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5546 std::pair<SDValue, SDValue> Res = 5547 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 5548 getValue(Arg0), getValue(Arg1), 5549 MachinePointerInfo(Arg0)); 5550 if (Res.first.getNode()) { 5551 processIntegerCallValue(I, Res.first, false); 5552 PendingLoads.push_back(Res.second); 5553 return true; 5554 } 5555 5556 return false; 5557 } 5558 5559 /// visitUnaryFloatCall - If a call instruction is a unary floating-point 5560 /// operation (as expected), translate it to an SDNode with the specified opcode 5561 /// and return true. 5562 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 5563 unsigned Opcode) { 5564 // Sanity check that it really is a unary floating-point call. 5565 if (I.getNumArgOperands() != 1 || 5566 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 5567 I.getType() != I.getArgOperand(0)->getType() || 5568 !I.onlyReadsMemory()) 5569 return false; 5570 5571 SDValue Tmp = getValue(I.getArgOperand(0)); 5572 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 5573 return true; 5574 } 5575 5576 /// visitBinaryFloatCall - If a call instruction is a binary floating-point 5577 /// operation (as expected), translate it to an SDNode with the specified opcode 5578 /// and return true. 5579 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 5580 unsigned Opcode) { 5581 // Sanity check that it really is a binary floating-point call. 5582 if (I.getNumArgOperands() != 2 || 5583 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 5584 I.getType() != I.getArgOperand(0)->getType() || 5585 I.getType() != I.getArgOperand(1)->getType() || 5586 !I.onlyReadsMemory()) 5587 return false; 5588 5589 SDValue Tmp0 = getValue(I.getArgOperand(0)); 5590 SDValue Tmp1 = getValue(I.getArgOperand(1)); 5591 EVT VT = Tmp0.getValueType(); 5592 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 5593 return true; 5594 } 5595 5596 void SelectionDAGBuilder::visitCall(const CallInst &I) { 5597 // Handle inline assembly differently. 5598 if (isa<InlineAsm>(I.getCalledValue())) { 5599 visitInlineAsm(&I); 5600 return; 5601 } 5602 5603 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5604 ComputeUsesVAFloatArgument(I, &MMI); 5605 5606 const char *RenameFn = nullptr; 5607 if (Function *F = I.getCalledFunction()) { 5608 if (F->isDeclaration()) { 5609 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 5610 if (unsigned IID = II->getIntrinsicID(F)) { 5611 RenameFn = visitIntrinsicCall(I, IID); 5612 if (!RenameFn) 5613 return; 5614 } 5615 } 5616 if (Intrinsic::ID IID = F->getIntrinsicID()) { 5617 RenameFn = visitIntrinsicCall(I, IID); 5618 if (!RenameFn) 5619 return; 5620 } 5621 } 5622 5623 // Check for well-known libc/libm calls. If the function is internal, it 5624 // can't be a library call. 5625 LibFunc::Func Func; 5626 if (!F->hasLocalLinkage() && F->hasName() && 5627 LibInfo->getLibFunc(F->getName(), Func) && 5628 LibInfo->hasOptimizedCodeGen(Func)) { 5629 switch (Func) { 5630 default: break; 5631 case LibFunc::copysign: 5632 case LibFunc::copysignf: 5633 case LibFunc::copysignl: 5634 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 5635 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5636 I.getType() == I.getArgOperand(0)->getType() && 5637 I.getType() == I.getArgOperand(1)->getType() && 5638 I.onlyReadsMemory()) { 5639 SDValue LHS = getValue(I.getArgOperand(0)); 5640 SDValue RHS = getValue(I.getArgOperand(1)); 5641 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 5642 LHS.getValueType(), LHS, RHS)); 5643 return; 5644 } 5645 break; 5646 case LibFunc::fabs: 5647 case LibFunc::fabsf: 5648 case LibFunc::fabsl: 5649 if (visitUnaryFloatCall(I, ISD::FABS)) 5650 return; 5651 break; 5652 case LibFunc::fmin: 5653 case LibFunc::fminf: 5654 case LibFunc::fminl: 5655 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 5656 return; 5657 break; 5658 case LibFunc::fmax: 5659 case LibFunc::fmaxf: 5660 case LibFunc::fmaxl: 5661 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 5662 return; 5663 break; 5664 case LibFunc::sin: 5665 case LibFunc::sinf: 5666 case LibFunc::sinl: 5667 if (visitUnaryFloatCall(I, ISD::FSIN)) 5668 return; 5669 break; 5670 case LibFunc::cos: 5671 case LibFunc::cosf: 5672 case LibFunc::cosl: 5673 if (visitUnaryFloatCall(I, ISD::FCOS)) 5674 return; 5675 break; 5676 case LibFunc::sqrt: 5677 case LibFunc::sqrtf: 5678 case LibFunc::sqrtl: 5679 case LibFunc::sqrt_finite: 5680 case LibFunc::sqrtf_finite: 5681 case LibFunc::sqrtl_finite: 5682 if (visitUnaryFloatCall(I, ISD::FSQRT)) 5683 return; 5684 break; 5685 case LibFunc::floor: 5686 case LibFunc::floorf: 5687 case LibFunc::floorl: 5688 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 5689 return; 5690 break; 5691 case LibFunc::nearbyint: 5692 case LibFunc::nearbyintf: 5693 case LibFunc::nearbyintl: 5694 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 5695 return; 5696 break; 5697 case LibFunc::ceil: 5698 case LibFunc::ceilf: 5699 case LibFunc::ceill: 5700 if (visitUnaryFloatCall(I, ISD::FCEIL)) 5701 return; 5702 break; 5703 case LibFunc::rint: 5704 case LibFunc::rintf: 5705 case LibFunc::rintl: 5706 if (visitUnaryFloatCall(I, ISD::FRINT)) 5707 return; 5708 break; 5709 case LibFunc::round: 5710 case LibFunc::roundf: 5711 case LibFunc::roundl: 5712 if (visitUnaryFloatCall(I, ISD::FROUND)) 5713 return; 5714 break; 5715 case LibFunc::trunc: 5716 case LibFunc::truncf: 5717 case LibFunc::truncl: 5718 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 5719 return; 5720 break; 5721 case LibFunc::log2: 5722 case LibFunc::log2f: 5723 case LibFunc::log2l: 5724 if (visitUnaryFloatCall(I, ISD::FLOG2)) 5725 return; 5726 break; 5727 case LibFunc::exp2: 5728 case LibFunc::exp2f: 5729 case LibFunc::exp2l: 5730 if (visitUnaryFloatCall(I, ISD::FEXP2)) 5731 return; 5732 break; 5733 case LibFunc::memcmp: 5734 if (visitMemCmpCall(I)) 5735 return; 5736 break; 5737 case LibFunc::memchr: 5738 if (visitMemChrCall(I)) 5739 return; 5740 break; 5741 case LibFunc::strcpy: 5742 if (visitStrCpyCall(I, false)) 5743 return; 5744 break; 5745 case LibFunc::stpcpy: 5746 if (visitStrCpyCall(I, true)) 5747 return; 5748 break; 5749 case LibFunc::strcmp: 5750 if (visitStrCmpCall(I)) 5751 return; 5752 break; 5753 case LibFunc::strlen: 5754 if (visitStrLenCall(I)) 5755 return; 5756 break; 5757 case LibFunc::strnlen: 5758 if (visitStrNLenCall(I)) 5759 return; 5760 break; 5761 } 5762 } 5763 } 5764 5765 SDValue Callee; 5766 if (!RenameFn) 5767 Callee = getValue(I.getCalledValue()); 5768 else 5769 Callee = DAG.getExternalSymbol( 5770 RenameFn, 5771 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5772 5773 // Check if we can potentially perform a tail call. More detailed checking is 5774 // be done within LowerCallTo, after more information about the call is known. 5775 LowerCallTo(&I, Callee, I.isTailCall()); 5776 } 5777 5778 namespace { 5779 5780 /// AsmOperandInfo - This contains information for each constraint that we are 5781 /// lowering. 5782 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 5783 public: 5784 /// CallOperand - If this is the result output operand or a clobber 5785 /// this is null, otherwise it is the incoming operand to the CallInst. 5786 /// This gets modified as the asm is processed. 5787 SDValue CallOperand; 5788 5789 /// AssignedRegs - If this is a register or register class operand, this 5790 /// contains the set of register corresponding to the operand. 5791 RegsForValue AssignedRegs; 5792 5793 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 5794 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) { 5795 } 5796 5797 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 5798 /// corresponds to. If there is no Value* for this operand, it returns 5799 /// MVT::Other. 5800 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 5801 const DataLayout &DL) const { 5802 if (!CallOperandVal) return MVT::Other; 5803 5804 if (isa<BasicBlock>(CallOperandVal)) 5805 return TLI.getPointerTy(DL); 5806 5807 llvm::Type *OpTy = CallOperandVal->getType(); 5808 5809 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 5810 // If this is an indirect operand, the operand is a pointer to the 5811 // accessed type. 5812 if (isIndirect) { 5813 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5814 if (!PtrTy) 5815 report_fatal_error("Indirect operand for inline asm not a pointer!"); 5816 OpTy = PtrTy->getElementType(); 5817 } 5818 5819 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5820 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5821 if (STy->getNumElements() == 1) 5822 OpTy = STy->getElementType(0); 5823 5824 // If OpTy is not a single value, it may be a struct/union that we 5825 // can tile with integers. 5826 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5827 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5828 switch (BitSize) { 5829 default: break; 5830 case 1: 5831 case 8: 5832 case 16: 5833 case 32: 5834 case 64: 5835 case 128: 5836 OpTy = IntegerType::get(Context, BitSize); 5837 break; 5838 } 5839 } 5840 5841 return TLI.getValueType(DL, OpTy, true); 5842 } 5843 }; 5844 5845 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 5846 5847 } // end anonymous namespace 5848 5849 /// GetRegistersForValue - Assign registers (virtual or physical) for the 5850 /// specified operand. We prefer to assign virtual registers, to allow the 5851 /// register allocator to handle the assignment process. However, if the asm 5852 /// uses features that we can't model on machineinstrs, we have SDISel do the 5853 /// allocation. This produces generally horrible, but correct, code. 5854 /// 5855 /// OpInfo describes the operand. 5856 /// 5857 static void GetRegistersForValue(SelectionDAG &DAG, 5858 const TargetLowering &TLI, 5859 SDLoc DL, 5860 SDISelAsmOperandInfo &OpInfo) { 5861 LLVMContext &Context = *DAG.getContext(); 5862 5863 MachineFunction &MF = DAG.getMachineFunction(); 5864 SmallVector<unsigned, 4> Regs; 5865 5866 // If this is a constraint for a single physreg, or a constraint for a 5867 // register class, find it. 5868 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 5869 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(), 5870 OpInfo.ConstraintCode, 5871 OpInfo.ConstraintVT); 5872 5873 unsigned NumRegs = 1; 5874 if (OpInfo.ConstraintVT != MVT::Other) { 5875 // If this is a FP input in an integer register (or visa versa) insert a bit 5876 // cast of the input value. More generally, handle any case where the input 5877 // value disagrees with the register class we plan to stick this in. 5878 if (OpInfo.Type == InlineAsm::isInput && 5879 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5880 // Try to convert to the first EVT that the reg class contains. If the 5881 // types are identical size, use a bitcast to convert (e.g. two differing 5882 // vector types). 5883 MVT RegVT = *PhysReg.second->vt_begin(); 5884 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 5885 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5886 RegVT, OpInfo.CallOperand); 5887 OpInfo.ConstraintVT = RegVT; 5888 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5889 // If the input is a FP value and we want it in FP registers, do a 5890 // bitcast to the corresponding integer type. This turns an f64 value 5891 // into i64, which can be passed with two i32 values on a 32-bit 5892 // machine. 5893 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 5894 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5895 RegVT, OpInfo.CallOperand); 5896 OpInfo.ConstraintVT = RegVT; 5897 } 5898 } 5899 5900 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5901 } 5902 5903 MVT RegVT; 5904 EVT ValueVT = OpInfo.ConstraintVT; 5905 5906 // If this is a constraint for a specific physical register, like {r17}, 5907 // assign it now. 5908 if (unsigned AssignedReg = PhysReg.first) { 5909 const TargetRegisterClass *RC = PhysReg.second; 5910 if (OpInfo.ConstraintVT == MVT::Other) 5911 ValueVT = *RC->vt_begin(); 5912 5913 // Get the actual register value type. This is important, because the user 5914 // may have asked for (e.g.) the AX register in i32 type. We need to 5915 // remember that AX is actually i16 to get the right extension. 5916 RegVT = *RC->vt_begin(); 5917 5918 // This is a explicit reference to a physical register. 5919 Regs.push_back(AssignedReg); 5920 5921 // If this is an expanded reference, add the rest of the regs to Regs. 5922 if (NumRegs != 1) { 5923 TargetRegisterClass::iterator I = RC->begin(); 5924 for (; *I != AssignedReg; ++I) 5925 assert(I != RC->end() && "Didn't find reg!"); 5926 5927 // Already added the first reg. 5928 --NumRegs; ++I; 5929 for (; NumRegs; --NumRegs, ++I) { 5930 assert(I != RC->end() && "Ran out of registers to allocate!"); 5931 Regs.push_back(*I); 5932 } 5933 } 5934 5935 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5936 return; 5937 } 5938 5939 // Otherwise, if this was a reference to an LLVM register class, create vregs 5940 // for this reference. 5941 if (const TargetRegisterClass *RC = PhysReg.second) { 5942 RegVT = *RC->vt_begin(); 5943 if (OpInfo.ConstraintVT == MVT::Other) 5944 ValueVT = RegVT; 5945 5946 // Create the appropriate number of virtual registers. 5947 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5948 for (; NumRegs; --NumRegs) 5949 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5950 5951 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5952 return; 5953 } 5954 5955 // Otherwise, we couldn't allocate enough registers for this. 5956 } 5957 5958 /// visitInlineAsm - Handle a call to an InlineAsm object. 5959 /// 5960 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 5961 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5962 5963 /// ConstraintOperands - Information about all of the constraints. 5964 SDISelAsmOperandInfoVector ConstraintOperands; 5965 5966 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5967 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 5968 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 5969 5970 bool hasMemory = false; 5971 5972 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5973 unsigned ResNo = 0; // ResNo - The result number of the next output. 5974 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5975 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 5976 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5977 5978 MVT OpVT = MVT::Other; 5979 5980 // Compute the value type for each operand. 5981 switch (OpInfo.Type) { 5982 case InlineAsm::isOutput: 5983 // Indirect outputs just consume an argument. 5984 if (OpInfo.isIndirect) { 5985 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5986 break; 5987 } 5988 5989 // The return value of the call is this value. As such, there is no 5990 // corresponding argument. 5991 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5992 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 5993 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 5994 STy->getElementType(ResNo)); 5995 } else { 5996 assert(ResNo == 0 && "Asm only has one result!"); 5997 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 5998 } 5999 ++ResNo; 6000 break; 6001 case InlineAsm::isInput: 6002 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6003 break; 6004 case InlineAsm::isClobber: 6005 // Nothing to do. 6006 break; 6007 } 6008 6009 // If this is an input or an indirect output, process the call argument. 6010 // BasicBlocks are labels, currently appearing only in asm's. 6011 if (OpInfo.CallOperandVal) { 6012 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 6013 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 6014 } else { 6015 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 6016 } 6017 6018 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 6019 DAG.getDataLayout()).getSimpleVT(); 6020 } 6021 6022 OpInfo.ConstraintVT = OpVT; 6023 6024 // Indirect operand accesses access memory. 6025 if (OpInfo.isIndirect) 6026 hasMemory = true; 6027 else { 6028 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 6029 TargetLowering::ConstraintType 6030 CType = TLI.getConstraintType(OpInfo.Codes[j]); 6031 if (CType == TargetLowering::C_Memory) { 6032 hasMemory = true; 6033 break; 6034 } 6035 } 6036 } 6037 } 6038 6039 SDValue Chain, Flag; 6040 6041 // We won't need to flush pending loads if this asm doesn't touch 6042 // memory and is nonvolatile. 6043 if (hasMemory || IA->hasSideEffects()) 6044 Chain = getRoot(); 6045 else 6046 Chain = DAG.getRoot(); 6047 6048 // Second pass over the constraints: compute which constraint option to use 6049 // and assign registers to constraints that want a specific physreg. 6050 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6051 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6052 6053 // If this is an output operand with a matching input operand, look up the 6054 // matching input. If their types mismatch, e.g. one is an integer, the 6055 // other is floating point, or their sizes are different, flag it as an 6056 // error. 6057 if (OpInfo.hasMatchingInput()) { 6058 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 6059 6060 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 6061 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 6062 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 6063 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 6064 OpInfo.ConstraintVT); 6065 std::pair<unsigned, const TargetRegisterClass *> InputRC = 6066 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 6067 Input.ConstraintVT); 6068 if ((OpInfo.ConstraintVT.isInteger() != 6069 Input.ConstraintVT.isInteger()) || 6070 (MatchRC.second != InputRC.second)) { 6071 report_fatal_error("Unsupported asm: input constraint" 6072 " with a matching output constraint of" 6073 " incompatible type!"); 6074 } 6075 Input.ConstraintVT = OpInfo.ConstraintVT; 6076 } 6077 } 6078 6079 // Compute the constraint code and ConstraintType to use. 6080 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 6081 6082 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6083 OpInfo.Type == InlineAsm::isClobber) 6084 continue; 6085 6086 // If this is a memory input, and if the operand is not indirect, do what we 6087 // need to to provide an address for the memory input. 6088 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6089 !OpInfo.isIndirect) { 6090 assert((OpInfo.isMultipleAlternative || 6091 (OpInfo.Type == InlineAsm::isInput)) && 6092 "Can only indirectify direct input operands!"); 6093 6094 // Memory operands really want the address of the value. If we don't have 6095 // an indirect input, put it in the constpool if we can, otherwise spill 6096 // it to a stack slot. 6097 // TODO: This isn't quite right. We need to handle these according to 6098 // the addressing mode that the constraint wants. Also, this may take 6099 // an additional register for the computation and we don't want that 6100 // either. 6101 6102 // If the operand is a float, integer, or vector constant, spill to a 6103 // constant pool entry to get its address. 6104 const Value *OpVal = OpInfo.CallOperandVal; 6105 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6106 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6107 OpInfo.CallOperand = DAG.getConstantPool( 6108 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 6109 } else { 6110 // Otherwise, create a stack slot and emit a store to it before the 6111 // asm. 6112 Type *Ty = OpVal->getType(); 6113 auto &DL = DAG.getDataLayout(); 6114 uint64_t TySize = DL.getTypeAllocSize(Ty); 6115 unsigned Align = DL.getPrefTypeAlignment(Ty); 6116 MachineFunction &MF = DAG.getMachineFunction(); 6117 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6118 SDValue StackSlot = 6119 DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout())); 6120 Chain = DAG.getStore( 6121 Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot, 6122 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), 6123 false, false, 0); 6124 OpInfo.CallOperand = StackSlot; 6125 } 6126 6127 // There is no longer a Value* corresponding to this operand. 6128 OpInfo.CallOperandVal = nullptr; 6129 6130 // It is now an indirect operand. 6131 OpInfo.isIndirect = true; 6132 } 6133 6134 // If this constraint is for a specific register, allocate it before 6135 // anything else. 6136 if (OpInfo.ConstraintType == TargetLowering::C_Register) 6137 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6138 } 6139 6140 // Second pass - Loop over all of the operands, assigning virtual or physregs 6141 // to register class operands. 6142 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6143 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6144 6145 // C_Register operands have already been allocated, Other/Memory don't need 6146 // to be. 6147 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 6148 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6149 } 6150 6151 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 6152 std::vector<SDValue> AsmNodeOperands; 6153 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 6154 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 6155 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 6156 6157 // If we have a !srcloc metadata node associated with it, we want to attach 6158 // this to the ultimately generated inline asm machineinstr. To do this, we 6159 // pass in the third operand as this (potentially null) inline asm MDNode. 6160 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 6161 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 6162 6163 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6164 // bits as operand 3. 6165 unsigned ExtraInfo = 0; 6166 if (IA->hasSideEffects()) 6167 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 6168 if (IA->isAlignStack()) 6169 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 6170 // Set the asm dialect. 6171 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 6172 6173 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 6174 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6175 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 6176 6177 // Compute the constraint code and ConstraintType to use. 6178 TLI.ComputeConstraintToUse(OpInfo, SDValue()); 6179 6180 // Ideally, we would only check against memory constraints. However, the 6181 // meaning of an other constraint can be target-specific and we can't easily 6182 // reason about it. Therefore, be conservative and set MayLoad/MayStore 6183 // for other constriants as well. 6184 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 6185 OpInfo.ConstraintType == TargetLowering::C_Other) { 6186 if (OpInfo.Type == InlineAsm::isInput) 6187 ExtraInfo |= InlineAsm::Extra_MayLoad; 6188 else if (OpInfo.Type == InlineAsm::isOutput) 6189 ExtraInfo |= InlineAsm::Extra_MayStore; 6190 else if (OpInfo.Type == InlineAsm::isClobber) 6191 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 6192 } 6193 } 6194 6195 AsmNodeOperands.push_back(DAG.getTargetConstant( 6196 ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6197 6198 // Loop over all of the inputs, copying the operand values into the 6199 // appropriate registers and processing the output regs. 6200 RegsForValue RetValRegs; 6201 6202 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 6203 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 6204 6205 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6206 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6207 6208 switch (OpInfo.Type) { 6209 case InlineAsm::isOutput: { 6210 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 6211 OpInfo.ConstraintType != TargetLowering::C_Register) { 6212 // Memory output, or 'other' output (e.g. 'X' constraint). 6213 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 6214 6215 unsigned ConstraintID = 6216 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6217 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6218 "Failed to convert memory constraint code to constraint id."); 6219 6220 // Add information to the INLINEASM node to know about this output. 6221 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6222 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 6223 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 6224 MVT::i32)); 6225 AsmNodeOperands.push_back(OpInfo.CallOperand); 6226 break; 6227 } 6228 6229 // Otherwise, this is a register or register class output. 6230 6231 // Copy the output from the appropriate register. Find a register that 6232 // we can use. 6233 if (OpInfo.AssignedRegs.Regs.empty()) { 6234 LLVMContext &Ctx = *DAG.getContext(); 6235 Ctx.emitError(CS.getInstruction(), 6236 "couldn't allocate output register for constraint '" + 6237 Twine(OpInfo.ConstraintCode) + "'"); 6238 return; 6239 } 6240 6241 // If this is an indirect operand, store through the pointer after the 6242 // asm. 6243 if (OpInfo.isIndirect) { 6244 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 6245 OpInfo.CallOperandVal)); 6246 } else { 6247 // This is the result value of the call. 6248 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6249 // Concatenate this output onto the outputs list. 6250 RetValRegs.append(OpInfo.AssignedRegs); 6251 } 6252 6253 // Add information to the INLINEASM node to know that this register is 6254 // set. 6255 OpInfo.AssignedRegs 6256 .AddInlineAsmOperands(OpInfo.isEarlyClobber 6257 ? InlineAsm::Kind_RegDefEarlyClobber 6258 : InlineAsm::Kind_RegDef, 6259 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 6260 break; 6261 } 6262 case InlineAsm::isInput: { 6263 SDValue InOperandVal = OpInfo.CallOperand; 6264 6265 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 6266 // If this is required to match an output register we have already set, 6267 // just use its register. 6268 unsigned OperandNo = OpInfo.getMatchedOperand(); 6269 6270 // Scan until we find the definition we already emitted of this operand. 6271 // When we find it, create a RegsForValue operand. 6272 unsigned CurOp = InlineAsm::Op_FirstOperand; 6273 for (; OperandNo; --OperandNo) { 6274 // Advance to the next operand. 6275 unsigned OpFlag = 6276 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6277 assert((InlineAsm::isRegDefKind(OpFlag) || 6278 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 6279 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 6280 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 6281 } 6282 6283 unsigned OpFlag = 6284 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6285 if (InlineAsm::isRegDefKind(OpFlag) || 6286 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 6287 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 6288 if (OpInfo.isIndirect) { 6289 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 6290 LLVMContext &Ctx = *DAG.getContext(); 6291 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 6292 " don't know how to handle tied " 6293 "indirect register inputs"); 6294 return; 6295 } 6296 6297 RegsForValue MatchedRegs; 6298 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 6299 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 6300 MatchedRegs.RegVTs.push_back(RegVT); 6301 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 6302 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 6303 i != e; ++i) { 6304 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 6305 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC)); 6306 else { 6307 LLVMContext &Ctx = *DAG.getContext(); 6308 Ctx.emitError(CS.getInstruction(), 6309 "inline asm error: This value" 6310 " type register class is not natively supported!"); 6311 return; 6312 } 6313 } 6314 SDLoc dl = getCurSDLoc(); 6315 // Use the produced MatchedRegs object to 6316 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, 6317 Chain, &Flag, CS.getInstruction()); 6318 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 6319 true, OpInfo.getMatchedOperand(), dl, 6320 DAG, AsmNodeOperands); 6321 break; 6322 } 6323 6324 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 6325 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 6326 "Unexpected number of operands"); 6327 // Add information to the INLINEASM node to know about this input. 6328 // See InlineAsm.h isUseOperandTiedToDef. 6329 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 6330 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 6331 OpInfo.getMatchedOperand()); 6332 AsmNodeOperands.push_back(DAG.getTargetConstant( 6333 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6334 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 6335 break; 6336 } 6337 6338 // Treat indirect 'X' constraint as memory. 6339 if (OpInfo.ConstraintType == TargetLowering::C_Other && 6340 OpInfo.isIndirect) 6341 OpInfo.ConstraintType = TargetLowering::C_Memory; 6342 6343 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 6344 std::vector<SDValue> Ops; 6345 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 6346 Ops, DAG); 6347 if (Ops.empty()) { 6348 LLVMContext &Ctx = *DAG.getContext(); 6349 Ctx.emitError(CS.getInstruction(), 6350 "invalid operand for inline asm constraint '" + 6351 Twine(OpInfo.ConstraintCode) + "'"); 6352 return; 6353 } 6354 6355 // Add information to the INLINEASM node to know about this input. 6356 unsigned ResOpType = 6357 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 6358 AsmNodeOperands.push_back(DAG.getTargetConstant( 6359 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6360 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 6361 break; 6362 } 6363 6364 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 6365 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 6366 assert(InOperandVal.getValueType() == 6367 TLI.getPointerTy(DAG.getDataLayout()) && 6368 "Memory operands expect pointer values"); 6369 6370 unsigned ConstraintID = 6371 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6372 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6373 "Failed to convert memory constraint code to constraint id."); 6374 6375 // Add information to the INLINEASM node to know about this input. 6376 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6377 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 6378 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6379 getCurSDLoc(), 6380 MVT::i32)); 6381 AsmNodeOperands.push_back(InOperandVal); 6382 break; 6383 } 6384 6385 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 6386 OpInfo.ConstraintType == TargetLowering::C_Register) && 6387 "Unknown constraint type!"); 6388 6389 // TODO: Support this. 6390 if (OpInfo.isIndirect) { 6391 LLVMContext &Ctx = *DAG.getContext(); 6392 Ctx.emitError(CS.getInstruction(), 6393 "Don't know how to handle indirect register inputs yet " 6394 "for constraint '" + 6395 Twine(OpInfo.ConstraintCode) + "'"); 6396 return; 6397 } 6398 6399 // Copy the input into the appropriate registers. 6400 if (OpInfo.AssignedRegs.Regs.empty()) { 6401 LLVMContext &Ctx = *DAG.getContext(); 6402 Ctx.emitError(CS.getInstruction(), 6403 "couldn't allocate input reg for constraint '" + 6404 Twine(OpInfo.ConstraintCode) + "'"); 6405 return; 6406 } 6407 6408 SDLoc dl = getCurSDLoc(); 6409 6410 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 6411 Chain, &Flag, CS.getInstruction()); 6412 6413 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 6414 dl, DAG, AsmNodeOperands); 6415 break; 6416 } 6417 case InlineAsm::isClobber: { 6418 // Add the clobbered value to the operand list, so that the register 6419 // allocator is aware that the physreg got clobbered. 6420 if (!OpInfo.AssignedRegs.Regs.empty()) 6421 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 6422 false, 0, getCurSDLoc(), DAG, 6423 AsmNodeOperands); 6424 break; 6425 } 6426 } 6427 } 6428 6429 // Finish up input operands. Set the input chain and add the flag last. 6430 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 6431 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 6432 6433 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 6434 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 6435 Flag = Chain.getValue(1); 6436 6437 // If this asm returns a register value, copy the result from that register 6438 // and set it as the value of the call. 6439 if (!RetValRegs.Regs.empty()) { 6440 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6441 Chain, &Flag, CS.getInstruction()); 6442 6443 // FIXME: Why don't we do this for inline asms with MRVs? 6444 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 6445 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 6446 6447 // If any of the results of the inline asm is a vector, it may have the 6448 // wrong width/num elts. This can happen for register classes that can 6449 // contain multiple different value types. The preg or vreg allocated may 6450 // not have the same VT as was expected. Convert it to the right type 6451 // with bit_convert. 6452 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 6453 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 6454 ResultType, Val); 6455 6456 } else if (ResultType != Val.getValueType() && 6457 ResultType.isInteger() && Val.getValueType().isInteger()) { 6458 // If a result value was tied to an input value, the computed result may 6459 // have a wider width than the expected result. Extract the relevant 6460 // portion. 6461 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 6462 } 6463 6464 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 6465 } 6466 6467 setValue(CS.getInstruction(), Val); 6468 // Don't need to use this as a chain in this case. 6469 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 6470 return; 6471 } 6472 6473 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 6474 6475 // Process indirect outputs, first output all of the flagged copies out of 6476 // physregs. 6477 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 6478 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 6479 const Value *Ptr = IndirectStoresToEmit[i].second; 6480 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6481 Chain, &Flag, IA); 6482 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 6483 } 6484 6485 // Emit the non-flagged stores from the physregs. 6486 SmallVector<SDValue, 8> OutChains; 6487 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 6488 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), 6489 StoresToEmit[i].first, 6490 getValue(StoresToEmit[i].second), 6491 MachinePointerInfo(StoresToEmit[i].second), 6492 false, false, 0); 6493 OutChains.push_back(Val); 6494 } 6495 6496 if (!OutChains.empty()) 6497 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 6498 6499 DAG.setRoot(Chain); 6500 } 6501 6502 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 6503 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 6504 MVT::Other, getRoot(), 6505 getValue(I.getArgOperand(0)), 6506 DAG.getSrcValue(I.getArgOperand(0)))); 6507 } 6508 6509 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 6510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6511 const DataLayout &DL = DAG.getDataLayout(); 6512 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6513 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 6514 DAG.getSrcValue(I.getOperand(0)), 6515 DL.getABITypeAlignment(I.getType())); 6516 setValue(&I, V); 6517 DAG.setRoot(V.getValue(1)); 6518 } 6519 6520 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 6521 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 6522 MVT::Other, getRoot(), 6523 getValue(I.getArgOperand(0)), 6524 DAG.getSrcValue(I.getArgOperand(0)))); 6525 } 6526 6527 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 6528 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 6529 MVT::Other, getRoot(), 6530 getValue(I.getArgOperand(0)), 6531 getValue(I.getArgOperand(1)), 6532 DAG.getSrcValue(I.getArgOperand(0)), 6533 DAG.getSrcValue(I.getArgOperand(1)))); 6534 } 6535 6536 /// \brief Lower an argument list according to the target calling convention. 6537 /// 6538 /// \return A tuple of <return-value, token-chain> 6539 /// 6540 /// This is a helper for lowering intrinsics that follow a target calling 6541 /// convention or require stack pointer adjustment. Only a subset of the 6542 /// intrinsic's operands need to participate in the calling convention. 6543 std::pair<SDValue, SDValue> 6544 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx, 6545 unsigned NumArgs, SDValue Callee, 6546 Type *ReturnTy, 6547 MachineBasicBlock *LandingPad, 6548 bool IsPatchPoint) { 6549 TargetLowering::ArgListTy Args; 6550 Args.reserve(NumArgs); 6551 6552 // Populate the argument list. 6553 // Attributes for args start at offset 1, after the return attribute. 6554 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1; 6555 ArgI != ArgE; ++ArgI) { 6556 const Value *V = CS->getOperand(ArgI); 6557 6558 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 6559 6560 TargetLowering::ArgListEntry Entry; 6561 Entry.Node = getValue(V); 6562 Entry.Ty = V->getType(); 6563 Entry.setAttributes(&CS, AttrI); 6564 Args.push_back(Entry); 6565 } 6566 6567 TargetLowering::CallLoweringInfo CLI(DAG); 6568 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot()) 6569 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs) 6570 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint); 6571 6572 return lowerInvokable(CLI, LandingPad); 6573 } 6574 6575 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 6576 /// or patchpoint target node's operand list. 6577 /// 6578 /// Constants are converted to TargetConstants purely as an optimization to 6579 /// avoid constant materialization and register allocation. 6580 /// 6581 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 6582 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 6583 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 6584 /// address materialization and register allocation, but may also be required 6585 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 6586 /// alloca in the entry block, then the runtime may assume that the alloca's 6587 /// StackMap location can be read immediately after compilation and that the 6588 /// location is valid at any point during execution (this is similar to the 6589 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 6590 /// only available in a register, then the runtime would need to trap when 6591 /// execution reaches the StackMap in order to read the alloca's location. 6592 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 6593 SDLoc DL, SmallVectorImpl<SDValue> &Ops, 6594 SelectionDAGBuilder &Builder) { 6595 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 6596 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 6597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 6598 Ops.push_back( 6599 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 6600 Ops.push_back( 6601 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 6602 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 6603 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 6604 Ops.push_back(Builder.DAG.getTargetFrameIndex( 6605 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout()))); 6606 } else 6607 Ops.push_back(OpVal); 6608 } 6609 } 6610 6611 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 6612 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 6613 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 6614 // [live variables...]) 6615 6616 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 6617 6618 SDValue Chain, InFlag, Callee, NullPtr; 6619 SmallVector<SDValue, 32> Ops; 6620 6621 SDLoc DL = getCurSDLoc(); 6622 Callee = getValue(CI.getCalledValue()); 6623 NullPtr = DAG.getIntPtrConstant(0, DL, true); 6624 6625 // The stackmap intrinsic only records the live variables (the arguemnts 6626 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 6627 // intrinsic, this won't be lowered to a function call. This means we don't 6628 // have to worry about calling conventions and target specific lowering code. 6629 // Instead we perform the call lowering right here. 6630 // 6631 // chain, flag = CALLSEQ_START(chain, 0) 6632 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 6633 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 6634 // 6635 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL); 6636 InFlag = Chain.getValue(1); 6637 6638 // Add the <id> and <numBytes> constants. 6639 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 6640 Ops.push_back(DAG.getTargetConstant( 6641 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 6642 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 6643 Ops.push_back(DAG.getTargetConstant( 6644 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 6645 MVT::i32)); 6646 6647 // Push live variables for the stack map. 6648 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 6649 6650 // We are not pushing any register mask info here on the operands list, 6651 // because the stackmap doesn't clobber anything. 6652 6653 // Push the chain and the glue flag. 6654 Ops.push_back(Chain); 6655 Ops.push_back(InFlag); 6656 6657 // Create the STACKMAP node. 6658 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6659 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 6660 Chain = SDValue(SM, 0); 6661 InFlag = Chain.getValue(1); 6662 6663 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 6664 6665 // Stackmaps don't generate values, so nothing goes into the NodeMap. 6666 6667 // Set the root to the target-lowered call chain. 6668 DAG.setRoot(Chain); 6669 6670 // Inform the Frame Information that we have a stackmap in this function. 6671 FuncInfo.MF->getFrameInfo()->setHasStackMap(); 6672 } 6673 6674 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 6675 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 6676 MachineBasicBlock *LandingPad) { 6677 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 6678 // i32 <numBytes>, 6679 // i8* <target>, 6680 // i32 <numArgs>, 6681 // [Args...], 6682 // [live variables...]) 6683 6684 CallingConv::ID CC = CS.getCallingConv(); 6685 bool IsAnyRegCC = CC == CallingConv::AnyReg; 6686 bool HasDef = !CS->getType()->isVoidTy(); 6687 SDLoc dl = getCurSDLoc(); 6688 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 6689 6690 // Handle immediate and symbolic callees. 6691 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 6692 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 6693 /*isTarget=*/true); 6694 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 6695 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 6696 SDLoc(SymbolicCallee), 6697 SymbolicCallee->getValueType(0)); 6698 6699 // Get the real number of arguments participating in the call <numArgs> 6700 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 6701 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 6702 6703 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 6704 // Intrinsics include all meta-operands up to but not including CC. 6705 unsigned NumMetaOpers = PatchPointOpers::CCPos; 6706 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 6707 "Not enough arguments provided to the patchpoint intrinsic"); 6708 6709 // For AnyRegCC the arguments are lowered later on manually. 6710 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 6711 Type *ReturnTy = 6712 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 6713 std::pair<SDValue, SDValue> Result = 6714 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 6715 LandingPad, true); 6716 6717 SDNode *CallEnd = Result.second.getNode(); 6718 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 6719 CallEnd = CallEnd->getOperand(0).getNode(); 6720 6721 /// Get a call instruction from the call sequence chain. 6722 /// Tail calls are not allowed. 6723 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 6724 "Expected a callseq node."); 6725 SDNode *Call = CallEnd->getOperand(0).getNode(); 6726 bool HasGlue = Call->getGluedNode(); 6727 6728 // Replace the target specific call node with the patchable intrinsic. 6729 SmallVector<SDValue, 8> Ops; 6730 6731 // Add the <id> and <numBytes> constants. 6732 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 6733 Ops.push_back(DAG.getTargetConstant( 6734 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 6735 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 6736 Ops.push_back(DAG.getTargetConstant( 6737 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 6738 MVT::i32)); 6739 6740 // Add the callee. 6741 Ops.push_back(Callee); 6742 6743 // Adjust <numArgs> to account for any arguments that have been passed on the 6744 // stack instead. 6745 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 6746 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 6747 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 6748 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 6749 6750 // Add the calling convention 6751 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 6752 6753 // Add the arguments we omitted previously. The register allocator should 6754 // place these in any free register. 6755 if (IsAnyRegCC) 6756 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 6757 Ops.push_back(getValue(CS.getArgument(i))); 6758 6759 // Push the arguments from the call instruction up to the register mask. 6760 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 6761 Ops.append(Call->op_begin() + 2, e); 6762 6763 // Push live variables for the stack map. 6764 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 6765 6766 // Push the register mask info. 6767 if (HasGlue) 6768 Ops.push_back(*(Call->op_end()-2)); 6769 else 6770 Ops.push_back(*(Call->op_end()-1)); 6771 6772 // Push the chain (this is originally the first operand of the call, but 6773 // becomes now the last or second to last operand). 6774 Ops.push_back(*(Call->op_begin())); 6775 6776 // Push the glue flag (last operand). 6777 if (HasGlue) 6778 Ops.push_back(*(Call->op_end()-1)); 6779 6780 SDVTList NodeTys; 6781 if (IsAnyRegCC && HasDef) { 6782 // Create the return types based on the intrinsic definition 6783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6784 SmallVector<EVT, 3> ValueVTs; 6785 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 6786 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 6787 6788 // There is always a chain and a glue type at the end 6789 ValueVTs.push_back(MVT::Other); 6790 ValueVTs.push_back(MVT::Glue); 6791 NodeTys = DAG.getVTList(ValueVTs); 6792 } else 6793 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6794 6795 // Replace the target specific call node with a PATCHPOINT node. 6796 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 6797 dl, NodeTys, Ops); 6798 6799 // Update the NodeMap. 6800 if (HasDef) { 6801 if (IsAnyRegCC) 6802 setValue(CS.getInstruction(), SDValue(MN, 0)); 6803 else 6804 setValue(CS.getInstruction(), Result.first); 6805 } 6806 6807 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 6808 // call sequence. Furthermore the location of the chain and glue can change 6809 // when the AnyReg calling convention is used and the intrinsic returns a 6810 // value. 6811 if (IsAnyRegCC && HasDef) { 6812 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 6813 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 6814 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 6815 } else 6816 DAG.ReplaceAllUsesWith(Call, MN); 6817 DAG.DeleteNode(Call); 6818 6819 // Inform the Frame Information that we have a patchpoint in this function. 6820 FuncInfo.MF->getFrameInfo()->setHasPatchPoint(); 6821 } 6822 6823 /// Returns an AttributeSet representing the attributes applied to the return 6824 /// value of the given call. 6825 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 6826 SmallVector<Attribute::AttrKind, 2> Attrs; 6827 if (CLI.RetSExt) 6828 Attrs.push_back(Attribute::SExt); 6829 if (CLI.RetZExt) 6830 Attrs.push_back(Attribute::ZExt); 6831 if (CLI.IsInReg) 6832 Attrs.push_back(Attribute::InReg); 6833 6834 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex, 6835 Attrs); 6836 } 6837 6838 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 6839 /// implementation, which just calls LowerCall. 6840 /// FIXME: When all targets are 6841 /// migrated to using LowerCall, this hook should be integrated into SDISel. 6842 std::pair<SDValue, SDValue> 6843 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 6844 // Handle the incoming return values from the call. 6845 CLI.Ins.clear(); 6846 Type *OrigRetTy = CLI.RetTy; 6847 SmallVector<EVT, 4> RetTys; 6848 SmallVector<uint64_t, 4> Offsets; 6849 auto &DL = CLI.DAG.getDataLayout(); 6850 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 6851 6852 SmallVector<ISD::OutputArg, 4> Outs; 6853 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 6854 6855 bool CanLowerReturn = 6856 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 6857 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 6858 6859 SDValue DemoteStackSlot; 6860 int DemoteStackIdx = -100; 6861 if (!CanLowerReturn) { 6862 // FIXME: equivalent assert? 6863 // assert(!CS.hasInAllocaArgument() && 6864 // "sret demotion is incompatible with inalloca"); 6865 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 6866 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 6867 MachineFunction &MF = CLI.DAG.getMachineFunction(); 6868 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6869 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 6870 6871 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL)); 6872 ArgListEntry Entry; 6873 Entry.Node = DemoteStackSlot; 6874 Entry.Ty = StackSlotPtrType; 6875 Entry.isSExt = false; 6876 Entry.isZExt = false; 6877 Entry.isInReg = false; 6878 Entry.isSRet = true; 6879 Entry.isNest = false; 6880 Entry.isByVal = false; 6881 Entry.isReturned = false; 6882 Entry.Alignment = Align; 6883 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 6884 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 6885 6886 // sret demotion isn't compatible with tail-calls, since the sret argument 6887 // points into the callers stack frame. 6888 CLI.IsTailCall = false; 6889 } else { 6890 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6891 EVT VT = RetTys[I]; 6892 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 6893 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 6894 for (unsigned i = 0; i != NumRegs; ++i) { 6895 ISD::InputArg MyFlags; 6896 MyFlags.VT = RegisterVT; 6897 MyFlags.ArgVT = VT; 6898 MyFlags.Used = CLI.IsReturnValueUsed; 6899 if (CLI.RetSExt) 6900 MyFlags.Flags.setSExt(); 6901 if (CLI.RetZExt) 6902 MyFlags.Flags.setZExt(); 6903 if (CLI.IsInReg) 6904 MyFlags.Flags.setInReg(); 6905 CLI.Ins.push_back(MyFlags); 6906 } 6907 } 6908 } 6909 6910 // Handle all of the outgoing arguments. 6911 CLI.Outs.clear(); 6912 CLI.OutVals.clear(); 6913 ArgListTy &Args = CLI.getArgs(); 6914 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6915 SmallVector<EVT, 4> ValueVTs; 6916 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 6917 Type *FinalType = Args[i].Ty; 6918 if (Args[i].isByVal) 6919 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 6920 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 6921 FinalType, CLI.CallConv, CLI.IsVarArg); 6922 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 6923 ++Value) { 6924 EVT VT = ValueVTs[Value]; 6925 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 6926 SDValue Op = SDValue(Args[i].Node.getNode(), 6927 Args[i].Node.getResNo() + Value); 6928 ISD::ArgFlagsTy Flags; 6929 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 6930 6931 if (Args[i].isZExt) 6932 Flags.setZExt(); 6933 if (Args[i].isSExt) 6934 Flags.setSExt(); 6935 if (Args[i].isInReg) 6936 Flags.setInReg(); 6937 if (Args[i].isSRet) 6938 Flags.setSRet(); 6939 if (Args[i].isByVal) 6940 Flags.setByVal(); 6941 if (Args[i].isInAlloca) { 6942 Flags.setInAlloca(); 6943 // Set the byval flag for CCAssignFn callbacks that don't know about 6944 // inalloca. This way we can know how many bytes we should've allocated 6945 // and how many bytes a callee cleanup function will pop. If we port 6946 // inalloca to more targets, we'll have to add custom inalloca handling 6947 // in the various CC lowering callbacks. 6948 Flags.setByVal(); 6949 } 6950 if (Args[i].isByVal || Args[i].isInAlloca) { 6951 PointerType *Ty = cast<PointerType>(Args[i].Ty); 6952 Type *ElementTy = Ty->getElementType(); 6953 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 6954 // For ByVal, alignment should come from FE. BE will guess if this 6955 // info is not there but there are cases it cannot get right. 6956 unsigned FrameAlign; 6957 if (Args[i].Alignment) 6958 FrameAlign = Args[i].Alignment; 6959 else 6960 FrameAlign = getByValTypeAlignment(ElementTy, DL); 6961 Flags.setByValAlign(FrameAlign); 6962 } 6963 if (Args[i].isNest) 6964 Flags.setNest(); 6965 if (NeedsRegBlock) 6966 Flags.setInConsecutiveRegs(); 6967 Flags.setOrigAlign(OriginalAlignment); 6968 6969 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT); 6970 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT); 6971 SmallVector<SDValue, 4> Parts(NumParts); 6972 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6973 6974 if (Args[i].isSExt) 6975 ExtendKind = ISD::SIGN_EXTEND; 6976 else if (Args[i].isZExt) 6977 ExtendKind = ISD::ZERO_EXTEND; 6978 6979 // Conservatively only handle 'returned' on non-vectors for now 6980 if (Args[i].isReturned && !Op.getValueType().isVector()) { 6981 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 6982 "unexpected use of 'returned'"); 6983 // Before passing 'returned' to the target lowering code, ensure that 6984 // either the register MVT and the actual EVT are the same size or that 6985 // the return value and argument are extended in the same way; in these 6986 // cases it's safe to pass the argument register value unchanged as the 6987 // return register value (although it's at the target's option whether 6988 // to do so) 6989 // TODO: allow code generation to take advantage of partially preserved 6990 // registers rather than clobbering the entire register when the 6991 // parameter extension method is not compatible with the return 6992 // extension method 6993 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 6994 (ExtendKind != ISD::ANY_EXTEND && 6995 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt)) 6996 Flags.setReturned(); 6997 } 6998 6999 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 7000 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind); 7001 7002 for (unsigned j = 0; j != NumParts; ++j) { 7003 // if it isn't first piece, alignment must be 1 7004 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 7005 i < CLI.NumFixedArgs, 7006 i, j*Parts[j].getValueType().getStoreSize()); 7007 if (NumParts > 1 && j == 0) 7008 MyFlags.Flags.setSplit(); 7009 else if (j != 0) 7010 MyFlags.Flags.setOrigAlign(1); 7011 7012 CLI.Outs.push_back(MyFlags); 7013 CLI.OutVals.push_back(Parts[j]); 7014 } 7015 7016 if (NeedsRegBlock && Value == NumValues - 1) 7017 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 7018 } 7019 } 7020 7021 SmallVector<SDValue, 4> InVals; 7022 CLI.Chain = LowerCall(CLI, InVals); 7023 7024 // Verify that the target's LowerCall behaved as expected. 7025 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 7026 "LowerCall didn't return a valid chain!"); 7027 assert((!CLI.IsTailCall || InVals.empty()) && 7028 "LowerCall emitted a return value for a tail call!"); 7029 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 7030 "LowerCall didn't emit the correct number of values!"); 7031 7032 // For a tail call, the return value is merely live-out and there aren't 7033 // any nodes in the DAG representing it. Return a special value to 7034 // indicate that a tail call has been emitted and no more Instructions 7035 // should be processed in the current block. 7036 if (CLI.IsTailCall) { 7037 CLI.DAG.setRoot(CLI.Chain); 7038 return std::make_pair(SDValue(), SDValue()); 7039 } 7040 7041 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 7042 assert(InVals[i].getNode() && 7043 "LowerCall emitted a null value!"); 7044 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 7045 "LowerCall emitted a value with the wrong type!"); 7046 }); 7047 7048 SmallVector<SDValue, 4> ReturnValues; 7049 if (!CanLowerReturn) { 7050 // The instruction result is the result of loading from the 7051 // hidden sret parameter. 7052 SmallVector<EVT, 1> PVTs; 7053 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy); 7054 7055 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 7056 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 7057 EVT PtrVT = PVTs[0]; 7058 7059 unsigned NumValues = RetTys.size(); 7060 ReturnValues.resize(NumValues); 7061 SmallVector<SDValue, 4> Chains(NumValues); 7062 7063 for (unsigned i = 0; i < NumValues; ++i) { 7064 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 7065 CLI.DAG.getConstant(Offsets[i], CLI.DL, 7066 PtrVT)); 7067 SDValue L = CLI.DAG.getLoad( 7068 RetTys[i], CLI.DL, CLI.Chain, Add, 7069 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 7070 DemoteStackIdx, Offsets[i]), 7071 false, false, false, 1); 7072 ReturnValues[i] = L; 7073 Chains[i] = L.getValue(1); 7074 } 7075 7076 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 7077 } else { 7078 // Collect the legal value parts into potentially illegal values 7079 // that correspond to the original function's return values. 7080 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7081 if (CLI.RetSExt) 7082 AssertOp = ISD::AssertSext; 7083 else if (CLI.RetZExt) 7084 AssertOp = ISD::AssertZext; 7085 unsigned CurReg = 0; 7086 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7087 EVT VT = RetTys[I]; 7088 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7089 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7090 7091 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 7092 NumRegs, RegisterVT, VT, nullptr, 7093 AssertOp)); 7094 CurReg += NumRegs; 7095 } 7096 7097 // For a function returning void, there is no return value. We can't create 7098 // such a node, so we just return a null return value in that case. In 7099 // that case, nothing will actually look at the value. 7100 if (ReturnValues.empty()) 7101 return std::make_pair(SDValue(), CLI.Chain); 7102 } 7103 7104 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 7105 CLI.DAG.getVTList(RetTys), ReturnValues); 7106 return std::make_pair(Res, CLI.Chain); 7107 } 7108 7109 void TargetLowering::LowerOperationWrapper(SDNode *N, 7110 SmallVectorImpl<SDValue> &Results, 7111 SelectionDAG &DAG) const { 7112 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 7113 if (Res.getNode()) 7114 Results.push_back(Res); 7115 } 7116 7117 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7118 llvm_unreachable("LowerOperation not implemented for this target!"); 7119 } 7120 7121 void 7122 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 7123 SDValue Op = getNonRegisterValue(V); 7124 assert((Op.getOpcode() != ISD::CopyFromReg || 7125 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 7126 "Copy from a reg to the same reg!"); 7127 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 7128 7129 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7130 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 7131 V->getType()); 7132 SDValue Chain = DAG.getEntryNode(); 7133 7134 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 7135 FuncInfo.PreferredExtendType.end()) 7136 ? ISD::ANY_EXTEND 7137 : FuncInfo.PreferredExtendType[V]; 7138 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 7139 PendingExports.push_back(Chain); 7140 } 7141 7142 #include "llvm/CodeGen/SelectionDAGISel.h" 7143 7144 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 7145 /// entry block, return true. This includes arguments used by switches, since 7146 /// the switch may expand into multiple basic blocks. 7147 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 7148 // With FastISel active, we may be splitting blocks, so force creation 7149 // of virtual registers for all non-dead arguments. 7150 if (FastISel) 7151 return A->use_empty(); 7152 7153 const BasicBlock *Entry = A->getParent()->begin(); 7154 for (const User *U : A->users()) 7155 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U)) 7156 return false; // Use not in entry block. 7157 7158 return true; 7159 } 7160 7161 void SelectionDAGISel::LowerArguments(const Function &F) { 7162 SelectionDAG &DAG = SDB->DAG; 7163 SDLoc dl = SDB->getCurSDLoc(); 7164 const DataLayout &DL = DAG.getDataLayout(); 7165 SmallVector<ISD::InputArg, 16> Ins; 7166 7167 if (!FuncInfo->CanLowerReturn) { 7168 // Put in an sret pointer parameter before all the other parameters. 7169 SmallVector<EVT, 1> ValueVTs; 7170 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7171 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7172 7173 // NOTE: Assuming that a pointer will never break down to more than one VT 7174 // or one register. 7175 ISD::ArgFlagsTy Flags; 7176 Flags.setSRet(); 7177 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 7178 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 7179 ISD::InputArg::NoArgIndex, 0); 7180 Ins.push_back(RetArg); 7181 } 7182 7183 // Set up the incoming argument description vector. 7184 unsigned Idx = 1; 7185 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 7186 I != E; ++I, ++Idx) { 7187 SmallVector<EVT, 4> ValueVTs; 7188 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7189 bool isArgValueUsed = !I->use_empty(); 7190 unsigned PartBase = 0; 7191 Type *FinalType = I->getType(); 7192 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7193 FinalType = cast<PointerType>(FinalType)->getElementType(); 7194 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 7195 FinalType, F.getCallingConv(), F.isVarArg()); 7196 for (unsigned Value = 0, NumValues = ValueVTs.size(); 7197 Value != NumValues; ++Value) { 7198 EVT VT = ValueVTs[Value]; 7199 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7200 ISD::ArgFlagsTy Flags; 7201 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7202 7203 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7204 Flags.setZExt(); 7205 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7206 Flags.setSExt(); 7207 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg)) 7208 Flags.setInReg(); 7209 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet)) 7210 Flags.setSRet(); 7211 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7212 Flags.setByVal(); 7213 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) { 7214 Flags.setInAlloca(); 7215 // Set the byval flag for CCAssignFn callbacks that don't know about 7216 // inalloca. This way we can know how many bytes we should've allocated 7217 // and how many bytes a callee cleanup function will pop. If we port 7218 // inalloca to more targets, we'll have to add custom inalloca handling 7219 // in the various CC lowering callbacks. 7220 Flags.setByVal(); 7221 } 7222 if (Flags.isByVal() || Flags.isInAlloca()) { 7223 PointerType *Ty = cast<PointerType>(I->getType()); 7224 Type *ElementTy = Ty->getElementType(); 7225 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 7226 // For ByVal, alignment should be passed from FE. BE will guess if 7227 // this info is not there but there are cases it cannot get right. 7228 unsigned FrameAlign; 7229 if (F.getParamAlignment(Idx)) 7230 FrameAlign = F.getParamAlignment(Idx); 7231 else 7232 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 7233 Flags.setByValAlign(FrameAlign); 7234 } 7235 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest)) 7236 Flags.setNest(); 7237 if (NeedsRegBlock) 7238 Flags.setInConsecutiveRegs(); 7239 Flags.setOrigAlign(OriginalAlignment); 7240 7241 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7242 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7243 for (unsigned i = 0; i != NumRegs; ++i) { 7244 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 7245 Idx-1, PartBase+i*RegisterVT.getStoreSize()); 7246 if (NumRegs > 1 && i == 0) 7247 MyFlags.Flags.setSplit(); 7248 // if it isn't first piece, alignment must be 1 7249 else if (i > 0) 7250 MyFlags.Flags.setOrigAlign(1); 7251 Ins.push_back(MyFlags); 7252 } 7253 if (NeedsRegBlock && Value == NumValues - 1) 7254 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 7255 PartBase += VT.getStoreSize(); 7256 } 7257 } 7258 7259 // Call the target to set up the argument values. 7260 SmallVector<SDValue, 8> InVals; 7261 SDValue NewRoot = TLI->LowerFormalArguments( 7262 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 7263 7264 // Verify that the target's LowerFormalArguments behaved as expected. 7265 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 7266 "LowerFormalArguments didn't return a valid chain!"); 7267 assert(InVals.size() == Ins.size() && 7268 "LowerFormalArguments didn't emit the correct number of values!"); 7269 DEBUG({ 7270 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 7271 assert(InVals[i].getNode() && 7272 "LowerFormalArguments emitted a null value!"); 7273 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 7274 "LowerFormalArguments emitted a value with the wrong type!"); 7275 } 7276 }); 7277 7278 // Update the DAG with the new chain value resulting from argument lowering. 7279 DAG.setRoot(NewRoot); 7280 7281 // Set up the argument values. 7282 unsigned i = 0; 7283 Idx = 1; 7284 if (!FuncInfo->CanLowerReturn) { 7285 // Create a virtual register for the sret pointer, and put in a copy 7286 // from the sret argument into it. 7287 SmallVector<EVT, 1> ValueVTs; 7288 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7289 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7290 MVT VT = ValueVTs[0].getSimpleVT(); 7291 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7292 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7293 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 7294 RegVT, VT, nullptr, AssertOp); 7295 7296 MachineFunction& MF = SDB->DAG.getMachineFunction(); 7297 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 7298 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 7299 FuncInfo->DemoteRegister = SRetReg; 7300 NewRoot = 7301 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 7302 DAG.setRoot(NewRoot); 7303 7304 // i indexes lowered arguments. Bump it past the hidden sret argument. 7305 // Idx indexes LLVM arguments. Don't touch it. 7306 ++i; 7307 } 7308 7309 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 7310 ++I, ++Idx) { 7311 SmallVector<SDValue, 4> ArgValues; 7312 SmallVector<EVT, 4> ValueVTs; 7313 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7314 unsigned NumValues = ValueVTs.size(); 7315 7316 // If this argument is unused then remember its value. It is used to generate 7317 // debugging information. 7318 if (I->use_empty() && NumValues) { 7319 SDB->setUnusedArgValue(I, InVals[i]); 7320 7321 // Also remember any frame index for use in FastISel. 7322 if (FrameIndexSDNode *FI = 7323 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 7324 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7325 } 7326 7327 for (unsigned Val = 0; Val != NumValues; ++Val) { 7328 EVT VT = ValueVTs[Val]; 7329 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7330 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7331 7332 if (!I->use_empty()) { 7333 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7334 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7335 AssertOp = ISD::AssertSext; 7336 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7337 AssertOp = ISD::AssertZext; 7338 7339 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 7340 NumParts, PartVT, VT, 7341 nullptr, AssertOp)); 7342 } 7343 7344 i += NumParts; 7345 } 7346 7347 // We don't need to do anything else for unused arguments. 7348 if (ArgValues.empty()) 7349 continue; 7350 7351 // Note down frame index. 7352 if (FrameIndexSDNode *FI = 7353 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 7354 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7355 7356 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 7357 SDB->getCurSDLoc()); 7358 7359 SDB->setValue(I, Res); 7360 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 7361 if (LoadSDNode *LNode = 7362 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode())) 7363 if (FrameIndexSDNode *FI = 7364 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 7365 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7366 } 7367 7368 // If this argument is live outside of the entry block, insert a copy from 7369 // wherever we got it to the vreg that other BB's will reference it as. 7370 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 7371 // If we can, though, try to skip creating an unnecessary vreg. 7372 // FIXME: This isn't very clean... it would be nice to make this more 7373 // general. It's also subtly incompatible with the hacks FastISel 7374 // uses with vregs. 7375 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 7376 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 7377 FuncInfo->ValueMap[I] = Reg; 7378 continue; 7379 } 7380 } 7381 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) { 7382 FuncInfo->InitializeRegForValue(I); 7383 SDB->CopyToExportRegsIfNeeded(I); 7384 } 7385 } 7386 7387 assert(i == InVals.size() && "Argument register count mismatch!"); 7388 7389 // Finally, if the target has anything special to do, allow it to do so. 7390 EmitFunctionEntryCode(); 7391 } 7392 7393 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 7394 /// ensure constants are generated when needed. Remember the virtual registers 7395 /// that need to be added to the Machine PHI nodes as input. We cannot just 7396 /// directly add them, because expansion might result in multiple MBB's for one 7397 /// BB. As such, the start of the BB might correspond to a different MBB than 7398 /// the end. 7399 /// 7400 void 7401 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 7402 const TerminatorInst *TI = LLVMBB->getTerminator(); 7403 7404 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 7405 7406 // Check PHI nodes in successors that expect a value to be available from this 7407 // block. 7408 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 7409 const BasicBlock *SuccBB = TI->getSuccessor(succ); 7410 if (!isa<PHINode>(SuccBB->begin())) continue; 7411 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 7412 7413 // If this terminator has multiple identical successors (common for 7414 // switches), only handle each succ once. 7415 if (!SuccsHandled.insert(SuccMBB).second) 7416 continue; 7417 7418 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 7419 7420 // At this point we know that there is a 1-1 correspondence between LLVM PHI 7421 // nodes and Machine PHI nodes, but the incoming operands have not been 7422 // emitted yet. 7423 for (BasicBlock::const_iterator I = SuccBB->begin(); 7424 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 7425 // Ignore dead phi's. 7426 if (PN->use_empty()) continue; 7427 7428 // Skip empty types 7429 if (PN->getType()->isEmptyTy()) 7430 continue; 7431 7432 unsigned Reg; 7433 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 7434 7435 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 7436 unsigned &RegOut = ConstantsOut[C]; 7437 if (RegOut == 0) { 7438 RegOut = FuncInfo.CreateRegs(C->getType()); 7439 CopyValueToVirtualRegister(C, RegOut); 7440 } 7441 Reg = RegOut; 7442 } else { 7443 DenseMap<const Value *, unsigned>::iterator I = 7444 FuncInfo.ValueMap.find(PHIOp); 7445 if (I != FuncInfo.ValueMap.end()) 7446 Reg = I->second; 7447 else { 7448 assert(isa<AllocaInst>(PHIOp) && 7449 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 7450 "Didn't codegen value into a register!??"); 7451 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 7452 CopyValueToVirtualRegister(PHIOp, Reg); 7453 } 7454 } 7455 7456 // Remember that this register needs to added to the machine PHI node as 7457 // the input for this MBB. 7458 SmallVector<EVT, 4> ValueVTs; 7459 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7460 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs); 7461 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 7462 EVT VT = ValueVTs[vti]; 7463 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 7464 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 7465 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 7466 Reg += NumRegisters; 7467 } 7468 } 7469 } 7470 7471 ConstantsOut.clear(); 7472 } 7473 7474 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 7475 /// is 0. 7476 MachineBasicBlock * 7477 SelectionDAGBuilder::StackProtectorDescriptor:: 7478 AddSuccessorMBB(const BasicBlock *BB, 7479 MachineBasicBlock *ParentMBB, 7480 bool IsLikely, 7481 MachineBasicBlock *SuccMBB) { 7482 // If SuccBB has not been created yet, create it. 7483 if (!SuccMBB) { 7484 MachineFunction *MF = ParentMBB->getParent(); 7485 MachineFunction::iterator BBI = ParentMBB; 7486 SuccMBB = MF->CreateMachineBasicBlock(BB); 7487 MF->insert(++BBI, SuccMBB); 7488 } 7489 // Add it as a successor of ParentMBB. 7490 ParentMBB->addSuccessor( 7491 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely)); 7492 return SuccMBB; 7493 } 7494 7495 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 7496 MachineFunction::iterator I = MBB; 7497 if (++I == FuncInfo.MF->end()) 7498 return nullptr; 7499 return I; 7500 } 7501 7502 /// During lowering new call nodes can be created (such as memset, etc.). 7503 /// Those will become new roots of the current DAG, but complications arise 7504 /// when they are tail calls. In such cases, the call lowering will update 7505 /// the root, but the builder still needs to know that a tail call has been 7506 /// lowered in order to avoid generating an additional return. 7507 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 7508 // If the node is null, we do have a tail call. 7509 if (MaybeTC.getNode() != nullptr) 7510 DAG.setRoot(MaybeTC); 7511 else 7512 HasTailCall = true; 7513 } 7514 7515 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters, 7516 unsigned *TotalCases, unsigned First, 7517 unsigned Last) { 7518 assert(Last >= First); 7519 assert(TotalCases[Last] >= TotalCases[First]); 7520 7521 APInt LowCase = Clusters[First].Low->getValue(); 7522 APInt HighCase = Clusters[Last].High->getValue(); 7523 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 7524 7525 // FIXME: A range of consecutive cases has 100% density, but only requires one 7526 // comparison to lower. We should discriminate against such consecutive ranges 7527 // in jump tables. 7528 7529 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100); 7530 uint64_t Range = Diff + 1; 7531 7532 uint64_t NumCases = 7533 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 7534 7535 assert(NumCases < UINT64_MAX / 100); 7536 assert(Range >= NumCases); 7537 7538 return NumCases * 100 >= Range * MinJumpTableDensity; 7539 } 7540 7541 static inline bool areJTsAllowed(const TargetLowering &TLI) { 7542 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 7543 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other); 7544 } 7545 7546 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters, 7547 unsigned First, unsigned Last, 7548 const SwitchInst *SI, 7549 MachineBasicBlock *DefaultMBB, 7550 CaseCluster &JTCluster) { 7551 assert(First <= Last); 7552 7553 uint32_t Weight = 0; 7554 unsigned NumCmps = 0; 7555 std::vector<MachineBasicBlock*> Table; 7556 DenseMap<MachineBasicBlock*, uint32_t> JTWeights; 7557 for (unsigned I = First; I <= Last; ++I) { 7558 assert(Clusters[I].Kind == CC_Range); 7559 Weight += Clusters[I].Weight; 7560 assert(Weight >= Clusters[I].Weight && "Weight overflow!"); 7561 APInt Low = Clusters[I].Low->getValue(); 7562 APInt High = Clusters[I].High->getValue(); 7563 NumCmps += (Low == High) ? 1 : 2; 7564 if (I != First) { 7565 // Fill the gap between this and the previous cluster. 7566 APInt PreviousHigh = Clusters[I - 1].High->getValue(); 7567 assert(PreviousHigh.slt(Low)); 7568 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 7569 for (uint64_t J = 0; J < Gap; J++) 7570 Table.push_back(DefaultMBB); 7571 } 7572 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 7573 for (uint64_t J = 0; J < ClusterSize; ++J) 7574 Table.push_back(Clusters[I].MBB); 7575 JTWeights[Clusters[I].MBB] += Clusters[I].Weight; 7576 } 7577 7578 unsigned NumDests = JTWeights.size(); 7579 if (isSuitableForBitTests(NumDests, NumCmps, 7580 Clusters[First].Low->getValue(), 7581 Clusters[Last].High->getValue())) { 7582 // Clusters[First..Last] should be lowered as bit tests instead. 7583 return false; 7584 } 7585 7586 // Create the MBB that will load from and jump through the table. 7587 // Note: We create it here, but it's not inserted into the function yet. 7588 MachineFunction *CurMF = FuncInfo.MF; 7589 MachineBasicBlock *JumpTableMBB = 7590 CurMF->CreateMachineBasicBlock(SI->getParent()); 7591 7592 // Add successors. Note: use table order for determinism. 7593 SmallPtrSet<MachineBasicBlock *, 8> Done; 7594 for (MachineBasicBlock *Succ : Table) { 7595 if (Done.count(Succ)) 7596 continue; 7597 addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]); 7598 Done.insert(Succ); 7599 } 7600 7601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7602 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 7603 ->createJumpTableIndex(Table); 7604 7605 // Set up the jump table info. 7606 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 7607 JumpTableHeader JTH(Clusters[First].Low->getValue(), 7608 Clusters[Last].High->getValue(), SI->getCondition(), 7609 nullptr, false); 7610 JTCases.emplace_back(std::move(JTH), std::move(JT)); 7611 7612 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 7613 JTCases.size() - 1, Weight); 7614 return true; 7615 } 7616 7617 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 7618 const SwitchInst *SI, 7619 MachineBasicBlock *DefaultMBB) { 7620 #ifndef NDEBUG 7621 // Clusters must be non-empty, sorted, and only contain Range clusters. 7622 assert(!Clusters.empty()); 7623 for (CaseCluster &C : Clusters) 7624 assert(C.Kind == CC_Range); 7625 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 7626 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 7627 #endif 7628 7629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7630 if (!areJTsAllowed(TLI)) 7631 return; 7632 7633 const int64_t N = Clusters.size(); 7634 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries(); 7635 7636 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 7637 SmallVector<unsigned, 8> TotalCases(N); 7638 7639 for (unsigned i = 0; i < N; ++i) { 7640 APInt Hi = Clusters[i].High->getValue(); 7641 APInt Lo = Clusters[i].Low->getValue(); 7642 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 7643 if (i != 0) 7644 TotalCases[i] += TotalCases[i - 1]; 7645 } 7646 7647 if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) { 7648 // Cheap case: the whole range might be suitable for jump table. 7649 CaseCluster JTCluster; 7650 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 7651 Clusters[0] = JTCluster; 7652 Clusters.resize(1); 7653 return; 7654 } 7655 } 7656 7657 // The algorithm below is not suitable for -O0. 7658 if (TM.getOptLevel() == CodeGenOpt::None) 7659 return; 7660 7661 // Split Clusters into minimum number of dense partitions. The algorithm uses 7662 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 7663 // for the Case Statement'" (1994), but builds the MinPartitions array in 7664 // reverse order to make it easier to reconstruct the partitions in ascending 7665 // order. In the choice between two optimal partitionings, it picks the one 7666 // which yields more jump tables. 7667 7668 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 7669 SmallVector<unsigned, 8> MinPartitions(N); 7670 // LastElement[i] is the last element of the partition starting at i. 7671 SmallVector<unsigned, 8> LastElement(N); 7672 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1]. 7673 SmallVector<unsigned, 8> NumTables(N); 7674 7675 // Base case: There is only one way to partition Clusters[N-1]. 7676 MinPartitions[N - 1] = 1; 7677 LastElement[N - 1] = N - 1; 7678 assert(MinJumpTableSize > 1); 7679 NumTables[N - 1] = 0; 7680 7681 // Note: loop indexes are signed to avoid underflow. 7682 for (int64_t i = N - 2; i >= 0; i--) { 7683 // Find optimal partitioning of Clusters[i..N-1]. 7684 // Baseline: Put Clusters[i] into a partition on its own. 7685 MinPartitions[i] = MinPartitions[i + 1] + 1; 7686 LastElement[i] = i; 7687 NumTables[i] = NumTables[i + 1]; 7688 7689 // Search for a solution that results in fewer partitions. 7690 for (int64_t j = N - 1; j > i; j--) { 7691 // Try building a partition from Clusters[i..j]. 7692 if (isDense(Clusters, &TotalCases[0], i, j)) { 7693 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 7694 bool IsTable = j - i + 1 >= MinJumpTableSize; 7695 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]); 7696 7697 // If this j leads to fewer partitions, or same number of partitions 7698 // with more lookup tables, it is a better partitioning. 7699 if (NumPartitions < MinPartitions[i] || 7700 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) { 7701 MinPartitions[i] = NumPartitions; 7702 LastElement[i] = j; 7703 NumTables[i] = Tables; 7704 } 7705 } 7706 } 7707 } 7708 7709 // Iterate over the partitions, replacing some with jump tables in-place. 7710 unsigned DstIndex = 0; 7711 for (unsigned First = 0, Last; First < N; First = Last + 1) { 7712 Last = LastElement[First]; 7713 assert(Last >= First); 7714 assert(DstIndex <= First); 7715 unsigned NumClusters = Last - First + 1; 7716 7717 CaseCluster JTCluster; 7718 if (NumClusters >= MinJumpTableSize && 7719 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 7720 Clusters[DstIndex++] = JTCluster; 7721 } else { 7722 for (unsigned I = First; I <= Last; ++I) 7723 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 7724 } 7725 } 7726 Clusters.resize(DstIndex); 7727 } 7728 7729 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) { 7730 // FIXME: Using the pointer type doesn't seem ideal. 7731 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits(); 7732 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1; 7733 return Range <= BW; 7734 } 7735 7736 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests, 7737 unsigned NumCmps, 7738 const APInt &Low, 7739 const APInt &High) { 7740 // FIXME: I don't think NumCmps is the correct metric: a single case and a 7741 // range of cases both require only one branch to lower. Just looking at the 7742 // number of clusters and destinations should be enough to decide whether to 7743 // build bit tests. 7744 7745 // To lower a range with bit tests, the range must fit the bitwidth of a 7746 // machine word. 7747 if (!rangeFitsInWord(Low, High)) 7748 return false; 7749 7750 // Decide whether it's profitable to lower this range with bit tests. Each 7751 // destination requires a bit test and branch, and there is an overall range 7752 // check branch. For a small number of clusters, separate comparisons might be 7753 // cheaper, and for many destinations, splitting the range might be better. 7754 return (NumDests == 1 && NumCmps >= 3) || 7755 (NumDests == 2 && NumCmps >= 5) || 7756 (NumDests == 3 && NumCmps >= 6); 7757 } 7758 7759 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 7760 unsigned First, unsigned Last, 7761 const SwitchInst *SI, 7762 CaseCluster &BTCluster) { 7763 assert(First <= Last); 7764 if (First == Last) 7765 return false; 7766 7767 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 7768 unsigned NumCmps = 0; 7769 for (int64_t I = First; I <= Last; ++I) { 7770 assert(Clusters[I].Kind == CC_Range); 7771 Dests.set(Clusters[I].MBB->getNumber()); 7772 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 7773 } 7774 unsigned NumDests = Dests.count(); 7775 7776 APInt Low = Clusters[First].Low->getValue(); 7777 APInt High = Clusters[Last].High->getValue(); 7778 assert(Low.slt(High)); 7779 7780 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High)) 7781 return false; 7782 7783 APInt LowBound; 7784 APInt CmpRange; 7785 7786 const int BitWidth = DAG.getTargetLoweringInfo() 7787 .getPointerTy(DAG.getDataLayout()) 7788 .getSizeInBits(); 7789 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!"); 7790 7791 // Check if the clusters cover a contiguous range such that no value in the 7792 // range will jump to the default statement. 7793 bool ContiguousRange = true; 7794 for (int64_t I = First + 1; I <= Last; ++I) { 7795 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 7796 ContiguousRange = false; 7797 break; 7798 } 7799 } 7800 7801 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 7802 // Optimize the case where all the case values fit in a word without having 7803 // to subtract minValue. In this case, we can optimize away the subtraction. 7804 LowBound = APInt::getNullValue(Low.getBitWidth()); 7805 CmpRange = High; 7806 ContiguousRange = false; 7807 } else { 7808 LowBound = Low; 7809 CmpRange = High - Low; 7810 } 7811 7812 CaseBitsVector CBV; 7813 uint32_t TotalWeight = 0; 7814 for (unsigned i = First; i <= Last; ++i) { 7815 // Find the CaseBits for this destination. 7816 unsigned j; 7817 for (j = 0; j < CBV.size(); ++j) 7818 if (CBV[j].BB == Clusters[i].MBB) 7819 break; 7820 if (j == CBV.size()) 7821 CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0)); 7822 CaseBits *CB = &CBV[j]; 7823 7824 // Update Mask, Bits and ExtraWeight. 7825 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 7826 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 7827 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 7828 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 7829 CB->Bits += Hi - Lo + 1; 7830 CB->ExtraWeight += Clusters[i].Weight; 7831 TotalWeight += Clusters[i].Weight; 7832 assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!"); 7833 } 7834 7835 BitTestInfo BTI; 7836 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 7837 // Sort by weight first, number of bits second. 7838 if (a.ExtraWeight != b.ExtraWeight) 7839 return a.ExtraWeight > b.ExtraWeight; 7840 return a.Bits > b.Bits; 7841 }); 7842 7843 for (auto &CB : CBV) { 7844 MachineBasicBlock *BitTestBB = 7845 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 7846 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight)); 7847 } 7848 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 7849 SI->getCondition(), -1U, MVT::Other, false, 7850 ContiguousRange, nullptr, nullptr, std::move(BTI), 7851 TotalWeight); 7852 7853 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 7854 BitTestCases.size() - 1, TotalWeight); 7855 return true; 7856 } 7857 7858 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 7859 const SwitchInst *SI) { 7860 // Partition Clusters into as few subsets as possible, where each subset has a 7861 // range that fits in a machine word and has <= 3 unique destinations. 7862 7863 #ifndef NDEBUG 7864 // Clusters must be sorted and contain Range or JumpTable clusters. 7865 assert(!Clusters.empty()); 7866 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 7867 for (const CaseCluster &C : Clusters) 7868 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 7869 for (unsigned i = 1; i < Clusters.size(); ++i) 7870 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 7871 #endif 7872 7873 // The algorithm below is not suitable for -O0. 7874 if (TM.getOptLevel() == CodeGenOpt::None) 7875 return; 7876 7877 // If target does not have legal shift left, do not emit bit tests at all. 7878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7879 EVT PTy = TLI.getPointerTy(DAG.getDataLayout()); 7880 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 7881 return; 7882 7883 int BitWidth = PTy.getSizeInBits(); 7884 const int64_t N = Clusters.size(); 7885 7886 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 7887 SmallVector<unsigned, 8> MinPartitions(N); 7888 // LastElement[i] is the last element of the partition starting at i. 7889 SmallVector<unsigned, 8> LastElement(N); 7890 7891 // FIXME: This might not be the best algorithm for finding bit test clusters. 7892 7893 // Base case: There is only one way to partition Clusters[N-1]. 7894 MinPartitions[N - 1] = 1; 7895 LastElement[N - 1] = N - 1; 7896 7897 // Note: loop indexes are signed to avoid underflow. 7898 for (int64_t i = N - 2; i >= 0; --i) { 7899 // Find optimal partitioning of Clusters[i..N-1]. 7900 // Baseline: Put Clusters[i] into a partition on its own. 7901 MinPartitions[i] = MinPartitions[i + 1] + 1; 7902 LastElement[i] = i; 7903 7904 // Search for a solution that results in fewer partitions. 7905 // Note: the search is limited by BitWidth, reducing time complexity. 7906 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 7907 // Try building a partition from Clusters[i..j]. 7908 7909 // Check the range. 7910 if (!rangeFitsInWord(Clusters[i].Low->getValue(), 7911 Clusters[j].High->getValue())) 7912 continue; 7913 7914 // Check nbr of destinations and cluster types. 7915 // FIXME: This works, but doesn't seem very efficient. 7916 bool RangesOnly = true; 7917 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 7918 for (int64_t k = i; k <= j; k++) { 7919 if (Clusters[k].Kind != CC_Range) { 7920 RangesOnly = false; 7921 break; 7922 } 7923 Dests.set(Clusters[k].MBB->getNumber()); 7924 } 7925 if (!RangesOnly || Dests.count() > 3) 7926 break; 7927 7928 // Check if it's a better partition. 7929 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 7930 if (NumPartitions < MinPartitions[i]) { 7931 // Found a better partition. 7932 MinPartitions[i] = NumPartitions; 7933 LastElement[i] = j; 7934 } 7935 } 7936 } 7937 7938 // Iterate over the partitions, replacing with bit-test clusters in-place. 7939 unsigned DstIndex = 0; 7940 for (unsigned First = 0, Last; First < N; First = Last + 1) { 7941 Last = LastElement[First]; 7942 assert(First <= Last); 7943 assert(DstIndex <= First); 7944 7945 CaseCluster BitTestCluster; 7946 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 7947 Clusters[DstIndex++] = BitTestCluster; 7948 } else { 7949 size_t NumClusters = Last - First + 1; 7950 std::memmove(&Clusters[DstIndex], &Clusters[First], 7951 sizeof(Clusters[0]) * NumClusters); 7952 DstIndex += NumClusters; 7953 } 7954 } 7955 Clusters.resize(DstIndex); 7956 } 7957 7958 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 7959 MachineBasicBlock *SwitchMBB, 7960 MachineBasicBlock *DefaultMBB) { 7961 MachineFunction *CurMF = FuncInfo.MF; 7962 MachineBasicBlock *NextMBB = nullptr; 7963 MachineFunction::iterator BBI = W.MBB; 7964 if (++BBI != FuncInfo.MF->end()) 7965 NextMBB = BBI; 7966 7967 unsigned Size = W.LastCluster - W.FirstCluster + 1; 7968 7969 BranchProbabilityInfo *BPI = FuncInfo.BPI; 7970 7971 if (Size == 2 && W.MBB == SwitchMBB) { 7972 // If any two of the cases has the same destination, and if one value 7973 // is the same as the other, but has one bit unset that the other has set, 7974 // use bit manipulation to do two compares at once. For example: 7975 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 7976 // TODO: This could be extended to merge any 2 cases in switches with 3 7977 // cases. 7978 // TODO: Handle cases where W.CaseBB != SwitchBB. 7979 CaseCluster &Small = *W.FirstCluster; 7980 CaseCluster &Big = *W.LastCluster; 7981 7982 if (Small.Low == Small.High && Big.Low == Big.High && 7983 Small.MBB == Big.MBB) { 7984 const APInt &SmallValue = Small.Low->getValue(); 7985 const APInt &BigValue = Big.Low->getValue(); 7986 7987 // Check that there is only one bit different. 7988 APInt CommonBit = BigValue ^ SmallValue; 7989 if (CommonBit.isPowerOf2()) { 7990 SDValue CondLHS = getValue(Cond); 7991 EVT VT = CondLHS.getValueType(); 7992 SDLoc DL = getCurSDLoc(); 7993 7994 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 7995 DAG.getConstant(CommonBit, DL, VT)); 7996 SDValue Cond = DAG.getSetCC( 7997 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 7998 ISD::SETEQ); 7999 8000 // Update successor info. 8001 // Both Small and Big will jump to Small.BB, so we sum up the weights. 8002 addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight); 8003 addSuccessorWithWeight( 8004 SwitchMBB, DefaultMBB, 8005 // The default destination is the first successor in IR. 8006 BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0) 8007 : 0); 8008 8009 // Insert the true branch. 8010 SDValue BrCond = 8011 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 8012 DAG.getBasicBlock(Small.MBB)); 8013 // Insert the false branch. 8014 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 8015 DAG.getBasicBlock(DefaultMBB)); 8016 8017 DAG.setRoot(BrCond); 8018 return; 8019 } 8020 } 8021 } 8022 8023 if (TM.getOptLevel() != CodeGenOpt::None) { 8024 // Order cases by weight so the most likely case will be checked first. 8025 std::sort(W.FirstCluster, W.LastCluster + 1, 8026 [](const CaseCluster &a, const CaseCluster &b) { 8027 return a.Weight > b.Weight; 8028 }); 8029 8030 // Rearrange the case blocks so that the last one falls through if possible 8031 // without without changing the order of weights. 8032 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 8033 --I; 8034 if (I->Weight > W.LastCluster->Weight) 8035 break; 8036 if (I->Kind == CC_Range && I->MBB == NextMBB) { 8037 std::swap(*I, *W.LastCluster); 8038 break; 8039 } 8040 } 8041 } 8042 8043 // Compute total weight. 8044 uint32_t UnhandledWeights = 0; 8045 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) { 8046 UnhandledWeights += I->Weight; 8047 assert(UnhandledWeights >= I->Weight && "Weight overflow!"); 8048 } 8049 8050 MachineBasicBlock *CurMBB = W.MBB; 8051 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 8052 MachineBasicBlock *Fallthrough; 8053 if (I == W.LastCluster) { 8054 // For the last cluster, fall through to the default destination. 8055 Fallthrough = DefaultMBB; 8056 } else { 8057 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 8058 CurMF->insert(BBI, Fallthrough); 8059 // Put Cond in a virtual register to make it available from the new blocks. 8060 ExportFromCurrentBlock(Cond); 8061 } 8062 UnhandledWeights -= I->Weight; 8063 8064 switch (I->Kind) { 8065 case CC_JumpTable: { 8066 // FIXME: Optimize away range check based on pivot comparisons. 8067 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 8068 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 8069 8070 // The jump block hasn't been inserted yet; insert it here. 8071 MachineBasicBlock *JumpMBB = JT->MBB; 8072 CurMF->insert(BBI, JumpMBB); 8073 8074 // Collect the sum of weights of outgoing edges from JumpMBB, which will 8075 // be the edge weight on CurMBB->JumpMBB. 8076 uint32_t JumpWeight = 0; 8077 for (auto Succ : JumpMBB->successors()) 8078 JumpWeight += getEdgeWeight(JumpMBB, Succ); 8079 uint32_t FallthruWeight = getEdgeWeight(CurMBB, Fallthrough); 8080 8081 addSuccessorWithWeight(CurMBB, Fallthrough, FallthruWeight); 8082 addSuccessorWithWeight(CurMBB, JumpMBB, JumpWeight); 8083 8084 // The jump table header will be inserted in our current block, do the 8085 // range check, and fall through to our fallthrough block. 8086 JTH->HeaderBB = CurMBB; 8087 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 8088 8089 // If we're in the right place, emit the jump table header right now. 8090 if (CurMBB == SwitchMBB) { 8091 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 8092 JTH->Emitted = true; 8093 } 8094 break; 8095 } 8096 case CC_BitTests: { 8097 // FIXME: Optimize away range check based on pivot comparisons. 8098 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 8099 8100 // The bit test blocks haven't been inserted yet; insert them here. 8101 for (BitTestCase &BTC : BTB->Cases) 8102 CurMF->insert(BBI, BTC.ThisBB); 8103 8104 // Fill in fields of the BitTestBlock. 8105 BTB->Parent = CurMBB; 8106 BTB->Default = Fallthrough; 8107 8108 // If we're in the right place, emit the bit test header header right now. 8109 if (CurMBB ==SwitchMBB) { 8110 visitBitTestHeader(*BTB, SwitchMBB); 8111 BTB->Emitted = true; 8112 } 8113 break; 8114 } 8115 case CC_Range: { 8116 const Value *RHS, *LHS, *MHS; 8117 ISD::CondCode CC; 8118 if (I->Low == I->High) { 8119 // Check Cond == I->Low. 8120 CC = ISD::SETEQ; 8121 LHS = Cond; 8122 RHS=I->Low; 8123 MHS = nullptr; 8124 } else { 8125 // Check I->Low <= Cond <= I->High. 8126 CC = ISD::SETLE; 8127 LHS = I->Low; 8128 MHS = Cond; 8129 RHS = I->High; 8130 } 8131 8132 // The false weight is the sum of all unhandled cases. 8133 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight, 8134 UnhandledWeights); 8135 8136 if (CurMBB == SwitchMBB) 8137 visitSwitchCase(CB, SwitchMBB); 8138 else 8139 SwitchCases.push_back(CB); 8140 8141 break; 8142 } 8143 } 8144 CurMBB = Fallthrough; 8145 } 8146 } 8147 8148 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 8149 CaseClusterIt First, 8150 CaseClusterIt Last) { 8151 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 8152 if (X.Weight != CC.Weight) 8153 return X.Weight > CC.Weight; 8154 8155 // Ties are broken by comparing the case value. 8156 return X.Low->getValue().slt(CC.Low->getValue()); 8157 }); 8158 } 8159 8160 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 8161 const SwitchWorkListItem &W, 8162 Value *Cond, 8163 MachineBasicBlock *SwitchMBB) { 8164 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 8165 "Clusters not sorted?"); 8166 8167 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 8168 8169 // Balance the tree based on branch weights to create a near-optimal (in terms 8170 // of search time given key frequency) binary search tree. See e.g. Kurt 8171 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 8172 CaseClusterIt LastLeft = W.FirstCluster; 8173 CaseClusterIt FirstRight = W.LastCluster; 8174 uint32_t LeftWeight = LastLeft->Weight; 8175 uint32_t RightWeight = FirstRight->Weight; 8176 8177 // Move LastLeft and FirstRight towards each other from opposite directions to 8178 // find a partitioning of the clusters which balances the weight on both 8179 // sides. If LeftWeight and RightWeight are equal, alternate which side is 8180 // taken to ensure 0-weight nodes are distributed evenly. 8181 unsigned I = 0; 8182 while (LastLeft + 1 < FirstRight) { 8183 if (LeftWeight < RightWeight || (LeftWeight == RightWeight && (I & 1))) 8184 LeftWeight += (++LastLeft)->Weight; 8185 else 8186 RightWeight += (--FirstRight)->Weight; 8187 I++; 8188 } 8189 8190 for (;;) { 8191 // Our binary search tree differs from a typical BST in that ours can have up 8192 // to three values in each leaf. The pivot selection above doesn't take that 8193 // into account, which means the tree might require more nodes and be less 8194 // efficient. We compensate for this here. 8195 8196 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 8197 unsigned NumRight = W.LastCluster - FirstRight + 1; 8198 8199 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 8200 // If one side has less than 3 clusters, and the other has more than 3, 8201 // consider taking a cluster from the other side. 8202 8203 if (NumLeft < NumRight) { 8204 // Consider moving the first cluster on the right to the left side. 8205 CaseCluster &CC = *FirstRight; 8206 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8207 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8208 if (LeftSideRank <= RightSideRank) { 8209 // Moving the cluster to the left does not demote it. 8210 ++LastLeft; 8211 ++FirstRight; 8212 continue; 8213 } 8214 } else { 8215 assert(NumRight < NumLeft); 8216 // Consider moving the last element on the left to the right side. 8217 CaseCluster &CC = *LastLeft; 8218 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8219 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8220 if (RightSideRank <= LeftSideRank) { 8221 // Moving the cluster to the right does not demot it. 8222 --LastLeft; 8223 --FirstRight; 8224 continue; 8225 } 8226 } 8227 } 8228 break; 8229 } 8230 8231 assert(LastLeft + 1 == FirstRight); 8232 assert(LastLeft >= W.FirstCluster); 8233 assert(FirstRight <= W.LastCluster); 8234 8235 // Use the first element on the right as pivot since we will make less-than 8236 // comparisons against it. 8237 CaseClusterIt PivotCluster = FirstRight; 8238 assert(PivotCluster > W.FirstCluster); 8239 assert(PivotCluster <= W.LastCluster); 8240 8241 CaseClusterIt FirstLeft = W.FirstCluster; 8242 CaseClusterIt LastRight = W.LastCluster; 8243 8244 const ConstantInt *Pivot = PivotCluster->Low; 8245 8246 // New blocks will be inserted immediately after the current one. 8247 MachineFunction::iterator BBI = W.MBB; 8248 ++BBI; 8249 8250 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 8251 // we can branch to its destination directly if it's squeezed exactly in 8252 // between the known lower bound and Pivot - 1. 8253 MachineBasicBlock *LeftMBB; 8254 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 8255 FirstLeft->Low == W.GE && 8256 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 8257 LeftMBB = FirstLeft->MBB; 8258 } else { 8259 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 8260 FuncInfo.MF->insert(BBI, LeftMBB); 8261 WorkList.push_back({LeftMBB, FirstLeft, LastLeft, W.GE, Pivot}); 8262 // Put Cond in a virtual register to make it available from the new blocks. 8263 ExportFromCurrentBlock(Cond); 8264 } 8265 8266 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 8267 // single cluster, RHS.Low == Pivot, and we can branch to its destination 8268 // directly if RHS.High equals the current upper bound. 8269 MachineBasicBlock *RightMBB; 8270 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 8271 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 8272 RightMBB = FirstRight->MBB; 8273 } else { 8274 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 8275 FuncInfo.MF->insert(BBI, RightMBB); 8276 WorkList.push_back({RightMBB, FirstRight, LastRight, Pivot, W.LT}); 8277 // Put Cond in a virtual register to make it available from the new blocks. 8278 ExportFromCurrentBlock(Cond); 8279 } 8280 8281 // Create the CaseBlock record that will be used to lower the branch. 8282 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 8283 LeftWeight, RightWeight); 8284 8285 if (W.MBB == SwitchMBB) 8286 visitSwitchCase(CB, SwitchMBB); 8287 else 8288 SwitchCases.push_back(CB); 8289 } 8290 8291 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 8292 // Extract cases from the switch. 8293 BranchProbabilityInfo *BPI = FuncInfo.BPI; 8294 CaseClusterVector Clusters; 8295 Clusters.reserve(SI.getNumCases()); 8296 for (auto I : SI.cases()) { 8297 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 8298 const ConstantInt *CaseVal = I.getCaseValue(); 8299 uint32_t Weight = 8300 BPI ? BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex()) : 0; 8301 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight)); 8302 } 8303 8304 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 8305 8306 // Cluster adjacent cases with the same destination. We do this at all 8307 // optimization levels because it's cheap to do and will make codegen faster 8308 // if there are many clusters. 8309 sortAndRangeify(Clusters); 8310 8311 if (TM.getOptLevel() != CodeGenOpt::None) { 8312 // Replace an unreachable default with the most popular destination. 8313 // FIXME: Exploit unreachable default more aggressively. 8314 bool UnreachableDefault = 8315 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 8316 if (UnreachableDefault && !Clusters.empty()) { 8317 DenseMap<const BasicBlock *, unsigned> Popularity; 8318 unsigned MaxPop = 0; 8319 const BasicBlock *MaxBB = nullptr; 8320 for (auto I : SI.cases()) { 8321 const BasicBlock *BB = I.getCaseSuccessor(); 8322 if (++Popularity[BB] > MaxPop) { 8323 MaxPop = Popularity[BB]; 8324 MaxBB = BB; 8325 } 8326 } 8327 // Set new default. 8328 assert(MaxPop > 0 && MaxBB); 8329 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 8330 8331 // Remove cases that were pointing to the destination that is now the 8332 // default. 8333 CaseClusterVector New; 8334 New.reserve(Clusters.size()); 8335 for (CaseCluster &CC : Clusters) { 8336 if (CC.MBB != DefaultMBB) 8337 New.push_back(CC); 8338 } 8339 Clusters = std::move(New); 8340 } 8341 } 8342 8343 // If there is only the default destination, jump there directly. 8344 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 8345 if (Clusters.empty()) { 8346 SwitchMBB->addSuccessor(DefaultMBB); 8347 if (DefaultMBB != NextBlock(SwitchMBB)) { 8348 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 8349 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 8350 } 8351 return; 8352 } 8353 8354 findJumpTables(Clusters, &SI, DefaultMBB); 8355 findBitTestClusters(Clusters, &SI); 8356 8357 DEBUG({ 8358 dbgs() << "Case clusters: "; 8359 for (const CaseCluster &C : Clusters) { 8360 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 8361 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 8362 8363 C.Low->getValue().print(dbgs(), true); 8364 if (C.Low != C.High) { 8365 dbgs() << '-'; 8366 C.High->getValue().print(dbgs(), true); 8367 } 8368 dbgs() << ' '; 8369 } 8370 dbgs() << '\n'; 8371 }); 8372 8373 assert(!Clusters.empty()); 8374 SwitchWorkList WorkList; 8375 CaseClusterIt First = Clusters.begin(); 8376 CaseClusterIt Last = Clusters.end() - 1; 8377 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr}); 8378 8379 while (!WorkList.empty()) { 8380 SwitchWorkListItem W = WorkList.back(); 8381 WorkList.pop_back(); 8382 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 8383 8384 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) { 8385 // For optimized builds, lower large range as a balanced binary tree. 8386 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 8387 continue; 8388 } 8389 8390 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 8391 } 8392 } 8393