1 //===- FastISel.cpp - Implementation of the FastISel class ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the FastISel class. 10 // 11 // "Fast" instruction selection is designed to emit very poor code quickly. 12 // Also, it is not designed to be able to do much lowering, so most illegal 13 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is 14 // also not intended to be able to do much optimization, except in a few cases 15 // where doing optimizations reduces overall compile time. For example, folding 16 // constants into immediate fields is often done, because it's cheap and it 17 // reduces the number of instructions later phases have to examine. 18 // 19 // "Fast" instruction selection is able to fail gracefully and transfer 20 // control to the SelectionDAG selector for operations that it doesn't 21 // support. In many cases, this allows us to avoid duplicating a lot of 22 // the complicated lowering logic that SelectionDAG currently has. 23 // 24 // The intended use for "fast" instruction selection is "-O0" mode 25 // compilation, where the quality of the generated code is irrelevant when 26 // weighed against the speed at which the code can be generated. Also, 27 // at -O0, the LLVM optimizers are not running, and this makes the 28 // compile time of codegen a much higher portion of the overall compile 29 // time. Despite its limitations, "fast" instruction selection is able to 30 // handle enough code on its own to provide noticeable overall speedups 31 // in -O0 compiles. 32 // 33 // Basic operations are supported in a target-independent way, by reading 34 // the same instruction descriptions that the SelectionDAG selector reads, 35 // and identifying simple arithmetic operations that can be directly selected 36 // from simple operators. More complicated operations currently require 37 // target-specific code. 38 // 39 //===----------------------------------------------------------------------===// 40 41 #include "llvm/CodeGen/FastISel.h" 42 #include "llvm/ADT/APFloat.h" 43 #include "llvm/ADT/APSInt.h" 44 #include "llvm/ADT/DenseMap.h" 45 #include "llvm/ADT/SmallPtrSet.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/SmallVector.h" 48 #include "llvm/ADT/Statistic.h" 49 #include "llvm/Analysis/BranchProbabilityInfo.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/CodeGen/Analysis.h" 52 #include "llvm/CodeGen/FunctionLoweringInfo.h" 53 #include "llvm/CodeGen/ISDOpcodes.h" 54 #include "llvm/CodeGen/MachineBasicBlock.h" 55 #include "llvm/CodeGen/MachineFrameInfo.h" 56 #include "llvm/CodeGen/MachineInstr.h" 57 #include "llvm/CodeGen/MachineInstrBuilder.h" 58 #include "llvm/CodeGen/MachineMemOperand.h" 59 #include "llvm/CodeGen/MachineModuleInfo.h" 60 #include "llvm/CodeGen/MachineOperand.h" 61 #include "llvm/CodeGen/MachineRegisterInfo.h" 62 #include "llvm/CodeGen/MachineValueType.h" 63 #include "llvm/CodeGen/StackMaps.h" 64 #include "llvm/CodeGen/TargetInstrInfo.h" 65 #include "llvm/CodeGen/TargetLowering.h" 66 #include "llvm/CodeGen/TargetSubtargetInfo.h" 67 #include "llvm/CodeGen/ValueTypes.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugLoc.h" 76 #include "llvm/IR/DerivedTypes.h" 77 #include "llvm/IR/DiagnosticInfo.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/GlobalValue.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Mangler.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Type.h" 92 #include "llvm/IR/User.h" 93 #include "llvm/IR/Value.h" 94 #include "llvm/MC/MCContext.h" 95 #include "llvm/MC/MCInstrDesc.h" 96 #include "llvm/Support/Casting.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/MathExtras.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include <algorithm> 104 #include <cassert> 105 #include <cstdint> 106 #include <iterator> 107 #include <optional> 108 #include <utility> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 113 #define DEBUG_TYPE "isel" 114 115 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by " 116 "target-independent selector"); 117 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by " 118 "target-specific selector"); 119 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure"); 120 121 /// Set the current block to which generated machine instructions will be 122 /// appended. 123 void FastISel::startNewBlock() { 124 assert(LocalValueMap.empty() && 125 "local values should be cleared after finishing a BB"); 126 127 // Instructions are appended to FuncInfo.MBB. If the basic block already 128 // contains labels or copies, use the last instruction as the last local 129 // value. 130 EmitStartPt = nullptr; 131 if (!FuncInfo.MBB->empty()) 132 EmitStartPt = &FuncInfo.MBB->back(); 133 LastLocalValue = EmitStartPt; 134 } 135 136 void FastISel::finishBasicBlock() { flushLocalValueMap(); } 137 138 bool FastISel::lowerArguments() { 139 if (!FuncInfo.CanLowerReturn) 140 // Fallback to SDISel argument lowering code to deal with sret pointer 141 // parameter. 142 return false; 143 144 if (!fastLowerArguments()) 145 return false; 146 147 // Enter arguments into ValueMap for uses in non-entry BBs. 148 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(), 149 E = FuncInfo.Fn->arg_end(); 150 I != E; ++I) { 151 DenseMap<const Value *, Register>::iterator VI = LocalValueMap.find(&*I); 152 assert(VI != LocalValueMap.end() && "Missed an argument?"); 153 FuncInfo.ValueMap[&*I] = VI->second; 154 } 155 return true; 156 } 157 158 /// Return the defined register if this instruction defines exactly one 159 /// virtual register and uses no other virtual registers. Otherwise return 0. 160 static Register findLocalRegDef(MachineInstr &MI) { 161 Register RegDef; 162 for (const MachineOperand &MO : MI.operands()) { 163 if (!MO.isReg()) 164 continue; 165 if (MO.isDef()) { 166 if (RegDef) 167 return Register(); 168 RegDef = MO.getReg(); 169 } else if (MO.getReg().isVirtual()) { 170 // This is another use of a vreg. Don't delete it. 171 return Register(); 172 } 173 } 174 return RegDef; 175 } 176 177 static bool isRegUsedByPhiNodes(Register DefReg, 178 FunctionLoweringInfo &FuncInfo) { 179 for (auto &P : FuncInfo.PHINodesToUpdate) 180 if (P.second == DefReg) 181 return true; 182 return false; 183 } 184 185 void FastISel::flushLocalValueMap() { 186 // If FastISel bails out, it could leave local value instructions behind 187 // that aren't used for anything. Detect and erase those. 188 if (LastLocalValue != EmitStartPt) { 189 // Save the first instruction after local values, for later. 190 MachineBasicBlock::iterator FirstNonValue(LastLocalValue); 191 ++FirstNonValue; 192 193 MachineBasicBlock::reverse_iterator RE = 194 EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt) 195 : FuncInfo.MBB->rend(); 196 MachineBasicBlock::reverse_iterator RI(LastLocalValue); 197 for (MachineInstr &LocalMI : 198 llvm::make_early_inc_range(llvm::make_range(RI, RE))) { 199 Register DefReg = findLocalRegDef(LocalMI); 200 if (!DefReg) 201 continue; 202 if (FuncInfo.RegsWithFixups.count(DefReg)) 203 continue; 204 bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo); 205 if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) { 206 if (EmitStartPt == &LocalMI) 207 EmitStartPt = EmitStartPt->getPrevNode(); 208 LLVM_DEBUG(dbgs() << "removing dead local value materialization" 209 << LocalMI); 210 LocalMI.eraseFromParent(); 211 } 212 } 213 214 if (FirstNonValue != FuncInfo.MBB->end()) { 215 // See if there are any local value instructions left. If so, we want to 216 // make sure the first one has a debug location; if it doesn't, use the 217 // first non-value instruction's debug location. 218 219 // If EmitStartPt is non-null, this block had copies at the top before 220 // FastISel started doing anything; it points to the last one, so the 221 // first local value instruction is the one after EmitStartPt. 222 // If EmitStartPt is null, the first local value instruction is at the 223 // top of the block. 224 MachineBasicBlock::iterator FirstLocalValue = 225 EmitStartPt ? ++MachineBasicBlock::iterator(EmitStartPt) 226 : FuncInfo.MBB->begin(); 227 if (FirstLocalValue != FirstNonValue && !FirstLocalValue->getDebugLoc()) 228 FirstLocalValue->setDebugLoc(FirstNonValue->getDebugLoc()); 229 } 230 } 231 232 LocalValueMap.clear(); 233 LastLocalValue = EmitStartPt; 234 recomputeInsertPt(); 235 SavedInsertPt = FuncInfo.InsertPt; 236 } 237 238 Register FastISel::getRegForValue(const Value *V) { 239 EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true); 240 // Don't handle non-simple values in FastISel. 241 if (!RealVT.isSimple()) 242 return Register(); 243 244 // Ignore illegal types. We must do this before looking up the value 245 // in ValueMap because Arguments are given virtual registers regardless 246 // of whether FastISel can handle them. 247 MVT VT = RealVT.getSimpleVT(); 248 if (!TLI.isTypeLegal(VT)) { 249 // Handle integer promotions, though, because they're common and easy. 250 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 251 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 252 else 253 return Register(); 254 } 255 256 // Look up the value to see if we already have a register for it. 257 Register Reg = lookUpRegForValue(V); 258 if (Reg) 259 return Reg; 260 261 // In bottom-up mode, just create the virtual register which will be used 262 // to hold the value. It will be materialized later. 263 if (isa<Instruction>(V) && 264 (!isa<AllocaInst>(V) || 265 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) 266 return FuncInfo.InitializeRegForValue(V); 267 268 SavePoint SaveInsertPt = enterLocalValueArea(); 269 270 // Materialize the value in a register. Emit any instructions in the 271 // local value area. 272 Reg = materializeRegForValue(V, VT); 273 274 leaveLocalValueArea(SaveInsertPt); 275 276 return Reg; 277 } 278 279 Register FastISel::materializeConstant(const Value *V, MVT VT) { 280 Register Reg; 281 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 282 if (CI->getValue().getActiveBits() <= 64) 283 Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 284 } else if (isa<AllocaInst>(V)) 285 Reg = fastMaterializeAlloca(cast<AllocaInst>(V)); 286 else if (isa<ConstantPointerNull>(V)) 287 // Translate this as an integer zero so that it can be 288 // local-CSE'd with actual integer zeros. 289 Reg = 290 getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getType()))); 291 else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 292 if (CF->isNullValue()) 293 Reg = fastMaterializeFloatZero(CF); 294 else 295 // Try to emit the constant directly. 296 Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF); 297 298 if (!Reg) { 299 // Try to emit the constant by using an integer constant with a cast. 300 const APFloat &Flt = CF->getValueAPF(); 301 EVT IntVT = TLI.getPointerTy(DL); 302 uint32_t IntBitWidth = IntVT.getSizeInBits(); 303 APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false); 304 bool isExact; 305 (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact); 306 if (isExact) { 307 Register IntegerReg = 308 getRegForValue(ConstantInt::get(V->getContext(), SIntVal)); 309 if (IntegerReg) 310 Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, 311 IntegerReg); 312 } 313 } 314 } else if (const auto *Op = dyn_cast<Operator>(V)) { 315 if (!selectOperator(Op, Op->getOpcode())) 316 if (!isa<Instruction>(Op) || 317 !fastSelectInstruction(cast<Instruction>(Op))) 318 return 0; 319 Reg = lookUpRegForValue(Op); 320 } else if (isa<UndefValue>(V)) { 321 Reg = createResultReg(TLI.getRegClassFor(VT)); 322 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 323 TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 324 } 325 return Reg; 326 } 327 328 /// Helper for getRegForValue. This function is called when the value isn't 329 /// already available in a register and must be materialized with new 330 /// instructions. 331 Register FastISel::materializeRegForValue(const Value *V, MVT VT) { 332 Register Reg; 333 // Give the target-specific code a try first. 334 if (isa<Constant>(V)) 335 Reg = fastMaterializeConstant(cast<Constant>(V)); 336 337 // If target-specific code couldn't or didn't want to handle the value, then 338 // give target-independent code a try. 339 if (!Reg) 340 Reg = materializeConstant(V, VT); 341 342 // Don't cache constant materializations in the general ValueMap. 343 // To do so would require tracking what uses they dominate. 344 if (Reg) { 345 LocalValueMap[V] = Reg; 346 LastLocalValue = MRI.getVRegDef(Reg); 347 } 348 return Reg; 349 } 350 351 Register FastISel::lookUpRegForValue(const Value *V) { 352 // Look up the value to see if we already have a register for it. We 353 // cache values defined by Instructions across blocks, and other values 354 // only locally. This is because Instructions already have the SSA 355 // def-dominates-use requirement enforced. 356 DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(V); 357 if (I != FuncInfo.ValueMap.end()) 358 return I->second; 359 return LocalValueMap[V]; 360 } 361 362 void FastISel::updateValueMap(const Value *I, Register Reg, unsigned NumRegs) { 363 if (!isa<Instruction>(I)) { 364 LocalValueMap[I] = Reg; 365 return; 366 } 367 368 Register &AssignedReg = FuncInfo.ValueMap[I]; 369 if (!AssignedReg) 370 // Use the new register. 371 AssignedReg = Reg; 372 else if (Reg != AssignedReg) { 373 // Arrange for uses of AssignedReg to be replaced by uses of Reg. 374 for (unsigned i = 0; i < NumRegs; i++) { 375 FuncInfo.RegFixups[AssignedReg + i] = Reg + i; 376 FuncInfo.RegsWithFixups.insert(Reg + i); 377 } 378 379 AssignedReg = Reg; 380 } 381 } 382 383 Register FastISel::getRegForGEPIndex(const Value *Idx) { 384 Register IdxN = getRegForValue(Idx); 385 if (!IdxN) 386 // Unhandled operand. Halt "fast" selection and bail. 387 return Register(); 388 389 // If the index is smaller or larger than intptr_t, truncate or extend it. 390 MVT PtrVT = TLI.getPointerTy(DL); 391 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 392 if (IdxVT.bitsLT(PtrVT)) { 393 IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN); 394 } else if (IdxVT.bitsGT(PtrVT)) { 395 IdxN = 396 fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN); 397 } 398 return IdxN; 399 } 400 401 void FastISel::recomputeInsertPt() { 402 if (getLastLocalValue()) { 403 FuncInfo.InsertPt = getLastLocalValue(); 404 FuncInfo.MBB = FuncInfo.InsertPt->getParent(); 405 ++FuncInfo.InsertPt; 406 } else 407 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI(); 408 } 409 410 void FastISel::removeDeadCode(MachineBasicBlock::iterator I, 411 MachineBasicBlock::iterator E) { 412 assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 && 413 "Invalid iterator!"); 414 while (I != E) { 415 if (SavedInsertPt == I) 416 SavedInsertPt = E; 417 if (EmitStartPt == I) 418 EmitStartPt = E.isValid() ? &*E : nullptr; 419 if (LastLocalValue == I) 420 LastLocalValue = E.isValid() ? &*E : nullptr; 421 422 MachineInstr *Dead = &*I; 423 ++I; 424 Dead->eraseFromParent(); 425 ++NumFastIselDead; 426 } 427 recomputeInsertPt(); 428 } 429 430 FastISel::SavePoint FastISel::enterLocalValueArea() { 431 SavePoint OldInsertPt = FuncInfo.InsertPt; 432 recomputeInsertPt(); 433 return OldInsertPt; 434 } 435 436 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) { 437 if (FuncInfo.InsertPt != FuncInfo.MBB->begin()) 438 LastLocalValue = &*std::prev(FuncInfo.InsertPt); 439 440 // Restore the previous insert position. 441 FuncInfo.InsertPt = OldInsertPt; 442 } 443 444 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) { 445 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 446 if (VT == MVT::Other || !VT.isSimple()) 447 // Unhandled type. Halt "fast" selection and bail. 448 return false; 449 450 // We only handle legal types. For example, on x86-32 the instruction 451 // selector contains all of the 64-bit instructions from x86-64, 452 // under the assumption that i64 won't be used if the target doesn't 453 // support it. 454 if (!TLI.isTypeLegal(VT)) { 455 // MVT::i1 is special. Allow AND, OR, or XOR because they 456 // don't require additional zeroing, which makes them easy. 457 if (VT == MVT::i1 && ISD::isBitwiseLogicOp(ISDOpcode)) 458 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 459 else 460 return false; 461 } 462 463 // Check if the first operand is a constant, and handle it as "ri". At -O0, 464 // we don't have anything that canonicalizes operand order. 465 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0))) 466 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) { 467 Register Op1 = getRegForValue(I->getOperand(1)); 468 if (!Op1) 469 return false; 470 471 Register ResultReg = 472 fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, CI->getZExtValue(), 473 VT.getSimpleVT()); 474 if (!ResultReg) 475 return false; 476 477 // We successfully emitted code for the given LLVM Instruction. 478 updateValueMap(I, ResultReg); 479 return true; 480 } 481 482 Register Op0 = getRegForValue(I->getOperand(0)); 483 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 484 return false; 485 486 // Check if the second operand is a constant and handle it appropriately. 487 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 488 uint64_t Imm = CI->getSExtValue(); 489 490 // Transform "sdiv exact X, 8" -> "sra X, 3". 491 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) && 492 cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) { 493 Imm = Log2_64(Imm); 494 ISDOpcode = ISD::SRA; 495 } 496 497 // Transform "urem x, pow2" -> "and x, pow2-1". 498 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) && 499 isPowerOf2_64(Imm)) { 500 --Imm; 501 ISDOpcode = ISD::AND; 502 } 503 504 Register ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, Imm, 505 VT.getSimpleVT()); 506 if (!ResultReg) 507 return false; 508 509 // We successfully emitted code for the given LLVM Instruction. 510 updateValueMap(I, ResultReg); 511 return true; 512 } 513 514 Register Op1 = getRegForValue(I->getOperand(1)); 515 if (!Op1) // Unhandled operand. Halt "fast" selection and bail. 516 return false; 517 518 // Now we have both operands in registers. Emit the instruction. 519 Register ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 520 ISDOpcode, Op0, Op1); 521 if (!ResultReg) 522 // Target-specific code wasn't able to find a machine opcode for 523 // the given ISD opcode and type. Halt "fast" selection and bail. 524 return false; 525 526 // We successfully emitted code for the given LLVM Instruction. 527 updateValueMap(I, ResultReg); 528 return true; 529 } 530 531 bool FastISel::selectGetElementPtr(const User *I) { 532 Register N = getRegForValue(I->getOperand(0)); 533 if (!N) // Unhandled operand. Halt "fast" selection and bail. 534 return false; 535 536 // FIXME: The code below does not handle vector GEPs. Halt "fast" selection 537 // and bail. 538 if (isa<VectorType>(I->getType())) 539 return false; 540 541 // Keep a running tab of the total offset to coalesce multiple N = N + Offset 542 // into a single N = N + TotalOffset. 543 uint64_t TotalOffs = 0; 544 // FIXME: What's a good SWAG number for MaxOffs? 545 uint64_t MaxOffs = 2048; 546 MVT VT = TLI.getPointerTy(DL); 547 for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I); 548 GTI != E; ++GTI) { 549 const Value *Idx = GTI.getOperand(); 550 if (StructType *StTy = GTI.getStructTypeOrNull()) { 551 uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue(); 552 if (Field) { 553 // N = N + Offset 554 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field); 555 if (TotalOffs >= MaxOffs) { 556 N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT); 557 if (!N) // Unhandled operand. Halt "fast" selection and bail. 558 return false; 559 TotalOffs = 0; 560 } 561 } 562 } else { 563 Type *Ty = GTI.getIndexedType(); 564 565 // If this is a constant subscript, handle it quickly. 566 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 567 if (CI->isZero()) 568 continue; 569 // N = N + Offset 570 uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue(); 571 TotalOffs += DL.getTypeAllocSize(Ty) * IdxN; 572 if (TotalOffs >= MaxOffs) { 573 N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT); 574 if (!N) // Unhandled operand. Halt "fast" selection and bail. 575 return false; 576 TotalOffs = 0; 577 } 578 continue; 579 } 580 if (TotalOffs) { 581 N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT); 582 if (!N) // Unhandled operand. Halt "fast" selection and bail. 583 return false; 584 TotalOffs = 0; 585 } 586 587 // N = N + Idx * ElementSize; 588 uint64_t ElementSize = DL.getTypeAllocSize(Ty); 589 Register IdxN = getRegForGEPIndex(Idx); 590 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 591 return false; 592 593 if (ElementSize != 1) { 594 IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT); 595 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 596 return false; 597 } 598 N = fastEmit_rr(VT, VT, ISD::ADD, N, IdxN); 599 if (!N) // Unhandled operand. Halt "fast" selection and bail. 600 return false; 601 } 602 } 603 if (TotalOffs) { 604 N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT); 605 if (!N) // Unhandled operand. Halt "fast" selection and bail. 606 return false; 607 } 608 609 // We successfully emitted code for the given LLVM Instruction. 610 updateValueMap(I, N); 611 return true; 612 } 613 614 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops, 615 const CallInst *CI, unsigned StartIdx) { 616 for (unsigned i = StartIdx, e = CI->arg_size(); i != e; ++i) { 617 Value *Val = CI->getArgOperand(i); 618 // Check for constants and encode them with a StackMaps::ConstantOp prefix. 619 if (const auto *C = dyn_cast<ConstantInt>(Val)) { 620 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 621 Ops.push_back(MachineOperand::CreateImm(C->getSExtValue())); 622 } else if (isa<ConstantPointerNull>(Val)) { 623 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 624 Ops.push_back(MachineOperand::CreateImm(0)); 625 } else if (auto *AI = dyn_cast<AllocaInst>(Val)) { 626 // Values coming from a stack location also require a special encoding, 627 // but that is added later on by the target specific frame index 628 // elimination implementation. 629 auto SI = FuncInfo.StaticAllocaMap.find(AI); 630 if (SI != FuncInfo.StaticAllocaMap.end()) 631 Ops.push_back(MachineOperand::CreateFI(SI->second)); 632 else 633 return false; 634 } else { 635 Register Reg = getRegForValue(Val); 636 if (!Reg) 637 return false; 638 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 639 } 640 } 641 return true; 642 } 643 644 bool FastISel::selectStackmap(const CallInst *I) { 645 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 646 // [live variables...]) 647 assert(I->getCalledFunction()->getReturnType()->isVoidTy() && 648 "Stackmap cannot return a value."); 649 650 // The stackmap intrinsic only records the live variables (the arguments 651 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 652 // intrinsic, this won't be lowered to a function call. This means we don't 653 // have to worry about calling conventions and target-specific lowering code. 654 // Instead we perform the call lowering right here. 655 // 656 // CALLSEQ_START(0, 0...) 657 // STACKMAP(id, nbytes, ...) 658 // CALLSEQ_END(0, 0) 659 // 660 SmallVector<MachineOperand, 32> Ops; 661 662 // Add the <id> and <numBytes> constants. 663 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 664 "Expected a constant integer."); 665 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 666 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 667 668 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 669 "Expected a constant integer."); 670 const auto *NumBytes = 671 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 672 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 673 674 // Push live variables for the stack map (skipping the first two arguments 675 // <id> and <numBytes>). 676 if (!addStackMapLiveVars(Ops, I, 2)) 677 return false; 678 679 // We are not adding any register mask info here, because the stackmap doesn't 680 // clobber anything. 681 682 // Add scratch registers as implicit def and early clobber. 683 CallingConv::ID CC = I->getCallingConv(); 684 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 685 for (unsigned i = 0; ScratchRegs[i]; ++i) 686 Ops.push_back(MachineOperand::CreateReg( 687 ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false, 688 /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true)); 689 690 // Issue CALLSEQ_START 691 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 692 auto Builder = 693 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackDown)); 694 const MCInstrDesc &MCID = Builder.getInstr()->getDesc(); 695 for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I) 696 Builder.addImm(0); 697 698 // Issue STACKMAP. 699 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 700 TII.get(TargetOpcode::STACKMAP)); 701 for (auto const &MO : Ops) 702 MIB.add(MO); 703 704 // Issue CALLSEQ_END 705 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackUp)) 707 .addImm(0) 708 .addImm(0); 709 710 // Inform the Frame Information that we have a stackmap in this function. 711 FuncInfo.MF->getFrameInfo().setHasStackMap(); 712 713 return true; 714 } 715 716 /// Lower an argument list according to the target calling convention. 717 /// 718 /// This is a helper for lowering intrinsics that follow a target calling 719 /// convention or require stack pointer adjustment. Only a subset of the 720 /// intrinsic's operands need to participate in the calling convention. 721 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx, 722 unsigned NumArgs, const Value *Callee, 723 bool ForceRetVoidTy, CallLoweringInfo &CLI) { 724 ArgListTy Args; 725 Args.reserve(NumArgs); 726 727 // Populate the argument list. 728 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) { 729 Value *V = CI->getOperand(ArgI); 730 731 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 732 733 ArgListEntry Entry; 734 Entry.Val = V; 735 Entry.Ty = V->getType(); 736 Entry.setAttributes(CI, ArgI); 737 Args.push_back(Entry); 738 } 739 740 Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext()) 741 : CI->getType(); 742 CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs); 743 744 return lowerCallTo(CLI); 745 } 746 747 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee( 748 const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy, 749 StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) { 750 SmallString<32> MangledName; 751 Mangler::getNameWithPrefix(MangledName, Target, DL); 752 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 753 return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs); 754 } 755 756 bool FastISel::selectPatchpoint(const CallInst *I) { 757 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 758 // i32 <numBytes>, 759 // i8* <target>, 760 // i32 <numArgs>, 761 // [Args...], 762 // [live variables...]) 763 CallingConv::ID CC = I->getCallingConv(); 764 bool IsAnyRegCC = CC == CallingConv::AnyReg; 765 bool HasDef = !I->getType()->isVoidTy(); 766 Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts(); 767 768 // Get the real number of arguments participating in the call <numArgs> 769 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) && 770 "Expected a constant integer."); 771 const auto *NumArgsVal = 772 cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)); 773 unsigned NumArgs = NumArgsVal->getZExtValue(); 774 775 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 776 // This includes all meta-operands up to but not including CC. 777 unsigned NumMetaOpers = PatchPointOpers::CCPos; 778 assert(I->arg_size() >= NumMetaOpers + NumArgs && 779 "Not enough arguments provided to the patchpoint intrinsic"); 780 781 // For AnyRegCC the arguments are lowered later on manually. 782 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 783 CallLoweringInfo CLI; 784 CLI.setIsPatchPoint(); 785 if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI)) 786 return false; 787 788 assert(CLI.Call && "No call instruction specified."); 789 790 SmallVector<MachineOperand, 32> Ops; 791 792 // Add an explicit result reg if we use the anyreg calling convention. 793 if (IsAnyRegCC && HasDef) { 794 assert(CLI.NumResultRegs == 0 && "Unexpected result register."); 795 CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64)); 796 CLI.NumResultRegs = 1; 797 Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true)); 798 } 799 800 // Add the <id> and <numBytes> constants. 801 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 802 "Expected a constant integer."); 803 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 804 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 805 806 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 807 "Expected a constant integer."); 808 const auto *NumBytes = 809 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 810 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 811 812 // Add the call target. 813 if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) { 814 uint64_t CalleeConstAddr = 815 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 816 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 817 } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) { 818 if (C->getOpcode() == Instruction::IntToPtr) { 819 uint64_t CalleeConstAddr = 820 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 821 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 822 } else 823 llvm_unreachable("Unsupported ConstantExpr."); 824 } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) { 825 Ops.push_back(MachineOperand::CreateGA(GV, 0)); 826 } else if (isa<ConstantPointerNull>(Callee)) 827 Ops.push_back(MachineOperand::CreateImm(0)); 828 else 829 llvm_unreachable("Unsupported callee address."); 830 831 // Adjust <numArgs> to account for any arguments that have been passed on 832 // the stack instead. 833 unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size(); 834 Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs)); 835 836 // Add the calling convention 837 Ops.push_back(MachineOperand::CreateImm((unsigned)CC)); 838 839 // Add the arguments we omitted previously. The register allocator should 840 // place these in any free register. 841 if (IsAnyRegCC) { 842 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) { 843 Register Reg = getRegForValue(I->getArgOperand(i)); 844 if (!Reg) 845 return false; 846 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 847 } 848 } 849 850 // Push the arguments from the call instruction. 851 for (auto Reg : CLI.OutRegs) 852 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 853 854 // Push live variables for the stack map. 855 if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs)) 856 return false; 857 858 // Push the register mask info. 859 Ops.push_back(MachineOperand::CreateRegMask( 860 TRI.getCallPreservedMask(*FuncInfo.MF, CC))); 861 862 // Add scratch registers as implicit def and early clobber. 863 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 864 for (unsigned i = 0; ScratchRegs[i]; ++i) 865 Ops.push_back(MachineOperand::CreateReg( 866 ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false, 867 /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true)); 868 869 // Add implicit defs (return values). 870 for (auto Reg : CLI.InRegs) 871 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true, 872 /*isImp=*/true)); 873 874 // Insert the patchpoint instruction before the call generated by the target. 875 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, MIMD, 876 TII.get(TargetOpcode::PATCHPOINT)); 877 878 for (auto &MO : Ops) 879 MIB.add(MO); 880 881 MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI); 882 883 // Delete the original call instruction. 884 CLI.Call->eraseFromParent(); 885 886 // Inform the Frame Information that we have a patchpoint in this function. 887 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 888 889 if (CLI.NumResultRegs) 890 updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs); 891 return true; 892 } 893 894 bool FastISel::selectXRayCustomEvent(const CallInst *I) { 895 const auto &Triple = TM.getTargetTriple(); 896 if (Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 897 return true; // don't do anything to this instruction. 898 SmallVector<MachineOperand, 8> Ops; 899 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 900 /*isDef=*/false)); 901 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 902 /*isDef=*/false)); 903 MachineInstrBuilder MIB = 904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 905 TII.get(TargetOpcode::PATCHABLE_EVENT_CALL)); 906 for (auto &MO : Ops) 907 MIB.add(MO); 908 909 // Insert the Patchable Event Call instruction, that gets lowered properly. 910 return true; 911 } 912 913 bool FastISel::selectXRayTypedEvent(const CallInst *I) { 914 const auto &Triple = TM.getTargetTriple(); 915 if (Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 916 return true; // don't do anything to this instruction. 917 SmallVector<MachineOperand, 8> Ops; 918 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 919 /*isDef=*/false)); 920 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 921 /*isDef=*/false)); 922 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)), 923 /*isDef=*/false)); 924 MachineInstrBuilder MIB = 925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 926 TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL)); 927 for (auto &MO : Ops) 928 MIB.add(MO); 929 930 // Insert the Patchable Typed Event Call instruction, that gets lowered properly. 931 return true; 932 } 933 934 /// Returns an AttributeList representing the attributes applied to the return 935 /// value of the given call. 936 static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) { 937 SmallVector<Attribute::AttrKind, 2> Attrs; 938 if (CLI.RetSExt) 939 Attrs.push_back(Attribute::SExt); 940 if (CLI.RetZExt) 941 Attrs.push_back(Attribute::ZExt); 942 if (CLI.IsInReg) 943 Attrs.push_back(Attribute::InReg); 944 945 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 946 Attrs); 947 } 948 949 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName, 950 unsigned NumArgs) { 951 MCContext &Ctx = MF->getContext(); 952 SmallString<32> MangledName; 953 Mangler::getNameWithPrefix(MangledName, SymName, DL); 954 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 955 return lowerCallTo(CI, Sym, NumArgs); 956 } 957 958 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol, 959 unsigned NumArgs) { 960 FunctionType *FTy = CI->getFunctionType(); 961 Type *RetTy = CI->getType(); 962 963 ArgListTy Args; 964 Args.reserve(NumArgs); 965 966 // Populate the argument list. 967 // Attributes for args start at offset 1, after the return attribute. 968 for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) { 969 Value *V = CI->getOperand(ArgI); 970 971 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 972 973 ArgListEntry Entry; 974 Entry.Val = V; 975 Entry.Ty = V->getType(); 976 Entry.setAttributes(CI, ArgI); 977 Args.push_back(Entry); 978 } 979 TLI.markLibCallAttributes(MF, CI->getCallingConv(), Args); 980 981 CallLoweringInfo CLI; 982 CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), *CI, NumArgs); 983 984 return lowerCallTo(CLI); 985 } 986 987 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) { 988 // Handle the incoming return values from the call. 989 CLI.clearIns(); 990 SmallVector<EVT, 4> RetTys; 991 ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys); 992 993 SmallVector<ISD::OutputArg, 4> Outs; 994 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL); 995 996 bool CanLowerReturn = TLI.CanLowerReturn( 997 CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 998 999 // FIXME: sret demotion isn't supported yet - bail out. 1000 if (!CanLowerReturn) 1001 return false; 1002 1003 for (EVT VT : RetTys) { 1004 MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT); 1005 unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT); 1006 for (unsigned i = 0; i != NumRegs; ++i) { 1007 ISD::InputArg MyFlags; 1008 MyFlags.VT = RegisterVT; 1009 MyFlags.ArgVT = VT; 1010 MyFlags.Used = CLI.IsReturnValueUsed; 1011 if (CLI.RetSExt) 1012 MyFlags.Flags.setSExt(); 1013 if (CLI.RetZExt) 1014 MyFlags.Flags.setZExt(); 1015 if (CLI.IsInReg) 1016 MyFlags.Flags.setInReg(); 1017 CLI.Ins.push_back(MyFlags); 1018 } 1019 } 1020 1021 // Handle all of the outgoing arguments. 1022 CLI.clearOuts(); 1023 for (auto &Arg : CLI.getArgs()) { 1024 Type *FinalType = Arg.Ty; 1025 if (Arg.IsByVal) 1026 FinalType = Arg.IndirectType; 1027 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1028 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 1029 1030 ISD::ArgFlagsTy Flags; 1031 if (Arg.IsZExt) 1032 Flags.setZExt(); 1033 if (Arg.IsSExt) 1034 Flags.setSExt(); 1035 if (Arg.IsInReg) 1036 Flags.setInReg(); 1037 if (Arg.IsSRet) 1038 Flags.setSRet(); 1039 if (Arg.IsSwiftSelf) 1040 Flags.setSwiftSelf(); 1041 if (Arg.IsSwiftAsync) 1042 Flags.setSwiftAsync(); 1043 if (Arg.IsSwiftError) 1044 Flags.setSwiftError(); 1045 if (Arg.IsCFGuardTarget) 1046 Flags.setCFGuardTarget(); 1047 if (Arg.IsByVal) 1048 Flags.setByVal(); 1049 if (Arg.IsInAlloca) { 1050 Flags.setInAlloca(); 1051 // Set the byval flag for CCAssignFn callbacks that don't know about 1052 // inalloca. This way we can know how many bytes we should've allocated 1053 // and how many bytes a callee cleanup function will pop. If we port 1054 // inalloca to more targets, we'll have to add custom inalloca handling in 1055 // the various CC lowering callbacks. 1056 Flags.setByVal(); 1057 } 1058 if (Arg.IsPreallocated) { 1059 Flags.setPreallocated(); 1060 // Set the byval flag for CCAssignFn callbacks that don't know about 1061 // preallocated. This way we can know how many bytes we should've 1062 // allocated and how many bytes a callee cleanup function will pop. If we 1063 // port preallocated to more targets, we'll have to add custom 1064 // preallocated handling in the various CC lowering callbacks. 1065 Flags.setByVal(); 1066 } 1067 MaybeAlign MemAlign = Arg.Alignment; 1068 if (Arg.IsByVal || Arg.IsInAlloca || Arg.IsPreallocated) { 1069 unsigned FrameSize = DL.getTypeAllocSize(Arg.IndirectType); 1070 1071 // For ByVal, alignment should come from FE. BE will guess if this info 1072 // is not there, but there are cases it cannot get right. 1073 if (!MemAlign) 1074 MemAlign = Align(TLI.getByValTypeAlignment(Arg.IndirectType, DL)); 1075 Flags.setByValSize(FrameSize); 1076 } else if (!MemAlign) { 1077 MemAlign = DL.getABITypeAlign(Arg.Ty); 1078 } 1079 Flags.setMemAlign(*MemAlign); 1080 if (Arg.IsNest) 1081 Flags.setNest(); 1082 if (NeedsRegBlock) 1083 Flags.setInConsecutiveRegs(); 1084 Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty)); 1085 CLI.OutVals.push_back(Arg.Val); 1086 CLI.OutFlags.push_back(Flags); 1087 } 1088 1089 if (!fastLowerCall(CLI)) 1090 return false; 1091 1092 // Set all unused physreg defs as dead. 1093 assert(CLI.Call && "No call instruction specified."); 1094 CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI); 1095 1096 if (CLI.NumResultRegs && CLI.CB) 1097 updateValueMap(CLI.CB, CLI.ResultReg, CLI.NumResultRegs); 1098 1099 // Set labels for heapallocsite call. 1100 if (CLI.CB) 1101 if (MDNode *MD = CLI.CB->getMetadata("heapallocsite")) 1102 CLI.Call->setHeapAllocMarker(*MF, MD); 1103 1104 return true; 1105 } 1106 1107 bool FastISel::lowerCall(const CallInst *CI) { 1108 FunctionType *FuncTy = CI->getFunctionType(); 1109 Type *RetTy = CI->getType(); 1110 1111 ArgListTy Args; 1112 ArgListEntry Entry; 1113 Args.reserve(CI->arg_size()); 1114 1115 for (auto i = CI->arg_begin(), e = CI->arg_end(); i != e; ++i) { 1116 Value *V = *i; 1117 1118 // Skip empty types 1119 if (V->getType()->isEmptyTy()) 1120 continue; 1121 1122 Entry.Val = V; 1123 Entry.Ty = V->getType(); 1124 1125 // Skip the first return-type Attribute to get to params. 1126 Entry.setAttributes(CI, i - CI->arg_begin()); 1127 Args.push_back(Entry); 1128 } 1129 1130 // Check if target-independent constraints permit a tail call here. 1131 // Target-dependent constraints are checked within fastLowerCall. 1132 bool IsTailCall = CI->isTailCall(); 1133 if (IsTailCall && !isInTailCallPosition(*CI, TM)) 1134 IsTailCall = false; 1135 if (IsTailCall && !CI->isMustTailCall() && 1136 MF->getFunction().getFnAttribute("disable-tail-calls").getValueAsBool()) 1137 IsTailCall = false; 1138 1139 CallLoweringInfo CLI; 1140 CLI.setCallee(RetTy, FuncTy, CI->getCalledOperand(), std::move(Args), *CI) 1141 .setTailCall(IsTailCall); 1142 1143 diagnoseDontCall(*CI); 1144 1145 return lowerCallTo(CLI); 1146 } 1147 1148 bool FastISel::selectCall(const User *I) { 1149 const CallInst *Call = cast<CallInst>(I); 1150 1151 // Handle simple inline asms. 1152 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledOperand())) { 1153 // Don't attempt to handle constraints. 1154 if (!IA->getConstraintString().empty()) 1155 return false; 1156 1157 unsigned ExtraInfo = 0; 1158 if (IA->hasSideEffects()) 1159 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 1160 if (IA->isAlignStack()) 1161 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 1162 if (Call->isConvergent()) 1163 ExtraInfo |= InlineAsm::Extra_IsConvergent; 1164 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 1165 1166 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 1167 TII.get(TargetOpcode::INLINEASM)); 1168 MIB.addExternalSymbol(IA->getAsmString().c_str()); 1169 MIB.addImm(ExtraInfo); 1170 1171 const MDNode *SrcLoc = Call->getMetadata("srcloc"); 1172 if (SrcLoc) 1173 MIB.addMetadata(SrcLoc); 1174 1175 return true; 1176 } 1177 1178 // Handle intrinsic function calls. 1179 if (const auto *II = dyn_cast<IntrinsicInst>(Call)) 1180 return selectIntrinsicCall(II); 1181 1182 return lowerCall(Call); 1183 } 1184 1185 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) { 1186 switch (II->getIntrinsicID()) { 1187 default: 1188 break; 1189 // At -O0 we don't care about the lifetime intrinsics. 1190 case Intrinsic::lifetime_start: 1191 case Intrinsic::lifetime_end: 1192 // The donothing intrinsic does, well, nothing. 1193 case Intrinsic::donothing: 1194 // Neither does the sideeffect intrinsic. 1195 case Intrinsic::sideeffect: 1196 // Neither does the assume intrinsic; it's also OK not to codegen its operand. 1197 case Intrinsic::assume: 1198 // Neither does the llvm.experimental.noalias.scope.decl intrinsic 1199 case Intrinsic::experimental_noalias_scope_decl: 1200 return true; 1201 case Intrinsic::dbg_declare: { 1202 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 1203 assert(DI->getVariable() && "Missing variable"); 1204 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1205 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1206 << " (!hasDebugInfo)\n"); 1207 return true; 1208 } 1209 1210 if (FuncInfo.PreprocessedDbgDeclares.contains(DI)) 1211 return true; 1212 1213 const Value *Address = DI->getAddress(); 1214 if (!Address || isa<UndefValue>(Address)) { 1215 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1216 << " (bad/undef address)\n"); 1217 return true; 1218 } 1219 1220 std::optional<MachineOperand> Op; 1221 if (Register Reg = lookUpRegForValue(Address)) 1222 Op = MachineOperand::CreateReg(Reg, false); 1223 1224 // If we have a VLA that has a "use" in a metadata node that's then used 1225 // here but it has no other uses, then we have a problem. E.g., 1226 // 1227 // int foo (const int *x) { 1228 // char a[*x]; 1229 // return 0; 1230 // } 1231 // 1232 // If we assign 'a' a vreg and fast isel later on has to use the selection 1233 // DAG isel, it will want to copy the value to the vreg. However, there are 1234 // no uses, which goes counter to what selection DAG isel expects. 1235 if (!Op && !Address->use_empty() && isa<Instruction>(Address) && 1236 (!isa<AllocaInst>(Address) || 1237 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address)))) 1238 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address), 1239 false); 1240 1241 if (Op) { 1242 assert(DI->getVariable()->isValidLocationForIntrinsic(MIMD.getDL()) && 1243 "Expected inlined-at fields to agree"); 1244 if (FuncInfo.MF->useDebugInstrRef() && Op->isReg()) { 1245 // If using instruction referencing, produce this as a DBG_INSTR_REF, 1246 // to be later patched up by finalizeDebugInstrRefs. Tack a deref onto 1247 // the expression, we don't have an "indirect" flag in DBG_INSTR_REF. 1248 SmallVector<uint64_t, 3> Ops( 1249 {dwarf::DW_OP_LLVM_arg, 0, dwarf::DW_OP_deref}); 1250 auto *NewExpr = DIExpression::prependOpcodes(DI->getExpression(), Ops); 1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), 1252 TII.get(TargetOpcode::DBG_INSTR_REF), /*IsIndirect*/ false, *Op, 1253 DI->getVariable(), NewExpr); 1254 } else { 1255 // A dbg.declare describes the address of a source variable, so lower it 1256 // into an indirect DBG_VALUE. 1257 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), 1258 TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true, *Op, 1259 DI->getVariable(), DI->getExpression()); 1260 } 1261 } else { 1262 // We can't yet handle anything else here because it would require 1263 // generating code, thus altering codegen because of debug info. 1264 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1265 << " (no materialized reg for address)\n"); 1266 } 1267 return true; 1268 } 1269 case Intrinsic::dbg_value: { 1270 // This form of DBG_VALUE is target-independent. 1271 const DbgValueInst *DI = cast<DbgValueInst>(II); 1272 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1273 const Value *V = DI->getValue(); 1274 DIExpression *Expr = DI->getExpression(); 1275 DILocalVariable *Var = DI->getVariable(); 1276 assert(Var->isValidLocationForIntrinsic(MIMD.getDL()) && 1277 "Expected inlined-at fields to agree"); 1278 if (!V || isa<UndefValue>(V) || DI->hasArgList()) { 1279 // DI is either undef or cannot produce a valid DBG_VALUE, so produce an 1280 // undef DBG_VALUE to terminate any prior location. 1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), II, false, 0U, 1282 Var, Expr); 1283 return true; 1284 } 1285 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 1286 // See if there's an expression to constant-fold. 1287 if (Expr) 1288 std::tie(Expr, CI) = Expr->constantFold(CI); 1289 if (CI->getBitWidth() > 64) 1290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 1291 .addCImm(CI) 1292 .addImm(0U) 1293 .addMetadata(Var) 1294 .addMetadata(Expr); 1295 else 1296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 1297 .addImm(CI->getZExtValue()) 1298 .addImm(0U) 1299 .addMetadata(Var) 1300 .addMetadata(Expr); 1301 return true; 1302 } 1303 if (const auto *CF = dyn_cast<ConstantFP>(V)) { 1304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 1305 .addFPImm(CF) 1306 .addImm(0U) 1307 .addMetadata(Var) 1308 .addMetadata(Expr); 1309 return true; 1310 } 1311 if (const auto *Arg = dyn_cast<Argument>(V); 1312 Arg && Expr && Expr->isEntryValue()) { 1313 // As per the Verifier, this case is only valid for swift async Args. 1314 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 1315 1316 Register Reg = getRegForValue(Arg); 1317 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 1318 if (Reg == VirtReg || Reg == PhysReg) { 1319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), II, 1320 false /*IsIndirect*/, PhysReg, Var, Expr); 1321 return true; 1322 } 1323 1324 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 1325 "couldn't find a physical register\n" 1326 << *DI << "\n"); 1327 return true; 1328 } 1329 if (auto SI = FuncInfo.StaticAllocaMap.find(dyn_cast<AllocaInst>(V)); 1330 SI != FuncInfo.StaticAllocaMap.end()) { 1331 MachineOperand FrameIndexOp = MachineOperand::CreateFI(SI->second); 1332 bool IsIndirect = false; 1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), II, IsIndirect, 1334 FrameIndexOp, Var, Expr); 1335 return true; 1336 } 1337 if (Register Reg = lookUpRegForValue(V)) { 1338 // FIXME: This does not handle register-indirect values at offset 0. 1339 if (!FuncInfo.MF->useDebugInstrRef()) { 1340 bool IsIndirect = false; 1341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), II, IsIndirect, 1342 Reg, Var, Expr); 1343 return true; 1344 } 1345 // If using instruction referencing, produce this as a DBG_INSTR_REF, 1346 // to be later patched up by finalizeDebugInstrRefs. 1347 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 1348 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 1349 /* isKill */ false, /* isDead */ false, 1350 /* isUndef */ false, /* isEarlyClobber */ false, 1351 /* SubReg */ 0, /* isDebug */ true)}); 1352 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 1353 auto *NewExpr = DIExpression::prependOpcodes(Expr, Ops); 1354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD.getDL(), 1355 TII.get(TargetOpcode::DBG_INSTR_REF), /*IsIndirect*/ false, MOs, 1356 Var, NewExpr); 1357 return true; 1358 } 1359 // We don't know how to handle other cases, so we drop. 1360 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1361 return true; 1362 } 1363 case Intrinsic::dbg_label: { 1364 const DbgLabelInst *DI = cast<DbgLabelInst>(II); 1365 assert(DI->getLabel() && "Missing label"); 1366 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1367 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1368 return true; 1369 } 1370 1371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 1372 TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel()); 1373 return true; 1374 } 1375 case Intrinsic::objectsize: 1376 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 1377 1378 case Intrinsic::is_constant: 1379 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 1380 1381 case Intrinsic::launder_invariant_group: 1382 case Intrinsic::strip_invariant_group: 1383 case Intrinsic::expect: { 1384 Register ResultReg = getRegForValue(II->getArgOperand(0)); 1385 if (!ResultReg) 1386 return false; 1387 updateValueMap(II, ResultReg); 1388 return true; 1389 } 1390 case Intrinsic::experimental_stackmap: 1391 return selectStackmap(II); 1392 case Intrinsic::experimental_patchpoint_void: 1393 case Intrinsic::experimental_patchpoint_i64: 1394 return selectPatchpoint(II); 1395 1396 case Intrinsic::xray_customevent: 1397 return selectXRayCustomEvent(II); 1398 case Intrinsic::xray_typedevent: 1399 return selectXRayTypedEvent(II); 1400 } 1401 1402 return fastLowerIntrinsicCall(II); 1403 } 1404 1405 bool FastISel::selectCast(const User *I, unsigned Opcode) { 1406 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1407 EVT DstVT = TLI.getValueType(DL, I->getType()); 1408 1409 if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other || 1410 !DstVT.isSimple()) 1411 // Unhandled type. Halt "fast" selection and bail. 1412 return false; 1413 1414 // Check if the destination type is legal. 1415 if (!TLI.isTypeLegal(DstVT)) 1416 return false; 1417 1418 // Check if the source operand is legal. 1419 if (!TLI.isTypeLegal(SrcVT)) 1420 return false; 1421 1422 Register InputReg = getRegForValue(I->getOperand(0)); 1423 if (!InputReg) 1424 // Unhandled operand. Halt "fast" selection and bail. 1425 return false; 1426 1427 Register ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), 1428 Opcode, InputReg); 1429 if (!ResultReg) 1430 return false; 1431 1432 updateValueMap(I, ResultReg); 1433 return true; 1434 } 1435 1436 bool FastISel::selectBitCast(const User *I) { 1437 EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1438 EVT DstEVT = TLI.getValueType(DL, I->getType()); 1439 if (SrcEVT == MVT::Other || DstEVT == MVT::Other || 1440 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT)) 1441 // Unhandled type. Halt "fast" selection and bail. 1442 return false; 1443 1444 MVT SrcVT = SrcEVT.getSimpleVT(); 1445 MVT DstVT = DstEVT.getSimpleVT(); 1446 Register Op0 = getRegForValue(I->getOperand(0)); 1447 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 1448 return false; 1449 1450 // If the bitcast doesn't change the type, just use the operand value. 1451 if (SrcVT == DstVT) { 1452 updateValueMap(I, Op0); 1453 return true; 1454 } 1455 1456 // Otherwise, select a BITCAST opcode. 1457 Register ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0); 1458 if (!ResultReg) 1459 return false; 1460 1461 updateValueMap(I, ResultReg); 1462 return true; 1463 } 1464 1465 bool FastISel::selectFreeze(const User *I) { 1466 Register Reg = getRegForValue(I->getOperand(0)); 1467 if (!Reg) 1468 // Unhandled operand. 1469 return false; 1470 1471 EVT ETy = TLI.getValueType(DL, I->getOperand(0)->getType()); 1472 if (ETy == MVT::Other || !TLI.isTypeLegal(ETy)) 1473 // Unhandled type, bail out. 1474 return false; 1475 1476 MVT Ty = ETy.getSimpleVT(); 1477 const TargetRegisterClass *TyRegClass = TLI.getRegClassFor(Ty); 1478 Register ResultReg = createResultReg(TyRegClass); 1479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 1480 TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg); 1481 1482 updateValueMap(I, ResultReg); 1483 return true; 1484 } 1485 1486 // Remove local value instructions starting from the instruction after 1487 // SavedLastLocalValue to the current function insert point. 1488 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue) 1489 { 1490 MachineInstr *CurLastLocalValue = getLastLocalValue(); 1491 if (CurLastLocalValue != SavedLastLocalValue) { 1492 // Find the first local value instruction to be deleted. 1493 // This is the instruction after SavedLastLocalValue if it is non-NULL. 1494 // Otherwise it's the first instruction in the block. 1495 MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue); 1496 if (SavedLastLocalValue) 1497 ++FirstDeadInst; 1498 else 1499 FirstDeadInst = FuncInfo.MBB->getFirstNonPHI(); 1500 setLastLocalValue(SavedLastLocalValue); 1501 removeDeadCode(FirstDeadInst, FuncInfo.InsertPt); 1502 } 1503 } 1504 1505 bool FastISel::selectInstruction(const Instruction *I) { 1506 // Flush the local value map before starting each instruction. 1507 // This improves locality and debugging, and can reduce spills. 1508 // Reuse of values across IR instructions is relatively uncommon. 1509 flushLocalValueMap(); 1510 1511 MachineInstr *SavedLastLocalValue = getLastLocalValue(); 1512 // Just before the terminator instruction, insert instructions to 1513 // feed PHI nodes in successor blocks. 1514 if (I->isTerminator()) { 1515 if (!handlePHINodesInSuccessorBlocks(I->getParent())) { 1516 // PHI node handling may have generated local value instructions, 1517 // even though it failed to handle all PHI nodes. 1518 // We remove these instructions because SelectionDAGISel will generate 1519 // them again. 1520 removeDeadLocalValueCode(SavedLastLocalValue); 1521 return false; 1522 } 1523 } 1524 1525 // FastISel does not handle any operand bundles except OB_funclet. 1526 if (auto *Call = dyn_cast<CallBase>(I)) 1527 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) 1528 if (Call->getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet) 1529 return false; 1530 1531 MIMD = MIMetadata(*I); 1532 1533 SavedInsertPt = FuncInfo.InsertPt; 1534 1535 if (const auto *Call = dyn_cast<CallInst>(I)) { 1536 const Function *F = Call->getCalledFunction(); 1537 LibFunc Func; 1538 1539 // As a special case, don't handle calls to builtin library functions that 1540 // may be translated directly to target instructions. 1541 if (F && !F->hasLocalLinkage() && F->hasName() && 1542 LibInfo->getLibFunc(F->getName(), Func) && 1543 LibInfo->hasOptimizedCodeGen(Func)) 1544 return false; 1545 1546 // Don't handle Intrinsic::trap if a trap function is specified. 1547 if (F && F->getIntrinsicID() == Intrinsic::trap && 1548 Call->hasFnAttr("trap-func-name")) 1549 return false; 1550 } 1551 1552 // First, try doing target-independent selection. 1553 if (!SkipTargetIndependentISel) { 1554 if (selectOperator(I, I->getOpcode())) { 1555 ++NumFastIselSuccessIndependent; 1556 MIMD = {}; 1557 return true; 1558 } 1559 // Remove dead code. 1560 recomputeInsertPt(); 1561 if (SavedInsertPt != FuncInfo.InsertPt) 1562 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1563 SavedInsertPt = FuncInfo.InsertPt; 1564 } 1565 // Next, try calling the target to attempt to handle the instruction. 1566 if (fastSelectInstruction(I)) { 1567 ++NumFastIselSuccessTarget; 1568 MIMD = {}; 1569 return true; 1570 } 1571 // Remove dead code. 1572 recomputeInsertPt(); 1573 if (SavedInsertPt != FuncInfo.InsertPt) 1574 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1575 1576 MIMD = {}; 1577 // Undo phi node updates, because they will be added again by SelectionDAG. 1578 if (I->isTerminator()) { 1579 // PHI node handling may have generated local value instructions. 1580 // We remove them because SelectionDAGISel will generate them again. 1581 removeDeadLocalValueCode(SavedLastLocalValue); 1582 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 1583 } 1584 return false; 1585 } 1586 1587 /// Emit an unconditional branch to the given block, unless it is the immediate 1588 /// (fall-through) successor, and update the CFG. 1589 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, 1590 const DebugLoc &DbgLoc) { 1591 if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 && 1592 FuncInfo.MBB->isLayoutSuccessor(MSucc)) { 1593 // For more accurate line information if this is the only non-debug 1594 // instruction in the block then emit it, otherwise we have the 1595 // unconditional fall-through case, which needs no instructions. 1596 } else { 1597 // The unconditional branch case. 1598 TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr, 1599 SmallVector<MachineOperand, 0>(), DbgLoc); 1600 } 1601 if (FuncInfo.BPI) { 1602 auto BranchProbability = FuncInfo.BPI->getEdgeProbability( 1603 FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock()); 1604 FuncInfo.MBB->addSuccessor(MSucc, BranchProbability); 1605 } else 1606 FuncInfo.MBB->addSuccessorWithoutProb(MSucc); 1607 } 1608 1609 void FastISel::finishCondBranch(const BasicBlock *BranchBB, 1610 MachineBasicBlock *TrueMBB, 1611 MachineBasicBlock *FalseMBB) { 1612 // Add TrueMBB as successor unless it is equal to the FalseMBB: This can 1613 // happen in degenerate IR and MachineIR forbids to have a block twice in the 1614 // successor/predecessor lists. 1615 if (TrueMBB != FalseMBB) { 1616 if (FuncInfo.BPI) { 1617 auto BranchProbability = 1618 FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock()); 1619 FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability); 1620 } else 1621 FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB); 1622 } 1623 1624 fastEmitBranch(FalseMBB, MIMD.getDL()); 1625 } 1626 1627 /// Emit an FNeg operation. 1628 bool FastISel::selectFNeg(const User *I, const Value *In) { 1629 Register OpReg = getRegForValue(In); 1630 if (!OpReg) 1631 return false; 1632 1633 // If the target has ISD::FNEG, use it. 1634 EVT VT = TLI.getValueType(DL, I->getType()); 1635 Register ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG, 1636 OpReg); 1637 if (ResultReg) { 1638 updateValueMap(I, ResultReg); 1639 return true; 1640 } 1641 1642 // Bitcast the value to integer, twiddle the sign bit with xor, 1643 // and then bitcast it back to floating-point. 1644 if (VT.getSizeInBits() > 64) 1645 return false; 1646 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 1647 if (!TLI.isTypeLegal(IntVT)) 1648 return false; 1649 1650 Register IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 1651 ISD::BITCAST, OpReg); 1652 if (!IntReg) 1653 return false; 1654 1655 Register IntResultReg = fastEmit_ri_( 1656 IntVT.getSimpleVT(), ISD::XOR, IntReg, 1657 UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT()); 1658 if (!IntResultReg) 1659 return false; 1660 1661 ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST, 1662 IntResultReg); 1663 if (!ResultReg) 1664 return false; 1665 1666 updateValueMap(I, ResultReg); 1667 return true; 1668 } 1669 1670 bool FastISel::selectExtractValue(const User *U) { 1671 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U); 1672 if (!EVI) 1673 return false; 1674 1675 // Make sure we only try to handle extracts with a legal result. But also 1676 // allow i1 because it's easy. 1677 EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true); 1678 if (!RealVT.isSimple()) 1679 return false; 1680 MVT VT = RealVT.getSimpleVT(); 1681 if (!TLI.isTypeLegal(VT) && VT != MVT::i1) 1682 return false; 1683 1684 const Value *Op0 = EVI->getOperand(0); 1685 Type *AggTy = Op0->getType(); 1686 1687 // Get the base result register. 1688 unsigned ResultReg; 1689 DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(Op0); 1690 if (I != FuncInfo.ValueMap.end()) 1691 ResultReg = I->second; 1692 else if (isa<Instruction>(Op0)) 1693 ResultReg = FuncInfo.InitializeRegForValue(Op0); 1694 else 1695 return false; // fast-isel can't handle aggregate constants at the moment 1696 1697 // Get the actual result register, which is an offset from the base register. 1698 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices()); 1699 1700 SmallVector<EVT, 4> AggValueVTs; 1701 ComputeValueVTs(TLI, DL, AggTy, AggValueVTs); 1702 1703 for (unsigned i = 0; i < VTIndex; i++) 1704 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]); 1705 1706 updateValueMap(EVI, ResultReg); 1707 return true; 1708 } 1709 1710 bool FastISel::selectOperator(const User *I, unsigned Opcode) { 1711 switch (Opcode) { 1712 case Instruction::Add: 1713 return selectBinaryOp(I, ISD::ADD); 1714 case Instruction::FAdd: 1715 return selectBinaryOp(I, ISD::FADD); 1716 case Instruction::Sub: 1717 return selectBinaryOp(I, ISD::SUB); 1718 case Instruction::FSub: 1719 return selectBinaryOp(I, ISD::FSUB); 1720 case Instruction::Mul: 1721 return selectBinaryOp(I, ISD::MUL); 1722 case Instruction::FMul: 1723 return selectBinaryOp(I, ISD::FMUL); 1724 case Instruction::SDiv: 1725 return selectBinaryOp(I, ISD::SDIV); 1726 case Instruction::UDiv: 1727 return selectBinaryOp(I, ISD::UDIV); 1728 case Instruction::FDiv: 1729 return selectBinaryOp(I, ISD::FDIV); 1730 case Instruction::SRem: 1731 return selectBinaryOp(I, ISD::SREM); 1732 case Instruction::URem: 1733 return selectBinaryOp(I, ISD::UREM); 1734 case Instruction::FRem: 1735 return selectBinaryOp(I, ISD::FREM); 1736 case Instruction::Shl: 1737 return selectBinaryOp(I, ISD::SHL); 1738 case Instruction::LShr: 1739 return selectBinaryOp(I, ISD::SRL); 1740 case Instruction::AShr: 1741 return selectBinaryOp(I, ISD::SRA); 1742 case Instruction::And: 1743 return selectBinaryOp(I, ISD::AND); 1744 case Instruction::Or: 1745 return selectBinaryOp(I, ISD::OR); 1746 case Instruction::Xor: 1747 return selectBinaryOp(I, ISD::XOR); 1748 1749 case Instruction::FNeg: 1750 return selectFNeg(I, I->getOperand(0)); 1751 1752 case Instruction::GetElementPtr: 1753 return selectGetElementPtr(I); 1754 1755 case Instruction::Br: { 1756 const BranchInst *BI = cast<BranchInst>(I); 1757 1758 if (BI->isUnconditional()) { 1759 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 1760 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc]; 1761 fastEmitBranch(MSucc, BI->getDebugLoc()); 1762 return true; 1763 } 1764 1765 // Conditional branches are not handed yet. 1766 // Halt "fast" selection and bail. 1767 return false; 1768 } 1769 1770 case Instruction::Unreachable: 1771 if (TM.Options.TrapUnreachable) 1772 return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0; 1773 else 1774 return true; 1775 1776 case Instruction::Alloca: 1777 // FunctionLowering has the static-sized case covered. 1778 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I))) 1779 return true; 1780 1781 // Dynamic-sized alloca is not handled yet. 1782 return false; 1783 1784 case Instruction::Call: 1785 // On AIX, normal call lowering uses the DAG-ISEL path currently so that the 1786 // callee of the direct function call instruction will be mapped to the 1787 // symbol for the function's entry point, which is distinct from the 1788 // function descriptor symbol. The latter is the symbol whose XCOFF symbol 1789 // name is the C-linkage name of the source level function. 1790 // But fast isel still has the ability to do selection for intrinsics. 1791 if (TM.getTargetTriple().isOSAIX() && !isa<IntrinsicInst>(I)) 1792 return false; 1793 return selectCall(I); 1794 1795 case Instruction::BitCast: 1796 return selectBitCast(I); 1797 1798 case Instruction::FPToSI: 1799 return selectCast(I, ISD::FP_TO_SINT); 1800 case Instruction::ZExt: 1801 return selectCast(I, ISD::ZERO_EXTEND); 1802 case Instruction::SExt: 1803 return selectCast(I, ISD::SIGN_EXTEND); 1804 case Instruction::Trunc: 1805 return selectCast(I, ISD::TRUNCATE); 1806 case Instruction::SIToFP: 1807 return selectCast(I, ISD::SINT_TO_FP); 1808 1809 case Instruction::IntToPtr: // Deliberate fall-through. 1810 case Instruction::PtrToInt: { 1811 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1812 EVT DstVT = TLI.getValueType(DL, I->getType()); 1813 if (DstVT.bitsGT(SrcVT)) 1814 return selectCast(I, ISD::ZERO_EXTEND); 1815 if (DstVT.bitsLT(SrcVT)) 1816 return selectCast(I, ISD::TRUNCATE); 1817 Register Reg = getRegForValue(I->getOperand(0)); 1818 if (!Reg) 1819 return false; 1820 updateValueMap(I, Reg); 1821 return true; 1822 } 1823 1824 case Instruction::ExtractValue: 1825 return selectExtractValue(I); 1826 1827 case Instruction::Freeze: 1828 return selectFreeze(I); 1829 1830 case Instruction::PHI: 1831 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 1832 1833 default: 1834 // Unhandled instruction. Halt "fast" selection and bail. 1835 return false; 1836 } 1837 } 1838 1839 FastISel::FastISel(FunctionLoweringInfo &FuncInfo, 1840 const TargetLibraryInfo *LibInfo, 1841 bool SkipTargetIndependentISel) 1842 : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()), 1843 MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()), 1844 TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()), 1845 TII(*MF->getSubtarget().getInstrInfo()), 1846 TLI(*MF->getSubtarget().getTargetLowering()), 1847 TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo), 1848 SkipTargetIndependentISel(SkipTargetIndependentISel) {} 1849 1850 FastISel::~FastISel() = default; 1851 1852 bool FastISel::fastLowerArguments() { return false; } 1853 1854 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; } 1855 1856 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) { 1857 return false; 1858 } 1859 1860 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; } 1861 1862 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/) { 1863 return 0; 1864 } 1865 1866 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/, 1867 unsigned /*Op1*/) { 1868 return 0; 1869 } 1870 1871 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 1872 return 0; 1873 } 1874 1875 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned, 1876 const ConstantFP * /*FPImm*/) { 1877 return 0; 1878 } 1879 1880 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/, 1881 uint64_t /*Imm*/) { 1882 return 0; 1883 } 1884 1885 /// This method is a wrapper of fastEmit_ri. It first tries to emit an 1886 /// instruction with an immediate operand using fastEmit_ri. 1887 /// If that fails, it materializes the immediate into a register and try 1888 /// fastEmit_rr instead. 1889 Register FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, 1890 uint64_t Imm, MVT ImmType) { 1891 // If this is a multiply by a power of two, emit this as a shift left. 1892 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) { 1893 Opcode = ISD::SHL; 1894 Imm = Log2_64(Imm); 1895 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) { 1896 // div x, 8 -> srl x, 3 1897 Opcode = ISD::SRL; 1898 Imm = Log2_64(Imm); 1899 } 1900 1901 // Horrible hack (to be removed), check to make sure shift amounts are 1902 // in-range. 1903 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) && 1904 Imm >= VT.getSizeInBits()) 1905 return 0; 1906 1907 // First check if immediate type is legal. If not, we can't use the ri form. 1908 Register ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Imm); 1909 if (ResultReg) 1910 return ResultReg; 1911 Register MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 1912 if (!MaterialReg) { 1913 // This is a bit ugly/slow, but failing here means falling out of 1914 // fast-isel, which would be very slow. 1915 IntegerType *ITy = 1916 IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits()); 1917 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm)); 1918 if (!MaterialReg) 1919 return 0; 1920 } 1921 return fastEmit_rr(VT, VT, Opcode, Op0, MaterialReg); 1922 } 1923 1924 Register FastISel::createResultReg(const TargetRegisterClass *RC) { 1925 return MRI.createVirtualRegister(RC); 1926 } 1927 1928 Register FastISel::constrainOperandRegClass(const MCInstrDesc &II, Register Op, 1929 unsigned OpNum) { 1930 if (Op.isVirtual()) { 1931 const TargetRegisterClass *RegClass = 1932 TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF); 1933 if (!MRI.constrainRegClass(Op, RegClass)) { 1934 // If it's not legal to COPY between the register classes, something 1935 // has gone very wrong before we got here. 1936 Register NewOp = createResultReg(RegClass); 1937 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, 1938 TII.get(TargetOpcode::COPY), NewOp).addReg(Op); 1939 return NewOp; 1940 } 1941 } 1942 return Op; 1943 } 1944 1945 Register FastISel::fastEmitInst_(unsigned MachineInstOpcode, 1946 const TargetRegisterClass *RC) { 1947 Register ResultReg = createResultReg(RC); 1948 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1949 1950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg); 1951 return ResultReg; 1952 } 1953 1954 Register FastISel::fastEmitInst_r(unsigned MachineInstOpcode, 1955 const TargetRegisterClass *RC, unsigned Op0) { 1956 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1957 1958 Register ResultReg = createResultReg(RC); 1959 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1960 1961 if (II.getNumDefs() >= 1) 1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 1963 .addReg(Op0); 1964 else { 1965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 1966 .addReg(Op0); 1967 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 1968 ResultReg) 1969 .addReg(II.implicit_defs()[0]); 1970 } 1971 1972 return ResultReg; 1973 } 1974 1975 Register FastISel::fastEmitInst_rr(unsigned MachineInstOpcode, 1976 const TargetRegisterClass *RC, unsigned Op0, 1977 unsigned Op1) { 1978 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1979 1980 Register ResultReg = createResultReg(RC); 1981 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1982 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 1983 1984 if (II.getNumDefs() >= 1) 1985 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 1986 .addReg(Op0) 1987 .addReg(Op1); 1988 else { 1989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 1990 .addReg(Op0) 1991 .addReg(Op1); 1992 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 1993 ResultReg) 1994 .addReg(II.implicit_defs()[0]); 1995 } 1996 return ResultReg; 1997 } 1998 1999 Register FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode, 2000 const TargetRegisterClass *RC, unsigned Op0, 2001 unsigned Op1, unsigned Op2) { 2002 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2003 2004 Register ResultReg = createResultReg(RC); 2005 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2006 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2007 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2); 2008 2009 if (II.getNumDefs() >= 1) 2010 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2011 .addReg(Op0) 2012 .addReg(Op1) 2013 .addReg(Op2); 2014 else { 2015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 2016 .addReg(Op0) 2017 .addReg(Op1) 2018 .addReg(Op2); 2019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2020 ResultReg) 2021 .addReg(II.implicit_defs()[0]); 2022 } 2023 return ResultReg; 2024 } 2025 2026 Register FastISel::fastEmitInst_ri(unsigned MachineInstOpcode, 2027 const TargetRegisterClass *RC, unsigned Op0, 2028 uint64_t Imm) { 2029 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2030 2031 Register ResultReg = createResultReg(RC); 2032 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2033 2034 if (II.getNumDefs() >= 1) 2035 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2036 .addReg(Op0) 2037 .addImm(Imm); 2038 else { 2039 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 2040 .addReg(Op0) 2041 .addImm(Imm); 2042 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2043 ResultReg) 2044 .addReg(II.implicit_defs()[0]); 2045 } 2046 return ResultReg; 2047 } 2048 2049 Register FastISel::fastEmitInst_rii(unsigned MachineInstOpcode, 2050 const TargetRegisterClass *RC, unsigned Op0, 2051 uint64_t Imm1, uint64_t Imm2) { 2052 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2053 2054 Register ResultReg = createResultReg(RC); 2055 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2056 2057 if (II.getNumDefs() >= 1) 2058 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2059 .addReg(Op0) 2060 .addImm(Imm1) 2061 .addImm(Imm2); 2062 else { 2063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 2064 .addReg(Op0) 2065 .addImm(Imm1) 2066 .addImm(Imm2); 2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2068 ResultReg) 2069 .addReg(II.implicit_defs()[0]); 2070 } 2071 return ResultReg; 2072 } 2073 2074 Register FastISel::fastEmitInst_f(unsigned MachineInstOpcode, 2075 const TargetRegisterClass *RC, 2076 const ConstantFP *FPImm) { 2077 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2078 2079 Register ResultReg = createResultReg(RC); 2080 2081 if (II.getNumDefs() >= 1) 2082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2083 .addFPImm(FPImm); 2084 else { 2085 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 2086 .addFPImm(FPImm); 2087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2088 ResultReg) 2089 .addReg(II.implicit_defs()[0]); 2090 } 2091 return ResultReg; 2092 } 2093 2094 Register FastISel::fastEmitInst_rri(unsigned MachineInstOpcode, 2095 const TargetRegisterClass *RC, unsigned Op0, 2096 unsigned Op1, uint64_t Imm) { 2097 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2098 2099 Register ResultReg = createResultReg(RC); 2100 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2101 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2102 2103 if (II.getNumDefs() >= 1) 2104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2105 .addReg(Op0) 2106 .addReg(Op1) 2107 .addImm(Imm); 2108 else { 2109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II) 2110 .addReg(Op0) 2111 .addReg(Op1) 2112 .addImm(Imm); 2113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2114 ResultReg) 2115 .addReg(II.implicit_defs()[0]); 2116 } 2117 return ResultReg; 2118 } 2119 2120 Register FastISel::fastEmitInst_i(unsigned MachineInstOpcode, 2121 const TargetRegisterClass *RC, uint64_t Imm) { 2122 Register ResultReg = createResultReg(RC); 2123 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2124 2125 if (II.getNumDefs() >= 1) 2126 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg) 2127 .addImm(Imm); 2128 else { 2129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II).addImm(Imm); 2130 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2131 ResultReg) 2132 .addReg(II.implicit_defs()[0]); 2133 } 2134 return ResultReg; 2135 } 2136 2137 Register FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, 2138 uint32_t Idx) { 2139 Register ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 2140 assert(Register::isVirtualRegister(Op0) && 2141 "Cannot yet extract from physregs"); 2142 const TargetRegisterClass *RC = MRI.getRegClass(Op0); 2143 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx)); 2144 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY), 2145 ResultReg).addReg(Op0, 0, Idx); 2146 return ResultReg; 2147 } 2148 2149 /// Emit MachineInstrs to compute the value of Op with all but the least 2150 /// significant bit set to zero. 2151 Register FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0) { 2152 return fastEmit_ri(VT, VT, ISD::AND, Op0, 1); 2153 } 2154 2155 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 2156 /// Emit code to ensure constants are copied into registers when needed. 2157 /// Remember the virtual registers that need to be added to the Machine PHI 2158 /// nodes as input. We cannot just directly add them, because expansion 2159 /// might result in multiple MBB's for one BB. As such, the start of the 2160 /// BB might correspond to a different MBB than the end. 2161 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 2162 const Instruction *TI = LLVMBB->getTerminator(); 2163 2164 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 2165 FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size(); 2166 2167 // Check successor nodes' PHI nodes that expect a constant to be available 2168 // from this block. 2169 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 2170 const BasicBlock *SuccBB = TI->getSuccessor(succ); 2171 if (!isa<PHINode>(SuccBB->begin())) 2172 continue; 2173 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 2174 2175 // If this terminator has multiple identical successors (common for 2176 // switches), only handle each succ once. 2177 if (!SuccsHandled.insert(SuccMBB).second) 2178 continue; 2179 2180 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 2181 2182 // At this point we know that there is a 1-1 correspondence between LLVM PHI 2183 // nodes and Machine PHI nodes, but the incoming operands have not been 2184 // emitted yet. 2185 for (const PHINode &PN : SuccBB->phis()) { 2186 // Ignore dead phi's. 2187 if (PN.use_empty()) 2188 continue; 2189 2190 // Only handle legal types. Two interesting things to note here. First, 2191 // by bailing out early, we may leave behind some dead instructions, 2192 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 2193 // own moves. Second, this check is necessary because FastISel doesn't 2194 // use CreateRegs to create registers, so it always creates 2195 // exactly one register for each non-void instruction. 2196 EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true); 2197 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 2198 // Handle integer promotions, though, because they're common and easy. 2199 if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) { 2200 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2201 return false; 2202 } 2203 } 2204 2205 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 2206 2207 // Set the DebugLoc for the copy. Use the location of the operand if 2208 // there is one; otherwise no location, flushLocalValueMap will fix it. 2209 MIMD = {}; 2210 if (const auto *Inst = dyn_cast<Instruction>(PHIOp)) 2211 MIMD = MIMetadata(*Inst); 2212 2213 Register Reg = getRegForValue(PHIOp); 2214 if (!Reg) { 2215 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2216 return false; 2217 } 2218 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg)); 2219 MIMD = {}; 2220 } 2221 } 2222 2223 return true; 2224 } 2225 2226 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) { 2227 assert(LI->hasOneUse() && 2228 "tryToFoldLoad expected a LoadInst with a single use"); 2229 // We know that the load has a single use, but don't know what it is. If it 2230 // isn't one of the folded instructions, then we can't succeed here. Handle 2231 // this by scanning the single-use users of the load until we get to FoldInst. 2232 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs. 2233 2234 const Instruction *TheUser = LI->user_back(); 2235 while (TheUser != FoldInst && // Scan up until we find FoldInst. 2236 // Stay in the right block. 2237 TheUser->getParent() == FoldInst->getParent() && 2238 --MaxUsers) { // Don't scan too far. 2239 // If there are multiple or no uses of this instruction, then bail out. 2240 if (!TheUser->hasOneUse()) 2241 return false; 2242 2243 TheUser = TheUser->user_back(); 2244 } 2245 2246 // If we didn't find the fold instruction, then we failed to collapse the 2247 // sequence. 2248 if (TheUser != FoldInst) 2249 return false; 2250 2251 // Don't try to fold volatile loads. Target has to deal with alignment 2252 // constraints. 2253 if (LI->isVolatile()) 2254 return false; 2255 2256 // Figure out which vreg this is going into. If there is no assigned vreg yet 2257 // then there actually was no reference to it. Perhaps the load is referenced 2258 // by a dead instruction. 2259 Register LoadReg = getRegForValue(LI); 2260 if (!LoadReg) 2261 return false; 2262 2263 // We can't fold if this vreg has no uses or more than one use. Multiple uses 2264 // may mean that the instruction got lowered to multiple MIs, or the use of 2265 // the loaded value ended up being multiple operands of the result. 2266 if (!MRI.hasOneUse(LoadReg)) 2267 return false; 2268 2269 // If the register has fixups, there may be additional uses through a 2270 // different alias of the register. 2271 if (FuncInfo.RegsWithFixups.contains(LoadReg)) 2272 return false; 2273 2274 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg); 2275 MachineInstr *User = RI->getParent(); 2276 2277 // Set the insertion point properly. Folding the load can cause generation of 2278 // other random instructions (like sign extends) for addressing modes; make 2279 // sure they get inserted in a logical place before the new instruction. 2280 FuncInfo.InsertPt = User; 2281 FuncInfo.MBB = User->getParent(); 2282 2283 // Ask the target to try folding the load. 2284 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI); 2285 } 2286 2287 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) { 2288 // Must be an add. 2289 if (!isa<AddOperator>(Add)) 2290 return false; 2291 // Type size needs to match. 2292 if (DL.getTypeSizeInBits(GEP->getType()) != 2293 DL.getTypeSizeInBits(Add->getType())) 2294 return false; 2295 // Must be in the same basic block. 2296 if (isa<Instruction>(Add) && 2297 FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB) 2298 return false; 2299 // Must have a constant operand. 2300 return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1)); 2301 } 2302 2303 MachineMemOperand * 2304 FastISel::createMachineMemOperandFor(const Instruction *I) const { 2305 const Value *Ptr; 2306 Type *ValTy; 2307 MaybeAlign Alignment; 2308 MachineMemOperand::Flags Flags; 2309 bool IsVolatile; 2310 2311 if (const auto *LI = dyn_cast<LoadInst>(I)) { 2312 Alignment = LI->getAlign(); 2313 IsVolatile = LI->isVolatile(); 2314 Flags = MachineMemOperand::MOLoad; 2315 Ptr = LI->getPointerOperand(); 2316 ValTy = LI->getType(); 2317 } else if (const auto *SI = dyn_cast<StoreInst>(I)) { 2318 Alignment = SI->getAlign(); 2319 IsVolatile = SI->isVolatile(); 2320 Flags = MachineMemOperand::MOStore; 2321 Ptr = SI->getPointerOperand(); 2322 ValTy = SI->getValueOperand()->getType(); 2323 } else 2324 return nullptr; 2325 2326 bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal); 2327 bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load); 2328 bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable); 2329 const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range); 2330 2331 AAMDNodes AAInfo = I->getAAMetadata(); 2332 2333 if (!Alignment) // Ensure that codegen never sees alignment 0. 2334 Alignment = DL.getABITypeAlign(ValTy); 2335 2336 unsigned Size = DL.getTypeStoreSize(ValTy); 2337 2338 if (IsVolatile) 2339 Flags |= MachineMemOperand::MOVolatile; 2340 if (IsNonTemporal) 2341 Flags |= MachineMemOperand::MONonTemporal; 2342 if (IsDereferenceable) 2343 Flags |= MachineMemOperand::MODereferenceable; 2344 if (IsInvariant) 2345 Flags |= MachineMemOperand::MOInvariant; 2346 2347 return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size, 2348 *Alignment, AAInfo, Ranges); 2349 } 2350 2351 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const { 2352 // If both operands are the same, then try to optimize or fold the cmp. 2353 CmpInst::Predicate Predicate = CI->getPredicate(); 2354 if (CI->getOperand(0) != CI->getOperand(1)) 2355 return Predicate; 2356 2357 switch (Predicate) { 2358 default: llvm_unreachable("Invalid predicate!"); 2359 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break; 2360 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break; 2361 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break; 2362 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break; 2363 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break; 2364 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break; 2365 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break; 2366 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break; 2367 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break; 2368 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break; 2369 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break; 2370 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2371 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break; 2372 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2373 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break; 2374 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break; 2375 2376 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break; 2377 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break; 2378 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break; 2379 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2380 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break; 2381 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2382 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break; 2383 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break; 2384 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break; 2385 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break; 2386 } 2387 2388 return Predicate; 2389 } 2390