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 #define DEBUG_TYPE "isel" 15 #include "SelectionDAGBuilder.h" 16 #include "FunctionLoweringInfo.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Constants.h" 21 #include "llvm/CallingConv.h" 22 #include "llvm/DerivedTypes.h" 23 #include "llvm/Function.h" 24 #include "llvm/GlobalVariable.h" 25 #include "llvm/InlineAsm.h" 26 #include "llvm/Instructions.h" 27 #include "llvm/Intrinsics.h" 28 #include "llvm/IntrinsicInst.h" 29 #include "llvm/LLVMContext.h" 30 #include "llvm/Module.h" 31 #include "llvm/CodeGen/FastISel.h" 32 #include "llvm/CodeGen/GCStrategy.h" 33 #include "llvm/CodeGen/GCMetadata.h" 34 #include "llvm/CodeGen/MachineFunction.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineInstrBuilder.h" 37 #include "llvm/CodeGen/MachineJumpTableInfo.h" 38 #include "llvm/CodeGen/MachineModuleInfo.h" 39 #include "llvm/CodeGen/MachineRegisterInfo.h" 40 #include "llvm/CodeGen/PseudoSourceValue.h" 41 #include "llvm/CodeGen/SelectionDAG.h" 42 #include "llvm/CodeGen/DwarfWriter.h" 43 #include "llvm/Analysis/DebugInfo.h" 44 #include "llvm/Target/TargetRegisterInfo.h" 45 #include "llvm/Target/TargetData.h" 46 #include "llvm/Target/TargetFrameInfo.h" 47 #include "llvm/Target/TargetInstrInfo.h" 48 #include "llvm/Target/TargetIntrinsicInfo.h" 49 #include "llvm/Target/TargetLowering.h" 50 #include "llvm/Target/TargetOptions.h" 51 #include "llvm/Support/Compiler.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Debug.h" 54 #include "llvm/Support/ErrorHandling.h" 55 #include "llvm/Support/MathExtras.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <algorithm> 58 using namespace llvm; 59 60 /// LimitFloatPrecision - Generate low-precision inline sequences for 61 /// some float libcalls (6, 8 or 12 bits). 62 static unsigned LimitFloatPrecision; 63 64 static cl::opt<unsigned, true> 65 LimitFPPrecision("limit-float-precision", 66 cl::desc("Generate low-precision inline sequences " 67 "for some float libcalls"), 68 cl::location(LimitFloatPrecision), 69 cl::init(0)); 70 71 namespace { 72 /// RegsForValue - This struct represents the registers (physical or virtual) 73 /// that a particular set of values is assigned, and the type information about 74 /// the value. The most common situation is to represent one value at a time, 75 /// but struct or array values are handled element-wise as multiple values. 76 /// The splitting of aggregates is performed recursively, so that we never 77 /// have aggregate-typed registers. The values at this point do not necessarily 78 /// have legal types, so each value may require one or more registers of some 79 /// legal type. 80 /// 81 struct RegsForValue { 82 /// TLI - The TargetLowering object. 83 /// 84 const TargetLowering *TLI; 85 86 /// ValueVTs - The value types of the values, which may not be legal, and 87 /// may need be promoted or synthesized from one or more registers. 88 /// 89 SmallVector<EVT, 4> ValueVTs; 90 91 /// RegVTs - The value types of the registers. This is the same size as 92 /// ValueVTs and it records, for each value, what the type of the assigned 93 /// register or registers are. (Individual values are never synthesized 94 /// from more than one type of register.) 95 /// 96 /// With virtual registers, the contents of RegVTs is redundant with TLI's 97 /// getRegisterType member function, however when with physical registers 98 /// it is necessary to have a separate record of the types. 99 /// 100 SmallVector<EVT, 4> RegVTs; 101 102 /// Regs - This list holds the registers assigned to the values. 103 /// Each legal or promoted value requires one register, and each 104 /// expanded value requires multiple registers. 105 /// 106 SmallVector<unsigned, 4> Regs; 107 108 RegsForValue() : TLI(0) {} 109 110 RegsForValue(const TargetLowering &tli, 111 const SmallVector<unsigned, 4> ®s, 112 EVT regvt, EVT valuevt) 113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 114 RegsForValue(const TargetLowering &tli, 115 const SmallVector<unsigned, 4> ®s, 116 const SmallVector<EVT, 4> ®vts, 117 const SmallVector<EVT, 4> &valuevts) 118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {} 119 RegsForValue(LLVMContext &Context, const TargetLowering &tli, 120 unsigned Reg, const Type *Ty) : TLI(&tli) { 121 ComputeValueVTs(tli, Ty, ValueVTs); 122 123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 124 EVT ValueVT = ValueVTs[Value]; 125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT); 126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT); 127 for (unsigned i = 0; i != NumRegs; ++i) 128 Regs.push_back(Reg + i); 129 RegVTs.push_back(RegisterVT); 130 Reg += NumRegs; 131 } 132 } 133 134 /// append - Add the specified values to this one. 135 void append(const RegsForValue &RHS) { 136 TLI = RHS.TLI; 137 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 138 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 139 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 140 } 141 142 143 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 144 /// this value and returns the result as a ValueVTs value. This uses 145 /// Chain/Flag as the input and updates them for the output Chain/Flag. 146 /// If the Flag pointer is NULL, no flag is used. 147 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, 148 SDValue &Chain, SDValue *Flag) const; 149 150 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 151 /// specified value into the registers specified by this object. This uses 152 /// Chain/Flag as the input and updates them for the output Chain/Flag. 153 /// If the Flag pointer is NULL, no flag is used. 154 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 155 SDValue &Chain, SDValue *Flag) const; 156 157 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 158 /// operand list. This adds the code marker, matching input operand index 159 /// (if applicable), and includes the number of values added into it. 160 void AddInlineAsmOperands(unsigned Code, 161 bool HasMatching, unsigned MatchingIdx, 162 SelectionDAG &DAG, std::vector<SDValue> &Ops) const; 163 }; 164 } 165 166 /// getCopyFromParts - Create a value that contains the specified legal parts 167 /// combined into the value they represent. If the parts combine to a type 168 /// larger then ValueVT then AssertOp can be used to specify whether the extra 169 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 170 /// (ISD::AssertSext). 171 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, 172 const SDValue *Parts, 173 unsigned NumParts, EVT PartVT, EVT ValueVT, 174 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 175 assert(NumParts > 0 && "No parts to assemble!"); 176 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (!ValueVT.isVector() && ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = NumParts & (NumParts - 1) ? 187 1 << Log2_32(NumParts) : NumParts; 188 unsigned RoundBits = PartBits * RoundParts; 189 EVT RoundVT = RoundBits == ValueBits ? 190 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 191 SDValue Lo, Hi; 192 193 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 194 195 if (RoundParts > 2) { 196 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT); 197 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2, 198 PartVT, HalfVT); 199 } else { 200 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]); 202 } 203 if (TLI.isBigEndian()) 204 std::swap(Lo, Hi); 205 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi); 206 207 if (RoundParts < NumParts) { 208 // Assemble the trailing non-power-of-2 part. 209 unsigned OddParts = NumParts - RoundParts; 210 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 211 Hi = getCopyFromParts(DAG, dl, 212 Parts+RoundParts, OddParts, PartVT, OddVT); 213 214 // Combine the round and odd parts. 215 Lo = Val; 216 if (TLI.isBigEndian()) 217 std::swap(Lo, Hi); 218 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 219 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi); 220 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi, 221 DAG.getConstant(Lo.getValueType().getSizeInBits(), 222 TLI.getPointerTy())); 223 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo); 224 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi); 225 } 226 } else if (ValueVT.isVector()) { 227 // Handle a multi-element vector. 228 EVT IntermediateVT, RegisterVT; 229 unsigned NumIntermediates; 230 unsigned NumRegs = 231 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 232 NumIntermediates, RegisterVT); 233 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 234 NumParts = NumRegs; // Silence a compiler warning. 235 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 236 assert(RegisterVT == Parts[0].getValueType() && 237 "Part type doesn't match part!"); 238 239 // Assemble the parts into intermediate operands. 240 SmallVector<SDValue, 8> Ops(NumIntermediates); 241 if (NumIntermediates == NumParts) { 242 // If the register was not expanded, truncate or copy the value, 243 // as appropriate. 244 for (unsigned i = 0; i != NumParts; ++i) 245 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1, 246 PartVT, IntermediateVT); 247 } else if (NumParts > 0) { 248 // If the intermediate type was expanded, build the intermediate operands 249 // from the parts. 250 assert(NumParts % NumIntermediates == 0 && 251 "Must expand into a divisible number of parts!"); 252 unsigned Factor = NumParts / NumIntermediates; 253 for (unsigned i = 0; i != NumIntermediates; ++i) 254 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor, 255 PartVT, IntermediateVT); 256 } 257 258 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate 259 // operands. 260 Val = DAG.getNode(IntermediateVT.isVector() ? 261 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl, 262 ValueVT, &Ops[0], NumIntermediates); 263 } else if (PartVT.isFloatingPoint()) { 264 // FP split into multiple FP parts (for ppcf128) 265 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) && 266 "Unexpected split"); 267 SDValue Lo, Hi; 268 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]); 269 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]); 270 if (TLI.isBigEndian()) 271 std::swap(Lo, Hi); 272 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi); 273 } else { 274 // FP split into integer parts (soft fp) 275 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 276 !PartVT.isVector() && "Unexpected split"); 277 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 278 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT); 279 } 280 } 281 282 // There is now one part, held in Val. Correct it to match ValueVT. 283 PartVT = Val.getValueType(); 284 285 if (PartVT == ValueVT) 286 return Val; 287 288 if (PartVT.isVector()) { 289 assert(ValueVT.isVector() && "Unknown vector conversion!"); 290 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val); 291 } 292 293 if (ValueVT.isVector()) { 294 assert(ValueVT.getVectorElementType() == PartVT && 295 ValueVT.getVectorNumElements() == 1 && 296 "Only trivial scalar-to-vector conversions should get here!"); 297 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val); 298 } 299 300 if (PartVT.isInteger() && 301 ValueVT.isInteger()) { 302 if (ValueVT.bitsLT(PartVT)) { 303 // For a truncate, see if we have any information to 304 // indicate whether the truncated bits will always be 305 // zero or sign-extension. 306 if (AssertOp != ISD::DELETED_NODE) 307 Val = DAG.getNode(AssertOp, dl, PartVT, Val, 308 DAG.getValueType(ValueVT)); 309 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 310 } else { 311 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val); 312 } 313 } 314 315 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 if (ValueVT.bitsLT(Val.getValueType())) 317 // FP_ROUND's are always exact here. 318 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val, 319 DAG.getIntPtrConstant(1)); 320 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val); 321 } 322 323 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) 324 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val); 325 326 llvm_unreachable("Unknown mismatch!"); 327 return SDValue(); 328 } 329 330 /// getCopyToParts - Create a series of nodes that contain the specified value 331 /// split into legal parts. If the parts contain more bits than Val, then, for 332 /// integers, ExtendKind can be used to specify how to generate the extra bits. 333 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val, 334 SDValue *Parts, unsigned NumParts, EVT PartVT, 335 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 337 EVT PtrVT = TLI.getPointerTy(); 338 EVT ValueVT = Val.getValueType(); 339 unsigned PartBits = PartVT.getSizeInBits(); 340 unsigned OrigNumParts = NumParts; 341 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 342 343 if (!NumParts) 344 return; 345 346 if (!ValueVT.isVector()) { 347 if (PartVT == ValueVT) { 348 assert(NumParts == 1 && "No-op copy with multiple parts!"); 349 Parts[0] = Val; 350 return; 351 } 352 353 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 354 // If the parts cover more bits than the value has, promote the value. 355 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 356 assert(NumParts == 1 && "Do not know what to promote to!"); 357 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val); 358 } else if (PartVT.isInteger() && ValueVT.isInteger()) { 359 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 360 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val); 361 } else { 362 llvm_unreachable("Unknown mismatch!"); 363 } 364 } else if (PartBits == ValueVT.getSizeInBits()) { 365 // Different types of the same size. 366 assert(NumParts == 1 && PartVT != ValueVT); 367 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val); 368 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 369 // If the parts cover less bits than value has, truncate the value. 370 if (PartVT.isInteger() && ValueVT.isInteger()) { 371 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 372 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 373 } else { 374 llvm_unreachable("Unknown mismatch!"); 375 } 376 } 377 378 // The value may have changed - recompute ValueVT. 379 ValueVT = Val.getValueType(); 380 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 381 "Failed to tile the value with PartVT!"); 382 383 if (NumParts == 1) { 384 assert(PartVT == ValueVT && "Type conversion failed!"); 385 Parts[0] = Val; 386 return; 387 } 388 389 // Expand the value into multiple parts. 390 if (NumParts & (NumParts - 1)) { 391 // The number of parts is not a power of 2. Split off and copy the tail. 392 assert(PartVT.isInteger() && ValueVT.isInteger() && 393 "Do not know what to expand to!"); 394 unsigned RoundParts = 1 << Log2_32(NumParts); 395 unsigned RoundBits = RoundParts * PartBits; 396 unsigned OddParts = NumParts - RoundParts; 397 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val, 398 DAG.getConstant(RoundBits, 399 TLI.getPointerTy())); 400 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT); 401 if (TLI.isBigEndian()) 402 // The odd parts were reversed by getCopyToParts - unreverse them. 403 std::reverse(Parts + RoundParts, Parts + NumParts); 404 NumParts = RoundParts; 405 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 406 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 407 } 408 409 // The number of parts is a power of 2. Repeatedly bisect the value using 410 // EXTRACT_ELEMENT. 411 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl, 412 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()), 413 Val); 414 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 415 for (unsigned i = 0; i < NumParts; i += StepSize) { 416 unsigned ThisBits = StepSize * PartBits / 2; 417 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 418 SDValue &Part0 = Parts[i]; 419 SDValue &Part1 = Parts[i+StepSize/2]; 420 421 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 422 ThisVT, Part0, 423 DAG.getConstant(1, PtrVT)); 424 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 425 ThisVT, Part0, 426 DAG.getConstant(0, PtrVT)); 427 428 if (ThisBits == PartBits && ThisVT != PartVT) { 429 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl, 430 PartVT, Part0); 431 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl, 432 PartVT, Part1); 433 } 434 } 435 } 436 437 if (TLI.isBigEndian()) 438 std::reverse(Parts, Parts + OrigNumParts); 439 440 return; 441 } 442 443 // Vector ValueVT. 444 if (NumParts == 1) { 445 if (PartVT != ValueVT) { 446 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 447 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val); 448 } else { 449 assert(ValueVT.getVectorElementType() == PartVT && 450 ValueVT.getVectorNumElements() == 1 && 451 "Only trivial vector-to-scalar conversions should get here!"); 452 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 453 PartVT, Val, 454 DAG.getConstant(0, PtrVT)); 455 } 456 } 457 458 Parts[0] = Val; 459 return; 460 } 461 462 // Handle a multi-element vector. 463 EVT IntermediateVT, RegisterVT; 464 unsigned NumIntermediates; 465 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 466 IntermediateVT, NumIntermediates, RegisterVT); 467 unsigned NumElements = ValueVT.getVectorNumElements(); 468 469 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 470 NumParts = NumRegs; // Silence a compiler warning. 471 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 472 473 // Split the vector into intermediate operands. 474 SmallVector<SDValue, 8> Ops(NumIntermediates); 475 for (unsigned i = 0; i != NumIntermediates; ++i) 476 if (IntermediateVT.isVector()) 477 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, 478 IntermediateVT, Val, 479 DAG.getConstant(i * (NumElements / NumIntermediates), 480 PtrVT)); 481 else 482 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 483 IntermediateVT, Val, 484 DAG.getConstant(i, PtrVT)); 485 486 // Split the intermediate operands into legal parts. 487 if (NumParts == NumIntermediates) { 488 // If the register was not expanded, promote or copy the value, 489 // as appropriate. 490 for (unsigned i = 0; i != NumParts; ++i) 491 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT); 492 } else if (NumParts > 0) { 493 // If the intermediate type was expanded, split each the value into 494 // legal parts. 495 assert(NumParts % NumIntermediates == 0 && 496 "Must expand into a divisible number of parts!"); 497 unsigned Factor = NumParts / NumIntermediates; 498 for (unsigned i = 0; i != NumIntermediates; ++i) 499 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT); 500 } 501 } 502 503 504 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) { 505 AA = &aa; 506 GFI = gfi; 507 TD = DAG.getTarget().getTargetData(); 508 } 509 510 /// clear - Clear out the curret SelectionDAG and the associated 511 /// state and prepare this SelectionDAGBuilder object to be used 512 /// for a new block. This doesn't clear out information about 513 /// additional blocks that are needed to complete switch lowering 514 /// or PHI node updating; that information is cleared out as it is 515 /// consumed. 516 void SelectionDAGBuilder::clear() { 517 NodeMap.clear(); 518 PendingLoads.clear(); 519 PendingExports.clear(); 520 EdgeMapping.clear(); 521 DAG.clear(); 522 CurDebugLoc = DebugLoc::getUnknownLoc(); 523 HasTailCall = false; 524 } 525 526 /// getRoot - Return the current virtual root of the Selection DAG, 527 /// flushing any PendingLoad items. This must be done before emitting 528 /// a store or any other node that may need to be ordered after any 529 /// prior load instructions. 530 /// 531 SDValue SelectionDAGBuilder::getRoot() { 532 if (PendingLoads.empty()) 533 return DAG.getRoot(); 534 535 if (PendingLoads.size() == 1) { 536 SDValue Root = PendingLoads[0]; 537 DAG.setRoot(Root); 538 PendingLoads.clear(); 539 return Root; 540 } 541 542 // Otherwise, we have to make a token factor node. 543 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 544 &PendingLoads[0], PendingLoads.size()); 545 PendingLoads.clear(); 546 DAG.setRoot(Root); 547 return Root; 548 } 549 550 /// getControlRoot - Similar to getRoot, but instead of flushing all the 551 /// PendingLoad items, flush all the PendingExports items. It is necessary 552 /// to do this before emitting a terminator instruction. 553 /// 554 SDValue SelectionDAGBuilder::getControlRoot() { 555 SDValue Root = DAG.getRoot(); 556 557 if (PendingExports.empty()) 558 return Root; 559 560 // Turn all of the CopyToReg chains into one factored node. 561 if (Root.getOpcode() != ISD::EntryToken) { 562 unsigned i = 0, e = PendingExports.size(); 563 for (; i != e; ++i) { 564 assert(PendingExports[i].getNode()->getNumOperands() > 1); 565 if (PendingExports[i].getNode()->getOperand(0) == Root) 566 break; // Don't add the root if we already indirectly depend on it. 567 } 568 569 if (i == e) 570 PendingExports.push_back(Root); 571 } 572 573 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 574 &PendingExports[0], 575 PendingExports.size()); 576 PendingExports.clear(); 577 DAG.setRoot(Root); 578 return Root; 579 } 580 581 void SelectionDAGBuilder::visit(Instruction &I) { 582 visit(I.getOpcode(), I); 583 } 584 585 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) { 586 // We're processing a new instruction. 587 ++SDNodeOrder; 588 589 // Note: this doesn't use InstVisitor, because it has to work with 590 // ConstantExpr's in addition to instructions. 591 switch (Opcode) { 592 default: llvm_unreachable("Unknown instruction type encountered!"); 593 // Build the switch statement using the Instruction.def file. 594 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 595 case Instruction::OPCODE: return visit##OPCODE((CLASS&)I); 596 #include "llvm/Instruction.def" 597 } 598 } 599 600 SDValue SelectionDAGBuilder::getValue(const Value *V) { 601 SDValue &N = NodeMap[V]; 602 if (N.getNode()) return N; 603 604 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) { 605 EVT VT = TLI.getValueType(V->getType(), true); 606 607 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 608 return N = DAG.getConstant(*CI, VT); 609 610 if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) 611 return N = DAG.getGlobalAddress(GV, VT); 612 613 if (isa<ConstantPointerNull>(C)) 614 return N = DAG.getConstant(0, TLI.getPointerTy()); 615 616 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 617 return N = DAG.getConstantFP(*CFP, VT); 618 619 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 620 return N = DAG.getUNDEF(VT); 621 622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 623 visit(CE->getOpcode(), *CE); 624 SDValue N1 = NodeMap[V]; 625 assert(N1.getNode() && "visit didn't populate the ValueMap!"); 626 return N1; 627 } 628 629 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 630 SmallVector<SDValue, 4> Constants; 631 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 632 OI != OE; ++OI) { 633 SDNode *Val = getValue(*OI).getNode(); 634 // If the operand is an empty aggregate, there are no values. 635 if (!Val) continue; 636 // Add each leaf value from the operand to the Constants list 637 // to form a flattened list of all the values. 638 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 639 Constants.push_back(SDValue(Val, i)); 640 } 641 642 SDValue Res = DAG.getMergeValues(&Constants[0], Constants.size(), 643 getCurDebugLoc()); 644 if (DisableScheduling) 645 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 646 return Res; 647 } 648 649 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) { 650 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 651 "Unknown struct or array constant!"); 652 653 SmallVector<EVT, 4> ValueVTs; 654 ComputeValueVTs(TLI, C->getType(), ValueVTs); 655 unsigned NumElts = ValueVTs.size(); 656 if (NumElts == 0) 657 return SDValue(); // empty struct 658 SmallVector<SDValue, 4> Constants(NumElts); 659 for (unsigned i = 0; i != NumElts; ++i) { 660 EVT EltVT = ValueVTs[i]; 661 if (isa<UndefValue>(C)) 662 Constants[i] = DAG.getUNDEF(EltVT); 663 else if (EltVT.isFloatingPoint()) 664 Constants[i] = DAG.getConstantFP(0, EltVT); 665 else 666 Constants[i] = DAG.getConstant(0, EltVT); 667 } 668 669 SDValue Res = DAG.getMergeValues(&Constants[0], NumElts, 670 getCurDebugLoc()); 671 if (DisableScheduling) 672 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 673 return Res; 674 } 675 676 if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) 677 return DAG.getBlockAddress(BA, VT); 678 679 const VectorType *VecTy = cast<VectorType>(V->getType()); 680 unsigned NumElements = VecTy->getNumElements(); 681 682 // Now that we know the number and type of the elements, get that number of 683 // elements into the Ops array based on what kind of constant it is. 684 SmallVector<SDValue, 16> Ops; 685 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 686 for (unsigned i = 0; i != NumElements; ++i) 687 Ops.push_back(getValue(CP->getOperand(i))); 688 } else { 689 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 690 EVT EltVT = TLI.getValueType(VecTy->getElementType()); 691 692 SDValue Op; 693 if (EltVT.isFloatingPoint()) 694 Op = DAG.getConstantFP(0, EltVT); 695 else 696 Op = DAG.getConstant(0, EltVT); 697 Ops.assign(NumElements, Op); 698 } 699 700 // Create a BUILD_VECTOR node. 701 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 702 VT, &Ops[0], Ops.size()); 703 if (DisableScheduling) 704 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 705 706 return NodeMap[V] = Res; 707 } 708 709 // If this is a static alloca, generate it as the frameindex instead of 710 // computation. 711 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 712 DenseMap<const AllocaInst*, int>::iterator SI = 713 FuncInfo.StaticAllocaMap.find(AI); 714 if (SI != FuncInfo.StaticAllocaMap.end()) 715 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 716 } 717 718 unsigned InReg = FuncInfo.ValueMap[V]; 719 assert(InReg && "Value not in map!"); 720 721 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType()); 722 SDValue Chain = DAG.getEntryNode(); 723 SDValue Res = RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL); 724 if (DisableScheduling) 725 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 726 return Res; 727 } 728 729 /// Get the EVTs and ArgFlags collections that represent the return type 730 /// of the given function. This does not require a DAG or a return value, and 731 /// is suitable for use before any DAGs for the function are constructed. 732 static void getReturnInfo(const Type* ReturnType, 733 Attributes attr, SmallVectorImpl<EVT> &OutVTs, 734 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags, 735 TargetLowering &TLI, 736 SmallVectorImpl<uint64_t> *Offsets = 0) { 737 SmallVector<EVT, 4> ValueVTs; 738 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets); 739 unsigned NumValues = ValueVTs.size(); 740 if ( NumValues == 0 ) return; 741 742 for (unsigned j = 0, f = NumValues; j != f; ++j) { 743 EVT VT = ValueVTs[j]; 744 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 745 746 if (attr & Attribute::SExt) 747 ExtendKind = ISD::SIGN_EXTEND; 748 else if (attr & Attribute::ZExt) 749 ExtendKind = ISD::ZERO_EXTEND; 750 751 // FIXME: C calling convention requires the return type to be promoted to 752 // at least 32-bit. But this is not necessary for non-C calling 753 // conventions. The frontend should mark functions whose return values 754 // require promoting with signext or zeroext attributes. 755 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 756 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32); 757 if (VT.bitsLT(MinVT)) 758 VT = MinVT; 759 } 760 761 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT); 762 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT); 763 // 'inreg' on function refers to return value 764 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 765 if (attr & Attribute::InReg) 766 Flags.setInReg(); 767 768 // Propagate extension type if any 769 if (attr & Attribute::SExt) 770 Flags.setSExt(); 771 else if (attr & Attribute::ZExt) 772 Flags.setZExt(); 773 774 for (unsigned i = 0; i < NumParts; ++i) { 775 OutVTs.push_back(PartVT); 776 OutFlags.push_back(Flags); 777 } 778 } 779 } 780 781 void SelectionDAGBuilder::visitRet(ReturnInst &I) { 782 SDValue Chain = getControlRoot(); 783 SmallVector<ISD::OutputArg, 8> Outs; 784 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); 785 786 if (!FLI.CanLowerReturn) { 787 unsigned DemoteReg = FLI.DemoteRegister; 788 const Function *F = I.getParent()->getParent(); 789 790 // Emit a store of the return value through the virtual register. 791 // Leave Outs empty so that LowerReturn won't try to load return 792 // registers the usual way. 793 SmallVector<EVT, 1> PtrValueVTs; 794 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), 795 PtrValueVTs); 796 797 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 798 SDValue RetOp = getValue(I.getOperand(0)); 799 800 SmallVector<EVT, 4> ValueVTs; 801 SmallVector<uint64_t, 4> Offsets; 802 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); 803 unsigned NumValues = ValueVTs.size(); 804 805 SmallVector<SDValue, 4> Chains(NumValues); 806 EVT PtrVT = PtrValueVTs[0]; 807 for (unsigned i = 0; i != NumValues; ++i) { 808 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr, 809 DAG.getConstant(Offsets[i], PtrVT)); 810 Chains[i] = 811 DAG.getStore(Chain, getCurDebugLoc(), 812 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 813 Add, NULL, Offsets[i], false, 0); 814 815 if (DisableScheduling) { 816 DAG.AssignOrdering(Add.getNode(), SDNodeOrder); 817 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder); 818 } 819 } 820 821 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 822 MVT::Other, &Chains[0], NumValues); 823 824 if (DisableScheduling) 825 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder); 826 } else { 827 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 828 SmallVector<EVT, 4> ValueVTs; 829 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs); 830 unsigned NumValues = ValueVTs.size(); 831 if (NumValues == 0) continue; 832 833 SDValue RetOp = getValue(I.getOperand(i)); 834 for (unsigned j = 0, f = NumValues; j != f; ++j) { 835 EVT VT = ValueVTs[j]; 836 837 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 838 839 const Function *F = I.getParent()->getParent(); 840 if (F->paramHasAttr(0, Attribute::SExt)) 841 ExtendKind = ISD::SIGN_EXTEND; 842 else if (F->paramHasAttr(0, Attribute::ZExt)) 843 ExtendKind = ISD::ZERO_EXTEND; 844 845 // FIXME: C calling convention requires the return type to be promoted to 846 // at least 32-bit. But this is not necessary for non-C calling 847 // conventions. The frontend should mark functions whose return values 848 // require promoting with signext or zeroext attributes. 849 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 850 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32); 851 if (VT.bitsLT(MinVT)) 852 VT = MinVT; 853 } 854 855 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT); 856 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT); 857 SmallVector<SDValue, 4> Parts(NumParts); 858 getCopyToParts(DAG, getCurDebugLoc(), 859 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 860 &Parts[0], NumParts, PartVT, ExtendKind); 861 862 // 'inreg' on function refers to return value 863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 864 if (F->paramHasAttr(0, Attribute::InReg)) 865 Flags.setInReg(); 866 867 // Propagate extension type if any 868 if (F->paramHasAttr(0, Attribute::SExt)) 869 Flags.setSExt(); 870 else if (F->paramHasAttr(0, Attribute::ZExt)) 871 Flags.setZExt(); 872 873 for (unsigned i = 0; i < NumParts; ++i) 874 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true)); 875 } 876 } 877 } 878 879 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 880 CallingConv::ID CallConv = 881 DAG.getMachineFunction().getFunction()->getCallingConv(); 882 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg, 883 Outs, getCurDebugLoc(), DAG); 884 885 // Verify that the target's LowerReturn behaved as expected. 886 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 887 "LowerReturn didn't return a valid chain!"); 888 889 // Update the DAG with the new chain value resulting from return lowering. 890 DAG.setRoot(Chain); 891 892 if (DisableScheduling) 893 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder); 894 } 895 896 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 897 /// created for it, emit nodes to copy the value into the virtual 898 /// registers. 899 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) { 900 if (!V->use_empty()) { 901 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 902 if (VMI != FuncInfo.ValueMap.end()) 903 CopyValueToVirtualRegister(V, VMI->second); 904 } 905 } 906 907 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 908 /// the current basic block, add it to ValueMap now so that we'll get a 909 /// CopyTo/FromReg. 910 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) { 911 // No need to export constants. 912 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 913 914 // Already exported? 915 if (FuncInfo.isExportedInst(V)) return; 916 917 unsigned Reg = FuncInfo.InitializeRegForValue(V); 918 CopyValueToVirtualRegister(V, Reg); 919 } 920 921 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V, 922 const BasicBlock *FromBB) { 923 // The operands of the setcc have to be in this block. We don't know 924 // how to export them from some other block. 925 if (Instruction *VI = dyn_cast<Instruction>(V)) { 926 // Can export from current BB. 927 if (VI->getParent() == FromBB) 928 return true; 929 930 // Is already exported, noop. 931 return FuncInfo.isExportedInst(V); 932 } 933 934 // If this is an argument, we can export it if the BB is the entry block or 935 // if it is already exported. 936 if (isa<Argument>(V)) { 937 if (FromBB == &FromBB->getParent()->getEntryBlock()) 938 return true; 939 940 // Otherwise, can only export this if it is already exported. 941 return FuncInfo.isExportedInst(V); 942 } 943 944 // Otherwise, constants can always be exported. 945 return true; 946 } 947 948 static bool InBlock(const Value *V, const BasicBlock *BB) { 949 if (const Instruction *I = dyn_cast<Instruction>(V)) 950 return I->getParent() == BB; 951 return true; 952 } 953 954 /// getFCmpCondCode - Return the ISD condition code corresponding to 955 /// the given LLVM IR floating-point condition code. This includes 956 /// consideration of global floating-point math flags. 957 /// 958 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) { 959 ISD::CondCode FPC, FOC; 960 switch (Pred) { 961 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break; 962 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break; 963 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break; 964 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break; 965 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break; 966 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break; 967 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break; 968 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break; 969 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break; 970 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break; 971 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break; 972 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break; 973 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break; 974 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break; 975 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break; 976 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break; 977 default: 978 llvm_unreachable("Invalid FCmp predicate opcode!"); 979 FOC = FPC = ISD::SETFALSE; 980 break; 981 } 982 if (FiniteOnlyFPMath()) 983 return FOC; 984 else 985 return FPC; 986 } 987 988 /// getICmpCondCode - Return the ISD condition code corresponding to 989 /// the given LLVM IR integer condition code. 990 /// 991 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) { 992 switch (Pred) { 993 case ICmpInst::ICMP_EQ: return ISD::SETEQ; 994 case ICmpInst::ICMP_NE: return ISD::SETNE; 995 case ICmpInst::ICMP_SLE: return ISD::SETLE; 996 case ICmpInst::ICMP_ULE: return ISD::SETULE; 997 case ICmpInst::ICMP_SGE: return ISD::SETGE; 998 case ICmpInst::ICMP_UGE: return ISD::SETUGE; 999 case ICmpInst::ICMP_SLT: return ISD::SETLT; 1000 case ICmpInst::ICMP_ULT: return ISD::SETULT; 1001 case ICmpInst::ICMP_SGT: return ISD::SETGT; 1002 case ICmpInst::ICMP_UGT: return ISD::SETUGT; 1003 default: 1004 llvm_unreachable("Invalid ICmp predicate opcode!"); 1005 return ISD::SETNE; 1006 } 1007 } 1008 1009 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1010 /// This function emits a branch and is used at the leaves of an OR or an 1011 /// AND operator tree. 1012 /// 1013 void 1014 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond, 1015 MachineBasicBlock *TBB, 1016 MachineBasicBlock *FBB, 1017 MachineBasicBlock *CurBB) { 1018 const BasicBlock *BB = CurBB->getBasicBlock(); 1019 1020 // If the leaf of the tree is a comparison, merge the condition into 1021 // the caseblock. 1022 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1023 // The operands of the cmp have to be in this block. We don't know 1024 // how to export them from some other block. If this is the first block 1025 // of the sequence, no exporting is needed. 1026 if (CurBB == CurMBB || 1027 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1028 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1029 ISD::CondCode Condition; 1030 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1031 Condition = getICmpCondCode(IC->getPredicate()); 1032 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1033 Condition = getFCmpCondCode(FC->getPredicate()); 1034 } else { 1035 Condition = ISD::SETEQ; // silence warning. 1036 llvm_unreachable("Unknown compare instruction"); 1037 } 1038 1039 CaseBlock CB(Condition, BOp->getOperand(0), 1040 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1041 SwitchCases.push_back(CB); 1042 return; 1043 } 1044 } 1045 1046 // Create a CaseBlock record representing this branch. 1047 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1048 NULL, TBB, FBB, CurBB); 1049 SwitchCases.push_back(CB); 1050 } 1051 1052 /// FindMergedConditions - If Cond is an expression like 1053 void SelectionDAGBuilder::FindMergedConditions(Value *Cond, 1054 MachineBasicBlock *TBB, 1055 MachineBasicBlock *FBB, 1056 MachineBasicBlock *CurBB, 1057 unsigned Opc) { 1058 // If this node is not part of the or/and tree, emit it as a branch. 1059 Instruction *BOp = dyn_cast<Instruction>(Cond); 1060 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1061 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1062 BOp->getParent() != CurBB->getBasicBlock() || 1063 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1064 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1065 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB); 1066 return; 1067 } 1068 1069 // Create TmpBB after CurBB. 1070 MachineFunction::iterator BBI = CurBB; 1071 MachineFunction &MF = DAG.getMachineFunction(); 1072 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1073 CurBB->getParent()->insert(++BBI, TmpBB); 1074 1075 if (Opc == Instruction::Or) { 1076 // Codegen X | Y as: 1077 // jmp_if_X TBB 1078 // jmp TmpBB 1079 // TmpBB: 1080 // jmp_if_Y TBB 1081 // jmp FBB 1082 // 1083 1084 // Emit the LHS condition. 1085 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc); 1086 1087 // Emit the RHS condition into TmpBB. 1088 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 1089 } else { 1090 assert(Opc == Instruction::And && "Unknown merge op!"); 1091 // Codegen X & Y as: 1092 // jmp_if_X TmpBB 1093 // jmp FBB 1094 // TmpBB: 1095 // jmp_if_Y TBB 1096 // jmp FBB 1097 // 1098 // This requires creation of TmpBB after CurBB. 1099 1100 // Emit the LHS condition. 1101 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc); 1102 1103 // Emit the RHS condition into TmpBB. 1104 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 1105 } 1106 } 1107 1108 /// If the set of cases should be emitted as a series of branches, return true. 1109 /// If we should emit this as a bunch of and/or'd together conditions, return 1110 /// false. 1111 bool 1112 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){ 1113 if (Cases.size() != 2) return true; 1114 1115 // If this is two comparisons of the same values or'd or and'd together, they 1116 // will get folded into a single comparison, so don't emit two blocks. 1117 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1118 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1119 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1120 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1121 return false; 1122 } 1123 1124 return true; 1125 } 1126 1127 void SelectionDAGBuilder::visitBr(BranchInst &I) { 1128 // Update machine-CFG edges. 1129 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1130 1131 // Figure out which block is immediately after the current one. 1132 MachineBasicBlock *NextBlock = 0; 1133 MachineFunction::iterator BBI = CurMBB; 1134 if (++BBI != FuncInfo.MF->end()) 1135 NextBlock = BBI; 1136 1137 if (I.isUnconditional()) { 1138 // Update machine-CFG edges. 1139 CurMBB->addSuccessor(Succ0MBB); 1140 1141 // If this is not a fall-through branch, emit the branch. 1142 if (Succ0MBB != NextBlock) { 1143 SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(), 1144 MVT::Other, getControlRoot(), 1145 DAG.getBasicBlock(Succ0MBB)); 1146 DAG.setRoot(V); 1147 1148 if (DisableScheduling) 1149 DAG.AssignOrdering(V.getNode(), SDNodeOrder); 1150 } 1151 1152 return; 1153 } 1154 1155 // If this condition is one of the special cases we handle, do special stuff 1156 // now. 1157 Value *CondVal = I.getCondition(); 1158 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1159 1160 // If this is a series of conditions that are or'd or and'd together, emit 1161 // this as a sequence of branches instead of setcc's with and/or operations. 1162 // For example, instead of something like: 1163 // cmp A, B 1164 // C = seteq 1165 // cmp D, E 1166 // F = setle 1167 // or C, F 1168 // jnz foo 1169 // Emit: 1170 // cmp A, B 1171 // je foo 1172 // cmp D, E 1173 // jle foo 1174 // 1175 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1176 if (BOp->hasOneUse() && 1177 (BOp->getOpcode() == Instruction::And || 1178 BOp->getOpcode() == Instruction::Or)) { 1179 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode()); 1180 // If the compares in later blocks need to use values not currently 1181 // exported from this block, export them now. This block should always 1182 // be the first entry. 1183 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!"); 1184 1185 // Allow some cases to be rejected. 1186 if (ShouldEmitAsBranches(SwitchCases)) { 1187 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1188 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1189 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1190 } 1191 1192 // Emit the branch for this block. 1193 visitSwitchCase(SwitchCases[0]); 1194 SwitchCases.erase(SwitchCases.begin()); 1195 return; 1196 } 1197 1198 // Okay, we decided not to do this, remove any inserted MBB's and clear 1199 // SwitchCases. 1200 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1201 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1202 1203 SwitchCases.clear(); 1204 } 1205 } 1206 1207 // Create a CaseBlock record representing this branch. 1208 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1209 NULL, Succ0MBB, Succ1MBB, CurMBB); 1210 1211 // Use visitSwitchCase to actually insert the fast branch sequence for this 1212 // cond branch. 1213 visitSwitchCase(CB); 1214 } 1215 1216 /// visitSwitchCase - Emits the necessary code to represent a single node in 1217 /// the binary search tree resulting from lowering a switch instruction. 1218 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) { 1219 SDValue Cond; 1220 SDValue CondLHS = getValue(CB.CmpLHS); 1221 DebugLoc dl = getCurDebugLoc(); 1222 1223 // Build the setcc now. 1224 if (CB.CmpMHS == NULL) { 1225 // Fold "(X == true)" to X and "(X == false)" to !X to 1226 // handle common cases produced by branch lowering. 1227 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1228 CB.CC == ISD::SETEQ) 1229 Cond = CondLHS; 1230 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1231 CB.CC == ISD::SETEQ) { 1232 SDValue True = DAG.getConstant(1, CondLHS.getValueType()); 1233 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1234 } else 1235 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1236 } else { 1237 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1238 1239 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1240 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1241 1242 SDValue CmpOp = getValue(CB.CmpMHS); 1243 EVT VT = CmpOp.getValueType(); 1244 1245 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1246 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), 1247 ISD::SETLE); 1248 } else { 1249 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1250 VT, CmpOp, DAG.getConstant(Low, VT)); 1251 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1252 DAG.getConstant(High-Low, VT), ISD::SETULE); 1253 } 1254 } 1255 1256 if (DisableScheduling) 1257 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder); 1258 1259 // Update successor info 1260 CurMBB->addSuccessor(CB.TrueBB); 1261 CurMBB->addSuccessor(CB.FalseBB); 1262 1263 // Set NextBlock to be the MBB immediately after the current one, if any. 1264 // This is used to avoid emitting unnecessary branches to the next block. 1265 MachineBasicBlock *NextBlock = 0; 1266 MachineFunction::iterator BBI = CurMBB; 1267 if (++BBI != FuncInfo.MF->end()) 1268 NextBlock = BBI; 1269 1270 // If the lhs block is the next block, invert the condition so that we can 1271 // fall through to the lhs instead of the rhs block. 1272 if (CB.TrueBB == NextBlock) { 1273 std::swap(CB.TrueBB, CB.FalseBB); 1274 SDValue True = DAG.getConstant(1, Cond.getValueType()); 1275 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1276 1277 if (DisableScheduling) 1278 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder); 1279 } 1280 1281 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1282 MVT::Other, getControlRoot(), Cond, 1283 DAG.getBasicBlock(CB.TrueBB)); 1284 1285 if (DisableScheduling) 1286 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder); 1287 1288 // If the branch was constant folded, fix up the CFG. 1289 if (BrCond.getOpcode() == ISD::BR) { 1290 CurMBB->removeSuccessor(CB.FalseBB); 1291 } else { 1292 // Otherwise, go ahead and insert the false branch. 1293 if (BrCond == getControlRoot()) 1294 CurMBB->removeSuccessor(CB.TrueBB); 1295 1296 if (CB.FalseBB != NextBlock) { 1297 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1298 DAG.getBasicBlock(CB.FalseBB)); 1299 1300 if (DisableScheduling) 1301 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder); 1302 } 1303 } 1304 1305 DAG.setRoot(BrCond); 1306 } 1307 1308 /// visitJumpTable - Emit JumpTable node in the current MBB 1309 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1310 // Emit the code for the jump table 1311 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1312 EVT PTy = TLI.getPointerTy(); 1313 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), 1314 JT.Reg, PTy); 1315 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1316 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(), 1317 MVT::Other, Index.getValue(1), 1318 Table, Index); 1319 DAG.setRoot(BrJumpTable); 1320 1321 if (DisableScheduling) { 1322 DAG.AssignOrdering(Index.getNode(), SDNodeOrder); 1323 DAG.AssignOrdering(Table.getNode(), SDNodeOrder); 1324 DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder); 1325 } 1326 } 1327 1328 /// visitJumpTableHeader - This function emits necessary code to produce index 1329 /// in the JumpTable from switch case. 1330 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1331 JumpTableHeader &JTH) { 1332 // Subtract the lowest switch case value from the value being switched on and 1333 // conditional branch to default mbb if the result is greater than the 1334 // difference between smallest and largest cases. 1335 SDValue SwitchOp = getValue(JTH.SValue); 1336 EVT VT = SwitchOp.getValueType(); 1337 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1338 DAG.getConstant(JTH.First, VT)); 1339 1340 // The SDNode we just created, which holds the value being switched on minus 1341 // the the smallest case value, needs to be copied to a virtual register so it 1342 // can be used as an index into the jump table in a subsequent basic block. 1343 // This value may be smaller or larger than the target's pointer type, and 1344 // therefore require extension or truncating. 1345 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy()); 1346 1347 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1348 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1349 JumpTableReg, SwitchOp); 1350 JT.Reg = JumpTableReg; 1351 1352 // Emit the range check for the jump table, and branch to the default block 1353 // for the switch statement if the value being switched on exceeds the largest 1354 // case in the switch. 1355 SDValue CMP = DAG.getSetCC(getCurDebugLoc(), 1356 TLI.getSetCCResultType(Sub.getValueType()), Sub, 1357 DAG.getConstant(JTH.Last-JTH.First,VT), 1358 ISD::SETUGT); 1359 1360 if (DisableScheduling) { 1361 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder); 1362 DAG.AssignOrdering(SwitchOp.getNode(), SDNodeOrder); 1363 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder); 1364 DAG.AssignOrdering(CMP.getNode(), SDNodeOrder); 1365 } 1366 1367 // Set NextBlock to be the MBB immediately after the current one, if any. 1368 // This is used to avoid emitting unnecessary branches to the next block. 1369 MachineBasicBlock *NextBlock = 0; 1370 MachineFunction::iterator BBI = CurMBB; 1371 1372 if (++BBI != FuncInfo.MF->end()) 1373 NextBlock = BBI; 1374 1375 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1376 MVT::Other, CopyTo, CMP, 1377 DAG.getBasicBlock(JT.Default)); 1378 1379 if (DisableScheduling) 1380 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder); 1381 1382 if (JT.MBB != NextBlock) { 1383 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond, 1384 DAG.getBasicBlock(JT.MBB)); 1385 1386 if (DisableScheduling) 1387 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder); 1388 } 1389 1390 DAG.setRoot(BrCond); 1391 } 1392 1393 /// visitBitTestHeader - This function emits necessary code to produce value 1394 /// suitable for "bit tests" 1395 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) { 1396 // Subtract the minimum value 1397 SDValue SwitchOp = getValue(B.SValue); 1398 EVT VT = SwitchOp.getValueType(); 1399 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1400 DAG.getConstant(B.First, VT)); 1401 1402 // Check range 1403 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(), 1404 TLI.getSetCCResultType(Sub.getValueType()), 1405 Sub, DAG.getConstant(B.Range, VT), 1406 ISD::SETUGT); 1407 1408 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), 1409 TLI.getPointerTy()); 1410 1411 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy()); 1412 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1413 B.Reg, ShiftOp); 1414 1415 if (DisableScheduling) { 1416 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder); 1417 DAG.AssignOrdering(RangeCmp.getNode(), SDNodeOrder); 1418 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder); 1419 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder); 1420 } 1421 1422 // Set NextBlock to be the MBB immediately after the current one, if any. 1423 // This is used to avoid emitting unnecessary branches to the next block. 1424 MachineBasicBlock *NextBlock = 0; 1425 MachineFunction::iterator BBI = CurMBB; 1426 if (++BBI != FuncInfo.MF->end()) 1427 NextBlock = BBI; 1428 1429 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1430 1431 CurMBB->addSuccessor(B.Default); 1432 CurMBB->addSuccessor(MBB); 1433 1434 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1435 MVT::Other, CopyTo, RangeCmp, 1436 DAG.getBasicBlock(B.Default)); 1437 1438 if (DisableScheduling) 1439 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder); 1440 1441 if (MBB != NextBlock) { 1442 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo, 1443 DAG.getBasicBlock(MBB)); 1444 1445 if (DisableScheduling) 1446 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder); 1447 } 1448 1449 DAG.setRoot(BrRange); 1450 } 1451 1452 /// visitBitTestCase - this function produces one "bit test" 1453 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB, 1454 unsigned Reg, 1455 BitTestCase &B) { 1456 // Make desired shift 1457 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg, 1458 TLI.getPointerTy()); 1459 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), 1460 TLI.getPointerTy(), 1461 DAG.getConstant(1, TLI.getPointerTy()), 1462 ShiftOp); 1463 1464 // Emit bit tests and jumps 1465 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), 1466 TLI.getPointerTy(), SwitchVal, 1467 DAG.getConstant(B.Mask, TLI.getPointerTy())); 1468 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(), 1469 TLI.getSetCCResultType(AndOp.getValueType()), 1470 AndOp, DAG.getConstant(0, TLI.getPointerTy()), 1471 ISD::SETNE); 1472 1473 if (DisableScheduling) { 1474 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder); 1475 DAG.AssignOrdering(SwitchVal.getNode(), SDNodeOrder); 1476 DAG.AssignOrdering(AndOp.getNode(), SDNodeOrder); 1477 DAG.AssignOrdering(AndCmp.getNode(), SDNodeOrder); 1478 } 1479 1480 CurMBB->addSuccessor(B.TargetBB); 1481 CurMBB->addSuccessor(NextMBB); 1482 1483 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1484 MVT::Other, getControlRoot(), 1485 AndCmp, DAG.getBasicBlock(B.TargetBB)); 1486 1487 if (DisableScheduling) 1488 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder); 1489 1490 // Set NextBlock to be the MBB immediately after the current one, if any. 1491 // This is used to avoid emitting unnecessary branches to the next block. 1492 MachineBasicBlock *NextBlock = 0; 1493 MachineFunction::iterator BBI = CurMBB; 1494 if (++BBI != FuncInfo.MF->end()) 1495 NextBlock = BBI; 1496 1497 if (NextMBB != NextBlock) { 1498 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd, 1499 DAG.getBasicBlock(NextMBB)); 1500 1501 if (DisableScheduling) 1502 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder); 1503 } 1504 1505 DAG.setRoot(BrAnd); 1506 } 1507 1508 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) { 1509 // Retrieve successors. 1510 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1511 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1512 1513 const Value *Callee(I.getCalledValue()); 1514 if (isa<InlineAsm>(Callee)) 1515 visitInlineAsm(&I); 1516 else 1517 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1518 1519 // If the value of the invoke is used outside of its defining block, make it 1520 // available as a virtual register. 1521 CopyToExportRegsIfNeeded(&I); 1522 1523 // Update successor info 1524 CurMBB->addSuccessor(Return); 1525 CurMBB->addSuccessor(LandingPad); 1526 1527 // Drop into normal successor. 1528 SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(), 1529 MVT::Other, getControlRoot(), 1530 DAG.getBasicBlock(Return)); 1531 DAG.setRoot(Branch); 1532 1533 if (DisableScheduling) 1534 DAG.AssignOrdering(Branch.getNode(), SDNodeOrder); 1535 } 1536 1537 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) { 1538 } 1539 1540 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1541 /// small case ranges). 1542 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, 1543 CaseRecVector& WorkList, 1544 Value* SV, 1545 MachineBasicBlock* Default) { 1546 Case& BackCase = *(CR.Range.second-1); 1547 1548 // Size is the number of Cases represented by this range. 1549 size_t Size = CR.Range.second - CR.Range.first; 1550 if (Size > 3) 1551 return false; 1552 1553 // Get the MachineFunction which holds the current MBB. This is used when 1554 // inserting any additional MBBs necessary to represent the switch. 1555 MachineFunction *CurMF = FuncInfo.MF; 1556 1557 // Figure out which block is immediately after the current one. 1558 MachineBasicBlock *NextBlock = 0; 1559 MachineFunction::iterator BBI = CR.CaseBB; 1560 1561 if (++BBI != FuncInfo.MF->end()) 1562 NextBlock = BBI; 1563 1564 // TODO: If any two of the cases has the same destination, and if one value 1565 // is the same as the other, but has one bit unset that the other has set, 1566 // use bit manipulation to do two compares at once. For example: 1567 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1568 1569 // Rearrange the case blocks so that the last one falls through if possible. 1570 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1571 // The last case block won't fall through into 'NextBlock' if we emit the 1572 // branches in this order. See if rearranging a case value would help. 1573 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1574 if (I->BB == NextBlock) { 1575 std::swap(*I, BackCase); 1576 break; 1577 } 1578 } 1579 } 1580 1581 // Create a CaseBlock record representing a conditional branch to 1582 // the Case's target mbb if the value being switched on SV is equal 1583 // to C. 1584 MachineBasicBlock *CurBlock = CR.CaseBB; 1585 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1586 MachineBasicBlock *FallThrough; 1587 if (I != E-1) { 1588 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); 1589 CurMF->insert(BBI, FallThrough); 1590 1591 // Put SV in a virtual register to make it available from the new blocks. 1592 ExportFromCurrentBlock(SV); 1593 } else { 1594 // If the last case doesn't match, go to the default block. 1595 FallThrough = Default; 1596 } 1597 1598 Value *RHS, *LHS, *MHS; 1599 ISD::CondCode CC; 1600 if (I->High == I->Low) { 1601 // This is just small small case range :) containing exactly 1 case 1602 CC = ISD::SETEQ; 1603 LHS = SV; RHS = I->High; MHS = NULL; 1604 } else { 1605 CC = ISD::SETLE; 1606 LHS = I->Low; MHS = SV; RHS = I->High; 1607 } 1608 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock); 1609 1610 // If emitting the first comparison, just call visitSwitchCase to emit the 1611 // code into the current block. Otherwise, push the CaseBlock onto the 1612 // vector to be later processed by SDISel, and insert the node's MBB 1613 // before the next MBB. 1614 if (CurBlock == CurMBB) 1615 visitSwitchCase(CB); 1616 else 1617 SwitchCases.push_back(CB); 1618 1619 CurBlock = FallThrough; 1620 } 1621 1622 return true; 1623 } 1624 1625 static inline bool areJTsAllowed(const TargetLowering &TLI) { 1626 return !DisableJumpTables && 1627 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 1628 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); 1629 } 1630 1631 static APInt ComputeRange(const APInt &First, const APInt &Last) { 1632 APInt LastExt(Last), FirstExt(First); 1633 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; 1634 LastExt.sext(BitWidth); FirstExt.sext(BitWidth); 1635 return (LastExt - FirstExt + 1ULL); 1636 } 1637 1638 /// handleJTSwitchCase - Emit jumptable for current switch case range 1639 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR, 1640 CaseRecVector& WorkList, 1641 Value* SV, 1642 MachineBasicBlock* Default) { 1643 Case& FrontCase = *CR.Range.first; 1644 Case& BackCase = *(CR.Range.second-1); 1645 1646 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1647 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1648 1649 APInt TSize(First.getBitWidth(), 0); 1650 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1651 I!=E; ++I) 1652 TSize += I->size(); 1653 1654 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4))) 1655 return false; 1656 1657 APInt Range = ComputeRange(First, Last); 1658 double Density = TSize.roundToDouble() / Range.roundToDouble(); 1659 if (Density < 0.4) 1660 return false; 1661 1662 DEBUG(errs() << "Lowering jump table\n" 1663 << "First entry: " << First << ". Last entry: " << Last << '\n' 1664 << "Range: " << Range 1665 << "Size: " << TSize << ". Density: " << Density << "\n\n"); 1666 1667 // Get the MachineFunction which holds the current MBB. This is used when 1668 // inserting any additional MBBs necessary to represent the switch. 1669 MachineFunction *CurMF = FuncInfo.MF; 1670 1671 // Figure out which block is immediately after the current one. 1672 MachineFunction::iterator BBI = CR.CaseBB; 1673 ++BBI; 1674 1675 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1676 1677 // Create a new basic block to hold the code for loading the address 1678 // of the jump table, and jumping to it. Update successor information; 1679 // we will either branch to the default case for the switch, or the jump 1680 // table. 1681 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1682 CurMF->insert(BBI, JumpTableBB); 1683 CR.CaseBB->addSuccessor(Default); 1684 CR.CaseBB->addSuccessor(JumpTableBB); 1685 1686 // Build a vector of destination BBs, corresponding to each target 1687 // of the jump table. If the value of the jump table slot corresponds to 1688 // a case statement, push the case's BB onto the vector, otherwise, push 1689 // the default BB. 1690 std::vector<MachineBasicBlock*> DestBBs; 1691 APInt TEI = First; 1692 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 1693 const APInt& Low = cast<ConstantInt>(I->Low)->getValue(); 1694 const APInt& High = cast<ConstantInt>(I->High)->getValue(); 1695 1696 if (Low.sle(TEI) && TEI.sle(High)) { 1697 DestBBs.push_back(I->BB); 1698 if (TEI==High) 1699 ++I; 1700 } else { 1701 DestBBs.push_back(Default); 1702 } 1703 } 1704 1705 // Update successor info. Add one edge to each unique successor. 1706 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 1707 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 1708 E = DestBBs.end(); I != E; ++I) { 1709 if (!SuccsHandled[(*I)->getNumber()]) { 1710 SuccsHandled[(*I)->getNumber()] = true; 1711 JumpTableBB->addSuccessor(*I); 1712 } 1713 } 1714 1715 // Create a jump table index for this jump table, or return an existing 1716 // one. 1717 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs); 1718 1719 // Set the jump table information so that we can codegen it as a second 1720 // MachineBasicBlock 1721 JumpTable JT(-1U, JTI, JumpTableBB, Default); 1722 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB)); 1723 if (CR.CaseBB == CurMBB) 1724 visitJumpTableHeader(JT, JTH); 1725 1726 JTCases.push_back(JumpTableBlock(JTH, JT)); 1727 1728 return true; 1729 } 1730 1731 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1732 /// 2 subtrees. 1733 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 1734 CaseRecVector& WorkList, 1735 Value* SV, 1736 MachineBasicBlock* Default) { 1737 // Get the MachineFunction which holds the current MBB. This is used when 1738 // inserting any additional MBBs necessary to represent the switch. 1739 MachineFunction *CurMF = FuncInfo.MF; 1740 1741 // Figure out which block is immediately after the current one. 1742 MachineFunction::iterator BBI = CR.CaseBB; 1743 ++BBI; 1744 1745 Case& FrontCase = *CR.Range.first; 1746 Case& BackCase = *(CR.Range.second-1); 1747 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1748 1749 // Size is the number of Cases represented by this range. 1750 unsigned Size = CR.Range.second - CR.Range.first; 1751 1752 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1753 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1754 double FMetric = 0; 1755 CaseItr Pivot = CR.Range.first + Size/2; 1756 1757 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1758 // (heuristically) allow us to emit JumpTable's later. 1759 APInt TSize(First.getBitWidth(), 0); 1760 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1761 I!=E; ++I) 1762 TSize += I->size(); 1763 1764 APInt LSize = FrontCase.size(); 1765 APInt RSize = TSize-LSize; 1766 DEBUG(errs() << "Selecting best pivot: \n" 1767 << "First: " << First << ", Last: " << Last <<'\n' 1768 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 1769 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 1770 J!=E; ++I, ++J) { 1771 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 1772 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 1773 APInt Range = ComputeRange(LEnd, RBegin); 1774 assert((Range - 2ULL).isNonNegative() && 1775 "Invalid case distance"); 1776 double LDensity = (double)LSize.roundToDouble() / 1777 (LEnd - First + 1ULL).roundToDouble(); 1778 double RDensity = (double)RSize.roundToDouble() / 1779 (Last - RBegin + 1ULL).roundToDouble(); 1780 double Metric = Range.logBase2()*(LDensity+RDensity); 1781 // Should always split in some non-trivial place 1782 DEBUG(errs() <<"=>Step\n" 1783 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 1784 << "LDensity: " << LDensity 1785 << ", RDensity: " << RDensity << '\n' 1786 << "Metric: " << Metric << '\n'); 1787 if (FMetric < Metric) { 1788 Pivot = J; 1789 FMetric = Metric; 1790 DEBUG(errs() << "Current metric set to: " << FMetric << '\n'); 1791 } 1792 1793 LSize += J->size(); 1794 RSize -= J->size(); 1795 } 1796 if (areJTsAllowed(TLI)) { 1797 // If our case is dense we *really* should handle it earlier! 1798 assert((FMetric > 0) && "Should handle dense range earlier!"); 1799 } else { 1800 Pivot = CR.Range.first + Size/2; 1801 } 1802 1803 CaseRange LHSR(CR.Range.first, Pivot); 1804 CaseRange RHSR(Pivot, CR.Range.second); 1805 Constant *C = Pivot->Low; 1806 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 1807 1808 // We know that we branch to the LHS if the Value being switched on is 1809 // less than the Pivot value, C. We use this to optimize our binary 1810 // tree a bit, by recognizing that if SV is greater than or equal to the 1811 // LHS's Case Value, and that Case Value is exactly one less than the 1812 // Pivot's Value, then we can branch directly to the LHS's Target, 1813 // rather than creating a leaf node for it. 1814 if ((LHSR.second - LHSR.first) == 1 && 1815 LHSR.first->High == CR.GE && 1816 cast<ConstantInt>(C)->getValue() == 1817 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 1818 TrueBB = LHSR.first->BB; 1819 } else { 1820 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1821 CurMF->insert(BBI, TrueBB); 1822 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 1823 1824 // Put SV in a virtual register to make it available from the new blocks. 1825 ExportFromCurrentBlock(SV); 1826 } 1827 1828 // Similar to the optimization above, if the Value being switched on is 1829 // known to be less than the Constant CR.LT, and the current Case Value 1830 // is CR.LT - 1, then we can branch directly to the target block for 1831 // the current Case Value, rather than emitting a RHS leaf node for it. 1832 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 1833 cast<ConstantInt>(RHSR.first->Low)->getValue() == 1834 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 1835 FalseBB = RHSR.first->BB; 1836 } else { 1837 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1838 CurMF->insert(BBI, FalseBB); 1839 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 1840 1841 // Put SV in a virtual register to make it available from the new blocks. 1842 ExportFromCurrentBlock(SV); 1843 } 1844 1845 // Create a CaseBlock record representing a conditional branch to 1846 // the LHS node if the value being switched on SV is less than C. 1847 // Otherwise, branch to LHS. 1848 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 1849 1850 if (CR.CaseBB == CurMBB) 1851 visitSwitchCase(CB); 1852 else 1853 SwitchCases.push_back(CB); 1854 1855 return true; 1856 } 1857 1858 /// handleBitTestsSwitchCase - if current case range has few destination and 1859 /// range span less, than machine word bitwidth, encode case range into series 1860 /// of masks and emit bit tests with these masks. 1861 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 1862 CaseRecVector& WorkList, 1863 Value* SV, 1864 MachineBasicBlock* Default){ 1865 EVT PTy = TLI.getPointerTy(); 1866 unsigned IntPtrBits = PTy.getSizeInBits(); 1867 1868 Case& FrontCase = *CR.Range.first; 1869 Case& BackCase = *(CR.Range.second-1); 1870 1871 // Get the MachineFunction which holds the current MBB. This is used when 1872 // inserting any additional MBBs necessary to represent the switch. 1873 MachineFunction *CurMF = FuncInfo.MF; 1874 1875 // If target does not have legal shift left, do not emit bit tests at all. 1876 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) 1877 return false; 1878 1879 size_t numCmps = 0; 1880 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1881 I!=E; ++I) { 1882 // Single case counts one, case range - two. 1883 numCmps += (I->Low == I->High ? 1 : 2); 1884 } 1885 1886 // Count unique destinations 1887 SmallSet<MachineBasicBlock*, 4> Dests; 1888 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1889 Dests.insert(I->BB); 1890 if (Dests.size() > 3) 1891 // Don't bother the code below, if there are too much unique destinations 1892 return false; 1893 } 1894 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n' 1895 << "Total number of comparisons: " << numCmps << '\n'); 1896 1897 // Compute span of values. 1898 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 1899 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 1900 APInt cmpRange = maxValue - minValue; 1901 1902 DEBUG(errs() << "Compare range: " << cmpRange << '\n' 1903 << "Low bound: " << minValue << '\n' 1904 << "High bound: " << maxValue << '\n'); 1905 1906 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) || 1907 (!(Dests.size() == 1 && numCmps >= 3) && 1908 !(Dests.size() == 2 && numCmps >= 5) && 1909 !(Dests.size() >= 3 && numCmps >= 6))) 1910 return false; 1911 1912 DEBUG(errs() << "Emitting bit tests\n"); 1913 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 1914 1915 // Optimize the case where all the case values fit in a 1916 // word without having to subtract minValue. In this case, 1917 // we can optimize away the subtraction. 1918 if (minValue.isNonNegative() && 1919 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) { 1920 cmpRange = maxValue; 1921 } else { 1922 lowBound = minValue; 1923 } 1924 1925 CaseBitsVector CasesBits; 1926 unsigned i, count = 0; 1927 1928 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1929 MachineBasicBlock* Dest = I->BB; 1930 for (i = 0; i < count; ++i) 1931 if (Dest == CasesBits[i].BB) 1932 break; 1933 1934 if (i == count) { 1935 assert((count < 3) && "Too much destinations to test!"); 1936 CasesBits.push_back(CaseBits(0, Dest, 0)); 1937 count++; 1938 } 1939 1940 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 1941 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 1942 1943 uint64_t lo = (lowValue - lowBound).getZExtValue(); 1944 uint64_t hi = (highValue - lowBound).getZExtValue(); 1945 1946 for (uint64_t j = lo; j <= hi; j++) { 1947 CasesBits[i].Mask |= 1ULL << j; 1948 CasesBits[i].Bits++; 1949 } 1950 1951 } 1952 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 1953 1954 BitTestInfo BTC; 1955 1956 // Figure out which block is immediately after the current one. 1957 MachineFunction::iterator BBI = CR.CaseBB; 1958 ++BBI; 1959 1960 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1961 1962 DEBUG(errs() << "Cases:\n"); 1963 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 1964 DEBUG(errs() << "Mask: " << CasesBits[i].Mask 1965 << ", Bits: " << CasesBits[i].Bits 1966 << ", BB: " << CasesBits[i].BB << '\n'); 1967 1968 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1969 CurMF->insert(BBI, CaseBB); 1970 BTC.push_back(BitTestCase(CasesBits[i].Mask, 1971 CaseBB, 1972 CasesBits[i].BB)); 1973 1974 // Put SV in a virtual register to make it available from the new blocks. 1975 ExportFromCurrentBlock(SV); 1976 } 1977 1978 BitTestBlock BTB(lowBound, cmpRange, SV, 1979 -1U, (CR.CaseBB == CurMBB), 1980 CR.CaseBB, Default, BTC); 1981 1982 if (CR.CaseBB == CurMBB) 1983 visitBitTestHeader(BTB); 1984 1985 BitTestCases.push_back(BTB); 1986 1987 return true; 1988 } 1989 1990 /// Clusterify - Transform simple list of Cases into list of CaseRange's 1991 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 1992 const SwitchInst& SI) { 1993 size_t numCmps = 0; 1994 1995 // Start with "simple" cases 1996 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) { 1997 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 1998 Cases.push_back(Case(SI.getSuccessorValue(i), 1999 SI.getSuccessorValue(i), 2000 SMBB)); 2001 } 2002 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 2003 2004 // Merge case into clusters 2005 if (Cases.size() >= 2) 2006 // Must recompute end() each iteration because it may be 2007 // invalidated by erase if we hold on to it 2008 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) { 2009 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue(); 2010 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue(); 2011 MachineBasicBlock* nextBB = J->BB; 2012 MachineBasicBlock* currentBB = I->BB; 2013 2014 // If the two neighboring cases go to the same destination, merge them 2015 // into a single case. 2016 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) { 2017 I->High = J->High; 2018 J = Cases.erase(J); 2019 } else { 2020 I = J++; 2021 } 2022 } 2023 2024 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 2025 if (I->Low != I->High) 2026 // A range counts double, since it requires two compares. 2027 ++numCmps; 2028 } 2029 2030 return numCmps; 2031 } 2032 2033 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) { 2034 // Figure out which block is immediately after the current one. 2035 MachineBasicBlock *NextBlock = 0; 2036 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2037 2038 // If there is only the default destination, branch to it if it is not the 2039 // next basic block. Otherwise, just fall through. 2040 if (SI.getNumOperands() == 2) { 2041 // Update machine-CFG edges. 2042 2043 // If this is not a fall-through branch, emit the branch. 2044 CurMBB->addSuccessor(Default); 2045 if (Default != NextBlock) { 2046 SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(), 2047 MVT::Other, getControlRoot(), 2048 DAG.getBasicBlock(Default)); 2049 DAG.setRoot(Res); 2050 2051 if (DisableScheduling) 2052 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2053 } 2054 2055 return; 2056 } 2057 2058 // If there are any non-default case statements, create a vector of Cases 2059 // representing each one, and sort the vector so that we can efficiently 2060 // create a binary search tree from them. 2061 CaseVector Cases; 2062 size_t numCmps = Clusterify(Cases, SI); 2063 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size() 2064 << ". Total compares: " << numCmps << '\n'); 2065 numCmps = 0; 2066 2067 // Get the Value to be switched on and default basic blocks, which will be 2068 // inserted into CaseBlock records, representing basic blocks in the binary 2069 // search tree. 2070 Value *SV = SI.getOperand(0); 2071 2072 // Push the initial CaseRec onto the worklist 2073 CaseRecVector WorkList; 2074 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end()))); 2075 2076 while (!WorkList.empty()) { 2077 // Grab a record representing a case range to process off the worklist 2078 CaseRec CR = WorkList.back(); 2079 WorkList.pop_back(); 2080 2081 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default)) 2082 continue; 2083 2084 // If the range has few cases (two or less) emit a series of specific 2085 // tests. 2086 if (handleSmallSwitchRange(CR, WorkList, SV, Default)) 2087 continue; 2088 2089 // If the switch has more than 5 blocks, and at least 40% dense, and the 2090 // target supports indirect branches, then emit a jump table rather than 2091 // lowering the switch to a binary tree of conditional branches. 2092 if (handleJTSwitchCase(CR, WorkList, SV, Default)) 2093 continue; 2094 2095 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2096 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2097 handleBTSplitSwitchCase(CR, WorkList, SV, Default); 2098 } 2099 } 2100 2101 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) { 2102 // Update machine-CFG edges. 2103 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) 2104 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]); 2105 2106 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(), 2107 MVT::Other, getControlRoot(), 2108 getValue(I.getAddress())); 2109 DAG.setRoot(Res); 2110 2111 if (DisableScheduling) 2112 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2113 } 2114 2115 void SelectionDAGBuilder::visitFSub(User &I) { 2116 // -0.0 - X --> fneg 2117 const Type *Ty = I.getType(); 2118 if (isa<VectorType>(Ty)) { 2119 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) { 2120 const VectorType *DestTy = cast<VectorType>(I.getType()); 2121 const Type *ElTy = DestTy->getElementType(); 2122 unsigned VL = DestTy->getNumElements(); 2123 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy)); 2124 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size()); 2125 if (CV == CNZ) { 2126 SDValue Op2 = getValue(I.getOperand(1)); 2127 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2128 Op2.getValueType(), Op2); 2129 setValue(&I, Res); 2130 2131 if (DisableScheduling) 2132 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2133 2134 return; 2135 } 2136 } 2137 } 2138 2139 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 2140 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) { 2141 SDValue Op2 = getValue(I.getOperand(1)); 2142 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2143 Op2.getValueType(), Op2); 2144 setValue(&I, Res); 2145 2146 if (DisableScheduling) 2147 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2148 2149 return; 2150 } 2151 2152 visitBinary(I, ISD::FSUB); 2153 } 2154 2155 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) { 2156 SDValue Op1 = getValue(I.getOperand(0)); 2157 SDValue Op2 = getValue(I.getOperand(1)); 2158 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(), 2159 Op1.getValueType(), Op1, Op2); 2160 setValue(&I, Res); 2161 2162 if (DisableScheduling) 2163 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2164 } 2165 2166 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) { 2167 SDValue Op1 = getValue(I.getOperand(0)); 2168 SDValue Op2 = getValue(I.getOperand(1)); 2169 if (!isa<VectorType>(I.getType()) && 2170 Op2.getValueType() != TLI.getShiftAmountTy()) { 2171 // If the operand is smaller than the shift count type, promote it. 2172 EVT PTy = TLI.getPointerTy(); 2173 EVT STy = TLI.getShiftAmountTy(); 2174 if (STy.bitsGT(Op2.getValueType())) 2175 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2176 TLI.getShiftAmountTy(), Op2); 2177 // If the operand is larger than the shift count type but the shift 2178 // count type has enough bits to represent any shift value, truncate 2179 // it now. This is a common case and it exposes the truncate to 2180 // optimization early. 2181 else if (STy.getSizeInBits() >= 2182 Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2183 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2184 TLI.getShiftAmountTy(), Op2); 2185 // Otherwise we'll need to temporarily settle for some other 2186 // convenient type; type legalization will make adjustments as 2187 // needed. 2188 else if (PTy.bitsLT(Op2.getValueType())) 2189 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2190 TLI.getPointerTy(), Op2); 2191 else if (PTy.bitsGT(Op2.getValueType())) 2192 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2193 TLI.getPointerTy(), Op2); 2194 } 2195 2196 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(), 2197 Op1.getValueType(), Op1, Op2); 2198 setValue(&I, Res); 2199 2200 if (DisableScheduling) { 2201 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder); 2202 DAG.AssignOrdering(Op2.getNode(), SDNodeOrder); 2203 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2204 } 2205 } 2206 2207 void SelectionDAGBuilder::visitICmp(User &I) { 2208 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2209 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2210 predicate = IC->getPredicate(); 2211 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2212 predicate = ICmpInst::Predicate(IC->getPredicate()); 2213 SDValue Op1 = getValue(I.getOperand(0)); 2214 SDValue Op2 = getValue(I.getOperand(1)); 2215 ISD::CondCode Opcode = getICmpCondCode(predicate); 2216 2217 EVT DestVT = TLI.getValueType(I.getType()); 2218 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode); 2219 setValue(&I, Res); 2220 2221 if (DisableScheduling) 2222 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2223 } 2224 2225 void SelectionDAGBuilder::visitFCmp(User &I) { 2226 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2227 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2228 predicate = FC->getPredicate(); 2229 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2230 predicate = FCmpInst::Predicate(FC->getPredicate()); 2231 SDValue Op1 = getValue(I.getOperand(0)); 2232 SDValue Op2 = getValue(I.getOperand(1)); 2233 ISD::CondCode Condition = getFCmpCondCode(predicate); 2234 EVT DestVT = TLI.getValueType(I.getType()); 2235 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition); 2236 setValue(&I, Res); 2237 2238 if (DisableScheduling) 2239 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2240 } 2241 2242 void SelectionDAGBuilder::visitSelect(User &I) { 2243 SmallVector<EVT, 4> ValueVTs; 2244 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2245 unsigned NumValues = ValueVTs.size(); 2246 if (NumValues == 0) return; 2247 2248 SmallVector<SDValue, 4> Values(NumValues); 2249 SDValue Cond = getValue(I.getOperand(0)); 2250 SDValue TrueVal = getValue(I.getOperand(1)); 2251 SDValue FalseVal = getValue(I.getOperand(2)); 2252 2253 for (unsigned i = 0; i != NumValues; ++i) { 2254 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 2255 TrueVal.getNode()->getValueType(i), Cond, 2256 SDValue(TrueVal.getNode(), 2257 TrueVal.getResNo() + i), 2258 SDValue(FalseVal.getNode(), 2259 FalseVal.getResNo() + i)); 2260 2261 if (DisableScheduling) 2262 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder); 2263 } 2264 2265 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2266 DAG.getVTList(&ValueVTs[0], NumValues), 2267 &Values[0], NumValues); 2268 setValue(&I, Res); 2269 2270 if (DisableScheduling) 2271 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2272 } 2273 2274 void SelectionDAGBuilder::visitTrunc(User &I) { 2275 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2276 SDValue N = getValue(I.getOperand(0)); 2277 EVT DestVT = TLI.getValueType(I.getType()); 2278 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N); 2279 setValue(&I, Res); 2280 2281 if (DisableScheduling) 2282 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2283 } 2284 2285 void SelectionDAGBuilder::visitZExt(User &I) { 2286 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2287 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2288 SDValue N = getValue(I.getOperand(0)); 2289 EVT DestVT = TLI.getValueType(I.getType()); 2290 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N); 2291 setValue(&I, Res); 2292 2293 if (DisableScheduling) 2294 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2295 } 2296 2297 void SelectionDAGBuilder::visitSExt(User &I) { 2298 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2299 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2300 SDValue N = getValue(I.getOperand(0)); 2301 EVT DestVT = TLI.getValueType(I.getType()); 2302 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N); 2303 setValue(&I, Res); 2304 2305 if (DisableScheduling) 2306 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2307 } 2308 2309 void SelectionDAGBuilder::visitFPTrunc(User &I) { 2310 // FPTrunc is never a no-op cast, no need to check 2311 SDValue N = getValue(I.getOperand(0)); 2312 EVT DestVT = TLI.getValueType(I.getType()); 2313 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 2314 DestVT, N, DAG.getIntPtrConstant(0)); 2315 setValue(&I, Res); 2316 2317 if (DisableScheduling) 2318 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2319 } 2320 2321 void SelectionDAGBuilder::visitFPExt(User &I){ 2322 // FPTrunc is never a no-op cast, no need to check 2323 SDValue N = getValue(I.getOperand(0)); 2324 EVT DestVT = TLI.getValueType(I.getType()); 2325 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N); 2326 setValue(&I, Res); 2327 2328 if (DisableScheduling) 2329 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2330 } 2331 2332 void SelectionDAGBuilder::visitFPToUI(User &I) { 2333 // FPToUI is never a no-op cast, no need to check 2334 SDValue N = getValue(I.getOperand(0)); 2335 EVT DestVT = TLI.getValueType(I.getType()); 2336 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N); 2337 setValue(&I, Res); 2338 2339 if (DisableScheduling) 2340 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2341 } 2342 2343 void SelectionDAGBuilder::visitFPToSI(User &I) { 2344 // FPToSI is never a no-op cast, no need to check 2345 SDValue N = getValue(I.getOperand(0)); 2346 EVT DestVT = TLI.getValueType(I.getType()); 2347 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N); 2348 setValue(&I, Res); 2349 2350 if (DisableScheduling) 2351 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2352 } 2353 2354 void SelectionDAGBuilder::visitUIToFP(User &I) { 2355 // UIToFP is never a no-op cast, no need to check 2356 SDValue N = getValue(I.getOperand(0)); 2357 EVT DestVT = TLI.getValueType(I.getType()); 2358 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N); 2359 setValue(&I, Res); 2360 2361 if (DisableScheduling) 2362 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2363 } 2364 2365 void SelectionDAGBuilder::visitSIToFP(User &I){ 2366 // SIToFP is never a no-op cast, no need to check 2367 SDValue N = getValue(I.getOperand(0)); 2368 EVT DestVT = TLI.getValueType(I.getType()); 2369 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N); 2370 setValue(&I, Res); 2371 2372 if (DisableScheduling) 2373 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2374 } 2375 2376 void SelectionDAGBuilder::visitPtrToInt(User &I) { 2377 // What to do depends on the size of the integer and the size of the pointer. 2378 // We can either truncate, zero extend, or no-op, accordingly. 2379 SDValue N = getValue(I.getOperand(0)); 2380 EVT SrcVT = N.getValueType(); 2381 EVT DestVT = TLI.getValueType(I.getType()); 2382 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT); 2383 setValue(&I, Res); 2384 2385 if (DisableScheduling) 2386 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2387 } 2388 2389 void SelectionDAGBuilder::visitIntToPtr(User &I) { 2390 // What to do depends on the size of the integer and the size of the pointer. 2391 // We can either truncate, zero extend, or no-op, accordingly. 2392 SDValue N = getValue(I.getOperand(0)); 2393 EVT SrcVT = N.getValueType(); 2394 EVT DestVT = TLI.getValueType(I.getType()); 2395 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT); 2396 setValue(&I, Res); 2397 2398 if (DisableScheduling) 2399 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2400 } 2401 2402 void SelectionDAGBuilder::visitBitCast(User &I) { 2403 SDValue N = getValue(I.getOperand(0)); 2404 EVT DestVT = TLI.getValueType(I.getType()); 2405 2406 // BitCast assures us that source and destination are the same size so this is 2407 // either a BIT_CONVERT or a no-op. 2408 if (DestVT != N.getValueType()) { 2409 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 2410 DestVT, N); // convert types. 2411 setValue(&I, Res); 2412 2413 if (DisableScheduling) 2414 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2415 } else { 2416 setValue(&I, N); // noop cast. 2417 } 2418 } 2419 2420 void SelectionDAGBuilder::visitInsertElement(User &I) { 2421 SDValue InVec = getValue(I.getOperand(0)); 2422 SDValue InVal = getValue(I.getOperand(1)); 2423 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2424 TLI.getPointerTy(), 2425 getValue(I.getOperand(2))); 2426 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 2427 TLI.getValueType(I.getType()), 2428 InVec, InVal, InIdx); 2429 setValue(&I, Res); 2430 2431 if (DisableScheduling) { 2432 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder); 2433 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2434 } 2435 } 2436 2437 void SelectionDAGBuilder::visitExtractElement(User &I) { 2438 SDValue InVec = getValue(I.getOperand(0)); 2439 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2440 TLI.getPointerTy(), 2441 getValue(I.getOperand(1))); 2442 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2443 TLI.getValueType(I.getType()), InVec, InIdx); 2444 setValue(&I, Res); 2445 2446 if (DisableScheduling) { 2447 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder); 2448 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2449 } 2450 } 2451 2452 2453 // Utility for visitShuffleVector - Returns true if the mask is mask starting 2454 // from SIndx and increasing to the element length (undefs are allowed). 2455 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) { 2456 unsigned MaskNumElts = Mask.size(); 2457 for (unsigned i = 0; i != MaskNumElts; ++i) 2458 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx))) 2459 return false; 2460 return true; 2461 } 2462 2463 void SelectionDAGBuilder::visitShuffleVector(User &I) { 2464 SmallVector<int, 8> Mask; 2465 SDValue Src1 = getValue(I.getOperand(0)); 2466 SDValue Src2 = getValue(I.getOperand(1)); 2467 2468 // Convert the ConstantVector mask operand into an array of ints, with -1 2469 // representing undef values. 2470 SmallVector<Constant*, 8> MaskElts; 2471 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(), 2472 MaskElts); 2473 unsigned MaskNumElts = MaskElts.size(); 2474 for (unsigned i = 0; i != MaskNumElts; ++i) { 2475 if (isa<UndefValue>(MaskElts[i])) 2476 Mask.push_back(-1); 2477 else 2478 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue()); 2479 } 2480 2481 EVT VT = TLI.getValueType(I.getType()); 2482 EVT SrcVT = Src1.getValueType(); 2483 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2484 2485 if (SrcNumElts == MaskNumElts) { 2486 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2487 &Mask[0]); 2488 setValue(&I, Res); 2489 2490 if (DisableScheduling) 2491 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2492 2493 return; 2494 } 2495 2496 // Normalize the shuffle vector since mask and vector length don't match. 2497 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2498 // Mask is longer than the source vectors and is a multiple of the source 2499 // vectors. We can use concatenate vector to make the mask and vectors 2500 // lengths match. 2501 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) { 2502 // The shuffle is concatenating two vectors together. 2503 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 2504 VT, Src1, Src2); 2505 setValue(&I, Res); 2506 2507 if (DisableScheduling) 2508 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2509 2510 return; 2511 } 2512 2513 // Pad both vectors with undefs to make them the same length as the mask. 2514 unsigned NumConcat = MaskNumElts / SrcNumElts; 2515 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2516 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2517 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2518 2519 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2520 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2521 MOps1[0] = Src1; 2522 MOps2[0] = Src2; 2523 2524 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2525 getCurDebugLoc(), VT, 2526 &MOps1[0], NumConcat); 2527 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2528 getCurDebugLoc(), VT, 2529 &MOps2[0], NumConcat); 2530 2531 // Readjust mask for new input vector length. 2532 SmallVector<int, 8> MappedOps; 2533 for (unsigned i = 0; i != MaskNumElts; ++i) { 2534 int Idx = Mask[i]; 2535 if (Idx < (int)SrcNumElts) 2536 MappedOps.push_back(Idx); 2537 else 2538 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); 2539 } 2540 2541 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2542 &MappedOps[0]); 2543 setValue(&I, Res); 2544 2545 if (DisableScheduling) { 2546 DAG.AssignOrdering(Src1.getNode(), SDNodeOrder); 2547 DAG.AssignOrdering(Src2.getNode(), SDNodeOrder); 2548 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2549 } 2550 2551 return; 2552 } 2553 2554 if (SrcNumElts > MaskNumElts) { 2555 // Analyze the access pattern of the vector to see if we can extract 2556 // two subvectors and do the shuffle. The analysis is done by calculating 2557 // the range of elements the mask access on both vectors. 2558 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1}; 2559 int MaxRange[2] = {-1, -1}; 2560 2561 for (unsigned i = 0; i != MaskNumElts; ++i) { 2562 int Idx = Mask[i]; 2563 int Input = 0; 2564 if (Idx < 0) 2565 continue; 2566 2567 if (Idx >= (int)SrcNumElts) { 2568 Input = 1; 2569 Idx -= SrcNumElts; 2570 } 2571 if (Idx > MaxRange[Input]) 2572 MaxRange[Input] = Idx; 2573 if (Idx < MinRange[Input]) 2574 MinRange[Input] = Idx; 2575 } 2576 2577 // Check if the access is smaller than the vector size and can we find 2578 // a reasonable extract index. 2579 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract. 2580 int StartIdx[2]; // StartIdx to extract from 2581 for (int Input=0; Input < 2; ++Input) { 2582 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { 2583 RangeUse[Input] = 0; // Unused 2584 StartIdx[Input] = 0; 2585 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) { 2586 // Fits within range but we should see if we can find a good 2587 // start index that is a multiple of the mask length. 2588 if (MaxRange[Input] < (int)MaskNumElts) { 2589 RangeUse[Input] = 1; // Extract from beginning of the vector 2590 StartIdx[Input] = 0; 2591 } else { 2592 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2593 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2594 StartIdx[Input] + MaskNumElts < SrcNumElts) 2595 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2596 } 2597 } 2598 } 2599 2600 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2601 SDValue Res = DAG.getUNDEF(VT); 2602 setValue(&I, Res); // Vectors are not used. 2603 2604 if (DisableScheduling) 2605 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2606 2607 return; 2608 } 2609 else if (RangeUse[0] < 2 && RangeUse[1] < 2) { 2610 // Extract appropriate subvector and generate a vector shuffle 2611 for (int Input=0; Input < 2; ++Input) { 2612 SDValue &Src = Input == 0 ? Src1 : Src2; 2613 if (RangeUse[Input] == 0) 2614 Src = DAG.getUNDEF(VT); 2615 else 2616 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT, 2617 Src, DAG.getIntPtrConstant(StartIdx[Input])); 2618 2619 if (DisableScheduling) 2620 DAG.AssignOrdering(Src.getNode(), SDNodeOrder); 2621 } 2622 2623 // Calculate new mask. 2624 SmallVector<int, 8> MappedOps; 2625 for (unsigned i = 0; i != MaskNumElts; ++i) { 2626 int Idx = Mask[i]; 2627 if (Idx < 0) 2628 MappedOps.push_back(Idx); 2629 else if (Idx < (int)SrcNumElts) 2630 MappedOps.push_back(Idx - StartIdx[0]); 2631 else 2632 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts); 2633 } 2634 2635 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2636 &MappedOps[0]); 2637 setValue(&I, Res); 2638 2639 if (DisableScheduling) 2640 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2641 2642 return; 2643 } 2644 } 2645 2646 // We can't use either concat vectors or extract subvectors so fall back to 2647 // replacing the shuffle with extract and build vector. 2648 // to insert and build vector. 2649 EVT EltVT = VT.getVectorElementType(); 2650 EVT PtrVT = TLI.getPointerTy(); 2651 SmallVector<SDValue,8> Ops; 2652 for (unsigned i = 0; i != MaskNumElts; ++i) { 2653 if (Mask[i] < 0) { 2654 Ops.push_back(DAG.getUNDEF(EltVT)); 2655 } else { 2656 int Idx = Mask[i]; 2657 SDValue Res; 2658 2659 if (Idx < (int)SrcNumElts) 2660 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2661 EltVT, Src1, DAG.getConstant(Idx, PtrVT)); 2662 else 2663 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2664 EltVT, Src2, 2665 DAG.getConstant(Idx - SrcNumElts, PtrVT)); 2666 2667 Ops.push_back(Res); 2668 2669 if (DisableScheduling) 2670 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2671 } 2672 } 2673 2674 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 2675 VT, &Ops[0], Ops.size()); 2676 setValue(&I, Res); 2677 2678 if (DisableScheduling) 2679 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2680 } 2681 2682 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) { 2683 const Value *Op0 = I.getOperand(0); 2684 const Value *Op1 = I.getOperand(1); 2685 const Type *AggTy = I.getType(); 2686 const Type *ValTy = Op1->getType(); 2687 bool IntoUndef = isa<UndefValue>(Op0); 2688 bool FromUndef = isa<UndefValue>(Op1); 2689 2690 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2691 I.idx_begin(), I.idx_end()); 2692 2693 SmallVector<EVT, 4> AggValueVTs; 2694 ComputeValueVTs(TLI, AggTy, AggValueVTs); 2695 SmallVector<EVT, 4> ValValueVTs; 2696 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2697 2698 unsigned NumAggValues = AggValueVTs.size(); 2699 unsigned NumValValues = ValValueVTs.size(); 2700 SmallVector<SDValue, 4> Values(NumAggValues); 2701 2702 SDValue Agg = getValue(Op0); 2703 SDValue Val = getValue(Op1); 2704 unsigned i = 0; 2705 // Copy the beginning value(s) from the original aggregate. 2706 for (; i != LinearIndex; ++i) 2707 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2708 SDValue(Agg.getNode(), Agg.getResNo() + i); 2709 // Copy values from the inserted value(s). 2710 for (; i != LinearIndex + NumValValues; ++i) 2711 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2712 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2713 // Copy remaining value(s) from the original aggregate. 2714 for (; i != NumAggValues; ++i) 2715 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2716 SDValue(Agg.getNode(), Agg.getResNo() + i); 2717 2718 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2719 DAG.getVTList(&AggValueVTs[0], NumAggValues), 2720 &Values[0], NumAggValues); 2721 setValue(&I, Res); 2722 2723 if (DisableScheduling) 2724 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2725 } 2726 2727 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) { 2728 const Value *Op0 = I.getOperand(0); 2729 const Type *AggTy = Op0->getType(); 2730 const Type *ValTy = I.getType(); 2731 bool OutOfUndef = isa<UndefValue>(Op0); 2732 2733 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2734 I.idx_begin(), I.idx_end()); 2735 2736 SmallVector<EVT, 4> ValValueVTs; 2737 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2738 2739 unsigned NumValValues = ValValueVTs.size(); 2740 SmallVector<SDValue, 4> Values(NumValValues); 2741 2742 SDValue Agg = getValue(Op0); 2743 // Copy out the selected value(s). 2744 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2745 Values[i - LinearIndex] = 2746 OutOfUndef ? 2747 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2748 SDValue(Agg.getNode(), Agg.getResNo() + i); 2749 2750 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2751 DAG.getVTList(&ValValueVTs[0], NumValValues), 2752 &Values[0], NumValValues); 2753 setValue(&I, Res); 2754 2755 if (DisableScheduling) 2756 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2757 } 2758 2759 void SelectionDAGBuilder::visitGetElementPtr(User &I) { 2760 SDValue N = getValue(I.getOperand(0)); 2761 const Type *Ty = I.getOperand(0)->getType(); 2762 2763 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 2764 OI != E; ++OI) { 2765 Value *Idx = *OI; 2766 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2767 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2768 if (Field) { 2769 // N = N + Offset 2770 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2771 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2772 DAG.getIntPtrConstant(Offset)); 2773 2774 if (DisableScheduling) 2775 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2776 } 2777 2778 Ty = StTy->getElementType(Field); 2779 } else { 2780 Ty = cast<SequentialType>(Ty)->getElementType(); 2781 2782 // If this is a constant subscript, handle it quickly. 2783 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2784 if (CI->getZExtValue() == 0) continue; 2785 uint64_t Offs = 2786 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2787 SDValue OffsVal; 2788 EVT PTy = TLI.getPointerTy(); 2789 unsigned PtrBits = PTy.getSizeInBits(); 2790 if (PtrBits < 64) 2791 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2792 TLI.getPointerTy(), 2793 DAG.getConstant(Offs, MVT::i64)); 2794 else 2795 OffsVal = DAG.getIntPtrConstant(Offs); 2796 2797 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2798 OffsVal); 2799 2800 if (DisableScheduling) { 2801 DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder); 2802 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2803 } 2804 2805 continue; 2806 } 2807 2808 // N = N + Idx * ElementSize; 2809 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(), 2810 TD->getTypeAllocSize(Ty)); 2811 SDValue IdxN = getValue(Idx); 2812 2813 // If the index is smaller or larger than intptr_t, truncate or extend 2814 // it. 2815 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType()); 2816 2817 // If this is a multiply by a power of two, turn it into a shl 2818 // immediately. This is a very common case. 2819 if (ElementSize != 1) { 2820 if (ElementSize.isPowerOf2()) { 2821 unsigned Amt = ElementSize.logBase2(); 2822 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 2823 N.getValueType(), IdxN, 2824 DAG.getConstant(Amt, TLI.getPointerTy())); 2825 } else { 2826 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy()); 2827 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 2828 N.getValueType(), IdxN, Scale); 2829 } 2830 2831 if (DisableScheduling) 2832 DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder); 2833 } 2834 2835 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2836 N.getValueType(), N, IdxN); 2837 2838 if (DisableScheduling) 2839 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2840 } 2841 } 2842 2843 setValue(&I, N); 2844 } 2845 2846 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) { 2847 // If this is a fixed sized alloca in the entry block of the function, 2848 // allocate it statically on the stack. 2849 if (FuncInfo.StaticAllocaMap.count(&I)) 2850 return; // getValue will auto-populate this. 2851 2852 const Type *Ty = I.getAllocatedType(); 2853 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 2854 unsigned Align = 2855 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2856 I.getAlignment()); 2857 2858 SDValue AllocSize = getValue(I.getArraySize()); 2859 2860 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(), 2861 AllocSize, 2862 DAG.getConstant(TySize, AllocSize.getValueType())); 2863 2864 2865 2866 EVT IntPtr = TLI.getPointerTy(); 2867 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); 2868 2869 // Handle alignment. If the requested alignment is less than or equal to 2870 // the stack alignment, ignore it. If the size is greater than or equal to 2871 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2872 unsigned StackAlign = 2873 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 2874 if (Align <= StackAlign) 2875 Align = 0; 2876 2877 // Round the size of the allocation up to the stack alignment size 2878 // by add SA-1 to the size. 2879 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2880 AllocSize.getValueType(), AllocSize, 2881 DAG.getIntPtrConstant(StackAlign-1)); 2882 // Mask out the low bits for alignment purposes. 2883 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 2884 AllocSize.getValueType(), AllocSize, 2885 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2886 2887 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 2888 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2889 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 2890 VTs, Ops, 3); 2891 setValue(&I, DSA); 2892 DAG.setRoot(DSA.getValue(1)); 2893 2894 // Inform the Frame Information that we have just allocated a variable-sized 2895 // object. 2896 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(); 2897 } 2898 2899 void SelectionDAGBuilder::visitLoad(LoadInst &I) { 2900 const Value *SV = I.getOperand(0); 2901 SDValue Ptr = getValue(SV); 2902 2903 const Type *Ty = I.getType(); 2904 bool isVolatile = I.isVolatile(); 2905 unsigned Alignment = I.getAlignment(); 2906 2907 SmallVector<EVT, 4> ValueVTs; 2908 SmallVector<uint64_t, 4> Offsets; 2909 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets); 2910 unsigned NumValues = ValueVTs.size(); 2911 if (NumValues == 0) 2912 return; 2913 2914 SDValue Root; 2915 bool ConstantMemory = false; 2916 if (I.isVolatile()) 2917 // Serialize volatile loads with other side effects. 2918 Root = getRoot(); 2919 else if (AA->pointsToConstantMemory(SV)) { 2920 // Do not serialize (non-volatile) loads of constant memory with anything. 2921 Root = DAG.getEntryNode(); 2922 ConstantMemory = true; 2923 } else { 2924 // Do not serialize non-volatile loads against each other. 2925 Root = DAG.getRoot(); 2926 } 2927 2928 SmallVector<SDValue, 4> Values(NumValues); 2929 SmallVector<SDValue, 4> Chains(NumValues); 2930 EVT PtrVT = Ptr.getValueType(); 2931 for (unsigned i = 0; i != NumValues; ++i) { 2932 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root, 2933 DAG.getNode(ISD::ADD, getCurDebugLoc(), 2934 PtrVT, Ptr, 2935 DAG.getConstant(Offsets[i], PtrVT)), 2936 SV, Offsets[i], isVolatile, Alignment); 2937 Values[i] = L; 2938 Chains[i] = L.getValue(1); 2939 } 2940 2941 if (!ConstantMemory) { 2942 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2943 MVT::Other, 2944 &Chains[0], NumValues); 2945 if (isVolatile) 2946 DAG.setRoot(Chain); 2947 else 2948 PendingLoads.push_back(Chain); 2949 } 2950 2951 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2952 DAG.getVTList(&ValueVTs[0], NumValues), 2953 &Values[0], NumValues)); 2954 } 2955 2956 2957 void SelectionDAGBuilder::visitStore(StoreInst &I) { 2958 Value *SrcV = I.getOperand(0); 2959 Value *PtrV = I.getOperand(1); 2960 2961 SmallVector<EVT, 4> ValueVTs; 2962 SmallVector<uint64_t, 4> Offsets; 2963 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets); 2964 unsigned NumValues = ValueVTs.size(); 2965 if (NumValues == 0) 2966 return; 2967 2968 // Get the lowered operands. Note that we do this after 2969 // checking if NumResults is zero, because with zero results 2970 // the operands won't have values in the map. 2971 SDValue Src = getValue(SrcV); 2972 SDValue Ptr = getValue(PtrV); 2973 2974 SDValue Root = getRoot(); 2975 SmallVector<SDValue, 4> Chains(NumValues); 2976 EVT PtrVT = Ptr.getValueType(); 2977 bool isVolatile = I.isVolatile(); 2978 unsigned Alignment = I.getAlignment(); 2979 for (unsigned i = 0; i != NumValues; ++i) 2980 Chains[i] = DAG.getStore(Root, getCurDebugLoc(), 2981 SDValue(Src.getNode(), Src.getResNo() + i), 2982 DAG.getNode(ISD::ADD, getCurDebugLoc(), 2983 PtrVT, Ptr, 2984 DAG.getConstant(Offsets[i], PtrVT)), 2985 PtrV, Offsets[i], isVolatile, Alignment); 2986 2987 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2988 MVT::Other, &Chains[0], NumValues)); 2989 } 2990 2991 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 2992 /// node. 2993 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I, 2994 unsigned Intrinsic) { 2995 bool HasChain = !I.doesNotAccessMemory(); 2996 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 2997 2998 // Build the operand list. 2999 SmallVector<SDValue, 8> Ops; 3000 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3001 if (OnlyLoad) { 3002 // We don't need to serialize loads against other loads. 3003 Ops.push_back(DAG.getRoot()); 3004 } else { 3005 Ops.push_back(getRoot()); 3006 } 3007 } 3008 3009 // Info is set by getTgtMemInstrinsic 3010 TargetLowering::IntrinsicInfo Info; 3011 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 3012 3013 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3014 if (!IsTgtIntrinsic) 3015 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 3016 3017 // Add all operands of the call to the operand list. 3018 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 3019 SDValue Op = getValue(I.getOperand(i)); 3020 assert(TLI.isTypeLegal(Op.getValueType()) && 3021 "Intrinsic uses a non-legal type?"); 3022 Ops.push_back(Op); 3023 } 3024 3025 SmallVector<EVT, 4> ValueVTs; 3026 ComputeValueVTs(TLI, I.getType(), ValueVTs); 3027 #ifndef NDEBUG 3028 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) { 3029 assert(TLI.isTypeLegal(ValueVTs[Val]) && 3030 "Intrinsic uses a non-legal type?"); 3031 } 3032 #endif // NDEBUG 3033 if (HasChain) 3034 ValueVTs.push_back(MVT::Other); 3035 3036 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 3037 3038 // Create the node. 3039 SDValue Result; 3040 if (IsTgtIntrinsic) { 3041 // This is target intrinsic that touches memory 3042 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(), 3043 VTs, &Ops[0], Ops.size(), 3044 Info.memVT, Info.ptrVal, Info.offset, 3045 Info.align, Info.vol, 3046 Info.readMem, Info.writeMem); 3047 } 3048 else if (!HasChain) 3049 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 3050 VTs, &Ops[0], Ops.size()); 3051 else if (I.getType() != Type::getVoidTy(*DAG.getContext())) 3052 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 3053 VTs, &Ops[0], Ops.size()); 3054 else 3055 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 3056 VTs, &Ops[0], Ops.size()); 3057 3058 if (HasChain) { 3059 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3060 if (OnlyLoad) 3061 PendingLoads.push_back(Chain); 3062 else 3063 DAG.setRoot(Chain); 3064 } 3065 if (I.getType() != Type::getVoidTy(*DAG.getContext())) { 3066 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3067 EVT VT = TLI.getValueType(PTy); 3068 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result); 3069 } 3070 setValue(&I, Result); 3071 } 3072 } 3073 3074 /// GetSignificand - Get the significand and build it into a floating-point 3075 /// number with exponent of 1: 3076 /// 3077 /// Op = (Op & 0x007fffff) | 0x3f800000; 3078 /// 3079 /// where Op is the hexidecimal representation of floating point value. 3080 static SDValue 3081 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) { 3082 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3083 DAG.getConstant(0x007fffff, MVT::i32)); 3084 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3085 DAG.getConstant(0x3f800000, MVT::i32)); 3086 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2); 3087 } 3088 3089 /// GetExponent - Get the exponent: 3090 /// 3091 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3092 /// 3093 /// where Op is the hexidecimal representation of floating point value. 3094 static SDValue 3095 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3096 DebugLoc dl) { 3097 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3098 DAG.getConstant(0x7f800000, MVT::i32)); 3099 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 3100 DAG.getConstant(23, TLI.getPointerTy())); 3101 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3102 DAG.getConstant(127, MVT::i32)); 3103 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3104 } 3105 3106 /// getF32Constant - Get 32-bit floating point constant. 3107 static SDValue 3108 getF32Constant(SelectionDAG &DAG, unsigned Flt) { 3109 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32); 3110 } 3111 3112 /// Inlined utility function to implement binary input atomic intrinsics for 3113 /// visitIntrinsicCall: I is a call instruction 3114 /// Op is the associated NodeType for I 3115 const char * 3116 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) { 3117 SDValue Root = getRoot(); 3118 SDValue L = 3119 DAG.getAtomic(Op, getCurDebugLoc(), 3120 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 3121 Root, 3122 getValue(I.getOperand(1)), 3123 getValue(I.getOperand(2)), 3124 I.getOperand(1)); 3125 setValue(&I, L); 3126 DAG.setRoot(L.getValue(1)); 3127 return 0; 3128 } 3129 3130 // implVisitAluOverflow - Lower arithmetic overflow instrinsics. 3131 const char * 3132 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) { 3133 SDValue Op1 = getValue(I.getOperand(1)); 3134 SDValue Op2 = getValue(I.getOperand(2)); 3135 3136 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 3137 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2); 3138 3139 setValue(&I, Result); 3140 return 0; 3141 } 3142 3143 /// visitExp - Lower an exp intrinsic. Handles the special sequences for 3144 /// limited-precision mode. 3145 void 3146 SelectionDAGBuilder::visitExp(CallInst &I) { 3147 SDValue result; 3148 DebugLoc dl = getCurDebugLoc(); 3149 3150 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3151 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3152 SDValue Op = getValue(I.getOperand(1)); 3153 3154 // Put the exponent in the right bit position for later addition to the 3155 // final result: 3156 // 3157 // #define LOG2OFe 1.4426950f 3158 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 3159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3160 getF32Constant(DAG, 0x3fb8aa3b)); 3161 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3162 3163 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 3164 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3165 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3166 3167 // IntegerPartOfX <<= 23; 3168 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3169 DAG.getConstant(23, TLI.getPointerTy())); 3170 3171 if (LimitFloatPrecision <= 6) { 3172 // For floating-point precision of 6: 3173 // 3174 // TwoToFractionalPartOfX = 3175 // 0.997535578f + 3176 // (0.735607626f + 0.252464424f * x) * x; 3177 // 3178 // error 0.0144103317, which is 6 bits 3179 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3180 getF32Constant(DAG, 0x3e814304)); 3181 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3182 getF32Constant(DAG, 0x3f3c50c8)); 3183 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3184 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3185 getF32Constant(DAG, 0x3f7f5e7e)); 3186 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5); 3187 3188 // Add the exponent into the result in integer domain. 3189 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3190 TwoToFracPartOfX, IntegerPartOfX); 3191 3192 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6); 3193 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3194 // For floating-point precision of 12: 3195 // 3196 // TwoToFractionalPartOfX = 3197 // 0.999892986f + 3198 // (0.696457318f + 3199 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3200 // 3201 // 0.000107046256 error, which is 13 to 14 bits 3202 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3203 getF32Constant(DAG, 0x3da235e3)); 3204 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3205 getF32Constant(DAG, 0x3e65b8f3)); 3206 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3207 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3208 getF32Constant(DAG, 0x3f324b07)); 3209 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3210 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3211 getF32Constant(DAG, 0x3f7ff8fd)); 3212 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7); 3213 3214 // Add the exponent into the result in integer domain. 3215 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3216 TwoToFracPartOfX, IntegerPartOfX); 3217 3218 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8); 3219 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3220 // For floating-point precision of 18: 3221 // 3222 // TwoToFractionalPartOfX = 3223 // 0.999999982f + 3224 // (0.693148872f + 3225 // (0.240227044f + 3226 // (0.554906021e-1f + 3227 // (0.961591928e-2f + 3228 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3229 // 3230 // error 2.47208000*10^(-7), which is better than 18 bits 3231 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3232 getF32Constant(DAG, 0x3924b03e)); 3233 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3234 getF32Constant(DAG, 0x3ab24b87)); 3235 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3236 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3237 getF32Constant(DAG, 0x3c1d8c17)); 3238 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3239 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3240 getF32Constant(DAG, 0x3d634a1d)); 3241 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3242 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3243 getF32Constant(DAG, 0x3e75fe14)); 3244 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3245 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3246 getF32Constant(DAG, 0x3f317234)); 3247 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3248 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3249 getF32Constant(DAG, 0x3f800000)); 3250 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl, 3251 MVT::i32, t13); 3252 3253 // Add the exponent into the result in integer domain. 3254 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3255 TwoToFracPartOfX, IntegerPartOfX); 3256 3257 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14); 3258 } 3259 } else { 3260 // No special expansion. 3261 result = DAG.getNode(ISD::FEXP, dl, 3262 getValue(I.getOperand(1)).getValueType(), 3263 getValue(I.getOperand(1))); 3264 } 3265 3266 setValue(&I, result); 3267 } 3268 3269 /// visitLog - Lower a log intrinsic. Handles the special sequences for 3270 /// limited-precision mode. 3271 void 3272 SelectionDAGBuilder::visitLog(CallInst &I) { 3273 SDValue result; 3274 DebugLoc dl = getCurDebugLoc(); 3275 3276 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3277 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3278 SDValue Op = getValue(I.getOperand(1)); 3279 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3280 3281 // Scale the exponent by log(2) [0.69314718f]. 3282 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3283 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3284 getF32Constant(DAG, 0x3f317218)); 3285 3286 // Get the significand and build it into a floating-point number with 3287 // exponent of 1. 3288 SDValue X = GetSignificand(DAG, Op1, dl); 3289 3290 if (LimitFloatPrecision <= 6) { 3291 // For floating-point precision of 6: 3292 // 3293 // LogofMantissa = 3294 // -1.1609546f + 3295 // (1.4034025f - 0.23903021f * x) * x; 3296 // 3297 // error 0.0034276066, which is better than 8 bits 3298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3299 getF32Constant(DAG, 0xbe74c456)); 3300 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3301 getF32Constant(DAG, 0x3fb3a2b1)); 3302 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3303 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3304 getF32Constant(DAG, 0x3f949a29)); 3305 3306 result = DAG.getNode(ISD::FADD, dl, 3307 MVT::f32, LogOfExponent, LogOfMantissa); 3308 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3309 // For floating-point precision of 12: 3310 // 3311 // LogOfMantissa = 3312 // -1.7417939f + 3313 // (2.8212026f + 3314 // (-1.4699568f + 3315 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3316 // 3317 // error 0.000061011436, which is 14 bits 3318 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3319 getF32Constant(DAG, 0xbd67b6d6)); 3320 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3321 getF32Constant(DAG, 0x3ee4f4b8)); 3322 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3323 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3324 getF32Constant(DAG, 0x3fbc278b)); 3325 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3326 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3327 getF32Constant(DAG, 0x40348e95)); 3328 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3329 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3330 getF32Constant(DAG, 0x3fdef31a)); 3331 3332 result = DAG.getNode(ISD::FADD, dl, 3333 MVT::f32, LogOfExponent, LogOfMantissa); 3334 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3335 // For floating-point precision of 18: 3336 // 3337 // LogOfMantissa = 3338 // -2.1072184f + 3339 // (4.2372794f + 3340 // (-3.7029485f + 3341 // (2.2781945f + 3342 // (-0.87823314f + 3343 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3344 // 3345 // error 0.0000023660568, which is better than 18 bits 3346 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3347 getF32Constant(DAG, 0xbc91e5ac)); 3348 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3349 getF32Constant(DAG, 0x3e4350aa)); 3350 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3351 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3352 getF32Constant(DAG, 0x3f60d3e3)); 3353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3355 getF32Constant(DAG, 0x4011cdf0)); 3356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3357 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3358 getF32Constant(DAG, 0x406cfd1c)); 3359 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3360 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3361 getF32Constant(DAG, 0x408797cb)); 3362 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3363 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3364 getF32Constant(DAG, 0x4006dcab)); 3365 3366 result = DAG.getNode(ISD::FADD, dl, 3367 MVT::f32, LogOfExponent, LogOfMantissa); 3368 } 3369 } else { 3370 // No special expansion. 3371 result = DAG.getNode(ISD::FLOG, dl, 3372 getValue(I.getOperand(1)).getValueType(), 3373 getValue(I.getOperand(1))); 3374 } 3375 3376 setValue(&I, result); 3377 } 3378 3379 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for 3380 /// limited-precision mode. 3381 void 3382 SelectionDAGBuilder::visitLog2(CallInst &I) { 3383 SDValue result; 3384 DebugLoc dl = getCurDebugLoc(); 3385 3386 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3387 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3388 SDValue Op = getValue(I.getOperand(1)); 3389 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3390 3391 // Get the exponent. 3392 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3393 3394 // Get the significand and build it into a floating-point number with 3395 // exponent of 1. 3396 SDValue X = GetSignificand(DAG, Op1, dl); 3397 3398 // Different possible minimax approximations of significand in 3399 // floating-point for various degrees of accuracy over [1,2]. 3400 if (LimitFloatPrecision <= 6) { 3401 // For floating-point precision of 6: 3402 // 3403 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3404 // 3405 // error 0.0049451742, which is more than 7 bits 3406 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3407 getF32Constant(DAG, 0xbeb08fe0)); 3408 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3409 getF32Constant(DAG, 0x40019463)); 3410 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3411 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3412 getF32Constant(DAG, 0x3fd6633d)); 3413 3414 result = DAG.getNode(ISD::FADD, dl, 3415 MVT::f32, LogOfExponent, Log2ofMantissa); 3416 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3417 // For floating-point precision of 12: 3418 // 3419 // Log2ofMantissa = 3420 // -2.51285454f + 3421 // (4.07009056f + 3422 // (-2.12067489f + 3423 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3424 // 3425 // error 0.0000876136000, which is better than 13 bits 3426 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3427 getF32Constant(DAG, 0xbda7262e)); 3428 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3429 getF32Constant(DAG, 0x3f25280b)); 3430 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3431 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3432 getF32Constant(DAG, 0x4007b923)); 3433 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3434 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3435 getF32Constant(DAG, 0x40823e2f)); 3436 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3437 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3438 getF32Constant(DAG, 0x4020d29c)); 3439 3440 result = DAG.getNode(ISD::FADD, dl, 3441 MVT::f32, LogOfExponent, Log2ofMantissa); 3442 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3443 // For floating-point precision of 18: 3444 // 3445 // Log2ofMantissa = 3446 // -3.0400495f + 3447 // (6.1129976f + 3448 // (-5.3420409f + 3449 // (3.2865683f + 3450 // (-1.2669343f + 3451 // (0.27515199f - 3452 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3453 // 3454 // error 0.0000018516, which is better than 18 bits 3455 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3456 getF32Constant(DAG, 0xbcd2769e)); 3457 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3458 getF32Constant(DAG, 0x3e8ce0b9)); 3459 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3460 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3461 getF32Constant(DAG, 0x3fa22ae7)); 3462 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3463 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3464 getF32Constant(DAG, 0x40525723)); 3465 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3466 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3467 getF32Constant(DAG, 0x40aaf200)); 3468 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3469 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3470 getF32Constant(DAG, 0x40c39dad)); 3471 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3472 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3473 getF32Constant(DAG, 0x4042902c)); 3474 3475 result = DAG.getNode(ISD::FADD, dl, 3476 MVT::f32, LogOfExponent, Log2ofMantissa); 3477 } 3478 } else { 3479 // No special expansion. 3480 result = DAG.getNode(ISD::FLOG2, dl, 3481 getValue(I.getOperand(1)).getValueType(), 3482 getValue(I.getOperand(1))); 3483 } 3484 3485 setValue(&I, result); 3486 } 3487 3488 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for 3489 /// limited-precision mode. 3490 void 3491 SelectionDAGBuilder::visitLog10(CallInst &I) { 3492 SDValue result; 3493 DebugLoc dl = getCurDebugLoc(); 3494 3495 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3496 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3497 SDValue Op = getValue(I.getOperand(1)); 3498 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3499 3500 // Scale the exponent by log10(2) [0.30102999f]. 3501 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3502 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3503 getF32Constant(DAG, 0x3e9a209a)); 3504 3505 // Get the significand and build it into a floating-point number with 3506 // exponent of 1. 3507 SDValue X = GetSignificand(DAG, Op1, dl); 3508 3509 if (LimitFloatPrecision <= 6) { 3510 // For floating-point precision of 6: 3511 // 3512 // Log10ofMantissa = 3513 // -0.50419619f + 3514 // (0.60948995f - 0.10380950f * x) * x; 3515 // 3516 // error 0.0014886165, which is 6 bits 3517 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3518 getF32Constant(DAG, 0xbdd49a13)); 3519 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3520 getF32Constant(DAG, 0x3f1c0789)); 3521 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3522 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3523 getF32Constant(DAG, 0x3f011300)); 3524 3525 result = DAG.getNode(ISD::FADD, dl, 3526 MVT::f32, LogOfExponent, Log10ofMantissa); 3527 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3528 // For floating-point precision of 12: 3529 // 3530 // Log10ofMantissa = 3531 // -0.64831180f + 3532 // (0.91751397f + 3533 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3534 // 3535 // error 0.00019228036, which is better than 12 bits 3536 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3537 getF32Constant(DAG, 0x3d431f31)); 3538 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3539 getF32Constant(DAG, 0x3ea21fb2)); 3540 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3541 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3542 getF32Constant(DAG, 0x3f6ae232)); 3543 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3544 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3545 getF32Constant(DAG, 0x3f25f7c3)); 3546 3547 result = DAG.getNode(ISD::FADD, dl, 3548 MVT::f32, LogOfExponent, Log10ofMantissa); 3549 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3550 // For floating-point precision of 18: 3551 // 3552 // Log10ofMantissa = 3553 // -0.84299375f + 3554 // (1.5327582f + 3555 // (-1.0688956f + 3556 // (0.49102474f + 3557 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3558 // 3559 // error 0.0000037995730, which is better than 18 bits 3560 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3561 getF32Constant(DAG, 0x3c5d51ce)); 3562 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3563 getF32Constant(DAG, 0x3e00685a)); 3564 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3565 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3566 getF32Constant(DAG, 0x3efb6798)); 3567 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3568 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3569 getF32Constant(DAG, 0x3f88d192)); 3570 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3571 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3572 getF32Constant(DAG, 0x3fc4316c)); 3573 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3574 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3575 getF32Constant(DAG, 0x3f57ce70)); 3576 3577 result = DAG.getNode(ISD::FADD, dl, 3578 MVT::f32, LogOfExponent, Log10ofMantissa); 3579 } 3580 } else { 3581 // No special expansion. 3582 result = DAG.getNode(ISD::FLOG10, dl, 3583 getValue(I.getOperand(1)).getValueType(), 3584 getValue(I.getOperand(1))); 3585 } 3586 3587 setValue(&I, result); 3588 } 3589 3590 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3591 /// limited-precision mode. 3592 void 3593 SelectionDAGBuilder::visitExp2(CallInst &I) { 3594 SDValue result; 3595 DebugLoc dl = getCurDebugLoc(); 3596 3597 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3598 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3599 SDValue Op = getValue(I.getOperand(1)); 3600 3601 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 3602 3603 // FractionalPartOfX = x - (float)IntegerPartOfX; 3604 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3605 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 3606 3607 // IntegerPartOfX <<= 23; 3608 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3609 DAG.getConstant(23, TLI.getPointerTy())); 3610 3611 if (LimitFloatPrecision <= 6) { 3612 // For floating-point precision of 6: 3613 // 3614 // TwoToFractionalPartOfX = 3615 // 0.997535578f + 3616 // (0.735607626f + 0.252464424f * x) * x; 3617 // 3618 // error 0.0144103317, which is 6 bits 3619 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3620 getF32Constant(DAG, 0x3e814304)); 3621 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3622 getF32Constant(DAG, 0x3f3c50c8)); 3623 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3624 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3625 getF32Constant(DAG, 0x3f7f5e7e)); 3626 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3627 SDValue TwoToFractionalPartOfX = 3628 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3629 3630 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3631 MVT::f32, TwoToFractionalPartOfX); 3632 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3633 // For floating-point precision of 12: 3634 // 3635 // TwoToFractionalPartOfX = 3636 // 0.999892986f + 3637 // (0.696457318f + 3638 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3639 // 3640 // error 0.000107046256, which is 13 to 14 bits 3641 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3642 getF32Constant(DAG, 0x3da235e3)); 3643 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3644 getF32Constant(DAG, 0x3e65b8f3)); 3645 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3646 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3647 getF32Constant(DAG, 0x3f324b07)); 3648 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3649 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3650 getF32Constant(DAG, 0x3f7ff8fd)); 3651 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3652 SDValue TwoToFractionalPartOfX = 3653 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3654 3655 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3656 MVT::f32, TwoToFractionalPartOfX); 3657 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3658 // For floating-point precision of 18: 3659 // 3660 // TwoToFractionalPartOfX = 3661 // 0.999999982f + 3662 // (0.693148872f + 3663 // (0.240227044f + 3664 // (0.554906021e-1f + 3665 // (0.961591928e-2f + 3666 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3667 // error 2.47208000*10^(-7), which is better than 18 bits 3668 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3669 getF32Constant(DAG, 0x3924b03e)); 3670 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3671 getF32Constant(DAG, 0x3ab24b87)); 3672 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3673 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3674 getF32Constant(DAG, 0x3c1d8c17)); 3675 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3676 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3677 getF32Constant(DAG, 0x3d634a1d)); 3678 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3679 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3680 getF32Constant(DAG, 0x3e75fe14)); 3681 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3682 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3683 getF32Constant(DAG, 0x3f317234)); 3684 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3685 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3686 getF32Constant(DAG, 0x3f800000)); 3687 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 3688 SDValue TwoToFractionalPartOfX = 3689 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3690 3691 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3692 MVT::f32, TwoToFractionalPartOfX); 3693 } 3694 } else { 3695 // No special expansion. 3696 result = DAG.getNode(ISD::FEXP2, dl, 3697 getValue(I.getOperand(1)).getValueType(), 3698 getValue(I.getOperand(1))); 3699 } 3700 3701 setValue(&I, result); 3702 } 3703 3704 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3705 /// limited-precision mode with x == 10.0f. 3706 void 3707 SelectionDAGBuilder::visitPow(CallInst &I) { 3708 SDValue result; 3709 Value *Val = I.getOperand(1); 3710 DebugLoc dl = getCurDebugLoc(); 3711 bool IsExp10 = false; 3712 3713 if (getValue(Val).getValueType() == MVT::f32 && 3714 getValue(I.getOperand(2)).getValueType() == MVT::f32 && 3715 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3716 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) { 3717 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 3718 APFloat Ten(10.0f); 3719 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten); 3720 } 3721 } 3722 } 3723 3724 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3725 SDValue Op = getValue(I.getOperand(2)); 3726 3727 // Put the exponent in the right bit position for later addition to the 3728 // final result: 3729 // 3730 // #define LOG2OF10 3.3219281f 3731 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 3732 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3733 getF32Constant(DAG, 0x40549a78)); 3734 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3735 3736 // FractionalPartOfX = x - (float)IntegerPartOfX; 3737 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3738 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3739 3740 // IntegerPartOfX <<= 23; 3741 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3742 DAG.getConstant(23, TLI.getPointerTy())); 3743 3744 if (LimitFloatPrecision <= 6) { 3745 // For floating-point precision of 6: 3746 // 3747 // twoToFractionalPartOfX = 3748 // 0.997535578f + 3749 // (0.735607626f + 0.252464424f * x) * x; 3750 // 3751 // error 0.0144103317, which is 6 bits 3752 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3753 getF32Constant(DAG, 0x3e814304)); 3754 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3755 getF32Constant(DAG, 0x3f3c50c8)); 3756 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3757 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3758 getF32Constant(DAG, 0x3f7f5e7e)); 3759 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3760 SDValue TwoToFractionalPartOfX = 3761 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3762 3763 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3764 MVT::f32, TwoToFractionalPartOfX); 3765 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3766 // For floating-point precision of 12: 3767 // 3768 // TwoToFractionalPartOfX = 3769 // 0.999892986f + 3770 // (0.696457318f + 3771 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3772 // 3773 // error 0.000107046256, which is 13 to 14 bits 3774 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3775 getF32Constant(DAG, 0x3da235e3)); 3776 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3777 getF32Constant(DAG, 0x3e65b8f3)); 3778 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3779 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3780 getF32Constant(DAG, 0x3f324b07)); 3781 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3782 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3783 getF32Constant(DAG, 0x3f7ff8fd)); 3784 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3785 SDValue TwoToFractionalPartOfX = 3786 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3787 3788 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3789 MVT::f32, TwoToFractionalPartOfX); 3790 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3791 // For floating-point precision of 18: 3792 // 3793 // TwoToFractionalPartOfX = 3794 // 0.999999982f + 3795 // (0.693148872f + 3796 // (0.240227044f + 3797 // (0.554906021e-1f + 3798 // (0.961591928e-2f + 3799 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3800 // error 2.47208000*10^(-7), which is better than 18 bits 3801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3802 getF32Constant(DAG, 0x3924b03e)); 3803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3804 getF32Constant(DAG, 0x3ab24b87)); 3805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3806 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3807 getF32Constant(DAG, 0x3c1d8c17)); 3808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3810 getF32Constant(DAG, 0x3d634a1d)); 3811 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3812 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3813 getF32Constant(DAG, 0x3e75fe14)); 3814 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3815 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3816 getF32Constant(DAG, 0x3f317234)); 3817 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3818 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3819 getF32Constant(DAG, 0x3f800000)); 3820 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 3821 SDValue TwoToFractionalPartOfX = 3822 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3823 3824 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3825 MVT::f32, TwoToFractionalPartOfX); 3826 } 3827 } else { 3828 // No special expansion. 3829 result = DAG.getNode(ISD::FPOW, dl, 3830 getValue(I.getOperand(1)).getValueType(), 3831 getValue(I.getOperand(1)), 3832 getValue(I.getOperand(2))); 3833 } 3834 3835 setValue(&I, result); 3836 } 3837 3838 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 3839 /// we want to emit this as a call to a named external function, return the name 3840 /// otherwise lower it and return null. 3841 const char * 3842 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) { 3843 DebugLoc dl = getCurDebugLoc(); 3844 switch (Intrinsic) { 3845 default: 3846 // By default, turn this into a target intrinsic node. 3847 visitTargetIntrinsic(I, Intrinsic); 3848 return 0; 3849 case Intrinsic::vastart: visitVAStart(I); return 0; 3850 case Intrinsic::vaend: visitVAEnd(I); return 0; 3851 case Intrinsic::vacopy: visitVACopy(I); return 0; 3852 case Intrinsic::returnaddress: 3853 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(), 3854 getValue(I.getOperand(1)))); 3855 return 0; 3856 case Intrinsic::frameaddress: 3857 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(), 3858 getValue(I.getOperand(1)))); 3859 return 0; 3860 case Intrinsic::setjmp: 3861 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 3862 break; 3863 case Intrinsic::longjmp: 3864 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 3865 break; 3866 case Intrinsic::memcpy: { 3867 SDValue Op1 = getValue(I.getOperand(1)); 3868 SDValue Op2 = getValue(I.getOperand(2)); 3869 SDValue Op3 = getValue(I.getOperand(3)); 3870 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3871 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false, 3872 I.getOperand(1), 0, I.getOperand(2), 0)); 3873 return 0; 3874 } 3875 case Intrinsic::memset: { 3876 SDValue Op1 = getValue(I.getOperand(1)); 3877 SDValue Op2 = getValue(I.getOperand(2)); 3878 SDValue Op3 = getValue(I.getOperand(3)); 3879 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3880 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, 3881 I.getOperand(1), 0)); 3882 return 0; 3883 } 3884 case Intrinsic::memmove: { 3885 SDValue Op1 = getValue(I.getOperand(1)); 3886 SDValue Op2 = getValue(I.getOperand(2)); 3887 SDValue Op3 = getValue(I.getOperand(3)); 3888 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3889 3890 // If the source and destination are known to not be aliases, we can 3891 // lower memmove as memcpy. 3892 uint64_t Size = -1ULL; 3893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3)) 3894 Size = C->getZExtValue(); 3895 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) == 3896 AliasAnalysis::NoAlias) { 3897 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false, 3898 I.getOperand(1), 0, I.getOperand(2), 0)); 3899 return 0; 3900 } 3901 3902 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, 3903 I.getOperand(1), 0, I.getOperand(2), 0)); 3904 return 0; 3905 } 3906 case Intrinsic::dbg_stoppoint: 3907 case Intrinsic::dbg_region_start: 3908 case Intrinsic::dbg_region_end: 3909 case Intrinsic::dbg_func_start: 3910 // FIXME - Remove this instructions once the dust settles. 3911 return 0; 3912 case Intrinsic::dbg_declare: { 3913 if (OptLevel != CodeGenOpt::None) 3914 // FIXME: Variable debug info is not supported here. 3915 return 0; 3916 DwarfWriter *DW = DAG.getDwarfWriter(); 3917 if (!DW) 3918 return 0; 3919 DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 3920 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None)) 3921 return 0; 3922 3923 MDNode *Variable = DI.getVariable(); 3924 Value *Address = DI.getAddress(); 3925 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 3926 Address = BCI->getOperand(0); 3927 AllocaInst *AI = dyn_cast<AllocaInst>(Address); 3928 // Don't handle byval struct arguments or VLAs, for example. 3929 if (!AI) 3930 return 0; 3931 DenseMap<const AllocaInst*, int>::iterator SI = 3932 FuncInfo.StaticAllocaMap.find(AI); 3933 if (SI == FuncInfo.StaticAllocaMap.end()) 3934 return 0; // VLAs. 3935 int FI = SI->second; 3936 3937 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 3938 if (MMI) { 3939 MetadataContext &TheMetadata = 3940 DI.getParent()->getContext().getMetadata(); 3941 unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); 3942 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI); 3943 MMI->setVariableDbgInfo(Variable, FI, Dbg); 3944 } 3945 return 0; 3946 } 3947 case Intrinsic::eh_exception: { 3948 // Insert the EXCEPTIONADDR instruction. 3949 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!"); 3950 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 3951 SDValue Ops[1]; 3952 Ops[0] = DAG.getRoot(); 3953 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1); 3954 setValue(&I, Op); 3955 DAG.setRoot(Op.getValue(1)); 3956 return 0; 3957 } 3958 3959 case Intrinsic::eh_selector: { 3960 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 3961 3962 if (CurMBB->isLandingPad()) 3963 AddCatchInfo(I, MMI, CurMBB); 3964 else { 3965 #ifndef NDEBUG 3966 FuncInfo.CatchInfoLost.insert(&I); 3967 #endif 3968 // FIXME: Mark exception selector register as live in. Hack for PR1508. 3969 unsigned Reg = TLI.getExceptionSelectorRegister(); 3970 if (Reg) CurMBB->addLiveIn(Reg); 3971 } 3972 3973 // Insert the EHSELECTION instruction. 3974 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 3975 SDValue Ops[2]; 3976 Ops[0] = getValue(I.getOperand(1)); 3977 Ops[1] = getRoot(); 3978 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2); 3979 3980 DAG.setRoot(Op.getValue(1)); 3981 3982 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32)); 3983 return 0; 3984 } 3985 3986 case Intrinsic::eh_typeid_for: { 3987 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 3988 3989 if (MMI) { 3990 // Find the type id for the given typeinfo. 3991 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1)); 3992 3993 unsigned TypeID = MMI->getTypeIDFor(GV); 3994 setValue(&I, DAG.getConstant(TypeID, MVT::i32)); 3995 } else { 3996 // Return something different to eh_selector. 3997 setValue(&I, DAG.getConstant(1, MVT::i32)); 3998 } 3999 4000 return 0; 4001 } 4002 4003 case Intrinsic::eh_return_i32: 4004 case Intrinsic::eh_return_i64: 4005 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) { 4006 MMI->setCallsEHReturn(true); 4007 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl, 4008 MVT::Other, 4009 getControlRoot(), 4010 getValue(I.getOperand(1)), 4011 getValue(I.getOperand(2)))); 4012 } else { 4013 setValue(&I, DAG.getConstant(0, TLI.getPointerTy())); 4014 } 4015 4016 return 0; 4017 case Intrinsic::eh_unwind_init: 4018 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) { 4019 MMI->setCallsUnwindInit(true); 4020 } 4021 4022 return 0; 4023 4024 case Intrinsic::eh_dwarf_cfa: { 4025 EVT VT = getValue(I.getOperand(1)).getValueType(); 4026 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl, 4027 TLI.getPointerTy()); 4028 4029 SDValue Offset = DAG.getNode(ISD::ADD, dl, 4030 TLI.getPointerTy(), 4031 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 4032 TLI.getPointerTy()), 4033 CfaArg); 4034 setValue(&I, DAG.getNode(ISD::ADD, dl, 4035 TLI.getPointerTy(), 4036 DAG.getNode(ISD::FRAMEADDR, dl, 4037 TLI.getPointerTy(), 4038 DAG.getConstant(0, 4039 TLI.getPointerTy())), 4040 Offset)); 4041 return 0; 4042 } 4043 case Intrinsic::convertff: 4044 case Intrinsic::convertfsi: 4045 case Intrinsic::convertfui: 4046 case Intrinsic::convertsif: 4047 case Intrinsic::convertuif: 4048 case Intrinsic::convertss: 4049 case Intrinsic::convertsu: 4050 case Intrinsic::convertus: 4051 case Intrinsic::convertuu: { 4052 ISD::CvtCode Code = ISD::CVT_INVALID; 4053 switch (Intrinsic) { 4054 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4055 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4056 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4057 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4058 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4059 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4060 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4061 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4062 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4063 } 4064 EVT DestVT = TLI.getValueType(I.getType()); 4065 Value* Op1 = I.getOperand(1); 4066 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1), 4067 DAG.getValueType(DestVT), 4068 DAG.getValueType(getValue(Op1).getValueType()), 4069 getValue(I.getOperand(2)), 4070 getValue(I.getOperand(3)), 4071 Code)); 4072 return 0; 4073 } 4074 4075 case Intrinsic::sqrt: 4076 setValue(&I, DAG.getNode(ISD::FSQRT, dl, 4077 getValue(I.getOperand(1)).getValueType(), 4078 getValue(I.getOperand(1)))); 4079 return 0; 4080 case Intrinsic::powi: 4081 setValue(&I, DAG.getNode(ISD::FPOWI, dl, 4082 getValue(I.getOperand(1)).getValueType(), 4083 getValue(I.getOperand(1)), 4084 getValue(I.getOperand(2)))); 4085 return 0; 4086 case Intrinsic::sin: 4087 setValue(&I, DAG.getNode(ISD::FSIN, dl, 4088 getValue(I.getOperand(1)).getValueType(), 4089 getValue(I.getOperand(1)))); 4090 return 0; 4091 case Intrinsic::cos: 4092 setValue(&I, DAG.getNode(ISD::FCOS, dl, 4093 getValue(I.getOperand(1)).getValueType(), 4094 getValue(I.getOperand(1)))); 4095 return 0; 4096 case Intrinsic::log: 4097 visitLog(I); 4098 return 0; 4099 case Intrinsic::log2: 4100 visitLog2(I); 4101 return 0; 4102 case Intrinsic::log10: 4103 visitLog10(I); 4104 return 0; 4105 case Intrinsic::exp: 4106 visitExp(I); 4107 return 0; 4108 case Intrinsic::exp2: 4109 visitExp2(I); 4110 return 0; 4111 case Intrinsic::pow: 4112 visitPow(I); 4113 return 0; 4114 case Intrinsic::pcmarker: { 4115 SDValue Tmp = getValue(I.getOperand(1)); 4116 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp)); 4117 return 0; 4118 } 4119 case Intrinsic::readcyclecounter: { 4120 SDValue Op = getRoot(); 4121 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl, 4122 DAG.getVTList(MVT::i64, MVT::Other), 4123 &Op, 1); 4124 setValue(&I, Tmp); 4125 DAG.setRoot(Tmp.getValue(1)); 4126 return 0; 4127 } 4128 case Intrinsic::bswap: 4129 setValue(&I, DAG.getNode(ISD::BSWAP, dl, 4130 getValue(I.getOperand(1)).getValueType(), 4131 getValue(I.getOperand(1)))); 4132 return 0; 4133 case Intrinsic::cttz: { 4134 SDValue Arg = getValue(I.getOperand(1)); 4135 EVT Ty = Arg.getValueType(); 4136 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg); 4137 setValue(&I, result); 4138 return 0; 4139 } 4140 case Intrinsic::ctlz: { 4141 SDValue Arg = getValue(I.getOperand(1)); 4142 EVT Ty = Arg.getValueType(); 4143 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg); 4144 setValue(&I, result); 4145 return 0; 4146 } 4147 case Intrinsic::ctpop: { 4148 SDValue Arg = getValue(I.getOperand(1)); 4149 EVT Ty = Arg.getValueType(); 4150 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg); 4151 setValue(&I, result); 4152 return 0; 4153 } 4154 case Intrinsic::stacksave: { 4155 SDValue Op = getRoot(); 4156 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl, 4157 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1); 4158 setValue(&I, Tmp); 4159 DAG.setRoot(Tmp.getValue(1)); 4160 return 0; 4161 } 4162 case Intrinsic::stackrestore: { 4163 SDValue Tmp = getValue(I.getOperand(1)); 4164 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp)); 4165 return 0; 4166 } 4167 case Intrinsic::stackprotector: { 4168 // Emit code into the DAG to store the stack guard onto the stack. 4169 MachineFunction &MF = DAG.getMachineFunction(); 4170 MachineFrameInfo *MFI = MF.getFrameInfo(); 4171 EVT PtrTy = TLI.getPointerTy(); 4172 4173 SDValue Src = getValue(I.getOperand(1)); // The guard's value. 4174 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2)); 4175 4176 int FI = FuncInfo.StaticAllocaMap[Slot]; 4177 MFI->setStackProtectorIndex(FI); 4178 4179 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4180 4181 // Store the stack protector onto the stack. 4182 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN, 4183 PseudoSourceValue::getFixedStack(FI), 4184 0, true); 4185 setValue(&I, Result); 4186 DAG.setRoot(Result); 4187 return 0; 4188 } 4189 case Intrinsic::objectsize: { 4190 // If we don't know by now, we're never going to know. 4191 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2)); 4192 4193 assert(CI && "Non-constant type in __builtin_object_size?"); 4194 4195 SDValue Arg = getValue(I.getOperand(0)); 4196 EVT Ty = Arg.getValueType(); 4197 4198 if (CI->getZExtValue() < 2) 4199 setValue(&I, DAG.getConstant(-1ULL, Ty)); 4200 else 4201 setValue(&I, DAG.getConstant(0, Ty)); 4202 return 0; 4203 } 4204 case Intrinsic::var_annotation: 4205 // Discard annotate attributes 4206 return 0; 4207 4208 case Intrinsic::init_trampoline: { 4209 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts()); 4210 4211 SDValue Ops[6]; 4212 Ops[0] = getRoot(); 4213 Ops[1] = getValue(I.getOperand(1)); 4214 Ops[2] = getValue(I.getOperand(2)); 4215 Ops[3] = getValue(I.getOperand(3)); 4216 Ops[4] = DAG.getSrcValue(I.getOperand(1)); 4217 Ops[5] = DAG.getSrcValue(F); 4218 4219 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl, 4220 DAG.getVTList(TLI.getPointerTy(), MVT::Other), 4221 Ops, 6); 4222 4223 setValue(&I, Tmp); 4224 DAG.setRoot(Tmp.getValue(1)); 4225 return 0; 4226 } 4227 4228 case Intrinsic::gcroot: 4229 if (GFI) { 4230 Value *Alloca = I.getOperand(1); 4231 Constant *TypeMap = cast<Constant>(I.getOperand(2)); 4232 4233 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4234 GFI->addStackRoot(FI->getIndex(), TypeMap); 4235 } 4236 return 0; 4237 4238 case Intrinsic::gcread: 4239 case Intrinsic::gcwrite: 4240 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4241 return 0; 4242 4243 case Intrinsic::flt_rounds: { 4244 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32)); 4245 return 0; 4246 } 4247 4248 case Intrinsic::trap: { 4249 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot())); 4250 return 0; 4251 } 4252 4253 case Intrinsic::uadd_with_overflow: 4254 return implVisitAluOverflow(I, ISD::UADDO); 4255 case Intrinsic::sadd_with_overflow: 4256 return implVisitAluOverflow(I, ISD::SADDO); 4257 case Intrinsic::usub_with_overflow: 4258 return implVisitAluOverflow(I, ISD::USUBO); 4259 case Intrinsic::ssub_with_overflow: 4260 return implVisitAluOverflow(I, ISD::SSUBO); 4261 case Intrinsic::umul_with_overflow: 4262 return implVisitAluOverflow(I, ISD::UMULO); 4263 case Intrinsic::smul_with_overflow: 4264 return implVisitAluOverflow(I, ISD::SMULO); 4265 4266 case Intrinsic::prefetch: { 4267 SDValue Ops[4]; 4268 Ops[0] = getRoot(); 4269 Ops[1] = getValue(I.getOperand(1)); 4270 Ops[2] = getValue(I.getOperand(2)); 4271 Ops[3] = getValue(I.getOperand(3)); 4272 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4)); 4273 return 0; 4274 } 4275 4276 case Intrinsic::memory_barrier: { 4277 SDValue Ops[6]; 4278 Ops[0] = getRoot(); 4279 for (int x = 1; x < 6; ++x) 4280 Ops[x] = getValue(I.getOperand(x)); 4281 4282 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6)); 4283 return 0; 4284 } 4285 case Intrinsic::atomic_cmp_swap: { 4286 SDValue Root = getRoot(); 4287 SDValue L = 4288 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 4289 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 4290 Root, 4291 getValue(I.getOperand(1)), 4292 getValue(I.getOperand(2)), 4293 getValue(I.getOperand(3)), 4294 I.getOperand(1)); 4295 setValue(&I, L); 4296 DAG.setRoot(L.getValue(1)); 4297 return 0; 4298 } 4299 case Intrinsic::atomic_load_add: 4300 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD); 4301 case Intrinsic::atomic_load_sub: 4302 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB); 4303 case Intrinsic::atomic_load_or: 4304 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR); 4305 case Intrinsic::atomic_load_xor: 4306 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR); 4307 case Intrinsic::atomic_load_and: 4308 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND); 4309 case Intrinsic::atomic_load_nand: 4310 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND); 4311 case Intrinsic::atomic_load_max: 4312 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX); 4313 case Intrinsic::atomic_load_min: 4314 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN); 4315 case Intrinsic::atomic_load_umin: 4316 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN); 4317 case Intrinsic::atomic_load_umax: 4318 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX); 4319 case Intrinsic::atomic_swap: 4320 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP); 4321 4322 case Intrinsic::invariant_start: 4323 case Intrinsic::lifetime_start: 4324 // Discard region information. 4325 setValue(&I, DAG.getUNDEF(TLI.getPointerTy())); 4326 return 0; 4327 case Intrinsic::invariant_end: 4328 case Intrinsic::lifetime_end: 4329 // Discard region information. 4330 return 0; 4331 } 4332 } 4333 4334 /// Test if the given instruction is in a position to be optimized 4335 /// with a tail-call. This roughly means that it's in a block with 4336 /// a return and there's nothing that needs to be scheduled 4337 /// between it and the return. 4338 /// 4339 /// This function only tests target-independent requirements. 4340 /// For target-dependent requirements, a target should override 4341 /// TargetLowering::IsEligibleForTailCallOptimization. 4342 /// 4343 static bool 4344 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr, 4345 const TargetLowering &TLI) { 4346 const BasicBlock *ExitBB = I->getParent(); 4347 const TerminatorInst *Term = ExitBB->getTerminator(); 4348 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 4349 const Function *F = ExitBB->getParent(); 4350 4351 // The block must end in a return statement or an unreachable. 4352 if (!Ret && !isa<UnreachableInst>(Term)) return false; 4353 4354 // If I will have a chain, make sure no other instruction that will have a 4355 // chain interposes between I and the return. 4356 if (I->mayHaveSideEffects() || I->mayReadFromMemory() || 4357 !I->isSafeToSpeculativelyExecute()) 4358 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ; 4359 --BBI) { 4360 if (&*BBI == I) 4361 break; 4362 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 4363 !BBI->isSafeToSpeculativelyExecute()) 4364 return false; 4365 } 4366 4367 // If the block ends with a void return or unreachable, it doesn't matter 4368 // what the call's return type is. 4369 if (!Ret || Ret->getNumOperands() == 0) return true; 4370 4371 // If the return value is undef, it doesn't matter what the call's 4372 // return type is. 4373 if (isa<UndefValue>(Ret->getOperand(0))) return true; 4374 4375 // Conservatively require the attributes of the call to match those of 4376 // the return. Ignore noalias because it doesn't affect the call sequence. 4377 unsigned CallerRetAttr = F->getAttributes().getRetAttributes(); 4378 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias) 4379 return false; 4380 4381 // Otherwise, make sure the unmodified return value of I is the return value. 4382 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ; 4383 U = dyn_cast<Instruction>(U->getOperand(0))) { 4384 if (!U) 4385 return false; 4386 if (!U->hasOneUse()) 4387 return false; 4388 if (U == I) 4389 break; 4390 // Check for a truly no-op truncate. 4391 if (isa<TruncInst>(U) && 4392 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType())) 4393 continue; 4394 // Check for a truly no-op bitcast. 4395 if (isa<BitCastInst>(U) && 4396 (U->getOperand(0)->getType() == U->getType() || 4397 (isa<PointerType>(U->getOperand(0)->getType()) && 4398 isa<PointerType>(U->getType())))) 4399 continue; 4400 // Otherwise it's not a true no-op. 4401 return false; 4402 } 4403 4404 return true; 4405 } 4406 4407 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee, 4408 bool isTailCall, 4409 MachineBasicBlock *LandingPad) { 4410 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 4411 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 4412 const Type *RetTy = FTy->getReturnType(); 4413 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4414 unsigned BeginLabel = 0, EndLabel = 0; 4415 4416 TargetLowering::ArgListTy Args; 4417 TargetLowering::ArgListEntry Entry; 4418 Args.reserve(CS.arg_size()); 4419 4420 // Check whether the function can return without sret-demotion. 4421 SmallVector<EVT, 4> OutVTs; 4422 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 4423 SmallVector<uint64_t, 4> Offsets; 4424 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), 4425 OutVTs, OutsFlags, TLI, &Offsets); 4426 4427 4428 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 4429 FTy->isVarArg(), OutVTs, OutsFlags, DAG); 4430 4431 SDValue DemoteStackSlot; 4432 4433 if (!CanLowerReturn) { 4434 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize( 4435 FTy->getReturnType()); 4436 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment( 4437 FTy->getReturnType()); 4438 MachineFunction &MF = DAG.getMachineFunction(); 4439 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 4440 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 4441 4442 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 4443 Entry.Node = DemoteStackSlot; 4444 Entry.Ty = StackSlotPtrType; 4445 Entry.isSExt = false; 4446 Entry.isZExt = false; 4447 Entry.isInReg = false; 4448 Entry.isSRet = true; 4449 Entry.isNest = false; 4450 Entry.isByVal = false; 4451 Entry.Alignment = Align; 4452 Args.push_back(Entry); 4453 RetTy = Type::getVoidTy(FTy->getContext()); 4454 } 4455 4456 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 4457 i != e; ++i) { 4458 SDValue ArgNode = getValue(*i); 4459 Entry.Node = ArgNode; Entry.Ty = (*i)->getType(); 4460 4461 unsigned attrInd = i - CS.arg_begin() + 1; 4462 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 4463 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 4464 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 4465 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 4466 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 4467 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 4468 Entry.Alignment = CS.getParamAlignment(attrInd); 4469 Args.push_back(Entry); 4470 } 4471 4472 if (LandingPad && MMI) { 4473 // Insert a label before the invoke call to mark the try range. This can be 4474 // used to detect deletion of the invoke via the MachineModuleInfo. 4475 BeginLabel = MMI->NextLabelID(); 4476 4477 // Both PendingLoads and PendingExports must be flushed here; 4478 // this call might not return. 4479 (void)getRoot(); 4480 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(), 4481 getControlRoot(), BeginLabel)); 4482 } 4483 4484 // Check if target-independent constraints permit a tail call here. 4485 // Target-dependent constraints are checked within TLI.LowerCallTo. 4486 if (isTailCall && 4487 !isInTailCallPosition(CS.getInstruction(), 4488 CS.getAttributes().getRetAttributes(), 4489 TLI)) 4490 isTailCall = false; 4491 4492 std::pair<SDValue,SDValue> Result = 4493 TLI.LowerCallTo(getRoot(), RetTy, 4494 CS.paramHasAttr(0, Attribute::SExt), 4495 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(), 4496 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(), 4497 CS.getCallingConv(), 4498 isTailCall, 4499 !CS.getInstruction()->use_empty(), 4500 Callee, Args, DAG, getCurDebugLoc()); 4501 assert((isTailCall || Result.second.getNode()) && 4502 "Non-null chain expected with non-tail call!"); 4503 assert((Result.second.getNode() || !Result.first.getNode()) && 4504 "Null value expected with tail call!"); 4505 if (Result.first.getNode()) 4506 setValue(CS.getInstruction(), Result.first); 4507 else if (!CanLowerReturn && Result.second.getNode()) { 4508 // The instruction result is the result of loading from the 4509 // hidden sret parameter. 4510 SmallVector<EVT, 1> PVTs; 4511 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 4512 4513 ComputeValueVTs(TLI, PtrRetTy, PVTs); 4514 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 4515 EVT PtrVT = PVTs[0]; 4516 unsigned NumValues = OutVTs.size(); 4517 SmallVector<SDValue, 4> Values(NumValues); 4518 SmallVector<SDValue, 4> Chains(NumValues); 4519 4520 for (unsigned i = 0; i < NumValues; ++i) { 4521 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second, 4522 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot, 4523 DAG.getConstant(Offsets[i], PtrVT)), 4524 NULL, Offsets[i], false, 1); 4525 Values[i] = L; 4526 Chains[i] = L.getValue(1); 4527 } 4528 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 4529 MVT::Other, &Chains[0], NumValues); 4530 PendingLoads.push_back(Chain); 4531 4532 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES, 4533 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues), 4534 &Values[0], NumValues)); 4535 } 4536 // As a special case, a null chain means that a tail call has 4537 // been emitted and the DAG root is already updated. 4538 if (Result.second.getNode()) 4539 DAG.setRoot(Result.second); 4540 else 4541 HasTailCall = true; 4542 4543 if (LandingPad && MMI) { 4544 // Insert a label at the end of the invoke call to mark the try range. This 4545 // can be used to detect deletion of the invoke via the MachineModuleInfo. 4546 EndLabel = MMI->NextLabelID(); 4547 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(), 4548 getRoot(), EndLabel)); 4549 4550 // Inform MachineModuleInfo of range. 4551 MMI->addInvoke(LandingPad, BeginLabel, EndLabel); 4552 } 4553 } 4554 4555 4556 void SelectionDAGBuilder::visitCall(CallInst &I) { 4557 const char *RenameFn = 0; 4558 if (Function *F = I.getCalledFunction()) { 4559 if (F->isDeclaration()) { 4560 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo(); 4561 if (II) { 4562 if (unsigned IID = II->getIntrinsicID(F)) { 4563 RenameFn = visitIntrinsicCall(I, IID); 4564 if (!RenameFn) 4565 return; 4566 } 4567 } 4568 if (unsigned IID = F->getIntrinsicID()) { 4569 RenameFn = visitIntrinsicCall(I, IID); 4570 if (!RenameFn) 4571 return; 4572 } 4573 } 4574 4575 // Check for well-known libc/libm calls. If the function is internal, it 4576 // can't be a library call. 4577 if (!F->hasLocalLinkage() && F->hasName()) { 4578 StringRef Name = F->getName(); 4579 if (Name == "copysign" || Name == "copysignf") { 4580 if (I.getNumOperands() == 3 && // Basic sanity checks. 4581 I.getOperand(1)->getType()->isFloatingPoint() && 4582 I.getType() == I.getOperand(1)->getType() && 4583 I.getType() == I.getOperand(2)->getType()) { 4584 SDValue LHS = getValue(I.getOperand(1)); 4585 SDValue RHS = getValue(I.getOperand(2)); 4586 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 4587 LHS.getValueType(), LHS, RHS)); 4588 return; 4589 } 4590 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") { 4591 if (I.getNumOperands() == 2 && // Basic sanity checks. 4592 I.getOperand(1)->getType()->isFloatingPoint() && 4593 I.getType() == I.getOperand(1)->getType()) { 4594 SDValue Tmp = getValue(I.getOperand(1)); 4595 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 4596 Tmp.getValueType(), Tmp)); 4597 return; 4598 } 4599 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") { 4600 if (I.getNumOperands() == 2 && // Basic sanity checks. 4601 I.getOperand(1)->getType()->isFloatingPoint() && 4602 I.getType() == I.getOperand(1)->getType() && 4603 I.onlyReadsMemory()) { 4604 SDValue Tmp = getValue(I.getOperand(1)); 4605 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 4606 Tmp.getValueType(), Tmp)); 4607 return; 4608 } 4609 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") { 4610 if (I.getNumOperands() == 2 && // Basic sanity checks. 4611 I.getOperand(1)->getType()->isFloatingPoint() && 4612 I.getType() == I.getOperand(1)->getType() && 4613 I.onlyReadsMemory()) { 4614 SDValue Tmp = getValue(I.getOperand(1)); 4615 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 4616 Tmp.getValueType(), Tmp)); 4617 return; 4618 } 4619 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") { 4620 if (I.getNumOperands() == 2 && // Basic sanity checks. 4621 I.getOperand(1)->getType()->isFloatingPoint() && 4622 I.getType() == I.getOperand(1)->getType() && 4623 I.onlyReadsMemory()) { 4624 SDValue Tmp = getValue(I.getOperand(1)); 4625 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(), 4626 Tmp.getValueType(), Tmp)); 4627 return; 4628 } 4629 } 4630 } 4631 } else if (isa<InlineAsm>(I.getOperand(0))) { 4632 visitInlineAsm(&I); 4633 return; 4634 } 4635 4636 SDValue Callee; 4637 if (!RenameFn) 4638 Callee = getValue(I.getOperand(0)); 4639 else 4640 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 4641 4642 // Check if we can potentially perform a tail call. More detailed 4643 // checking is be done within LowerCallTo, after more information 4644 // about the call is known. 4645 bool isTailCall = PerformTailCallOpt && I.isTailCall(); 4646 4647 LowerCallTo(&I, Callee, isTailCall); 4648 } 4649 4650 4651 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 4652 /// this value and returns the result as a ValueVT value. This uses 4653 /// Chain/Flag as the input and updates them for the output Chain/Flag. 4654 /// If the Flag pointer is NULL, no flag is used. 4655 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, 4656 SDValue &Chain, 4657 SDValue *Flag) const { 4658 // Assemble the legal parts into the final values. 4659 SmallVector<SDValue, 4> Values(ValueVTs.size()); 4660 SmallVector<SDValue, 8> Parts; 4661 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 4662 // Copy the legal parts from the registers. 4663 EVT ValueVT = ValueVTs[Value]; 4664 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT); 4665 EVT RegisterVT = RegVTs[Value]; 4666 4667 Parts.resize(NumRegs); 4668 for (unsigned i = 0; i != NumRegs; ++i) { 4669 SDValue P; 4670 if (Flag == 0) 4671 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 4672 else { 4673 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 4674 *Flag = P.getValue(2); 4675 } 4676 Chain = P.getValue(1); 4677 4678 // If the source register was virtual and if we know something about it, 4679 // add an assert node. 4680 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) && 4681 RegisterVT.isInteger() && !RegisterVT.isVector()) { 4682 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister; 4683 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); 4684 if (FLI.LiveOutRegInfo.size() > SlotNo) { 4685 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo]; 4686 4687 unsigned RegSize = RegisterVT.getSizeInBits(); 4688 unsigned NumSignBits = LOI.NumSignBits; 4689 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes(); 4690 4691 // FIXME: We capture more information than the dag can represent. For 4692 // now, just use the tightest assertzext/assertsext possible. 4693 bool isSExt = true; 4694 EVT FromVT(MVT::Other); 4695 if (NumSignBits == RegSize) 4696 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 4697 else if (NumZeroBits >= RegSize-1) 4698 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 4699 else if (NumSignBits > RegSize-8) 4700 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 4701 else if (NumZeroBits >= RegSize-8) 4702 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 4703 else if (NumSignBits > RegSize-16) 4704 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 4705 else if (NumZeroBits >= RegSize-16) 4706 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 4707 else if (NumSignBits > RegSize-32) 4708 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 4709 else if (NumZeroBits >= RegSize-32) 4710 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 4711 4712 if (FromVT != MVT::Other) { 4713 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 4714 RegisterVT, P, DAG.getValueType(FromVT)); 4715 4716 } 4717 } 4718 } 4719 4720 Parts[i] = P; 4721 } 4722 4723 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 4724 NumRegs, RegisterVT, ValueVT); 4725 Part += NumRegs; 4726 Parts.clear(); 4727 } 4728 4729 return DAG.getNode(ISD::MERGE_VALUES, dl, 4730 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 4731 &Values[0], ValueVTs.size()); 4732 } 4733 4734 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 4735 /// specified value into the registers specified by this object. This uses 4736 /// Chain/Flag as the input and updates them for the output Chain/Flag. 4737 /// If the Flag pointer is NULL, no flag is used. 4738 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 4739 SDValue &Chain, SDValue *Flag) const { 4740 // Get the list of the values's legal parts. 4741 unsigned NumRegs = Regs.size(); 4742 SmallVector<SDValue, 8> Parts(NumRegs); 4743 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 4744 EVT ValueVT = ValueVTs[Value]; 4745 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT); 4746 EVT RegisterVT = RegVTs[Value]; 4747 4748 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 4749 &Parts[Part], NumParts, RegisterVT); 4750 Part += NumParts; 4751 } 4752 4753 // Copy the parts into the registers. 4754 SmallVector<SDValue, 8> Chains(NumRegs); 4755 for (unsigned i = 0; i != NumRegs; ++i) { 4756 SDValue Part; 4757 if (Flag == 0) 4758 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 4759 else { 4760 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 4761 *Flag = Part.getValue(1); 4762 } 4763 Chains[i] = Part.getValue(0); 4764 } 4765 4766 if (NumRegs == 1 || Flag) 4767 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 4768 // flagged to it. That is the CopyToReg nodes and the user are considered 4769 // a single scheduling unit. If we create a TokenFactor and return it as 4770 // chain, then the TokenFactor is both a predecessor (operand) of the 4771 // user as well as a successor (the TF operands are flagged to the user). 4772 // c1, f1 = CopyToReg 4773 // c2, f2 = CopyToReg 4774 // c3 = TokenFactor c1, c2 4775 // ... 4776 // = op c3, ..., f2 4777 Chain = Chains[NumRegs-1]; 4778 else 4779 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 4780 } 4781 4782 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 4783 /// operand list. This adds the code marker and includes the number of 4784 /// values added into it. 4785 void RegsForValue::AddInlineAsmOperands(unsigned Code, 4786 bool HasMatching,unsigned MatchingIdx, 4787 SelectionDAG &DAG, 4788 std::vector<SDValue> &Ops) const { 4789 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy(); 4790 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!"); 4791 unsigned Flag = Code | (Regs.size() << 3); 4792 if (HasMatching) 4793 Flag |= 0x80000000 | (MatchingIdx << 16); 4794 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy)); 4795 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 4796 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 4797 EVT RegisterVT = RegVTs[Value]; 4798 for (unsigned i = 0; i != NumRegs; ++i) { 4799 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 4800 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); 4801 } 4802 } 4803 } 4804 4805 /// isAllocatableRegister - If the specified register is safe to allocate, 4806 /// i.e. it isn't a stack pointer or some other special register, return the 4807 /// register class for the register. Otherwise, return null. 4808 static const TargetRegisterClass * 4809 isAllocatableRegister(unsigned Reg, MachineFunction &MF, 4810 const TargetLowering &TLI, 4811 const TargetRegisterInfo *TRI) { 4812 EVT FoundVT = MVT::Other; 4813 const TargetRegisterClass *FoundRC = 0; 4814 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(), 4815 E = TRI->regclass_end(); RCI != E; ++RCI) { 4816 EVT ThisVT = MVT::Other; 4817 4818 const TargetRegisterClass *RC = *RCI; 4819 // If none of the the value types for this register class are valid, we 4820 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4821 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 4822 I != E; ++I) { 4823 if (TLI.isTypeLegal(*I)) { 4824 // If we have already found this register in a different register class, 4825 // choose the one with the largest VT specified. For example, on 4826 // PowerPC, we favor f64 register classes over f32. 4827 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) { 4828 ThisVT = *I; 4829 break; 4830 } 4831 } 4832 } 4833 4834 if (ThisVT == MVT::Other) continue; 4835 4836 // NOTE: This isn't ideal. In particular, this might allocate the 4837 // frame pointer in functions that need it (due to them not being taken 4838 // out of allocation, because a variable sized allocation hasn't been seen 4839 // yet). This is a slight code pessimization, but should still work. 4840 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 4841 E = RC->allocation_order_end(MF); I != E; ++I) 4842 if (*I == Reg) { 4843 // We found a matching register class. Keep looking at others in case 4844 // we find one with larger registers that this physreg is also in. 4845 FoundRC = RC; 4846 FoundVT = ThisVT; 4847 break; 4848 } 4849 } 4850 return FoundRC; 4851 } 4852 4853 4854 namespace llvm { 4855 /// AsmOperandInfo - This contains information for each constraint that we are 4856 /// lowering. 4857 class VISIBILITY_HIDDEN SDISelAsmOperandInfo : 4858 public TargetLowering::AsmOperandInfo { 4859 public: 4860 /// CallOperand - If this is the result output operand or a clobber 4861 /// this is null, otherwise it is the incoming operand to the CallInst. 4862 /// This gets modified as the asm is processed. 4863 SDValue CallOperand; 4864 4865 /// AssignedRegs - If this is a register or register class operand, this 4866 /// contains the set of register corresponding to the operand. 4867 RegsForValue AssignedRegs; 4868 4869 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info) 4870 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 4871 } 4872 4873 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 4874 /// busy in OutputRegs/InputRegs. 4875 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 4876 std::set<unsigned> &OutputRegs, 4877 std::set<unsigned> &InputRegs, 4878 const TargetRegisterInfo &TRI) const { 4879 if (isOutReg) { 4880 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 4881 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 4882 } 4883 if (isInReg) { 4884 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 4885 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 4886 } 4887 } 4888 4889 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 4890 /// corresponds to. If there is no Value* for this operand, it returns 4891 /// MVT::Other. 4892 EVT getCallOperandValEVT(LLVMContext &Context, 4893 const TargetLowering &TLI, 4894 const TargetData *TD) const { 4895 if (CallOperandVal == 0) return MVT::Other; 4896 4897 if (isa<BasicBlock>(CallOperandVal)) 4898 return TLI.getPointerTy(); 4899 4900 const llvm::Type *OpTy = CallOperandVal->getType(); 4901 4902 // If this is an indirect operand, the operand is a pointer to the 4903 // accessed type. 4904 if (isIndirect) 4905 OpTy = cast<PointerType>(OpTy)->getElementType(); 4906 4907 // If OpTy is not a single value, it may be a struct/union that we 4908 // can tile with integers. 4909 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4910 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 4911 switch (BitSize) { 4912 default: break; 4913 case 1: 4914 case 8: 4915 case 16: 4916 case 32: 4917 case 64: 4918 case 128: 4919 OpTy = IntegerType::get(Context, BitSize); 4920 break; 4921 } 4922 } 4923 4924 return TLI.getValueType(OpTy, true); 4925 } 4926 4927 private: 4928 /// MarkRegAndAliases - Mark the specified register and all aliases in the 4929 /// specified set. 4930 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 4931 const TargetRegisterInfo &TRI) { 4932 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 4933 Regs.insert(Reg); 4934 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 4935 for (; *Aliases; ++Aliases) 4936 Regs.insert(*Aliases); 4937 } 4938 }; 4939 } // end llvm namespace. 4940 4941 4942 /// GetRegistersForValue - Assign registers (virtual or physical) for the 4943 /// specified operand. We prefer to assign virtual registers, to allow the 4944 /// register allocator to handle the assignment process. However, if the asm 4945 /// uses features that we can't model on machineinstrs, we have SDISel do the 4946 /// allocation. This produces generally horrible, but correct, code. 4947 /// 4948 /// OpInfo describes the operand. 4949 /// Input and OutputRegs are the set of already allocated physical registers. 4950 /// 4951 void SelectionDAGBuilder:: 4952 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, 4953 std::set<unsigned> &OutputRegs, 4954 std::set<unsigned> &InputRegs) { 4955 LLVMContext &Context = FuncInfo.Fn->getContext(); 4956 4957 // Compute whether this value requires an input register, an output register, 4958 // or both. 4959 bool isOutReg = false; 4960 bool isInReg = false; 4961 switch (OpInfo.Type) { 4962 case InlineAsm::isOutput: 4963 isOutReg = true; 4964 4965 // If there is an input constraint that matches this, we need to reserve 4966 // the input register so no other inputs allocate to it. 4967 isInReg = OpInfo.hasMatchingInput(); 4968 break; 4969 case InlineAsm::isInput: 4970 isInReg = true; 4971 isOutReg = false; 4972 break; 4973 case InlineAsm::isClobber: 4974 isOutReg = true; 4975 isInReg = true; 4976 break; 4977 } 4978 4979 4980 MachineFunction &MF = DAG.getMachineFunction(); 4981 SmallVector<unsigned, 4> Regs; 4982 4983 // If this is a constraint for a single physreg, or a constraint for a 4984 // register class, find it. 4985 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 4986 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 4987 OpInfo.ConstraintVT); 4988 4989 unsigned NumRegs = 1; 4990 if (OpInfo.ConstraintVT != MVT::Other) { 4991 // If this is a FP input in an integer register (or visa versa) insert a bit 4992 // cast of the input value. More generally, handle any case where the input 4993 // value disagrees with the register class we plan to stick this in. 4994 if (OpInfo.Type == InlineAsm::isInput && 4995 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 4996 // Try to convert to the first EVT that the reg class contains. If the 4997 // types are identical size, use a bitcast to convert (e.g. two differing 4998 // vector types). 4999 EVT RegVT = *PhysReg.second->vt_begin(); 5000 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 5001 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5002 RegVT, OpInfo.CallOperand); 5003 OpInfo.ConstraintVT = RegVT; 5004 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5005 // If the input is a FP value and we want it in FP registers, do a 5006 // bitcast to the corresponding integer type. This turns an f64 value 5007 // into i64, which can be passed with two i32 values on a 32-bit 5008 // machine. 5009 RegVT = EVT::getIntegerVT(Context, 5010 OpInfo.ConstraintVT.getSizeInBits()); 5011 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5012 RegVT, OpInfo.CallOperand); 5013 OpInfo.ConstraintVT = RegVT; 5014 } 5015 } 5016 5017 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5018 } 5019 5020 EVT RegVT; 5021 EVT ValueVT = OpInfo.ConstraintVT; 5022 5023 // If this is a constraint for a specific physical register, like {r17}, 5024 // assign it now. 5025 if (unsigned AssignedReg = PhysReg.first) { 5026 const TargetRegisterClass *RC = PhysReg.second; 5027 if (OpInfo.ConstraintVT == MVT::Other) 5028 ValueVT = *RC->vt_begin(); 5029 5030 // Get the actual register value type. This is important, because the user 5031 // may have asked for (e.g.) the AX register in i32 type. We need to 5032 // remember that AX is actually i16 to get the right extension. 5033 RegVT = *RC->vt_begin(); 5034 5035 // This is a explicit reference to a physical register. 5036 Regs.push_back(AssignedReg); 5037 5038 // If this is an expanded reference, add the rest of the regs to Regs. 5039 if (NumRegs != 1) { 5040 TargetRegisterClass::iterator I = RC->begin(); 5041 for (; *I != AssignedReg; ++I) 5042 assert(I != RC->end() && "Didn't find reg!"); 5043 5044 // Already added the first reg. 5045 --NumRegs; ++I; 5046 for (; NumRegs; --NumRegs, ++I) { 5047 assert(I != RC->end() && "Ran out of registers to allocate!"); 5048 Regs.push_back(*I); 5049 } 5050 } 5051 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 5052 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5053 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5054 return; 5055 } 5056 5057 // Otherwise, if this was a reference to an LLVM register class, create vregs 5058 // for this reference. 5059 if (const TargetRegisterClass *RC = PhysReg.second) { 5060 RegVT = *RC->vt_begin(); 5061 if (OpInfo.ConstraintVT == MVT::Other) 5062 ValueVT = RegVT; 5063 5064 // Create the appropriate number of virtual registers. 5065 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5066 for (; NumRegs; --NumRegs) 5067 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5068 5069 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 5070 return; 5071 } 5072 5073 // This is a reference to a register class that doesn't directly correspond 5074 // to an LLVM register class. Allocate NumRegs consecutive, available, 5075 // registers from the class. 5076 std::vector<unsigned> RegClassRegs 5077 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 5078 OpInfo.ConstraintVT); 5079 5080 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5081 unsigned NumAllocated = 0; 5082 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 5083 unsigned Reg = RegClassRegs[i]; 5084 // See if this register is available. 5085 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 5086 (isInReg && InputRegs.count(Reg))) { // Already used. 5087 // Make sure we find consecutive registers. 5088 NumAllocated = 0; 5089 continue; 5090 } 5091 5092 // Check to see if this register is allocatable (i.e. don't give out the 5093 // stack pointer). 5094 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI); 5095 if (!RC) { // Couldn't allocate this register. 5096 // Reset NumAllocated to make sure we return consecutive registers. 5097 NumAllocated = 0; 5098 continue; 5099 } 5100 5101 // Okay, this register is good, we can use it. 5102 ++NumAllocated; 5103 5104 // If we allocated enough consecutive registers, succeed. 5105 if (NumAllocated == NumRegs) { 5106 unsigned RegStart = (i-NumAllocated)+1; 5107 unsigned RegEnd = i+1; 5108 // Mark all of the allocated registers used. 5109 for (unsigned i = RegStart; i != RegEnd; ++i) 5110 Regs.push_back(RegClassRegs[i]); 5111 5112 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 5113 OpInfo.ConstraintVT); 5114 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5115 return; 5116 } 5117 } 5118 5119 // Otherwise, we couldn't allocate enough registers for this. 5120 } 5121 5122 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being 5123 /// processed uses a memory 'm' constraint. 5124 static bool 5125 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos, 5126 const TargetLowering &TLI) { 5127 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { 5128 InlineAsm::ConstraintInfo &CI = CInfos[i]; 5129 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { 5130 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); 5131 if (CType == TargetLowering::C_Memory) 5132 return true; 5133 } 5134 5135 // Indirect operand accesses access memory. 5136 if (CI.isIndirect) 5137 return true; 5138 } 5139 5140 return false; 5141 } 5142 5143 /// visitInlineAsm - Handle a call to an InlineAsm object. 5144 /// 5145 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) { 5146 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5147 5148 /// ConstraintOperands - Information about all of the constraints. 5149 std::vector<SDISelAsmOperandInfo> ConstraintOperands; 5150 5151 std::set<unsigned> OutputRegs, InputRegs; 5152 5153 // Do a prepass over the constraints, canonicalizing them, and building up the 5154 // ConstraintOperands list. 5155 std::vector<InlineAsm::ConstraintInfo> 5156 ConstraintInfos = IA->ParseConstraints(); 5157 5158 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI); 5159 5160 SDValue Chain, Flag; 5161 5162 // We won't need to flush pending loads if this asm doesn't touch 5163 // memory and is nonvolatile. 5164 if (hasMemory || IA->hasSideEffects()) 5165 Chain = getRoot(); 5166 else 5167 Chain = DAG.getRoot(); 5168 5169 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5170 unsigned ResNo = 0; // ResNo - The result number of the next output. 5171 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5172 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i])); 5173 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5174 5175 EVT OpVT = MVT::Other; 5176 5177 // Compute the value type for each operand. 5178 switch (OpInfo.Type) { 5179 case InlineAsm::isOutput: 5180 // Indirect outputs just consume an argument. 5181 if (OpInfo.isIndirect) { 5182 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 5183 break; 5184 } 5185 5186 // The return value of the call is this value. As such, there is no 5187 // corresponding argument. 5188 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) && 5189 "Bad inline asm!"); 5190 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) { 5191 OpVT = TLI.getValueType(STy->getElementType(ResNo)); 5192 } else { 5193 assert(ResNo == 0 && "Asm only has one result!"); 5194 OpVT = TLI.getValueType(CS.getType()); 5195 } 5196 ++ResNo; 5197 break; 5198 case InlineAsm::isInput: 5199 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 5200 break; 5201 case InlineAsm::isClobber: 5202 // Nothing to do. 5203 break; 5204 } 5205 5206 // If this is an input or an indirect output, process the call argument. 5207 // BasicBlocks are labels, currently appearing only in asm's. 5208 if (OpInfo.CallOperandVal) { 5209 // Strip bitcasts, if any. This mostly comes up for functions. 5210 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts(); 5211 5212 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5213 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5214 } else { 5215 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5216 } 5217 5218 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD); 5219 } 5220 5221 OpInfo.ConstraintVT = OpVT; 5222 } 5223 5224 // Second pass over the constraints: compute which constraint option to use 5225 // and assign registers to constraints that want a specific physreg. 5226 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5227 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5228 5229 // If this is an output operand with a matching input operand, look up the 5230 // matching input. If their types mismatch, e.g. one is an integer, the 5231 // other is floating point, or their sizes are different, flag it as an 5232 // error. 5233 if (OpInfo.hasMatchingInput()) { 5234 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5235 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5236 if ((OpInfo.ConstraintVT.isInteger() != 5237 Input.ConstraintVT.isInteger()) || 5238 (OpInfo.ConstraintVT.getSizeInBits() != 5239 Input.ConstraintVT.getSizeInBits())) { 5240 llvm_report_error("Unsupported asm: input constraint" 5241 " with a matching output constraint of incompatible" 5242 " type!"); 5243 } 5244 Input.ConstraintVT = OpInfo.ConstraintVT; 5245 } 5246 } 5247 5248 // Compute the constraint code and ConstraintType to use. 5249 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG); 5250 5251 // If this is a memory input, and if the operand is not indirect, do what we 5252 // need to to provide an address for the memory input. 5253 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5254 !OpInfo.isIndirect) { 5255 assert(OpInfo.Type == InlineAsm::isInput && 5256 "Can only indirectify direct input operands!"); 5257 5258 // Memory operands really want the address of the value. If we don't have 5259 // an indirect input, put it in the constpool if we can, otherwise spill 5260 // it to a stack slot. 5261 5262 // If the operand is a float, integer, or vector constant, spill to a 5263 // constant pool entry to get its address. 5264 Value *OpVal = OpInfo.CallOperandVal; 5265 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 5266 isa<ConstantVector>(OpVal)) { 5267 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 5268 TLI.getPointerTy()); 5269 } else { 5270 // Otherwise, create a stack slot and emit a store to it before the 5271 // asm. 5272 const Type *Ty = OpVal->getType(); 5273 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 5274 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 5275 MachineFunction &MF = DAG.getMachineFunction(); 5276 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5277 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 5278 Chain = DAG.getStore(Chain, getCurDebugLoc(), 5279 OpInfo.CallOperand, StackSlot, NULL, 0); 5280 OpInfo.CallOperand = StackSlot; 5281 } 5282 5283 // There is no longer a Value* corresponding to this operand. 5284 OpInfo.CallOperandVal = 0; 5285 // It is now an indirect operand. 5286 OpInfo.isIndirect = true; 5287 } 5288 5289 // If this constraint is for a specific register, allocate it before 5290 // anything else. 5291 if (OpInfo.ConstraintType == TargetLowering::C_Register) 5292 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5293 } 5294 ConstraintInfos.clear(); 5295 5296 5297 // Second pass - Loop over all of the operands, assigning virtual or physregs 5298 // to register class operands. 5299 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5300 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5301 5302 // C_Register operands have already been allocated, Other/Memory don't need 5303 // to be. 5304 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 5305 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5306 } 5307 5308 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 5309 std::vector<SDValue> AsmNodeOperands; 5310 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 5311 AsmNodeOperands.push_back( 5312 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other)); 5313 5314 5315 // Loop over all of the inputs, copying the operand values into the 5316 // appropriate registers and processing the output regs. 5317 RegsForValue RetValRegs; 5318 5319 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 5320 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 5321 5322 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5323 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5324 5325 switch (OpInfo.Type) { 5326 case InlineAsm::isOutput: { 5327 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 5328 OpInfo.ConstraintType != TargetLowering::C_Register) { 5329 // Memory output, or 'other' output (e.g. 'X' constraint). 5330 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 5331 5332 // Add information to the INLINEASM node to know about this output. 5333 unsigned ResOpType = 4/*MEM*/ | (1<<3); 5334 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5335 TLI.getPointerTy())); 5336 AsmNodeOperands.push_back(OpInfo.CallOperand); 5337 break; 5338 } 5339 5340 // Otherwise, this is a register or register class output. 5341 5342 // Copy the output from the appropriate register. Find a register that 5343 // we can use. 5344 if (OpInfo.AssignedRegs.Regs.empty()) { 5345 llvm_report_error("Couldn't allocate output reg for" 5346 " constraint '" + OpInfo.ConstraintCode + "'!"); 5347 } 5348 5349 // If this is an indirect operand, store through the pointer after the 5350 // asm. 5351 if (OpInfo.isIndirect) { 5352 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 5353 OpInfo.CallOperandVal)); 5354 } else { 5355 // This is the result value of the call. 5356 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) && 5357 "Bad inline asm!"); 5358 // Concatenate this output onto the outputs list. 5359 RetValRegs.append(OpInfo.AssignedRegs); 5360 } 5361 5362 // Add information to the INLINEASM node to know that this register is 5363 // set. 5364 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ? 5365 6 /* EARLYCLOBBER REGDEF */ : 5366 2 /* REGDEF */ , 5367 false, 5368 0, 5369 DAG, AsmNodeOperands); 5370 break; 5371 } 5372 case InlineAsm::isInput: { 5373 SDValue InOperandVal = OpInfo.CallOperand; 5374 5375 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 5376 // If this is required to match an output register we have already set, 5377 // just use its register. 5378 unsigned OperandNo = OpInfo.getMatchedOperand(); 5379 5380 // Scan until we find the definition we already emitted of this operand. 5381 // When we find it, create a RegsForValue operand. 5382 unsigned CurOp = 2; // The first operand. 5383 for (; OperandNo; --OperandNo) { 5384 // Advance to the next operand. 5385 unsigned OpFlag = 5386 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5387 assert(((OpFlag & 7) == 2 /*REGDEF*/ || 5388 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ || 5389 (OpFlag & 7) == 4 /*MEM*/) && 5390 "Skipped past definitions?"); 5391 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 5392 } 5393 5394 unsigned OpFlag = 5395 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5396 if ((OpFlag & 7) == 2 /*REGDEF*/ 5397 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) { 5398 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 5399 if (OpInfo.isIndirect) { 5400 llvm_report_error("Don't know how to handle tied indirect " 5401 "register inputs yet!"); 5402 } 5403 RegsForValue MatchedRegs; 5404 MatchedRegs.TLI = &TLI; 5405 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 5406 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType(); 5407 MatchedRegs.RegVTs.push_back(RegVT); 5408 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 5409 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 5410 i != e; ++i) 5411 MatchedRegs.Regs. 5412 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); 5413 5414 // Use the produced MatchedRegs object to 5415 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5416 Chain, &Flag); 5417 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, 5418 true, OpInfo.getMatchedOperand(), 5419 DAG, AsmNodeOperands); 5420 break; 5421 } else { 5422 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!"); 5423 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 && 5424 "Unexpected number of operands"); 5425 // Add information to the INLINEASM node to know about this input. 5426 // See InlineAsm.h isUseOperandTiedToDef. 5427 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16); 5428 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 5429 TLI.getPointerTy())); 5430 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 5431 break; 5432 } 5433 } 5434 5435 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 5436 assert(!OpInfo.isIndirect && 5437 "Don't know how to handle indirect other inputs yet!"); 5438 5439 std::vector<SDValue> Ops; 5440 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0], 5441 hasMemory, Ops, DAG); 5442 if (Ops.empty()) { 5443 llvm_report_error("Invalid operand for inline asm" 5444 " constraint '" + OpInfo.ConstraintCode + "'!"); 5445 } 5446 5447 // Add information to the INLINEASM node to know about this input. 5448 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3); 5449 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5450 TLI.getPointerTy())); 5451 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 5452 break; 5453 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 5454 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 5455 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 5456 "Memory operands expect pointer values"); 5457 5458 // Add information to the INLINEASM node to know about this input. 5459 unsigned ResOpType = 4/*MEM*/ | (1<<3); 5460 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5461 TLI.getPointerTy())); 5462 AsmNodeOperands.push_back(InOperandVal); 5463 break; 5464 } 5465 5466 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 5467 OpInfo.ConstraintType == TargetLowering::C_Register) && 5468 "Unknown constraint type!"); 5469 assert(!OpInfo.isIndirect && 5470 "Don't know how to handle indirect register inputs yet!"); 5471 5472 // Copy the input into the appropriate registers. 5473 if (OpInfo.AssignedRegs.Regs.empty()) { 5474 llvm_report_error("Couldn't allocate input reg for" 5475 " constraint '"+ OpInfo.ConstraintCode +"'!"); 5476 } 5477 5478 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5479 Chain, &Flag); 5480 5481 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0, 5482 DAG, AsmNodeOperands); 5483 break; 5484 } 5485 case InlineAsm::isClobber: { 5486 // Add the clobbered value to the operand list, so that the register 5487 // allocator is aware that the physreg got clobbered. 5488 if (!OpInfo.AssignedRegs.Regs.empty()) 5489 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */, 5490 false, 0, DAG,AsmNodeOperands); 5491 break; 5492 } 5493 } 5494 } 5495 5496 // Finish up input operands. 5497 AsmNodeOperands[0] = Chain; 5498 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 5499 5500 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(), 5501 DAG.getVTList(MVT::Other, MVT::Flag), 5502 &AsmNodeOperands[0], AsmNodeOperands.size()); 5503 Flag = Chain.getValue(1); 5504 5505 // If this asm returns a register value, copy the result from that register 5506 // and set it as the value of the call. 5507 if (!RetValRegs.Regs.empty()) { 5508 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(), 5509 Chain, &Flag); 5510 5511 // FIXME: Why don't we do this for inline asms with MRVs? 5512 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 5513 EVT ResultType = TLI.getValueType(CS.getType()); 5514 5515 // If any of the results of the inline asm is a vector, it may have the 5516 // wrong width/num elts. This can happen for register classes that can 5517 // contain multiple different value types. The preg or vreg allocated may 5518 // not have the same VT as was expected. Convert it to the right type 5519 // with bit_convert. 5520 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 5521 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5522 ResultType, Val); 5523 5524 } else if (ResultType != Val.getValueType() && 5525 ResultType.isInteger() && Val.getValueType().isInteger()) { 5526 // If a result value was tied to an input value, the computed result may 5527 // have a wider width than the expected result. Extract the relevant 5528 // portion. 5529 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val); 5530 } 5531 5532 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 5533 } 5534 5535 setValue(CS.getInstruction(), Val); 5536 // Don't need to use this as a chain in this case. 5537 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 5538 return; 5539 } 5540 5541 std::vector<std::pair<SDValue, Value*> > StoresToEmit; 5542 5543 // Process indirect outputs, first output all of the flagged copies out of 5544 // physregs. 5545 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 5546 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 5547 Value *Ptr = IndirectStoresToEmit[i].second; 5548 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(), 5549 Chain, &Flag); 5550 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 5551 5552 } 5553 5554 // Emit the non-flagged stores from the physregs. 5555 SmallVector<SDValue, 8> OutChains; 5556 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) 5557 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(), 5558 StoresToEmit[i].first, 5559 getValue(StoresToEmit[i].second), 5560 StoresToEmit[i].second, 0)); 5561 if (!OutChains.empty()) 5562 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 5563 &OutChains[0], OutChains.size()); 5564 DAG.setRoot(Chain); 5565 } 5566 5567 void SelectionDAGBuilder::visitVAStart(CallInst &I) { 5568 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(), 5569 MVT::Other, getRoot(), 5570 getValue(I.getOperand(1)), 5571 DAG.getSrcValue(I.getOperand(1)))); 5572 } 5573 5574 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) { 5575 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(), 5576 getRoot(), getValue(I.getOperand(0)), 5577 DAG.getSrcValue(I.getOperand(0))); 5578 setValue(&I, V); 5579 DAG.setRoot(V.getValue(1)); 5580 } 5581 5582 void SelectionDAGBuilder::visitVAEnd(CallInst &I) { 5583 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(), 5584 MVT::Other, getRoot(), 5585 getValue(I.getOperand(1)), 5586 DAG.getSrcValue(I.getOperand(1)))); 5587 } 5588 5589 void SelectionDAGBuilder::visitVACopy(CallInst &I) { 5590 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(), 5591 MVT::Other, getRoot(), 5592 getValue(I.getOperand(1)), 5593 getValue(I.getOperand(2)), 5594 DAG.getSrcValue(I.getOperand(1)), 5595 DAG.getSrcValue(I.getOperand(2)))); 5596 } 5597 5598 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 5599 /// implementation, which just calls LowerCall. 5600 /// FIXME: When all targets are 5601 /// migrated to using LowerCall, this hook should be integrated into SDISel. 5602 std::pair<SDValue, SDValue> 5603 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy, 5604 bool RetSExt, bool RetZExt, bool isVarArg, 5605 bool isInreg, unsigned NumFixedArgs, 5606 CallingConv::ID CallConv, bool isTailCall, 5607 bool isReturnValueUsed, 5608 SDValue Callee, 5609 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) { 5610 5611 assert((!isTailCall || PerformTailCallOpt) && 5612 "isTailCall set when tail-call optimizations are disabled!"); 5613 5614 // Handle all of the outgoing arguments. 5615 SmallVector<ISD::OutputArg, 32> Outs; 5616 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5617 SmallVector<EVT, 4> ValueVTs; 5618 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 5619 for (unsigned Value = 0, NumValues = ValueVTs.size(); 5620 Value != NumValues; ++Value) { 5621 EVT VT = ValueVTs[Value]; 5622 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext()); 5623 SDValue Op = SDValue(Args[i].Node.getNode(), 5624 Args[i].Node.getResNo() + Value); 5625 ISD::ArgFlagsTy Flags; 5626 unsigned OriginalAlignment = 5627 getTargetData()->getABITypeAlignment(ArgTy); 5628 5629 if (Args[i].isZExt) 5630 Flags.setZExt(); 5631 if (Args[i].isSExt) 5632 Flags.setSExt(); 5633 if (Args[i].isInReg) 5634 Flags.setInReg(); 5635 if (Args[i].isSRet) 5636 Flags.setSRet(); 5637 if (Args[i].isByVal) { 5638 Flags.setByVal(); 5639 const PointerType *Ty = cast<PointerType>(Args[i].Ty); 5640 const Type *ElementTy = Ty->getElementType(); 5641 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 5642 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy); 5643 // For ByVal, alignment should come from FE. BE will guess if this 5644 // info is not there but there are cases it cannot get right. 5645 if (Args[i].Alignment) 5646 FrameAlign = Args[i].Alignment; 5647 Flags.setByValAlign(FrameAlign); 5648 Flags.setByValSize(FrameSize); 5649 } 5650 if (Args[i].isNest) 5651 Flags.setNest(); 5652 Flags.setOrigAlign(OriginalAlignment); 5653 5654 EVT PartVT = getRegisterType(RetTy->getContext(), VT); 5655 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT); 5656 SmallVector<SDValue, 4> Parts(NumParts); 5657 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 5658 5659 if (Args[i].isSExt) 5660 ExtendKind = ISD::SIGN_EXTEND; 5661 else if (Args[i].isZExt) 5662 ExtendKind = ISD::ZERO_EXTEND; 5663 5664 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind); 5665 5666 for (unsigned j = 0; j != NumParts; ++j) { 5667 // if it isn't first piece, alignment must be 1 5668 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs); 5669 if (NumParts > 1 && j == 0) 5670 MyFlags.Flags.setSplit(); 5671 else if (j != 0) 5672 MyFlags.Flags.setOrigAlign(1); 5673 5674 Outs.push_back(MyFlags); 5675 } 5676 } 5677 } 5678 5679 // Handle the incoming return values from the call. 5680 SmallVector<ISD::InputArg, 32> Ins; 5681 SmallVector<EVT, 4> RetTys; 5682 ComputeValueVTs(*this, RetTy, RetTys); 5683 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 5684 EVT VT = RetTys[I]; 5685 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 5686 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 5687 for (unsigned i = 0; i != NumRegs; ++i) { 5688 ISD::InputArg MyFlags; 5689 MyFlags.VT = RegisterVT; 5690 MyFlags.Used = isReturnValueUsed; 5691 if (RetSExt) 5692 MyFlags.Flags.setSExt(); 5693 if (RetZExt) 5694 MyFlags.Flags.setZExt(); 5695 if (isInreg) 5696 MyFlags.Flags.setInReg(); 5697 Ins.push_back(MyFlags); 5698 } 5699 } 5700 5701 // Check if target-dependent constraints permit a tail call here. 5702 // Target-independent constraints should be checked by the caller. 5703 if (isTailCall && 5704 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG)) 5705 isTailCall = false; 5706 5707 SmallVector<SDValue, 4> InVals; 5708 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall, 5709 Outs, Ins, dl, DAG, InVals); 5710 5711 // Verify that the target's LowerCall behaved as expected. 5712 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 5713 "LowerCall didn't return a valid chain!"); 5714 assert((!isTailCall || InVals.empty()) && 5715 "LowerCall emitted a return value for a tail call!"); 5716 assert((isTailCall || InVals.size() == Ins.size()) && 5717 "LowerCall didn't emit the correct number of values!"); 5718 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 5719 assert(InVals[i].getNode() && 5720 "LowerCall emitted a null value!"); 5721 assert(Ins[i].VT == InVals[i].getValueType() && 5722 "LowerCall emitted a value with the wrong type!"); 5723 }); 5724 5725 // For a tail call, the return value is merely live-out and there aren't 5726 // any nodes in the DAG representing it. Return a special value to 5727 // indicate that a tail call has been emitted and no more Instructions 5728 // should be processed in the current block. 5729 if (isTailCall) { 5730 DAG.setRoot(Chain); 5731 return std::make_pair(SDValue(), SDValue()); 5732 } 5733 5734 // Collect the legal value parts into potentially illegal values 5735 // that correspond to the original function's return values. 5736 ISD::NodeType AssertOp = ISD::DELETED_NODE; 5737 if (RetSExt) 5738 AssertOp = ISD::AssertSext; 5739 else if (RetZExt) 5740 AssertOp = ISD::AssertZext; 5741 SmallVector<SDValue, 4> ReturnValues; 5742 unsigned CurReg = 0; 5743 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 5744 EVT VT = RetTys[I]; 5745 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 5746 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 5747 5748 SDValue ReturnValue = 5749 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT, 5750 AssertOp); 5751 ReturnValues.push_back(ReturnValue); 5752 CurReg += NumRegs; 5753 } 5754 5755 // For a function returning void, there is no return value. We can't create 5756 // such a node, so we just return a null return value in that case. In 5757 // that case, nothing will actualy look at the value. 5758 if (ReturnValues.empty()) 5759 return std::make_pair(SDValue(), Chain); 5760 5761 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 5762 DAG.getVTList(&RetTys[0], RetTys.size()), 5763 &ReturnValues[0], ReturnValues.size()); 5764 5765 return std::make_pair(Res, Chain); 5766 } 5767 5768 void TargetLowering::LowerOperationWrapper(SDNode *N, 5769 SmallVectorImpl<SDValue> &Results, 5770 SelectionDAG &DAG) { 5771 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 5772 if (Res.getNode()) 5773 Results.push_back(Res); 5774 } 5775 5776 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { 5777 llvm_unreachable("LowerOperation not implemented for this target!"); 5778 return SDValue(); 5779 } 5780 5781 5782 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) { 5783 SDValue Op = getValue(V); 5784 assert((Op.getOpcode() != ISD::CopyFromReg || 5785 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 5786 "Copy from a reg to the same reg!"); 5787 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 5788 5789 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType()); 5790 SDValue Chain = DAG.getEntryNode(); 5791 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0); 5792 PendingExports.push_back(Chain); 5793 } 5794 5795 #include "llvm/CodeGen/SelectionDAGISel.h" 5796 5797 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) { 5798 // If this is the entry block, emit arguments. 5799 Function &F = *LLVMBB->getParent(); 5800 SelectionDAG &DAG = SDB->DAG; 5801 SDValue OldRoot = DAG.getRoot(); 5802 DebugLoc dl = SDB->getCurDebugLoc(); 5803 const TargetData *TD = TLI.getTargetData(); 5804 SmallVector<ISD::InputArg, 16> Ins; 5805 5806 // Check whether the function can return without sret-demotion. 5807 SmallVector<EVT, 4> OutVTs; 5808 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 5809 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), 5810 OutVTs, OutsFlags, TLI); 5811 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); 5812 5813 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(), 5814 OutVTs, OutsFlags, DAG); 5815 if (!FLI.CanLowerReturn) { 5816 // Put in an sret pointer parameter before all the other parameters. 5817 SmallVector<EVT, 1> ValueVTs; 5818 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 5819 5820 // NOTE: Assuming that a pointer will never break down to more than one VT 5821 // or one register. 5822 ISD::ArgFlagsTy Flags; 5823 Flags.setSRet(); 5824 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]); 5825 ISD::InputArg RetArg(Flags, RegisterVT, true); 5826 Ins.push_back(RetArg); 5827 } 5828 5829 // Set up the incoming argument description vector. 5830 unsigned Idx = 1; 5831 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 5832 I != E; ++I, ++Idx) { 5833 SmallVector<EVT, 4> ValueVTs; 5834 ComputeValueVTs(TLI, I->getType(), ValueVTs); 5835 bool isArgValueUsed = !I->use_empty(); 5836 for (unsigned Value = 0, NumValues = ValueVTs.size(); 5837 Value != NumValues; ++Value) { 5838 EVT VT = ValueVTs[Value]; 5839 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5840 ISD::ArgFlagsTy Flags; 5841 unsigned OriginalAlignment = 5842 TD->getABITypeAlignment(ArgTy); 5843 5844 if (F.paramHasAttr(Idx, Attribute::ZExt)) 5845 Flags.setZExt(); 5846 if (F.paramHasAttr(Idx, Attribute::SExt)) 5847 Flags.setSExt(); 5848 if (F.paramHasAttr(Idx, Attribute::InReg)) 5849 Flags.setInReg(); 5850 if (F.paramHasAttr(Idx, Attribute::StructRet)) 5851 Flags.setSRet(); 5852 if (F.paramHasAttr(Idx, Attribute::ByVal)) { 5853 Flags.setByVal(); 5854 const PointerType *Ty = cast<PointerType>(I->getType()); 5855 const Type *ElementTy = Ty->getElementType(); 5856 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy); 5857 unsigned FrameSize = TD->getTypeAllocSize(ElementTy); 5858 // For ByVal, alignment should be passed from FE. BE will guess if 5859 // this info is not there but there are cases it cannot get right. 5860 if (F.getParamAlignment(Idx)) 5861 FrameAlign = F.getParamAlignment(Idx); 5862 Flags.setByValAlign(FrameAlign); 5863 Flags.setByValSize(FrameSize); 5864 } 5865 if (F.paramHasAttr(Idx, Attribute::Nest)) 5866 Flags.setNest(); 5867 Flags.setOrigAlign(OriginalAlignment); 5868 5869 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 5870 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT); 5871 for (unsigned i = 0; i != NumRegs; ++i) { 5872 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed); 5873 if (NumRegs > 1 && i == 0) 5874 MyFlags.Flags.setSplit(); 5875 // if it isn't first piece, alignment must be 1 5876 else if (i > 0) 5877 MyFlags.Flags.setOrigAlign(1); 5878 Ins.push_back(MyFlags); 5879 } 5880 } 5881 } 5882 5883 // Call the target to set up the argument values. 5884 SmallVector<SDValue, 8> InVals; 5885 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 5886 F.isVarArg(), Ins, 5887 dl, DAG, InVals); 5888 5889 // Verify that the target's LowerFormalArguments behaved as expected. 5890 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 5891 "LowerFormalArguments didn't return a valid chain!"); 5892 assert(InVals.size() == Ins.size() && 5893 "LowerFormalArguments didn't emit the correct number of values!"); 5894 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 5895 assert(InVals[i].getNode() && 5896 "LowerFormalArguments emitted a null value!"); 5897 assert(Ins[i].VT == InVals[i].getValueType() && 5898 "LowerFormalArguments emitted a value with the wrong type!"); 5899 }); 5900 5901 // Update the DAG with the new chain value resulting from argument lowering. 5902 DAG.setRoot(NewRoot); 5903 5904 // Set up the argument values. 5905 unsigned i = 0; 5906 Idx = 1; 5907 if (!FLI.CanLowerReturn) { 5908 // Create a virtual register for the sret pointer, and put in a copy 5909 // from the sret argument into it. 5910 SmallVector<EVT, 1> ValueVTs; 5911 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 5912 EVT VT = ValueVTs[0]; 5913 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 5914 ISD::NodeType AssertOp = ISD::DELETED_NODE; 5915 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, 5916 VT, AssertOp); 5917 5918 MachineFunction& MF = SDB->DAG.getMachineFunction(); 5919 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 5920 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); 5921 FLI.DemoteRegister = SRetReg; 5922 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue); 5923 DAG.setRoot(NewRoot); 5924 5925 // i indexes lowered arguments. Bump it past the hidden sret argument. 5926 // Idx indexes LLVM arguments. Don't touch it. 5927 ++i; 5928 } 5929 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 5930 ++I, ++Idx) { 5931 SmallVector<SDValue, 4> ArgValues; 5932 SmallVector<EVT, 4> ValueVTs; 5933 ComputeValueVTs(TLI, I->getType(), ValueVTs); 5934 unsigned NumValues = ValueVTs.size(); 5935 for (unsigned Value = 0; Value != NumValues; ++Value) { 5936 EVT VT = ValueVTs[Value]; 5937 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 5938 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT); 5939 5940 if (!I->use_empty()) { 5941 ISD::NodeType AssertOp = ISD::DELETED_NODE; 5942 if (F.paramHasAttr(Idx, Attribute::SExt)) 5943 AssertOp = ISD::AssertSext; 5944 else if (F.paramHasAttr(Idx, Attribute::ZExt)) 5945 AssertOp = ISD::AssertZext; 5946 5947 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 5948 PartVT, VT, AssertOp)); 5949 } 5950 i += NumParts; 5951 } 5952 if (!I->use_empty()) { 5953 SDB->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues, 5954 SDB->getCurDebugLoc())); 5955 // If this argument is live outside of the entry block, insert a copy from 5956 // whereever we got it to the vreg that other BB's will reference it as. 5957 SDB->CopyToExportRegsIfNeeded(I); 5958 } 5959 } 5960 assert(i == InVals.size() && "Argument register count mismatch!"); 5961 5962 // Finally, if the target has anything special to do, allow it to do so. 5963 // FIXME: this should insert code into the DAG! 5964 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction()); 5965 } 5966 5967 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 5968 /// ensure constants are generated when needed. Remember the virtual registers 5969 /// that need to be added to the Machine PHI nodes as input. We cannot just 5970 /// directly add them, because expansion might result in multiple MBB's for one 5971 /// BB. As such, the start of the BB might correspond to a different MBB than 5972 /// the end. 5973 /// 5974 void 5975 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) { 5976 TerminatorInst *TI = LLVMBB->getTerminator(); 5977 5978 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 5979 5980 // Check successor nodes' PHI nodes that expect a constant to be available 5981 // from this block. 5982 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 5983 BasicBlock *SuccBB = TI->getSuccessor(succ); 5984 if (!isa<PHINode>(SuccBB->begin())) continue; 5985 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB]; 5986 5987 // If this terminator has multiple identical successors (common for 5988 // switches), only handle each succ once. 5989 if (!SuccsHandled.insert(SuccMBB)) continue; 5990 5991 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 5992 PHINode *PN; 5993 5994 // At this point we know that there is a 1-1 correspondence between LLVM PHI 5995 // nodes and Machine PHI nodes, but the incoming operands have not been 5996 // emitted yet. 5997 for (BasicBlock::iterator I = SuccBB->begin(); 5998 (PN = dyn_cast<PHINode>(I)); ++I) { 5999 // Ignore dead phi's. 6000 if (PN->use_empty()) continue; 6001 6002 unsigned Reg; 6003 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6004 6005 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 6006 unsigned &RegOut = SDB->ConstantsOut[C]; 6007 if (RegOut == 0) { 6008 RegOut = FuncInfo->CreateRegForValue(C); 6009 SDB->CopyValueToVirtualRegister(C, RegOut); 6010 } 6011 Reg = RegOut; 6012 } else { 6013 Reg = FuncInfo->ValueMap[PHIOp]; 6014 if (Reg == 0) { 6015 assert(isa<AllocaInst>(PHIOp) && 6016 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 6017 "Didn't codegen value into a register!??"); 6018 Reg = FuncInfo->CreateRegForValue(PHIOp); 6019 SDB->CopyValueToVirtualRegister(PHIOp, Reg); 6020 } 6021 } 6022 6023 // Remember that this register needs to added to the machine PHI node as 6024 // the input for this MBB. 6025 SmallVector<EVT, 4> ValueVTs; 6026 ComputeValueVTs(TLI, PN->getType(), ValueVTs); 6027 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 6028 EVT VT = ValueVTs[vti]; 6029 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6030 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 6031 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 6032 Reg += NumRegisters; 6033 } 6034 } 6035 } 6036 SDB->ConstantsOut.clear(); 6037 } 6038 6039 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only 6040 /// supports legal types, and it emits MachineInstrs directly instead of 6041 /// creating SelectionDAG nodes. 6042 /// 6043 bool 6044 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB, 6045 FastISel *F) { 6046 TerminatorInst *TI = LLVMBB->getTerminator(); 6047 6048 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6049 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size(); 6050 6051 // Check successor nodes' PHI nodes that expect a constant to be available 6052 // from this block. 6053 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6054 BasicBlock *SuccBB = TI->getSuccessor(succ); 6055 if (!isa<PHINode>(SuccBB->begin())) continue; 6056 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB]; 6057 6058 // If this terminator has multiple identical successors (common for 6059 // switches), only handle each succ once. 6060 if (!SuccsHandled.insert(SuccMBB)) continue; 6061 6062 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6063 PHINode *PN; 6064 6065 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6066 // nodes and Machine PHI nodes, but the incoming operands have not been 6067 // emitted yet. 6068 for (BasicBlock::iterator I = SuccBB->begin(); 6069 (PN = dyn_cast<PHINode>(I)); ++I) { 6070 // Ignore dead phi's. 6071 if (PN->use_empty()) continue; 6072 6073 // Only handle legal types. Two interesting things to note here. First, 6074 // by bailing out early, we may leave behind some dead instructions, 6075 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 6076 // own moves. Second, this check is necessary becuase FastISel doesn't 6077 // use CreateRegForValue to create registers, so it always creates 6078 // exactly one register for each non-void instruction. 6079 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true); 6080 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 6081 // Promote MVT::i1. 6082 if (VT == MVT::i1) 6083 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT); 6084 else { 6085 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 6086 return false; 6087 } 6088 } 6089 6090 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6091 6092 unsigned Reg = F->getRegForValue(PHIOp); 6093 if (Reg == 0) { 6094 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 6095 return false; 6096 } 6097 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg)); 6098 } 6099 } 6100 6101 return true; 6102 } 6103